text
stringlengths 54
60.6k
|
---|
<commit_before>// This file is intended to be included into an array of 'BuiltinFunc'
{"traditional-transformer", {
traditional_transformer,
{1}}},
{"gensym", {
gensym,
{0}}},
{"sc-macro-transformer", {
sc_macro_transformer,
{1}}},
{"make-syntactic-closure", {
make_syntactic_closure,
{3}}},
{"capture-syntactic-environment", {
capture_env,
{1}}},
{"identifier?", {
proc_identifierp,
{1}}},
{"identifier=?", {
proc_identifier_eq,
{4}}},
{"make_synthetic_identifier", {
make_synthetic_identifier,
{1}}},
{"exit", {
exit_func,
{0}}},
{"eq-hash", {
eq_hash_func,
{1}}},
<commit_msg>fixed typo<commit_after>// This file is intended to be included into an array of 'BuiltinFunc'
{"traditional-transformer", {
traditional_transformer,
{1}}},
{"gensym", {
gensym,
{0}}},
{"sc-macro-transformer", {
sc_macro_transformer,
{1}}},
{"make-syntactic-closure", {
make_syntactic_closure,
{3}}},
{"capture-syntactic-environment", {
capture_env,
{1}}},
{"identifier?", {
proc_identifierp,
{1}}},
{"identifier=?", {
proc_identifier_eq,
{4}}},
{"make-synthetic-identifier", {
make_synthetic_identifier,
{1}}},
{"exit", {
exit_func,
{0}}},
{"eq-hash", {
eq_hash_func,
{1}}},
<|endoftext|> |
<commit_before>/* cuda_wrapper/vector.hpp
*
* Copyright (C) 2007 Peter Colberg
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef CUDA_ARRAY_HPP
#define CUDA_ARRAY_HPP
#include <cuda_runtime.h>
#include <cuda_wrapper/allocator.hpp>
#include <cuda_wrapper/symbol.hpp>
#include <cuda_wrapper/host/vector.hpp>
#include <algorithm>
#include <assert.h>
namespace cuda
{
namespace host
{
template <typename T, typename Alloc>
class vector;
}
template <typename T>
class symbol;
template <typename T>
class vector
{
protected:
size_t n;
T *ptr;
public:
vector(size_t n): n(n), ptr(allocator<T>().allocate(n)) { }
vector(const vector<T>& src): n(0), ptr(NULL)
{
if (this != &src) {
vector<T> dst(src.dim());
dst = src;
swap(*this, dst);
}
}
vector(const host::vector<T>& src): n(0), ptr(NULL)
{
vector<T> dst(src.size());
dst = src;
swap(*this, dst);
}
vector(const symbol<T> &src): n(0), ptr(NULL)
{
vector<T> dst(1);
dst = src;
swap(*this, dst);
}
~vector()
{
if (ptr != NULL) {
allocator<T>().deallocate(ptr, n);
}
}
vector<T>& operator=(const vector<T>& v)
{
if (this != &v) {
assert(v.dim() == n);
// copy from device memory area to device memory area
CUDA_CALL(cudaMemcpy(ptr, v.get_ptr(), n * sizeof(T), cudaMemcpyDeviceToDevice));
}
return *this;
}
vector<T>& operator=(const host::vector<T>& v)
{
assert(v.size() == n);
// copy from host memory area to device memory area
CUDA_CALL(cudaMemcpy(ptr, &v.front(), n * sizeof(T), cudaMemcpyHostToDevice));
return *this;
}
vector<T>& operator=(const symbol<T>& symbol)
{
assert(symbol.dim() == n);
// copy from device symbol to device memory area
CUDA_CALL(cudaMemcpyFromSymbol(ptr, reinterpret_cast<const char *>(symbol.get_ptr()), n * sizeof(T), 0, cudaMemcpyDeviceToDevice));
return *this;
}
vector<T>& operator=(const T& value)
{
host::vector<T> v(n);
*this = v = value;
return *this;
}
static void swap(vector<T>& a, vector<T>& b)
{
std::swap(a.n, b.n);
std::swap(a.ptr, b.ptr);
}
size_t dim() const
{
return n;
}
T *get_ptr() const
{
return ptr;
}
};
}
#endif /* CUDA_ARRAY_HPP */
<commit_msg>Refactor CUDA device vector container<commit_after>/* cuda_wrapper/vector.hpp
*
* Copyright (C) 2007 Peter Colberg
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef CUDA_VECTOR_HPP
#define CUDA_VECTOR_HPP
#include <cuda_runtime.h>
#include <cuda_wrapper/allocator.hpp>
#include <cuda_wrapper/symbol.hpp>
#include <cuda_wrapper/host/vector.hpp>
#include <algorithm>
#include <assert.h>
namespace cuda
{
namespace host
{
template <typename T, typename Alloc>
class vector;
}
template <typename T>
class symbol;
/**
* vector pseudo-container for linear global device memory
*/
template <typename T>
class vector
{
protected:
size_t _size;
T *_ptr;
public:
/**
* initialize device vector of given size
*/
vector(size_t n): _size(n), _ptr(allocator<T>().allocate(n))
{
}
/**
* initialize device vector with content of device vector
*/
vector(const vector<T>& src): _size(0), _ptr(NULL)
{
// ensure deallocation of device memory in case of an exception
vector<T> dst(src.size());
dst.memcpy(src);
swap(*this, dst);
}
/**
* initialize device vector with content of host vector
*/
template <typename Alloc>
vector(const host::vector<T, Alloc>& src): _size(0), _ptr(NULL)
{
// ensure deallocation of device memory in case of an exception
vector<T> dst(src.size());
dst.memcpy(src);
swap(*this, dst);
}
/**
* initialize device vector with content of device symbol
*/
vector(const symbol<T> &src): _size(0), _ptr(NULL)
{
// ensure deallocation of device memory in case of an exception
vector<T> dst(src.dim());
dst.memcpy(src);
swap(*this, dst);
}
/**
* deallocate device vector
*/
~vector()
{
if (_ptr != NULL) {
allocator<T>().deallocate(_ptr, _size);
}
}
/**
* copy from device memory area to device memory area
*/
void memcpy(const vector<T>& v)
{
assert(v.size() == size());
CUDA_CALL(cudaMemcpy(ptr(), v.ptr(), v.size() * sizeof(T), cudaMemcpyDeviceToDevice));
}
/*
* copy from host memory area to device memory area
*/
template <typename Alloc>
void memcpy(const host::vector<T, Alloc>& v)
{
assert(v.size() == size());
CUDA_CALL(cudaMemcpy(ptr(), &v.front(), v.size() * sizeof(T), cudaMemcpyHostToDevice));
}
/*
* copy from device symbol to device memory area
*/
void memcpy(const symbol<T>& symbol)
{
assert(symbol.dim() == size());
CUDA_CALL(cudaMemcpyFromSymbol(ptr(), reinterpret_cast<const char *>(symbol.get_ptr()), symbol.size() * sizeof(T), 0, cudaMemcpyDeviceToDevice));
}
/**
* assign content of device vector to device vector
*/
vector<T>& operator=(const vector<T>& v)
{
if (this != &v) {
memcpy(v);
}
return *this;
}
/**
* assign content of host vector to device vector
*/
template <typename Alloc>
vector<T>& operator=(const host::vector<T, Alloc>& v)
{
memcpy(v);
return *this;
}
/**
* assign content of device symbol to device vector
*/
vector<T>& operator=(const symbol<T>& symbol)
{
memcpy(symbol);
return *this;
}
/**
* assign copies of value to device vector
*/
vector<T>& operator=(const T& value)
{
host::vector<T> v(size(), value);
memcpy(v);
return *this;
}
/**
* swap device memory areas with another device vector
*/
static void swap(vector<T>& a, vector<T>& b)
{
std::swap(a._size, b._size);
std::swap(a._ptr, b._ptr);
}
/**
* returns element count of device vector
*/
size_t size() const
{
return _size;
}
/**
* FIXME obsolete
*/
size_t dim() const
{
return _size;
}
/**
* returns device pointer to allocated device memory
*/
T *ptr() const
{
return _ptr;
}
/**
* FIXME obsolete
*/
T *get_ptr() const
{
return _ptr;
}
};
}
#endif /* CUDA_VECTOR_HPP */
<|endoftext|> |
<commit_before>//
// main.cpp
// builtins
//
// Created by Sunil on 5/3/17.
// Copyright © 2017 Sunil. All rights reserved.
//
#include <iostream>
using namespace std;
int main(int argc, const char * argv[]) {
// function with __builtin_xxx are hidden. But not really! They are still
// available. You can call them. Are they platform specific ? I don't know.
// List of builtin functions: http://www.keil.com/support/man/docs/armcc/armcc_chr1359125006834.htm
auto ffs = __builtin_ffs(10);
auto clz = __builtin_clz(10);
auto popcount = __builtin_popcount(10);
auto gcd = __gcd(10, 8);
cout << "ffs: " << ffs << endl;
cout << "clz: " << clz << endl;
cout << "popcount: " << popcount << endl;
cout << "gcd: " << gcd << endl;
return 0;
}
<commit_msg>some weird code<commit_after>//
// main.cpp
// builtins
//
// Created by Sunil on 5/3/17.
// Copyright © 2017 Sunil. All rights reserved.
//
#include <iostream>
using namespace std;
struct Foo {
string name;
int id;
};
void bar(Foo f) {
cout << f.name << " " << f.id << endl;
}
int main(int argc, const char * argv[]) {
// function with __builtin_xxx are hidden. But not really! They are still
// available. You can call them. Are they platform specific ? I don't know.
// List of builtin functions: http://www.keil.com/support/man/docs/armcc/armcc_chr1359125006834.htm
auto ffs = __builtin_ffs(10);
auto clz = __builtin_clz(10);
auto popcount = __builtin_popcount(10);
auto gcd = __gcd(10, 8);
cout << "ffs: " << ffs << endl;
cout << "clz: " << clz << endl;
cout << "popcount: " << popcount << endl;
cout << "gcd: " << gcd << endl;
// odd expressions in c++ arrays
const char* name = "welcome to UC boulder!";
cout << name << endl;
char x = "Hello" " " "World"[8];
cout << x << endl;
char y = 8["Hello" " " "World"];
cout << y << endl;
// crazy ternary operator
int a = 7;
int b = 8;
((a < b) ? a : b) = -((a > b) ? a : b);
cout << a << " " << b << endl;
// You think you have mastered for (...) loop ?
// take a look at the below for loop & think again!
for (struct {int min; int max;} i = {0, 10}; i.min < i.max; i.min++) {
cout << i.min << endl;
}
// I got you now, didn't I ? Haha.
bar(*(new Foo {"sunil", 45}));
// wait, I got into my own hell. How do I delete Foo now ??
return 0;
}
<|endoftext|> |
<commit_before>//****************************************************************************//
// coresubmesh.cpp //
// Copyright (C) 2001, 2002 Bruno 'Beosil' Heidelberger //
//****************************************************************************//
// This library is free software; you can redistribute it and/or modify it //
// under the terms of the GNU Lesser General Public License as published by //
// the Free Software Foundation; either version 2.1 of the License, or (at //
// your option) any later version. //
//****************************************************************************//
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
//****************************************************************************//
// Includes //
//****************************************************************************//
#include "cal3d/coresubmesh.h"
#include "cal3d/coresubmorphtarget.h"
/*****************************************************************************/
/** Constructs the core submesh instance.
*
* This function is the default constructor of the core submesh instance.
*****************************************************************************/
CalCoreSubmesh::CalCoreSubmesh(int vertexCount, int textureCoordinateCount, int faceCount)
: m_coreMaterialThreadId(0)
, m_lodCount(0)
, m_isStatic(false)
, m_currentVertexId(0)
{
m_hasNonWhiteVertexColors = false;
// reserve the space needed in all the vectors
m_vertices.resize(vertexCount);
m_vertexColors.resize(vertexCount);
m_lodData.resize(vertexCount);
m_influenceRanges.resize(vertexCount);
m_vectorvectorTextureCoordinate.resize(textureCoordinateCount);
for(int textureCoordinateId = 0; textureCoordinateId < textureCoordinateCount; ++textureCoordinateId)
{
m_vectorvectorTextureCoordinate[textureCoordinateId].resize(vertexCount);
}
m_vectorFace.resize(faceCount);
}
/*****************************************************************************/
/** Destructs the core submesh instance.
*
* This function is the destructor of the core submesh instance.
*****************************************************************************/
void CalCoreSubmesh::setSubMorphTargetGroupIndexArray( unsigned int len, unsigned int const * indexArray )
{
m_vectorSubMorphTargetGroupIndex.reserve( len );
m_vectorSubMorphTargetGroupIndex.resize( len );
unsigned int i;
for( i = 0; i < len; i++ ) {
m_vectorSubMorphTargetGroupIndex[ i ] = indexArray[ i ];
}
}
template<typename T>
size_t vectorSize(const SSEArray<T>& v) {
return sizeof(T) * v.size();
}
template<typename T>
size_t vectorSize(const std::vector<T>& v) {
return sizeof(T) * v.size();
}
size_t CalCoreSubmesh::sizeWithoutSubMorphTargets()
{
unsigned int r = sizeof( CalCoreSubmesh );
r += vectorSize(m_vertices);
r += vectorSize(m_vertexColors);
r += vectorSize(m_vectorFace);
r += vectorSize(m_vectorSubMorphTargetGroupIndex);
r += vectorSize(m_lodData);
std::vector<std::vector<TextureCoordinate> >::iterator iter3;
for( iter3 = m_vectorvectorTextureCoordinate.begin(); iter3 != m_vectorvectorTextureCoordinate.end(); ++iter3 ) {
r += sizeof( TextureCoordinate ) * (*iter3).size();
}
return r;
}
size_t CalCoreSubmesh::size()
{
unsigned int r = sizeWithoutSubMorphTargets();
CoreSubMorphTargetVector::iterator iter1;
for( iter1 = m_vectorCoreSubMorphTarget.begin(); iter1 != m_vectorCoreSubMorphTarget.end(); ++iter1 ) {
r += (*iter1)->size();
}
return r;
}
/*****************************************************************************/
/** Returns the ID of the core material thread.
*
* This function returns the ID of the core material thread of this core
* submesh instance.
*
* @return The ID of the core material thread.
*****************************************************************************/
int CalCoreSubmesh::getCoreMaterialThreadId()
{
return m_coreMaterialThreadId;
}
/*****************************************************************************/
/** Returns the number of faces.
*
* This function returns the number of faces in the core submesh instance.
*
* @return The number of faces.
*****************************************************************************/
int CalCoreSubmesh::getFaceCount()
{
return m_vectorFace.size();
}
/*****************************************************************************/
/** Returns the number of LOD steps.
*
* This function returns the number of LOD steps in the core submesh instance.
*
* @return The number of LOD steps.
*****************************************************************************/
int CalCoreSubmesh::getLodCount()
{
return m_lodCount;
}
const std::vector<CalCoreSubmesh::Face>& CalCoreSubmesh::getVectorFace() const
{
return m_vectorFace;
}
std::vector<std::vector<CalCoreSubmesh::TextureCoordinate> > & CalCoreSubmesh::getVectorVectorTextureCoordinate()
{
return m_vectorvectorTextureCoordinate;
}
std::vector<CalColor32>& CalCoreSubmesh::getVertexColors()
{
return m_vertexColors;
}
int CalCoreSubmesh::getVertexCount()
{
return m_vertices.size();
}
/*****************************************************************************/
/** Sets the ID of the core material thread.
*
* This function sets the ID of the core material thread of the core submesh
* instance.
*
* @param coreMaterialThreadId The ID of the core material thread that should
* be set.
*****************************************************************************/
void CalCoreSubmesh::setCoreMaterialThreadId(int coreMaterialThreadId)
{
m_coreMaterialThreadId = coreMaterialThreadId;
}
/*****************************************************************************/
/** Sets a specified face.
*
* This function sets a specified face in the core submesh instance.
*
* @param faceId The ID of the face.
* @param face The face that should be set.
*
* @return One of the following values:
* \li \b true if successful
* \li \b false if an error happend
*****************************************************************************/
bool CalCoreSubmesh::setFace(int faceId, const Face& face)
{
if((faceId < 0) || (faceId >= (int)m_vectorFace.size())) return false;
m_vectorFace[faceId] = face;
return true;
}
/*****************************************************************************/
/** Sets the number of LOD steps.
*
* This function sets the number of LOD steps of the core submesh instance.
*
* @param lodCount The number of LOD steps that should be set.
*****************************************************************************/
void CalCoreSubmesh::setLodCount(int lodCount)
{
m_lodCount = lodCount;
}
/*****************************************************************************/
/** Sets a specified texture coordinate.
*
* This function sets a specified texture coordinate in the core submesh
* instance.
*
* @param vertexId The ID of the vertex.
* @param textureCoordinateId The ID of the texture coordinate.
* @param textureCoordinate The texture coordinate that should be set.
*
* @return One of the following values:
* \li \b true if successful
* \li \b false if an error happend
*****************************************************************************/
bool CalCoreSubmesh::setTextureCoordinate(int vertexId, int textureCoordinateId, const TextureCoordinate& textureCoordinate)
{
if((textureCoordinateId < 0) || (textureCoordinateId >= (int)m_vectorvectorTextureCoordinate.size())) return false;
if((vertexId < 0) || (vertexId >= (int)m_vectorvectorTextureCoordinate[textureCoordinateId].size())) return false;
m_vectorvectorTextureCoordinate[textureCoordinateId][vertexId] = textureCoordinate;
return true;
}
void CalCoreSubmesh::addVertex(const Vertex& vertex, CalColor32 vertexColor, const LodData& lodData, std::vector<Influence> inf) {
assert(m_currentVertexId < m_vertices.size());
const int vertexId = m_currentVertexId++;
if (vertexId == 0) {
m_isStatic = true;
m_staticInfluenceSet = inf;
} else if (m_isStatic) {
m_isStatic = m_staticInfluenceSet == inf;
}
m_vertices[vertexId] = vertex;
m_vertexColors[vertexId] = vertexColor;
m_lodData[vertexId] = lodData;
// Each vertex needs at least one influence.
if (inf.empty()) {
Influence i;
i.boneId = 0;
i.weight = 0.0f;
inf.push_back(i);
}
// Mark the last influence as the last one. :)
for (size_t i = 0; i + 1 < inf.size(); ++i) {
inf[i].lastInfluenceForThisVertex = 0;
}
inf[inf.size() - 1].lastInfluenceForThisVertex = 1;
m_influenceRanges[vertexId].influenceStart = influences.size();
m_influenceRanges[vertexId].influenceEnd = influences.size() + inf.size();
influences.insert(influences.end(), inf.begin(), inf.end());
}
/*****************************************************************************/
/** Adds a core sub morph target.
*
* This function adds a core sub morph target to the core sub mesh instance.
*
* @param pCoreSubMorphTarget A pointer to the core sub morph target that should be added.
*
* @return One of the following values:
* \li the assigned sub morph target \b ID of the added core sub morph target
* \li \b -1 if an error happend
*****************************************************************************/
int CalCoreSubmesh::addCoreSubMorphTarget(boost::shared_ptr<CalCoreSubMorphTarget> pCoreSubMorphTarget)
{
// get next sub morph target id
int subMorphTargetId;
subMorphTargetId = m_vectorCoreSubMorphTarget.size();
m_vectorCoreSubMorphTarget.push_back(pCoreSubMorphTarget);
return subMorphTargetId;
}
/*****************************************************************************/
/** Provides access to a core sub morph target.
*
* This function returns the core sub morph target with the given ID.
*
* @param id The ID of the core sub morph target that should be returned.
*
* @return One of the following values:
* \li a pointer to the core sub morph target
* \li \b 0 if an error happend
*****************************************************************************/
boost::shared_ptr<CalCoreSubMorphTarget> CalCoreSubmesh::getCoreSubMorphTarget(int id)
{
if((id < 0) || (id >= (int)m_vectorCoreSubMorphTarget.size()))
{
// should assert
return boost::shared_ptr<CalCoreSubMorphTarget>();
}
return m_vectorCoreSubMorphTarget[id];
}
/*****************************************************************************/
/** Returns the number of core sub morph targets.
*
* This function returns the number of core sub morph targets in the core sub mesh
* instance.
*
* @return The number of core sub morph targets.
*****************************************************************************/
int CalCoreSubmesh::getCoreSubMorphTargetCount()
{
return m_vectorCoreSubMorphTarget.size();
}
/*****************************************************************************/
/** Returns the core sub morph target vector.
*
* This function returns the vector that contains all core sub morph target
* of the core submesh instance.
*
* @return A reference to the core sub morph target vector.
*****************************************************************************/
CalCoreSubmesh::CoreSubMorphTargetVector& CalCoreSubmesh::getVectorCoreSubMorphTarget()
{
return m_vectorCoreSubMorphTarget;
}
/*****************************************************************************/
/** Scale the Submesh.
*
* This function rescale all the data that are in the core submesh instance.
*
* @param factor A float with the scale factor
*
*****************************************************************************/
void CalCoreSubmesh::scale(float factor)
{
for(int vertexId = 0; vertexId < m_vertices.size(); vertexId++) {
m_vertices[vertexId].position*=factor;
}
}
bool CalCoreSubmesh::isStatic() const {
return m_isStatic && m_vectorCoreSubMorphTarget.empty();
}
BoneTransform CalCoreSubmesh::getStaticTransform(const BoneTransform* bones) {
BoneTransform rm;
std::set<Influence>::const_iterator current = m_staticInfluenceSet.influences.begin();
while (current != m_staticInfluenceSet.influences.end()) {
const BoneTransform& influence = bones[current->boneId];
rm.rowx.x += current->weight * influence.rowx.x;
rm.rowx.y += current->weight * influence.rowx.y;
rm.rowx.z += current->weight * influence.rowx.z;
rm.rowx.w += current->weight * influence.rowx.w;
rm.rowy.x += current->weight * influence.rowy.x;
rm.rowy.y += current->weight * influence.rowy.y;
rm.rowy.z += current->weight * influence.rowy.z;
rm.rowy.w += current->weight * influence.rowy.w;
rm.rowz.x += current->weight * influence.rowz.x;
rm.rowz.y += current->weight * influence.rowz.y;
rm.rowz.z += current->weight * influence.rowz.z;
rm.rowz.w += current->weight * influence.rowz.w;
++current;
}
return rm;
}
<commit_msg>Skip the skinning pipeline for submeshes marked as static.<commit_after>//****************************************************************************//
// coresubmesh.cpp //
// Copyright (C) 2001, 2002 Bruno 'Beosil' Heidelberger //
//****************************************************************************//
// This library is free software; you can redistribute it and/or modify it //
// under the terms of the GNU Lesser General Public License as published by //
// the Free Software Foundation; either version 2.1 of the License, or (at //
// your option) any later version. //
//****************************************************************************//
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
//****************************************************************************//
// Includes //
//****************************************************************************//
#include "cal3d/coresubmesh.h"
#include "cal3d/coresubmorphtarget.h"
/*****************************************************************************/
/** Constructs the core submesh instance.
*
* This function is the default constructor of the core submesh instance.
*****************************************************************************/
CalCoreSubmesh::CalCoreSubmesh(int vertexCount, int textureCoordinateCount, int faceCount)
: m_coreMaterialThreadId(0)
, m_lodCount(0)
, m_isStatic(false)
, m_currentVertexId(0)
{
m_hasNonWhiteVertexColors = false;
// reserve the space needed in all the vectors
m_vertices.resize(vertexCount);
m_vertexColors.resize(vertexCount);
m_lodData.resize(vertexCount);
m_influenceRanges.resize(vertexCount);
m_vectorvectorTextureCoordinate.resize(textureCoordinateCount);
for(int textureCoordinateId = 0; textureCoordinateId < textureCoordinateCount; ++textureCoordinateId)
{
m_vectorvectorTextureCoordinate[textureCoordinateId].resize(vertexCount);
}
m_vectorFace.resize(faceCount);
}
/*****************************************************************************/
/** Destructs the core submesh instance.
*
* This function is the destructor of the core submesh instance.
*****************************************************************************/
void CalCoreSubmesh::setSubMorphTargetGroupIndexArray( unsigned int len, unsigned int const * indexArray )
{
m_vectorSubMorphTargetGroupIndex.reserve( len );
m_vectorSubMorphTargetGroupIndex.resize( len );
unsigned int i;
for( i = 0; i < len; i++ ) {
m_vectorSubMorphTargetGroupIndex[ i ] = indexArray[ i ];
}
}
template<typename T>
size_t vectorSize(const SSEArray<T>& v) {
return sizeof(T) * v.size();
}
template<typename T>
size_t vectorSize(const std::vector<T>& v) {
return sizeof(T) * v.size();
}
size_t CalCoreSubmesh::sizeWithoutSubMorphTargets()
{
unsigned int r = sizeof( CalCoreSubmesh );
r += vectorSize(m_vertices);
r += vectorSize(m_vertexColors);
r += vectorSize(m_vectorFace);
r += vectorSize(m_vectorSubMorphTargetGroupIndex);
r += vectorSize(m_lodData);
std::vector<std::vector<TextureCoordinate> >::iterator iter3;
for( iter3 = m_vectorvectorTextureCoordinate.begin(); iter3 != m_vectorvectorTextureCoordinate.end(); ++iter3 ) {
r += sizeof( TextureCoordinate ) * (*iter3).size();
}
return r;
}
size_t CalCoreSubmesh::size()
{
unsigned int r = sizeWithoutSubMorphTargets();
CoreSubMorphTargetVector::iterator iter1;
for( iter1 = m_vectorCoreSubMorphTarget.begin(); iter1 != m_vectorCoreSubMorphTarget.end(); ++iter1 ) {
r += (*iter1)->size();
}
return r;
}
/*****************************************************************************/
/** Returns the ID of the core material thread.
*
* This function returns the ID of the core material thread of this core
* submesh instance.
*
* @return The ID of the core material thread.
*****************************************************************************/
int CalCoreSubmesh::getCoreMaterialThreadId()
{
return m_coreMaterialThreadId;
}
/*****************************************************************************/
/** Returns the number of faces.
*
* This function returns the number of faces in the core submesh instance.
*
* @return The number of faces.
*****************************************************************************/
int CalCoreSubmesh::getFaceCount()
{
return m_vectorFace.size();
}
/*****************************************************************************/
/** Returns the number of LOD steps.
*
* This function returns the number of LOD steps in the core submesh instance.
*
* @return The number of LOD steps.
*****************************************************************************/
int CalCoreSubmesh::getLodCount()
{
return m_lodCount;
}
const std::vector<CalCoreSubmesh::Face>& CalCoreSubmesh::getVectorFace() const
{
return m_vectorFace;
}
std::vector<std::vector<CalCoreSubmesh::TextureCoordinate> > & CalCoreSubmesh::getVectorVectorTextureCoordinate()
{
return m_vectorvectorTextureCoordinate;
}
std::vector<CalColor32>& CalCoreSubmesh::getVertexColors()
{
return m_vertexColors;
}
int CalCoreSubmesh::getVertexCount()
{
return m_vertices.size();
}
/*****************************************************************************/
/** Sets the ID of the core material thread.
*
* This function sets the ID of the core material thread of the core submesh
* instance.
*
* @param coreMaterialThreadId The ID of the core material thread that should
* be set.
*****************************************************************************/
void CalCoreSubmesh::setCoreMaterialThreadId(int coreMaterialThreadId)
{
m_coreMaterialThreadId = coreMaterialThreadId;
}
/*****************************************************************************/
/** Sets a specified face.
*
* This function sets a specified face in the core submesh instance.
*
* @param faceId The ID of the face.
* @param face The face that should be set.
*
* @return One of the following values:
* \li \b true if successful
* \li \b false if an error happend
*****************************************************************************/
bool CalCoreSubmesh::setFace(int faceId, const Face& face)
{
if((faceId < 0) || (faceId >= (int)m_vectorFace.size())) return false;
m_vectorFace[faceId] = face;
return true;
}
/*****************************************************************************/
/** Sets the number of LOD steps.
*
* This function sets the number of LOD steps of the core submesh instance.
*
* @param lodCount The number of LOD steps that should be set.
*****************************************************************************/
void CalCoreSubmesh::setLodCount(int lodCount)
{
m_lodCount = lodCount;
}
/*****************************************************************************/
/** Sets a specified texture coordinate.
*
* This function sets a specified texture coordinate in the core submesh
* instance.
*
* @param vertexId The ID of the vertex.
* @param textureCoordinateId The ID of the texture coordinate.
* @param textureCoordinate The texture coordinate that should be set.
*
* @return One of the following values:
* \li \b true if successful
* \li \b false if an error happend
*****************************************************************************/
bool CalCoreSubmesh::setTextureCoordinate(int vertexId, int textureCoordinateId, const TextureCoordinate& textureCoordinate)
{
if((textureCoordinateId < 0) || (textureCoordinateId >= (int)m_vectorvectorTextureCoordinate.size())) return false;
if((vertexId < 0) || (vertexId >= (int)m_vectorvectorTextureCoordinate[textureCoordinateId].size())) return false;
m_vectorvectorTextureCoordinate[textureCoordinateId][vertexId] = textureCoordinate;
return true;
}
void CalCoreSubmesh::addVertex(const Vertex& vertex, CalColor32 vertexColor, const LodData& lodData, std::vector<Influence> inf) {
assert(m_currentVertexId < m_vertices.size());
const int vertexId = m_currentVertexId++;
if (vertexId == 0) {
m_isStatic = true;
m_staticInfluenceSet = inf;
} else if (m_isStatic) {
m_isStatic = m_staticInfluenceSet == inf;
}
m_vertices[vertexId] = vertex;
m_vertexColors[vertexId] = vertexColor;
m_lodData[vertexId] = lodData;
// Each vertex needs at least one influence.
if (inf.empty()) {
m_isStatic = false;
Influence i;
i.boneId = 0;
i.weight = 0.0f;
inf.push_back(i);
}
// Mark the last influence as the last one. :)
for (size_t i = 0; i + 1 < inf.size(); ++i) {
inf[i].lastInfluenceForThisVertex = 0;
}
inf[inf.size() - 1].lastInfluenceForThisVertex = 1;
m_influenceRanges[vertexId].influenceStart = influences.size();
m_influenceRanges[vertexId].influenceEnd = influences.size() + inf.size();
influences.insert(influences.end(), inf.begin(), inf.end());
}
/*****************************************************************************/
/** Adds a core sub morph target.
*
* This function adds a core sub morph target to the core sub mesh instance.
*
* @param pCoreSubMorphTarget A pointer to the core sub morph target that should be added.
*
* @return One of the following values:
* \li the assigned sub morph target \b ID of the added core sub morph target
* \li \b -1 if an error happend
*****************************************************************************/
int CalCoreSubmesh::addCoreSubMorphTarget(boost::shared_ptr<CalCoreSubMorphTarget> pCoreSubMorphTarget)
{
// get next sub morph target id
int subMorphTargetId;
subMorphTargetId = m_vectorCoreSubMorphTarget.size();
m_vectorCoreSubMorphTarget.push_back(pCoreSubMorphTarget);
return subMorphTargetId;
}
/*****************************************************************************/
/** Provides access to a core sub morph target.
*
* This function returns the core sub morph target with the given ID.
*
* @param id The ID of the core sub morph target that should be returned.
*
* @return One of the following values:
* \li a pointer to the core sub morph target
* \li \b 0 if an error happend
*****************************************************************************/
boost::shared_ptr<CalCoreSubMorphTarget> CalCoreSubmesh::getCoreSubMorphTarget(int id)
{
if((id < 0) || (id >= (int)m_vectorCoreSubMorphTarget.size()))
{
// should assert
return boost::shared_ptr<CalCoreSubMorphTarget>();
}
return m_vectorCoreSubMorphTarget[id];
}
/*****************************************************************************/
/** Returns the number of core sub morph targets.
*
* This function returns the number of core sub morph targets in the core sub mesh
* instance.
*
* @return The number of core sub morph targets.
*****************************************************************************/
int CalCoreSubmesh::getCoreSubMorphTargetCount()
{
return m_vectorCoreSubMorphTarget.size();
}
/*****************************************************************************/
/** Returns the core sub morph target vector.
*
* This function returns the vector that contains all core sub morph target
* of the core submesh instance.
*
* @return A reference to the core sub morph target vector.
*****************************************************************************/
CalCoreSubmesh::CoreSubMorphTargetVector& CalCoreSubmesh::getVectorCoreSubMorphTarget()
{
return m_vectorCoreSubMorphTarget;
}
/*****************************************************************************/
/** Scale the Submesh.
*
* This function rescale all the data that are in the core submesh instance.
*
* @param factor A float with the scale factor
*
*****************************************************************************/
void CalCoreSubmesh::scale(float factor)
{
for(int vertexId = 0; vertexId < m_vertices.size(); vertexId++) {
m_vertices[vertexId].position*=factor;
}
}
bool CalCoreSubmesh::isStatic() const {
return m_isStatic && m_vectorCoreSubMorphTarget.empty();
}
BoneTransform CalCoreSubmesh::getStaticTransform(const BoneTransform* bones) {
BoneTransform rm;
std::set<Influence>::const_iterator current = m_staticInfluenceSet.influences.begin();
while (current != m_staticInfluenceSet.influences.end()) {
const BoneTransform& influence = bones[current->boneId];
rm.rowx.x += current->weight * influence.rowx.x;
rm.rowx.y += current->weight * influence.rowx.y;
rm.rowx.z += current->weight * influence.rowx.z;
rm.rowx.w += current->weight * influence.rowx.w;
rm.rowy.x += current->weight * influence.rowy.x;
rm.rowy.y += current->weight * influence.rowy.y;
rm.rowy.z += current->weight * influence.rowy.z;
rm.rowy.w += current->weight * influence.rowy.w;
rm.rowz.x += current->weight * influence.rowz.x;
rm.rowz.y += current->weight * influence.rowz.y;
rm.rowz.z += current->weight * influence.rowz.z;
rm.rowz.w += current->weight * influence.rowz.w;
++current;
}
return rm;
}
<|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright 2015 Cloudius Systems
*
* Modified by Cloudius Systems
*/
#include "cql3/selection/selection.hh"
#include "cql3/selection/selector_factories.hh"
#include "cql3/result_set.hh"
namespace cql3 {
namespace selection {
selection::selection(schema_ptr schema,
std::vector<const column_definition*> columns,
std::vector<::shared_ptr<column_specification>> metadata_,
bool collect_timestamps,
bool collect_TTLs)
: _schema(std::move(schema))
, _columns(std::move(columns))
, _metadata(::make_shared<metadata>(std::move(metadata_)))
, _collect_timestamps(collect_timestamps)
, _collect_TTLs(collect_TTLs)
, _contains_static_columns(std::any_of(_columns.begin(), _columns.end(), std::mem_fn(&column_definition::is_static)))
{ }
query::partition_slice::option_set selection::get_query_options() {
query::partition_slice::option_set opts;
opts.set_if<query::partition_slice::option::send_timestamp_and_expiry>(_collect_timestamps || _collect_TTLs);
opts.set_if<query::partition_slice::option::send_partition_key>(
std::any_of(_columns.begin(), _columns.end(),
std::mem_fn(&column_definition::is_partition_key)));
opts.set_if<query::partition_slice::option::send_clustering_key>(
std::any_of(_columns.begin(), _columns.end(),
std::mem_fn(&column_definition::is_clustering_key)));
return opts;
}
// Special cased selection for when no function is used (this save some allocations).
class simple_selection : public selection {
private:
const bool _is_wildcard;
public:
static ::shared_ptr<simple_selection> make(schema_ptr schema, std::vector<const column_definition*> columns, bool is_wildcard) {
std::vector<::shared_ptr<column_specification>> metadata;
metadata.reserve(columns.size());
for (auto&& col : columns) {
metadata.emplace_back(col->column_specification);
}
return ::make_shared<simple_selection>(schema, std::move(columns), std::move(metadata), is_wildcard);
}
/*
* In theory, even a simple selection could have multiple time the same column, so we
* could filter those duplicate out of columns. But since we're very unlikely to
* get much duplicate in practice, it's more efficient not to bother.
*/
simple_selection(schema_ptr schema, std::vector<const column_definition*> columns,
std::vector<::shared_ptr<column_specification>> metadata, bool is_wildcard)
: selection(schema, std::move(columns), std::move(metadata), false, false)
, _is_wildcard(is_wildcard)
{ }
virtual bool is_wildcard() const override { return _is_wildcard; }
virtual bool is_aggregate() const override { return false; }
protected:
class simple_selectors : public selectors {
private:
std::vector<bytes_opt> _current;
public:
virtual void reset() override {
_current.clear();
}
virtual std::vector<bytes_opt> get_output_row(serialization_format sf) override {
return std::move(_current);
}
virtual void add_input_row(serialization_format sf, result_set_builder& rs) override {
_current = std::move(*rs.current);
}
virtual bool is_aggregate() {
return false;
}
};
std::unique_ptr<selectors> new_selectors() {
return std::make_unique<simple_selectors>();
}
};
class selection_with_processing : public selection {
private:
::shared_ptr<selector_factories> _factories;
public:
selection_with_processing(schema_ptr schema, std::vector<const column_definition*> columns,
std::vector<::shared_ptr<column_specification>> metadata, ::shared_ptr<selector_factories> factories)
: selection(schema, std::move(columns), std::move(metadata),
factories->contains_write_time_selector_factory(),
factories->contains_ttl_selector_factory())
, _factories(std::move(factories))
{
if (_factories->does_aggregation() && !_factories->contains_only_aggregate_functions()) {
throw exceptions::invalid_request_exception("the select clause must either contains only aggregates or none");
}
}
virtual bool uses_function(const sstring& ks_name, const sstring& function_name) const override {
return _factories->uses_function(ks_name, function_name);
}
virtual uint32_t add_column_for_ordering(const column_definition& c) override {
uint32_t index = selection::add_column_for_ordering(c);
_factories->add_selector_for_ordering(c, index);
return index;
}
virtual bool is_aggregate() const override {
return _factories->contains_only_aggregate_functions();
}
protected:
class selectors_with_processing : public selectors {
private:
::shared_ptr<selector_factories> _factories;
std::vector<::shared_ptr<selector>> _selectors;
public:
selectors_with_processing(::shared_ptr<selector_factories> factories)
: _factories(std::move(factories))
, _selectors(_factories->new_instances())
{ }
virtual void reset() override {
for (auto&& s : _selectors) {
s->reset();
}
}
virtual bool is_aggregate() override {
return _factories->contains_only_aggregate_functions();
}
virtual std::vector<bytes_opt> get_output_row(serialization_format sf) override {
std::vector<bytes_opt> output_row;
output_row.reserve(_selectors.size());
for (auto&& s : _selectors) {
output_row.emplace_back(s->get_output(sf));
}
return output_row;
}
virtual void add_input_row(serialization_format sf, result_set_builder& rs) {
for (auto&& s : _selectors) {
s->add_input(sf, rs);
}
}
};
std::unique_ptr<selectors> new_selectors() {
return std::make_unique<selectors_with_processing>(_factories);
}
};
::shared_ptr<selection> selection::wildcard(schema_ptr schema) {
return simple_selection::make(schema, column_definition::vectorize(schema->all_columns_in_select_order()), true);
}
::shared_ptr<selection> selection::for_columns(schema_ptr schema, std::vector<const column_definition*> columns) {
return simple_selection::make(schema, std::move(columns), false);
}
uint32_t selection::add_column_for_ordering(const column_definition& c) {
_columns.push_back(&c);
_metadata->add_non_serialized_column(c.column_specification);
return _columns.size() - 1;
}
::shared_ptr<selection> selection::from_selectors(database& db, schema_ptr schema, const std::vector<::shared_ptr<raw_selector>>& raw_selectors) {
std::vector<const column_definition*> defs;
::shared_ptr<selector_factories> factories =
selector_factories::create_factories_and_collect_column_definitions(
raw_selector::to_selectables(raw_selectors, schema), db, schema, defs);
auto metadata = collect_metadata(schema, raw_selectors, *factories);
if (processes_selection(raw_selectors)) {
return ::make_shared<selection_with_processing>(schema, std::move(defs), std::move(metadata), std::move(factories));
} else {
return ::make_shared<simple_selection>(schema, std::move(defs), std::move(metadata), false);
}
}
std::vector<::shared_ptr<column_specification>>
selection::collect_metadata(schema_ptr schema, const std::vector<::shared_ptr<raw_selector>>& raw_selectors,
const selector_factories& factories) {
std::vector<::shared_ptr<column_specification>> r;
r.reserve(raw_selectors.size());
auto i = raw_selectors.begin();
for (auto&& factory : factories) {
::shared_ptr<column_specification> col_spec = factory->get_column_specification(schema);
::shared_ptr<column_identifier> alias = (*i++)->alias;
r.push_back(alias ? col_spec->with_alias(alias) : col_spec);
}
return r;
}
result_set_builder::result_set_builder(selection& s, db_clock::time_point now, serialization_format sf)
: _result_set(std::make_unique<result_set>(::make_shared<metadata>(*(s.get_result_metadata()))))
, _selectors(s.new_selectors())
, _now(now)
, _serialization_format(sf)
{
if (s._collect_timestamps) {
_timestamps.resize(s._columns.size(), 0);
}
if (s._collect_TTLs) {
_ttls.resize(s._columns.size(), 0);
}
}
void result_set_builder::add_empty() {
current->emplace_back();
if (!_timestamps.empty()) {
_timestamps[current->size() - 1] = api::min_timestamp;
}
if (!_ttls.empty()) {
_ttls[current->size() - 1] = -1;
}
}
void result_set_builder::add(bytes_opt value) {
current->emplace_back(std::move(value));
}
void result_set_builder::add(const column_definition& def, const query::result_atomic_cell_view& c) {
current->emplace_back(get_value(def.type, c));
if (!_timestamps.empty()) {
_timestamps[current->size() - 1] = c.timestamp();
}
if (!_ttls.empty()) {
gc_clock::duration ttl_left(-1);
expiry_opt e = c.expiry();
if (e) {
ttl_left = *e - to_gc_clock(_now);
}
_ttls[current->size() - 1] = ttl_left.count();
}
}
void result_set_builder::add(const column_definition& def, collection_mutation::view c) {
auto&& ctype = static_cast<const collection_type_impl*>(def.type.get());
current->emplace_back(ctype->to_value(c, _serialization_format));
// timestamps, ttls meaningless for collections
}
void result_set_builder::new_row() {
if (current) {
_selectors->add_input_row(_serialization_format, *this);
if (!_selectors->is_aggregate()) {
_result_set->add_row(_selectors->get_output_row(_serialization_format));
_selectors->reset();
}
current->clear();
} else {
// FIXME: we use optional<> here because we don't have an end_row() signal
// instead, !current means that new_row has never been called, so this
// call to new_row() does not end a previous row.
current.emplace();
}
}
std::unique_ptr<result_set> result_set_builder::build() {
if (current) {
_selectors->add_input_row(_serialization_format, *this);
_result_set->add_row(_selectors->get_output_row(_serialization_format));
_selectors->reset();
current = std::experimental::nullopt;
}
if (_result_set->empty() && _selectors->is_aggregate()) {
_result_set->add_row(_selectors->get_output_row(_serialization_format));
}
return std::move(_result_set);
}
api::timestamp_type result_set_builder::timestamp_of(size_t idx) {
return _timestamps[idx];
}
int32_t result_set_builder::ttl_of(size_t idx) {
return _ttls[idx];
}
bytes_opt result_set_builder::get_value(data_type t, query::result_atomic_cell_view c) {
if (t->is_counter()) {
fail(unimplemented::cause::COUNTERS);
#if 0
ByteBufferUtil.bytes(CounterContext.instance().total(c.value()))
#endif
}
return {to_bytes(c.value())};
}
}
}<commit_msg>cql3: use api::missing_timestamp for missing timestamps<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright 2015 Cloudius Systems
*
* Modified by Cloudius Systems
*/
#include "cql3/selection/selection.hh"
#include "cql3/selection/selector_factories.hh"
#include "cql3/result_set.hh"
namespace cql3 {
namespace selection {
selection::selection(schema_ptr schema,
std::vector<const column_definition*> columns,
std::vector<::shared_ptr<column_specification>> metadata_,
bool collect_timestamps,
bool collect_TTLs)
: _schema(std::move(schema))
, _columns(std::move(columns))
, _metadata(::make_shared<metadata>(std::move(metadata_)))
, _collect_timestamps(collect_timestamps)
, _collect_TTLs(collect_TTLs)
, _contains_static_columns(std::any_of(_columns.begin(), _columns.end(), std::mem_fn(&column_definition::is_static)))
{ }
query::partition_slice::option_set selection::get_query_options() {
query::partition_slice::option_set opts;
opts.set_if<query::partition_slice::option::send_timestamp_and_expiry>(_collect_timestamps || _collect_TTLs);
opts.set_if<query::partition_slice::option::send_partition_key>(
std::any_of(_columns.begin(), _columns.end(),
std::mem_fn(&column_definition::is_partition_key)));
opts.set_if<query::partition_slice::option::send_clustering_key>(
std::any_of(_columns.begin(), _columns.end(),
std::mem_fn(&column_definition::is_clustering_key)));
return opts;
}
// Special cased selection for when no function is used (this save some allocations).
class simple_selection : public selection {
private:
const bool _is_wildcard;
public:
static ::shared_ptr<simple_selection> make(schema_ptr schema, std::vector<const column_definition*> columns, bool is_wildcard) {
std::vector<::shared_ptr<column_specification>> metadata;
metadata.reserve(columns.size());
for (auto&& col : columns) {
metadata.emplace_back(col->column_specification);
}
return ::make_shared<simple_selection>(schema, std::move(columns), std::move(metadata), is_wildcard);
}
/*
* In theory, even a simple selection could have multiple time the same column, so we
* could filter those duplicate out of columns. But since we're very unlikely to
* get much duplicate in practice, it's more efficient not to bother.
*/
simple_selection(schema_ptr schema, std::vector<const column_definition*> columns,
std::vector<::shared_ptr<column_specification>> metadata, bool is_wildcard)
: selection(schema, std::move(columns), std::move(metadata), false, false)
, _is_wildcard(is_wildcard)
{ }
virtual bool is_wildcard() const override { return _is_wildcard; }
virtual bool is_aggregate() const override { return false; }
protected:
class simple_selectors : public selectors {
private:
std::vector<bytes_opt> _current;
public:
virtual void reset() override {
_current.clear();
}
virtual std::vector<bytes_opt> get_output_row(serialization_format sf) override {
return std::move(_current);
}
virtual void add_input_row(serialization_format sf, result_set_builder& rs) override {
_current = std::move(*rs.current);
}
virtual bool is_aggregate() {
return false;
}
};
std::unique_ptr<selectors> new_selectors() {
return std::make_unique<simple_selectors>();
}
};
class selection_with_processing : public selection {
private:
::shared_ptr<selector_factories> _factories;
public:
selection_with_processing(schema_ptr schema, std::vector<const column_definition*> columns,
std::vector<::shared_ptr<column_specification>> metadata, ::shared_ptr<selector_factories> factories)
: selection(schema, std::move(columns), std::move(metadata),
factories->contains_write_time_selector_factory(),
factories->contains_ttl_selector_factory())
, _factories(std::move(factories))
{
if (_factories->does_aggregation() && !_factories->contains_only_aggregate_functions()) {
throw exceptions::invalid_request_exception("the select clause must either contains only aggregates or none");
}
}
virtual bool uses_function(const sstring& ks_name, const sstring& function_name) const override {
return _factories->uses_function(ks_name, function_name);
}
virtual uint32_t add_column_for_ordering(const column_definition& c) override {
uint32_t index = selection::add_column_for_ordering(c);
_factories->add_selector_for_ordering(c, index);
return index;
}
virtual bool is_aggregate() const override {
return _factories->contains_only_aggregate_functions();
}
protected:
class selectors_with_processing : public selectors {
private:
::shared_ptr<selector_factories> _factories;
std::vector<::shared_ptr<selector>> _selectors;
public:
selectors_with_processing(::shared_ptr<selector_factories> factories)
: _factories(std::move(factories))
, _selectors(_factories->new_instances())
{ }
virtual void reset() override {
for (auto&& s : _selectors) {
s->reset();
}
}
virtual bool is_aggregate() override {
return _factories->contains_only_aggregate_functions();
}
virtual std::vector<bytes_opt> get_output_row(serialization_format sf) override {
std::vector<bytes_opt> output_row;
output_row.reserve(_selectors.size());
for (auto&& s : _selectors) {
output_row.emplace_back(s->get_output(sf));
}
return output_row;
}
virtual void add_input_row(serialization_format sf, result_set_builder& rs) {
for (auto&& s : _selectors) {
s->add_input(sf, rs);
}
}
};
std::unique_ptr<selectors> new_selectors() {
return std::make_unique<selectors_with_processing>(_factories);
}
};
::shared_ptr<selection> selection::wildcard(schema_ptr schema) {
return simple_selection::make(schema, column_definition::vectorize(schema->all_columns_in_select_order()), true);
}
::shared_ptr<selection> selection::for_columns(schema_ptr schema, std::vector<const column_definition*> columns) {
return simple_selection::make(schema, std::move(columns), false);
}
uint32_t selection::add_column_for_ordering(const column_definition& c) {
_columns.push_back(&c);
_metadata->add_non_serialized_column(c.column_specification);
return _columns.size() - 1;
}
::shared_ptr<selection> selection::from_selectors(database& db, schema_ptr schema, const std::vector<::shared_ptr<raw_selector>>& raw_selectors) {
std::vector<const column_definition*> defs;
::shared_ptr<selector_factories> factories =
selector_factories::create_factories_and_collect_column_definitions(
raw_selector::to_selectables(raw_selectors, schema), db, schema, defs);
auto metadata = collect_metadata(schema, raw_selectors, *factories);
if (processes_selection(raw_selectors)) {
return ::make_shared<selection_with_processing>(schema, std::move(defs), std::move(metadata), std::move(factories));
} else {
return ::make_shared<simple_selection>(schema, std::move(defs), std::move(metadata), false);
}
}
std::vector<::shared_ptr<column_specification>>
selection::collect_metadata(schema_ptr schema, const std::vector<::shared_ptr<raw_selector>>& raw_selectors,
const selector_factories& factories) {
std::vector<::shared_ptr<column_specification>> r;
r.reserve(raw_selectors.size());
auto i = raw_selectors.begin();
for (auto&& factory : factories) {
::shared_ptr<column_specification> col_spec = factory->get_column_specification(schema);
::shared_ptr<column_identifier> alias = (*i++)->alias;
r.push_back(alias ? col_spec->with_alias(alias) : col_spec);
}
return r;
}
result_set_builder::result_set_builder(selection& s, db_clock::time_point now, serialization_format sf)
: _result_set(std::make_unique<result_set>(::make_shared<metadata>(*(s.get_result_metadata()))))
, _selectors(s.new_selectors())
, _now(now)
, _serialization_format(sf)
{
if (s._collect_timestamps) {
_timestamps.resize(s._columns.size(), 0);
}
if (s._collect_TTLs) {
_ttls.resize(s._columns.size(), 0);
}
}
void result_set_builder::add_empty() {
current->emplace_back();
if (!_timestamps.empty()) {
_timestamps[current->size() - 1] = api::missing_timestamp;
}
if (!_ttls.empty()) {
_ttls[current->size() - 1] = -1;
}
}
void result_set_builder::add(bytes_opt value) {
current->emplace_back(std::move(value));
}
void result_set_builder::add(const column_definition& def, const query::result_atomic_cell_view& c) {
current->emplace_back(get_value(def.type, c));
if (!_timestamps.empty()) {
_timestamps[current->size() - 1] = c.timestamp();
}
if (!_ttls.empty()) {
gc_clock::duration ttl_left(-1);
expiry_opt e = c.expiry();
if (e) {
ttl_left = *e - to_gc_clock(_now);
}
_ttls[current->size() - 1] = ttl_left.count();
}
}
void result_set_builder::add(const column_definition& def, collection_mutation::view c) {
auto&& ctype = static_cast<const collection_type_impl*>(def.type.get());
current->emplace_back(ctype->to_value(c, _serialization_format));
// timestamps, ttls meaningless for collections
}
void result_set_builder::new_row() {
if (current) {
_selectors->add_input_row(_serialization_format, *this);
if (!_selectors->is_aggregate()) {
_result_set->add_row(_selectors->get_output_row(_serialization_format));
_selectors->reset();
}
current->clear();
} else {
// FIXME: we use optional<> here because we don't have an end_row() signal
// instead, !current means that new_row has never been called, so this
// call to new_row() does not end a previous row.
current.emplace();
}
}
std::unique_ptr<result_set> result_set_builder::build() {
if (current) {
_selectors->add_input_row(_serialization_format, *this);
_result_set->add_row(_selectors->get_output_row(_serialization_format));
_selectors->reset();
current = std::experimental::nullopt;
}
if (_result_set->empty() && _selectors->is_aggregate()) {
_result_set->add_row(_selectors->get_output_row(_serialization_format));
}
return std::move(_result_set);
}
api::timestamp_type result_set_builder::timestamp_of(size_t idx) {
return _timestamps[idx];
}
int32_t result_set_builder::ttl_of(size_t idx) {
return _ttls[idx];
}
bytes_opt result_set_builder::get_value(data_type t, query::result_atomic_cell_view c) {
if (t->is_counter()) {
fail(unimplemented::cause::COUNTERS);
#if 0
ByteBufferUtil.bytes(CounterContext.instance().total(c.value()))
#endif
}
return {to_bytes(c.value())};
}
}
}<|endoftext|> |
<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <boost/filesystem.hpp>
#include "SurgSim/Collision/ShapeCollisionRepresentation.h"
#include "SurgSim/Framework/ApplicationData.h"
#include "SurgSim/Framework/ObjectFactory.h"
#include "SurgSim/Framework/Runtime.h"
#include "SurgSim/Math/MathConvert.h"
#include "SurgSim/Math/MeshShape.h"
#include "SurgSim/Physics/Representation.h"
namespace
{
SURGSIM_REGISTER(SurgSim::Framework::Component, SurgSim::Collision::ShapeCollisionRepresentation);
}
namespace SurgSim
{
namespace Collision
{
ShapeCollisionRepresentation::ShapeCollisionRepresentation(const std::string& name) :
Representation(name)
{
SURGSIM_ADD_SERIALIZABLE_PROPERTY(ShapeCollisionRepresentation, std::shared_ptr<SurgSim::Math::Shape>, Shape,
getShape, setShape);
}
ShapeCollisionRepresentation::~ShapeCollisionRepresentation()
{
}
int ShapeCollisionRepresentation::getShapeType() const
{
return m_shape->getType();
}
void ShapeCollisionRepresentation::setLocalPose(const SurgSim::Math::RigidTransform3d& pose)
{
Representation::setLocalPose(pose);
update(0.0);
}
void ShapeCollisionRepresentation::setShape(const std::shared_ptr<SurgSim::Math::Shape>& shape)
{
SURGSIM_ASSERT(nullptr != shape) << "Can not set a empty shape.";
m_shape = shape;
update(0.0);
}
const std::shared_ptr<SurgSim::Math::Shape> ShapeCollisionRepresentation::getShape() const
{
return m_shape;
}
void ShapeCollisionRepresentation::update(const double& dt)
{
auto meshShape = std::dynamic_pointer_cast<SurgSim::Math::MeshShape>(m_shape);
if (nullptr != meshShape && meshShape->isValid())
{
meshShape->setPose(getPose());
}
}
bool ShapeCollisionRepresentation::doInitialize()
{
auto meshShape = std::dynamic_pointer_cast<SurgSim::Math::MeshShape>(m_shape);
if (nullptr != meshShape)
{
auto data = std::make_shared<SurgSim::Framework::ApplicationData>(*(getRuntime()->getApplicationData()));
SURGSIM_ASSERT(meshShape->initialize(data)) << "DeformableCollisionRepresentation::doInitialize(): "
"m_shape initialization failed.";
update(0.0);
}
return true;
}
}; // namespace Collision
}; // namespace SurgSim
<commit_msg>Remove 'update()' call in ShapeCollisionRepresentation::doInitialize()<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <boost/filesystem.hpp>
#include "SurgSim/Collision/ShapeCollisionRepresentation.h"
#include "SurgSim/Framework/ApplicationData.h"
#include "SurgSim/Framework/ObjectFactory.h"
#include "SurgSim/Framework/Runtime.h"
#include "SurgSim/Math/MathConvert.h"
#include "SurgSim/Math/MeshShape.h"
#include "SurgSim/Physics/Representation.h"
namespace
{
SURGSIM_REGISTER(SurgSim::Framework::Component, SurgSim::Collision::ShapeCollisionRepresentation);
}
namespace SurgSim
{
namespace Collision
{
ShapeCollisionRepresentation::ShapeCollisionRepresentation(const std::string& name) :
Representation(name)
{
SURGSIM_ADD_SERIALIZABLE_PROPERTY(ShapeCollisionRepresentation, std::shared_ptr<SurgSim::Math::Shape>, Shape,
getShape, setShape);
}
ShapeCollisionRepresentation::~ShapeCollisionRepresentation()
{
}
int ShapeCollisionRepresentation::getShapeType() const
{
return m_shape->getType();
}
void ShapeCollisionRepresentation::setLocalPose(const SurgSim::Math::RigidTransform3d& pose)
{
Representation::setLocalPose(pose);
update(0.0);
}
void ShapeCollisionRepresentation::setShape(const std::shared_ptr<SurgSim::Math::Shape>& shape)
{
SURGSIM_ASSERT(nullptr != shape) << "Can not set a empty shape.";
m_shape = shape;
update(0.0);
}
const std::shared_ptr<SurgSim::Math::Shape> ShapeCollisionRepresentation::getShape() const
{
return m_shape;
}
void ShapeCollisionRepresentation::update(const double& dt)
{
auto meshShape = std::dynamic_pointer_cast<SurgSim::Math::MeshShape>(m_shape);
if (nullptr != meshShape && meshShape->isValid())
{
meshShape->setPose(getPose());
}
}
bool ShapeCollisionRepresentation::doInitialize()
{
auto meshShape = std::dynamic_pointer_cast<SurgSim::Math::MeshShape>(m_shape);
if (nullptr != meshShape)
{
auto data = std::make_shared<SurgSim::Framework::ApplicationData>(*(getRuntime()->getApplicationData()));
SURGSIM_ASSERT(meshShape->initialize(data)) << "DeformableCollisionRepresentation::doInitialize(): "
"m_shape initialization failed.";
}
return true;
}
}; // namespace Collision
}; // namespace SurgSim
<|endoftext|> |
<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2016, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "SurgSim/Physics/FemConstraintFrictionalSliding.h"
#include "SurgSim/Math/Vector.h"
#include "SurgSim/Physics/SlidingConstraintData.h"
#include "SurgSim/Physics/FemElement.h"
#include "SurgSim/Physics/FemLocalization.h"
#include "SurgSim/Physics/FemRepresentation.h"
using SurgSim::Math::Vector3d;
namespace SurgSim
{
namespace Physics
{
FemConstraintFrictionalSliding::FemConstraintFrictionalSliding()
{
}
FemConstraintFrictionalSliding::~FemConstraintFrictionalSliding()
{
}
void FemConstraintFrictionalSliding::doBuild(double dt,
const ConstraintData& data,
const std::shared_ptr<Localization>& localization,
MlcpPhysicsProblem* mlcp,
size_t indexOfRepresentation,
size_t indexOfConstraint,
ConstraintSideSign sign)
{
auto fem = std::static_pointer_cast<FemRepresentation>(localization->getRepresentation());
if (!fem->isActive())
{
return;
}
const size_t numDofPerNode = fem->getNumDofPerNode();
const double scale = (sign == CONSTRAINT_POSITIVE_SIDE) ? 1.0 : -1.0;
const SlidingConstraintData& constraintData = static_cast<const SlidingConstraintData&>(data);
std::array<Math::Vector3d, 3> directions;
directions[0] = constraintData.getNormals()[0];
directions[1] = constraintData.getNormals()[1];
directions[2] = constraintData.getTangent();
const DataStructures::IndexedLocalCoordinate& coord
= std::static_pointer_cast<FemLocalization>(localization)->getLocalPosition();
Vector3d globalPosition = localization->calculatePosition();
m_newH.resize(fem->getNumDof());
auto femElement = fem->getFemElement(coord.index);
auto numNodes = fem->getFemElement(coord.index)->getNumNodes();
m_newH.reserve(numNodes * 3);
for (size_t i = 0; i < 3; ++i)
{
// Update b with new violation
double violation = directions[i].dot(globalPosition);
mlcp->b[indexOfConstraint + i] += violation * scale;
// Fill the new H.
m_newH.setZero();
for (size_t j = 0; j < numNodes; ++j)
{
auto nodeId = femElement->getNodeId(j);
m_newH.insert(numDofPerNode * nodeId + 0) = coord.coordinate[j] * directions[i][0] * scale * dt;
m_newH.insert(numDofPerNode * nodeId + 1) = coord.coordinate[j] * directions[i][1] * scale * dt;
m_newH.insert(numDofPerNode * nodeId + 2) = coord.coordinate[j] * directions[i][2] * scale * dt;
}
mlcp->updateConstraint(m_newH, fem->getComplianceMatrix() * m_newH.transpose(), indexOfRepresentation,
indexOfConstraint + i);
}
mlcp->mu[indexOfConstraint] = 0.5; // Friction coefficient for this frictional sliding constraint
}
SurgSim::Physics::ConstraintType FemConstraintFrictionalSliding::getConstraintType() const
{
return SurgSim::Physics::FRICTIONAL_SLIDING;
}
size_t FemConstraintFrictionalSliding::doGetNumDof() const
{
return 3;
}
}; // namespace Physics
}; // namespace SurgSim
<commit_msg>Use friction coefficient from SlidingConstraintData<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2016, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "SurgSim/Physics/FemConstraintFrictionalSliding.h"
#include "SurgSim/Math/Vector.h"
#include "SurgSim/Physics/SlidingConstraintData.h"
#include "SurgSim/Physics/FemElement.h"
#include "SurgSim/Physics/FemLocalization.h"
#include "SurgSim/Physics/FemRepresentation.h"
using SurgSim::Math::Vector3d;
namespace SurgSim
{
namespace Physics
{
FemConstraintFrictionalSliding::FemConstraintFrictionalSliding()
{
}
FemConstraintFrictionalSliding::~FemConstraintFrictionalSliding()
{
}
void FemConstraintFrictionalSliding::doBuild(double dt,
const ConstraintData& data,
const std::shared_ptr<Localization>& localization,
MlcpPhysicsProblem* mlcp,
size_t indexOfRepresentation,
size_t indexOfConstraint,
ConstraintSideSign sign)
{
auto fem = std::static_pointer_cast<FemRepresentation>(localization->getRepresentation());
if (!fem->isActive())
{
return;
}
const size_t numDofPerNode = fem->getNumDofPerNode();
const double scale = (sign == CONSTRAINT_POSITIVE_SIDE) ? 1.0 : -1.0;
const SlidingConstraintData& constraintData = static_cast<const SlidingConstraintData&>(data);
std::array<Math::Vector3d, 3> directions;
directions[0] = constraintData.getNormals()[0];
directions[1] = constraintData.getNormals()[1];
directions[2] = constraintData.getTangent();
const DataStructures::IndexedLocalCoordinate& coord
= std::static_pointer_cast<FemLocalization>(localization)->getLocalPosition();
Vector3d globalPosition = localization->calculatePosition();
m_newH.resize(fem->getNumDof());
auto femElement = fem->getFemElement(coord.index);
auto numNodes = fem->getFemElement(coord.index)->getNumNodes();
m_newH.reserve(numNodes * 3);
for (size_t i = 0; i < 3; ++i)
{
// Update b with new violation
double violation = directions[i].dot(globalPosition);
mlcp->b[indexOfConstraint + i] += violation * scale;
// Fill the new H.
m_newH.setZero();
for (size_t j = 0; j < numNodes; ++j)
{
auto nodeId = femElement->getNodeId(j);
m_newH.insert(numDofPerNode * nodeId + 0) = coord.coordinate[j] * directions[i][0] * scale * dt;
m_newH.insert(numDofPerNode * nodeId + 1) = coord.coordinate[j] * directions[i][1] * scale * dt;
m_newH.insert(numDofPerNode * nodeId + 2) = coord.coordinate[j] * directions[i][2] * scale * dt;
}
mlcp->updateConstraint(m_newH, fem->getComplianceMatrix() * m_newH.transpose(), indexOfRepresentation,
indexOfConstraint + i);
}
mlcp->mu[indexOfConstraint] = constraintData.getFrictionCoefficient();
}
SurgSim::Physics::ConstraintType FemConstraintFrictionalSliding::getConstraintType() const
{
return SurgSim::Physics::FRICTIONAL_SLIDING;
}
size_t FemConstraintFrictionalSliding::doGetNumDof() const
{
return 3;
}
}; // namespace Physics
}; // namespace SurgSim
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fourboxwipe.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-07 20:53:55 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#if ! defined INCLUDED_SLIDESHOW_FOURBOXWIPE_HXX
#define INCLUDED_SLIDESHOW_FOURBOXWIPE_HXX
#include "parametricpolypolygon.hxx"
#include "transitiontools.hxx"
#include "basegfx/polygon/b2dpolygon.hxx"
namespace presentation {
namespace internal {
/// Generate a 4-box wipe
class FourBoxWipe : public ParametricPolyPolygon
{
public:
FourBoxWipe( bool cornersOut ) : m_cornersOut(cornersOut),
m_unitRect( createUnitRect() )
{}
virtual ::basegfx::B2DPolyPolygon operator () ( double t );
private:
const bool m_cornersOut;
const ::basegfx::B2DPolygon m_unitRect;
};
}
}
#endif /* INCLUDED_SLIDESHOW_FOURBOXWIPE_HXX */
<commit_msg>INTEGRATION: CWS presfixes09 (1.3.18); FILE MERGED 2006/03/24 18:23:24 thb 1.3.18.1: #i37778# Moved whole slideshow engine from namespace presentation (which conflicts with one of the UNO subnamespaces) to slideshow<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fourboxwipe.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: kz $ $Date: 2006-12-13 15:42:20 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#if ! defined INCLUDED_SLIDESHOW_FOURBOXWIPE_HXX
#define INCLUDED_SLIDESHOW_FOURBOXWIPE_HXX
#include "parametricpolypolygon.hxx"
#include "transitiontools.hxx"
#include "basegfx/polygon/b2dpolygon.hxx"
namespace slideshow {
namespace internal {
/// Generate a 4-box wipe
class FourBoxWipe : public ParametricPolyPolygon
{
public:
FourBoxWipe( bool cornersOut ) : m_cornersOut(cornersOut),
m_unitRect( createUnitRect() )
{}
virtual ::basegfx::B2DPolyPolygon operator () ( double t );
private:
const bool m_cornersOut;
const ::basegfx::B2DPolygon m_unitRect;
};
}
}
#endif /* INCLUDED_SLIDESHOW_FOURBOXWIPE_HXX */
<|endoftext|> |
<commit_before>#include "arbitrary_precision_integer.h"
#include <iostream>
#include <cassert>
#include <cstdlib>
using namespace std;
int main() {
srand(213123213);
/*
int a = 24024, b = 240;
ArbitraryPrecisionInteger BigA(a), BigB(b);
ArbitraryPrecisionInteger BigAns = BigA / BigB;
int ans = a / b;
assert(BigAns == ArbitraryPrecisionInteger(ans));
cout << "Assert " << a << '-' << b << " success" << endl;
*/
while (true) {
int a, b;
int ans;
a = rand();
b = rand();
ArbitraryPrecisionInteger BigA(a), BigB(b);
ans = a + b;
ArbitraryPrecisionInteger BigAns = BigA + BigB;
assert(BigAns == ArbitraryPrecisionInteger(ans));
cout << "Assert " << a << '+' << b << " success" << endl;
ans = a - b;
BigAns = BigA - BigB;
assert(BigAns == ArbitraryPrecisionInteger(ans));
cout << "Assert " << a << '-' << b << " success" << endl;
ans = a * b;
BigAns = BigA * BigB;
assert(BigAns == ArbitraryPrecisionInteger(ans));
cout << "Assert " << a << '*' << b << " success" << endl;
if (b == 0) continue;
ans = a / b;
BigAns = BigA / BigB;
assert(BigAns == ArbitraryPrecisionInteger(ans));
cout << "Assert " << a << '/' << b << " success" << endl;
ans = a % b;
BigAns = BigA % BigB;
assert(BigAns == ArbitraryPrecisionInteger(ans));
cout << "Assert " << a << '%' << b << " success" << endl;
}
system("pause");
return 0;
}<commit_msg>删除一段注释<commit_after>#include "arbitrary_precision_integer.h"
#include <iostream>
#include <cassert>
#include <cstdlib>
using namespace std;
int main() {
srand(213123213);
while (true) {
int a, b;
int ans;
a = rand();
b = rand();
ArbitraryPrecisionInteger BigA(a), BigB(b);
ans = a + b;
ArbitraryPrecisionInteger BigAns = BigA + BigB;
assert(BigAns == ArbitraryPrecisionInteger(ans));
cout << "Assert " << a << '+' << b << " success" << endl;
ans = a - b;
BigAns = BigA - BigB;
assert(BigAns == ArbitraryPrecisionInteger(ans));
cout << "Assert " << a << '-' << b << " success" << endl;
ans = a * b;
BigAns = BigA * BigB;
assert(BigAns == ArbitraryPrecisionInteger(ans));
cout << "Assert " << a << '*' << b << " success" << endl;
if (b == 0) continue;
ans = a / b;
BigAns = BigA / BigB;
assert(BigAns == ArbitraryPrecisionInteger(ans));
cout << "Assert " << a << '/' << b << " success" << endl;
ans = a % b;
BigAns = BigA % BigB;
assert(BigAns == ArbitraryPrecisionInteger(ans));
cout << "Assert " << a << '%' << b << " success" << endl;
}
system("pause");
return 0;
}<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: ImageRegionIterator.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// Software Guide : BeginLatex
//
// \index{Iterators!speed}
// The \code{itk::ImageRegionIterator} has been optimized for iteration speed.
// It is the first choice for iterative, pixel-wise operations where location
// in the image is not important and no special iteration path through the
// image is required. \code{itk::ImageRegionIterator} is the most commonly
// used and least specialized of the ITK image iterator classes. It implements
// all of the methods described in the preceding section.
//
// The following example illustrates the use of
// \code{itk::ImageRegionConstIterator} and \code{itk::ImageRegionIterator}.
// Most of the code constructs introduced apply to other ITK iterators as
// well. This simple application crops a subregion from an image by copying
// pixel values into to a second image.
//
// \index{Iterators!and image regions}
// \index{itk::ImageRegionIterator!example of using|(}
// We begin by including the appropriate header files.
// Software Guide : EndLatex
#include "itkImage.h"
// Software Guide : BeginCodeSnippet
#include "itkImageRegionConstIterator.h"
#include "itkImageRegionIterator.h"
// Software Guide : EndCodeSnippet
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
int main( int argc, char ** argv )
{
// Verify the number of parameters on the command line.
if ( argc < 7 )
{
std::cerr << "Missing parameters. " << std::endl;
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0]
<< " inputImageFile outputImageFile startX startY sizeX sizeY"
<< std::endl;
return -1;
}
// Software Guide : BeginLatex
//
// Next we define a pixel type and corresponding image type. ITK iterator classes
// expect the image type as their template parameter.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
const unsigned int Dimension = 2;
typedef unsigned short PixelType;
typedef itk::Image< PixelType, Dimension > ImageType;
typedef itk::ImageRegionConstIterator< ImageType > ConstIteratorType;
typedef itk::ImageRegionIterator< ImageType> IteratorType;
// Software Guide : EndCodeSnippet
typedef itk::ImageFileReader< ImageType > ReaderType;
typedef itk::ImageFileWriter< ImageType > WriterType;
// Software Guide : BeginLatex
//
// Information about the subregion to copy is read from the command line. The
// subregion is defined by an \code{itk::ImageRegion} object, with a starting
// grid index and a size (section~\ref{sec:ImageSection}).
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
ImageType::RegionType region;
ImageType::RegionType::IndexType index;
ImageType::RegionType::SizeType size;
index[0] = ::atoi( argv[3] );
index[1] = ::atoi( argv[4] );
size[0] = ::atoi( argv[5] );
size[1] = ::atoi( argv[6] );
region.SetSize(size);
region.SetIndex(index);
// Software Guide : EndCodeSnippet
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[1] );
try
{
reader->Update();
}
catch ( itk::ExceptionObject &err)
{
std::cout << "ExceptionObject caught !" << std::endl;
std::cout << err << std::endl;
return -1;
}
// Check that the region is contained within the input image.
if ( ! reader->GetOutput()->GetRequestedRegion().IsInside( region ) )
{
std::cerr << "Error" << std::endl;
std::cerr << "The region " << region << "is not contained within the input image region "
<< reader->GetOutput()->GetRequestedRegion() << std::endl;
return -1;
}
// Software Guide : BeginLatex
//
// After reading the input image and checking that the desired subregion is,
// in fact, contained in the input, we allocate an output image. Allocating
// this image with the same region object we just created guarantees that the output image has
// the same starting index and size as the extracted subregion. Preserving
// the starting index may be an important detail later if the cropped image
// requires registering against the original image. The origin and spacing
// information is passed to the new image by \code{CopyInformation}.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
ImageType::Pointer outputImage = ImageType::New();
outputImage->SetRegions( region );
outputImage->CopyInformation( reader->GetOutput() );
outputImage->Allocate();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// \index{Iterators!construction of}
// \index{Iterators!and image regions}
// The necessary images and region definitions are now in place. All that is
// left is to create the iterators and perform the copy. Note that image
// iterators are not smart pointers so their constructors are called directly.
// Also notice how the input and output iterators are defined over the
// \emph{same region}. Though the images are different sizes, they both
// contain the same target subregion.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
ConstIteratorType inputIt( reader->GetOutput(), region );
IteratorType outputIt( outputImage, region );
for ( inputIt.GoToBegin(), outputIt.GoToBegin(); !inputIt.IsAtEnd();
++inputIt, ++outputIt)
{
outputIt.Set(inputIt.Get());
}
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// \index{Iterators!image dimensionality}
// The \code{for} loop above is a common construct in ITK. The beauty of these
// four lines of code is that they are equally valid for one, two, three, or
// even ten dimensional data. Consider the ugly alternative of ten nested
// \code{for} loops for traversing an image, which would also require explicit
// knowledge of the size of each image dimension.
//
// Software Guide : EndLatex
WriterType::Pointer writer = WriterType::New();
writer->SetFileName( argv[2] );
writer->SetInput(outputImage);
try
{
writer->Update();
}
catch ( itk::ExceptionObject &err)
{
std::cout << "ExceptionObject caught !" << std::endl;
std::cout << err << std::endl;
return -1;
}
// Software Guide : BeginLatex
//
// Let's run this example on the image \code{FatMRISlice.png} found
// in \code{Insight/Examples/Data}. The command line arguments specify the
// input and output file names, then the $x$, $y$ origin and the $x$, $y$ size
// of the cropped subregion.
//
// \begin{verbatim}
// ImageRegionIterator FatMRISlice.png ImageRegionIteratorOutput.png 20 70 210 140
// \end{verbatim}
//
// The output is the cropped subregion shown in figure~\ref{fig:ImageRegionIteratorOutput}.
//
// \begin{figure}
// \centering
// \includegraphics[width=0.4\textwidth]{FatMRISlice.eps}
// \includegraphics[width=0.3\textwidth]{ImageRegionIteratorOutput.eps}
// \caption[Copying an image subregion using ImageRegionIterator]{Cropping a
// region from an image. The original image is shown at left. The image on
// the right is the result of applying the ImageRegionIterator example code.}
// \protect\label{fig:ImageRegionIteratorOutput}
// \end{figure}
//
// \index{itk::ImageRegionIterator!example of using|)}
//
// Software Guide : EndLatex
return 0;
}
<commit_msg>ENH: \doxygen keyword used to replace \code when referencing ITK classes.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: ImageRegionIterator.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// Software Guide : BeginLatex
//
// \index{Iterators!speed}
// The \doxygen{ImageRegionIterator} has been optimized for iteration speed.
// It is the first choice for iterative, pixel-wise operations where location
// in the image is not important and no special iteration path through the
// image is required. \doxygen{ImageRegionIterator} is the most commonly
// used and least specialized of the ITK image iterator classes. It implements
// all of the methods described in the preceding section.
//
// The following example illustrates the use of
// \doxygen{ImageRegionConstIterator} and \doxygen{ImageRegionIterator}.
// Most of the code constructs introduced apply to other ITK iterators as
// well. This simple application crops a subregion from an image by copying
// pixel values into to a second image.
//
// \index{Iterators!and image regions}
// \index{itk::ImageRegionIterator!example of using|(}
// We begin by including the appropriate header files.
// Software Guide : EndLatex
#include "itkImage.h"
// Software Guide : BeginCodeSnippet
#include "itkImageRegionConstIterator.h"
#include "itkImageRegionIterator.h"
// Software Guide : EndCodeSnippet
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
int main( int argc, char ** argv )
{
// Verify the number of parameters on the command line.
if ( argc < 7 )
{
std::cerr << "Missing parameters. " << std::endl;
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0]
<< " inputImageFile outputImageFile startX startY sizeX sizeY"
<< std::endl;
return -1;
}
// Software Guide : BeginLatex
//
// Next we define a pixel type and corresponding image type. ITK iterator classes
// expect the image type as their template parameter.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
const unsigned int Dimension = 2;
typedef unsigned short PixelType;
typedef itk::Image< PixelType, Dimension > ImageType;
typedef itk::ImageRegionConstIterator< ImageType > ConstIteratorType;
typedef itk::ImageRegionIterator< ImageType> IteratorType;
// Software Guide : EndCodeSnippet
typedef itk::ImageFileReader< ImageType > ReaderType;
typedef itk::ImageFileWriter< ImageType > WriterType;
// Software Guide : BeginLatex
//
// Information about the subregion to copy is read from the command line. The
// subregion is defined by an \doxygen{ImageRegion} object, with a starting
// grid index and a size (section~\ref{sec:ImageSection}).
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
ImageType::RegionType region;
ImageType::RegionType::IndexType index;
ImageType::RegionType::SizeType size;
index[0] = ::atoi( argv[3] );
index[1] = ::atoi( argv[4] );
size[0] = ::atoi( argv[5] );
size[1] = ::atoi( argv[6] );
region.SetSize(size);
region.SetIndex(index);
// Software Guide : EndCodeSnippet
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[1] );
try
{
reader->Update();
}
catch ( itk::ExceptionObject &err)
{
std::cout << "ExceptionObject caught !" << std::endl;
std::cout << err << std::endl;
return -1;
}
// Check that the region is contained within the input image.
if ( ! reader->GetOutput()->GetRequestedRegion().IsInside( region ) )
{
std::cerr << "Error" << std::endl;
std::cerr << "The region " << region << "is not contained within the input image region "
<< reader->GetOutput()->GetRequestedRegion() << std::endl;
return -1;
}
// Software Guide : BeginLatex
//
// After reading the input image and checking that the desired subregion is,
// in fact, contained in the input, we allocate an output image. Allocating
// this image with the same region object we just created guarantees that the output image has
// the same starting index and size as the extracted subregion. Preserving
// the starting index may be an important detail later if the cropped image
// requires registering against the original image. The origin and spacing
// information is passed to the new image by \code{CopyInformation()}.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
ImageType::Pointer outputImage = ImageType::New();
outputImage->SetRegions( region );
outputImage->CopyInformation( reader->GetOutput() );
outputImage->Allocate();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// \index{Iterators!construction of}
// \index{Iterators!and image regions}
// The necessary images and region definitions are now in place. All that is
// left is to create the iterators and perform the copy. Note that image
// iterators are not smart pointers so their constructors are called directly.
// Also notice how the input and output iterators are defined over the
// \emph{same region}. Though the images are different sizes, they both
// contain the same target subregion.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
ConstIteratorType inputIt( reader->GetOutput(), region );
IteratorType outputIt( outputImage, region );
for ( inputIt.GoToBegin(), outputIt.GoToBegin(); !inputIt.IsAtEnd();
++inputIt, ++outputIt)
{
outputIt.Set(inputIt.Get());
}
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// \index{Iterators!image dimensionality}
// The \code{for} loop above is a common construct in ITK. The beauty of these
// four lines of code is that they are equally valid for one, two, three, or
// even ten dimensional data. Consider the ugly alternative of ten nested
// \code{for} loops for traversing an image, which would also require explicit
// knowledge of the size of each image dimension.
//
// Software Guide : EndLatex
WriterType::Pointer writer = WriterType::New();
writer->SetFileName( argv[2] );
writer->SetInput(outputImage);
try
{
writer->Update();
}
catch ( itk::ExceptionObject &err)
{
std::cout << "ExceptionObject caught !" << std::endl;
std::cout << err << std::endl;
return -1;
}
// Software Guide : BeginLatex
//
// Let's run this example on the image \code{FatMRISlice.png} found
// in \code{Insight/Examples/Data}. The command line arguments specify the
// input and output file names, then the $x$, $y$ origin and the $x$, $y$ size
// of the cropped subregion.
//
// \begin{verbatim}
// ImageRegionIterator FatMRISlice.png ImageRegionIteratorOutput.png 20 70 210 140
// \end{verbatim}
//
// The output is the cropped subregion shown in figure~\ref{fig:ImageRegionIteratorOutput}.
//
// \begin{figure}
// \centering
// \includegraphics[width=0.4\textwidth]{FatMRISlice.eps}
// \includegraphics[width=0.3\textwidth]{ImageRegionIteratorOutput.eps}
// \caption[Copying an image subregion using ImageRegionIterator]{Cropping a
// region from an image. The original image is shown at left. The image on
// the right is the result of applying the ImageRegionIterator example code.}
// \protect\label{fig:ImageRegionIteratorOutput}
// \end{figure}
//
// \index{itk::ImageRegionIterator!example of using|)}
//
// Software Guide : EndLatex
return 0;
}
<|endoftext|> |
<commit_before>#include "MyConditionalPrior.h"
#include "DNest4/code/Utils.h"
#include "Data.h"
#include <cmath>
using namespace DNest4;
MyWideConditionalPrior::MyWideConditionalPrior(double x_min, double x_max)
:x_min(x_min)
,x_max(x_max)
{
}
void MyWideConditionalPrior::from_prior(RNG& rng)
{
// Cauchy prior on the mean of the exponential amplitude prior
mu_amp = tan(M_PI*(0.97*rng.rand() - 0.485));
mu_amp = exp(mu_amp);
// Uniform prior on the mean of the Laplacian logq prior:
mu_logq = (log(2.)-log(1E-5))*rng.rand() + log(1E-5);
// Uniform prior on the width of the Laplacian logq prior:
sigma_logq = 2.*rng.rand();
// mu_widths = exp(log(1E-3*(x_max - x_min)) + log(1E3)*rng.rand());
// a = -10. + 20.*rng.rand();
// b = 2.*rng.rand();
}
double MyWideConditionalPrior::perturb_hyperparameters(RNG& rng)
{
double logH = 0.;
int which = rng.rand_int(3);
if(which == 0)
{
mu_amp = log(mu_amp);
mu_amp = (atan(mu_amp)/M_PI + 0.485)/0.97;
mu_amp += rng.randh();
wrap(mu_amp, 0., 1.);
mu_amp = tan(M_PI*(0.97*mu_amp - 0.485));
mu_amp = exp(mu_amp);
}
if(which == 1)
{
// check this!
mu_logq = mu_logq/(log(2.) - log(1E-5));
mu_logq += rng.randh()*(log(2.)-log(1E-5)); //log(100)*pow(10., log(2.) - log(100.)*rng.rand())*rng.randn();
wrap(mu_logq, log(1E-5), log(2.));
//mu_logq = mod(mu_logq - log(.2), log(100.)) + log(2.);
mu_logq = (log(2.) - log(1E-5))*mu_logq;
}
if(which == 2)
{
sigma_logq += 2.*rng.randh();
wrap(sigma_logq, 0., 2.);
}
return logH;
}
double MyWideConditionalPrior::log_pdf(const std::vector<double>& vec) const
{
if(vec[0] < x_min || vec[0] > x_max || vec[1] < 0.0)
return -1E300;
return -log(mu_amp) - vec[1]/mu_amp - log(2.*sigma_logq) -
std::abs(vec[2]-mu_logq)/sigma_logq;
//return -log(mu) - vec[1]/mu - log(mu_widths)
// - (vec[2] - min_width)/mu_widths - log(2.*b*vec[3]);
}
void MyWideConditionalPrior::from_uniform(std::vector<double>& vec) const
{
vec[0] = x_min + (x_max - x_min)*vec[0];
vec[1] = -mu_amp*log(1. - vec[1]);
if (vec[2] < 0.5)
vec[2] = mu_logq + sigma_logq*log(2.*vec[2]);
else
vec[2] = mu_logq + sigma_logq*log(2. - 2.*vec[2]);
}
void MyWideConditionalPrior::to_uniform(std::vector<double>& vec) const
{
vec[0] = (vec[0] - x_min)/(x_max - x_min);
vec[1] = 1. - exp(-vec[1]/mu_amp);
if (vec[2] < mu_logq)
vec[2] = 0.5*exp((vec[2] - mu_logq)/sigma_logq);
else
vec[2] = 1.0 - 0.5*exp((mu_logq - vec[2])/sigma_logq);
}
void MyWideConditionalPrior::print(std::ostream& out) const
{
out<<mu_amp<<' '<<mu_logq<<' '<<sigma_logq<<' ';
}
MyNarrowConditionalPrior::MyNarrowConditionalPrior(double x_min, double x_max)
:x_min(x_min)
,x_max(x_max)
{
}
void MyNarrowConditionalPrior::from_prior(RNG& rng)
{
// Cauchy prior on the mean of the exponential amplitude prior
mu_amp = tan(M_PI*(0.97*rng.rand() - 0.485));
mu_amp = exp(mu_amp);
// Uniform prior on the mean of the Laplacian logq prior:
mu_logq = (log(100.)-log(2.))*rng.rand() + log(2.);
// Uniform prior on the width of the Laplacian logq prior:
sigma_logq = 2.*rng.rand();
// mu_widths = exp(log(1E-3*(x_max - x_min)) + log(1E3)*rng.rand());
// a = -10. + 20.*rng.rand();
// b = 2.*rng.rand();
}
double MyNarrowConditionalPrior::perturb_hyperparameters(RNG& rng)
{
double logH = 0.;
int which = rng.rand_int(3);
if(which == 0)
{
mu_amp = log(mu_amp);
mu_amp = (atan(mu_amp)/M_PI + 0.485)/0.97;
mu_amp += rng.randh();
wrap(mu_amp, 0., 1.);
mu_amp = tan(M_PI*(0.97*mu_amp - 0.485));
mu_amp = exp(mu_amp);
}
if(which == 1)
{
// check this!
mu_logq = mu_logq/(log(100.) - log(2.));
mu_logq += rng.randh()*(log(100.)-log(2.)); //log(100)*pow(10., log(2.) - log(100.)*rng.rand())*rng.randn();
wrap(mu_logq, log(2.), log(100));
//mu_logq = mod(mu_logq - log(.2), log(100.)) + log(2.);
mu_logq = (log(100.) - log(2.0))*mu_logq;
}
if(which == 2)
{
sigma_logq += 2.*rng.randh();
wrap(sigma_logq, 0., 2.);
}
return logH;
}
double MyNarrowConditionalPrior::log_pdf(const std::vector<double>& vec) const
{
if(vec[0] < x_min || vec[0] > x_max || vec[1] < 0.0)
return -1E300;
return -log(mu_amp) - vec[1]/mu_amp - log(2.*sigma_logq) -
std::abs(vec[2]-mu_logq)/sigma_logq;
//return -log(mu) - vec[1]/mu - log(mu_widths)
// - (vec[2] - min_width)/mu_widths - log(2.*b*vec[3]);
}
void MyNarrowConditionalPrior::from_uniform(std::vector<double>& vec) const
{
vec[0] = x_min + (x_max - x_min)*vec[0];
vec[1] = -mu_amp*log(1. - vec[1]);
if (vec[2] < 0.5)
vec[2] = mu_logq + sigma_logq*log(2.*vec[2]);
else
vec[2] = mu_logq + sigma_logq*log(2. - 2.*vec[2]);
}
void MyNarrowConditionalPrior::to_uniform(std::vector<double>& vec) const
{
vec[0] = (vec[0] - x_min)/(x_max - x_min);
vec[1] = 1. - exp(-vec[1]/mu_amp);
if (vec[2] < mu_logq)
vec[2] = 0.5*exp((vec[2] - mu_logq)/sigma_logq);
else
vec[2] = 1.0 - 0.5*exp((mu_logq - vec[2])/sigma_logq);
}
void MyNarrowConditionalPrior::print(std::ostream& out) const
{
out<<mu_amp<<' '<<mu_logq<<' '<<sigma_logq<<' ';
}
<commit_msg>Fixed some issues in proposals<commit_after>#include "MyConditionalPrior.h"
#include "DNest4/code/Utils.h"
#include "Data.h"
#include <cmath>
using namespace DNest4;
MyWideConditionalPrior::MyWideConditionalPrior(double x_min, double x_max)
:x_min(x_min)
,x_max(x_max)
{
}
void MyWideConditionalPrior::from_prior(RNG& rng)
{
// Cauchy prior on the mean of the exponential amplitude prior
mu_amp = tan(M_PI*(0.97*rng.rand() - 0.485));
mu_amp = exp(mu_amp);
// Uniform prior on the mean of the Laplacian logq prior:
mu_logq = (log(2.)-log(1E-5))*rng.rand() + log(1E-5);
// Uniform prior on the width of the Laplacian logq prior:
sigma_logq = 2.*rng.rand();
// mu_widths = exp(log(1E-3*(x_max - x_min)) + log(1E3)*rng.rand());
// a = -10. + 20.*rng.rand();
// b = 2.*rng.rand();
}
double MyWideConditionalPrior::perturb_hyperparameters(RNG& rng)
{
double logH = 0.;
int which = rng.rand_int(3);
if(which == 0)
{
mu_amp = log(mu_amp);
mu_amp = (atan(mu_amp)/M_PI + 0.485)/0.97;
mu_amp += rng.randh();
wrap(mu_amp, 0., 1.);
mu_amp = tan(M_PI*(0.97*mu_amp - 0.485));
mu_amp = exp(mu_amp);
}
if(which == 1)
{
// check this!
mu_logq += rng.randh()*(log(2.)-log(1E-5)); //log(100)*pow(10., log(2.) - log(100.)*rng.rand())*rng.randn();
wrap(mu_logq, log(1E-5), log(2.));
//mu_logq = mod(mu_logq - log(.2), log(100.)) + log(2.);
}
if(which == 2)
{
sigma_logq += 2.*rng.randh();
wrap(sigma_logq, 0., 2.);
}
return logH;
}
double MyWideConditionalPrior::log_pdf(const std::vector<double>& vec) const
{
if(vec[0] < x_min || vec[0] > x_max || vec[1] < 0.0)
return -1E300;
return -log(mu_amp) - vec[1]/mu_amp - log(2.*sigma_logq) -
std::abs(vec[2]-mu_logq)/sigma_logq;
//return -log(mu) - vec[1]/mu - log(mu_widths)
// - (vec[2] - min_width)/mu_widths - log(2.*b*vec[3]);
}
void MyWideConditionalPrior::from_uniform(std::vector<double>& vec) const
{
vec[0] = x_min + (x_max - x_min)*vec[0];
vec[1] = -mu_amp*log(1. - vec[1]);
if (vec[2] < 0.5)
vec[2] = mu_logq + sigma_logq*log(2.*vec[2]);
else
vec[2] = mu_logq + sigma_logq*log(2. - 2.*vec[2]);
}
void MyWideConditionalPrior::to_uniform(std::vector<double>& vec) const
{
vec[0] = (vec[0] - x_min)/(x_max - x_min);
vec[1] = 1. - exp(-vec[1]/mu_amp);
if (vec[2] < mu_logq)
vec[2] = 0.5*exp((vec[2] - mu_logq)/sigma_logq);
else
vec[2] = 1.0 - 0.5*exp((mu_logq - vec[2])/sigma_logq);
}
void MyWideConditionalPrior::print(std::ostream& out) const
{
out<<mu_amp<<' '<<mu_logq<<' '<<sigma_logq<<' ';
}
MyNarrowConditionalPrior::MyNarrowConditionalPrior(double x_min, double x_max)
:x_min(x_min)
,x_max(x_max)
{
}
void MyNarrowConditionalPrior::from_prior(RNG& rng)
{
// Cauchy prior on the mean of the exponential amplitude prior
mu_amp = tan(M_PI*(0.97*rng.rand() - 0.485));
mu_amp = exp(mu_amp);
// Uniform prior on the mean of the Laplacian logq prior:
mu_logq = (log(100.)-log(2.))*rng.rand() + log(2.);
// Uniform prior on the width of the Laplacian logq prior:
sigma_logq = 2.*rng.rand();
// mu_widths = exp(log(1E-3*(x_max - x_min)) + log(1E3)*rng.rand());
// a = -10. + 20.*rng.rand();
// b = 2.*rng.rand();
}
double MyNarrowConditionalPrior::perturb_hyperparameters(RNG& rng)
{
double logH = 0.;
int which = rng.rand_int(3);
if(which == 0)
{
mu_amp = log(mu_amp);
mu_amp = (atan(mu_amp)/M_PI + 0.485)/0.97;
mu_amp += rng.randh();
wrap(mu_amp, 0., 1.);
mu_amp = tan(M_PI*(0.97*mu_amp - 0.485));
mu_amp = exp(mu_amp);
}
if(which == 1)
{
// check this!
mu_logq += rng.randh()*(log(100.)-log(2.)); //log(100)*pow(10., log(2.) - log(100.)*rng.rand())*rng.randn();
wrap(mu_logq, log(2.), log(100));
//mu_logq = mod(mu_logq - log(.2), log(100.)) + log(2.);
}
if(which == 2)
{
sigma_logq += 2.*rng.randh();
wrap(sigma_logq, 0., 2.);
}
return logH;
}
double MyNarrowConditionalPrior::log_pdf(const std::vector<double>& vec) const
{
if(vec[0] < x_min || vec[0] > x_max || vec[1] < 0.0)
return -1E300;
return -log(mu_amp) - vec[1]/mu_amp - log(2.*sigma_logq) -
std::abs(vec[2]-mu_logq)/sigma_logq;
//return -log(mu) - vec[1]/mu - log(mu_widths)
// - (vec[2] - min_width)/mu_widths - log(2.*b*vec[3]);
}
void MyNarrowConditionalPrior::from_uniform(std::vector<double>& vec) const
{
vec[0] = x_min + (x_max - x_min)*vec[0];
vec[1] = -mu_amp*log(1. - vec[1]);
if (vec[2] < 0.5)
vec[2] = mu_logq + sigma_logq*log(2.*vec[2]);
else
vec[2] = mu_logq + sigma_logq*log(2. - 2.*vec[2]);
}
void MyNarrowConditionalPrior::to_uniform(std::vector<double>& vec) const
{
vec[0] = (vec[0] - x_min)/(x_max - x_min);
vec[1] = 1. - exp(-vec[1]/mu_amp);
if (vec[2] < mu_logq)
vec[2] = 0.5*exp((vec[2] - mu_logq)/sigma_logq);
else
vec[2] = 1.0 - 0.5*exp((mu_logq - vec[2])/sigma_logq);
}
void MyNarrowConditionalPrior::print(std::ostream& out) const
{
out<<mu_amp<<' '<<mu_logq<<' '<<sigma_logq<<' ';
}
<|endoftext|> |
<commit_before>/*
* RudeControl.cpp
*
* Bork3D Game Engine
* Copyright (c) 2009 Bork 3D LLC. All rights reserved.
*
*/
#include "RudeControl.h"
#include "RudeGL.h"
RudeControl::RudeControl()
: m_rect(0,0,0,0)
, m_hitId(-1)
, m_translation(0,0,0)
, m_animSpeed(3.0f)
, m_animType(kAnimNone)
{
}
bool RudeControl::Contains(const RudeScreenVertex &p)
{
return m_rect.Contains(p);
}
bool RudeControl::TouchDown(RudeTouch *t)
{
if(!Contains(t->m_location))
return false;
m_hitId = t->m_touchId;
m_hitStart = t->m_location;
m_hitMove = m_hitStart;
m_hitMoveDelta = RudeScreenVertex(0,0);
m_hitDelta = RudeScreenVertex(0,0);
m_hitDistanceTraveled = RudeScreenVertex(0,0);
return true;
}
bool RudeControl::TouchMove(RudeTouch *t)
{
if(m_hitId != t->m_touchId)
return false;
m_hitMoveDelta = t->m_location - m_hitMove;
m_hitMove = t->m_location;
m_hitDelta = t->m_location - m_hitStart;
m_hitDistanceTraveled.m_x += abs(m_hitDelta.m_x);
m_hitDistanceTraveled.m_y += abs(m_hitDelta.m_y);
return true;
}
bool RudeControl::TouchUp(RudeTouch *t)
{
if(m_hitId != t->m_touchId)
return false;
m_hitId = -1;
m_hitMoveDelta = t->m_location - m_hitMove;
m_hitMove = t->m_location;
m_hitDelta = t->m_location - m_hitStart;
return true;
}
void RudeControl::NextFrame(float delta)
{
switch(m_animType)
{
case kAnimNone:
break;
case kAnimPopSlide:
{
m_translation += (m_desiredTranslation - m_translation) * delta * m_animSpeed;
}
break;
}
}
void RudeControl::Render()
{
RGL.LoadIdentity();
if(m_animType != kAnimNone)
RGL.Translate(m_translation.x(), m_translation.y(), m_translation.z());
}
<commit_msg>RudeControl uninitialized variable fixes<commit_after>/*
* RudeControl.cpp
*
* Bork3D Game Engine
* Copyright (c) 2009 Bork 3D LLC. All rights reserved.
*
*/
#include "RudeControl.h"
#include "RudeGL.h"
RudeControl::RudeControl()
: m_rect(0,0,0,0)
, m_hitStart(0,0)
, m_hitMove(0,0)
, m_hitMoveDelta(0,0)
, m_hitDelta(0,0)
, m_hitDistanceTraveled(0,0)
, m_hitId(-1)
, m_translation(0,0,0)
, m_desiredTranslation(0,0,0)
, m_animSpeed(3.0f)
, m_animType(kAnimNone)
{
}
bool RudeControl::Contains(const RudeScreenVertex &p)
{
return m_rect.Contains(p);
}
bool RudeControl::TouchDown(RudeTouch *t)
{
if(!Contains(t->m_location))
return false;
m_hitId = t->m_touchId;
m_hitStart = t->m_location;
m_hitMove = m_hitStart;
m_hitMoveDelta = RudeScreenVertex(0,0);
m_hitDelta = RudeScreenVertex(0,0);
m_hitDistanceTraveled = RudeScreenVertex(0,0);
return true;
}
bool RudeControl::TouchMove(RudeTouch *t)
{
if(m_hitId != t->m_touchId)
return false;
m_hitMoveDelta = t->m_location - m_hitMove;
m_hitMove = t->m_location;
m_hitDelta = t->m_location - m_hitStart;
m_hitDistanceTraveled.m_x += abs(m_hitDelta.m_x);
m_hitDistanceTraveled.m_y += abs(m_hitDelta.m_y);
return true;
}
bool RudeControl::TouchUp(RudeTouch *t)
{
if(m_hitId != t->m_touchId)
return false;
m_hitId = -1;
m_hitMoveDelta = t->m_location - m_hitMove;
m_hitMove = t->m_location;
m_hitDelta = t->m_location - m_hitStart;
return true;
}
void RudeControl::NextFrame(float delta)
{
switch(m_animType)
{
default:
case kAnimNone:
break;
case kAnimPopSlide:
{
m_translation += (m_desiredTranslation - m_translation) * delta * m_animSpeed;
}
break;
}
}
void RudeControl::Render()
{
RGL.LoadIdentity();
if(m_animType != kAnimNone)
RGL.Translate(m_translation.x(), m_translation.y(), m_translation.z());
}
<|endoftext|> |
<commit_before>#include <iso646.h>
#include <string>
#include <windows.h>
#include "rtl_exec.h"
#include "enums.inc"
struct Process {
HANDLE process;
};
namespace rtl {
void os$chdir(const std::string &path)
{
BOOL r = SetCurrentDirectory(path.c_str());
if (not r) {
throw RtlException(Exception_file$PathNotFound, path);
}
}
std::string os$getcwd()
{
char buf[MAX_PATH];
GetCurrentDirectory(sizeof(buf), buf);
return buf;
}
Cell os$platform()
{
return Cell(ENUM_Platform_win32);
}
bool os$fork(Cell **process)
{
Process **pp = reinterpret_cast<Process **>(process);
*pp = NULL;
throw RtlException(Exception_os$UnsupportedFunction, "os.fork");
}
void os$kill(void *process)
{
Process *p = reinterpret_cast<Process *>(process);
TerminateProcess(p->process, 1);
CloseHandle(p->process);
p->process = INVALID_HANDLE_VALUE;
delete p;
}
void *os$spawn(const std::string &command)
{
Process *p = new Process;
STARTUPINFO si;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
PROCESS_INFORMATION pi;
BOOL r = CreateProcess(
NULL,
const_cast<LPSTR>(command.c_str()),
NULL,
NULL,
FALSE,
0,
NULL,
NULL,
&si,
&pi);
if (not r) {
throw RtlException(Exception_file$PathNotFound, command.c_str());
}
p->process = pi.hProcess;
CloseHandle(pi.hThread);
return p;
}
Number os$wait(Cell **process)
{
DWORD r;
{
Process **pp = reinterpret_cast<Process **>(process);
WaitForSingleObject((*pp)->process, INFINITE);
GetExitCodeProcess((*pp)->process, &r);
CloseHandle((*pp)->process);
(*pp)->process = INVALID_HANDLE_VALUE;
delete *pp;
*pp = NULL;
}
return number_from_uint32(r);
}
}
<commit_msg>Create subprocesses in job object<commit_after>#include <iso646.h>
#include <string>
#include <windows.h>
#include "rtl_exec.h"
#include "enums.inc"
struct Process {
HANDLE process;
};
namespace rtl {
void os$chdir(const std::string &path)
{
BOOL r = SetCurrentDirectory(path.c_str());
if (not r) {
throw RtlException(Exception_file$PathNotFound, path);
}
}
std::string os$getcwd()
{
char buf[MAX_PATH];
GetCurrentDirectory(sizeof(buf), buf);
return buf;
}
Cell os$platform()
{
return Cell(ENUM_Platform_win32);
}
bool os$fork(Cell **process)
{
Process **pp = reinterpret_cast<Process **>(process);
*pp = NULL;
throw RtlException(Exception_os$UnsupportedFunction, "os.fork");
}
void os$kill(void *process)
{
Process *p = reinterpret_cast<Process *>(process);
TerminateProcess(p->process, 1);
CloseHandle(p->process);
p->process = INVALID_HANDLE_VALUE;
delete p;
}
void *os$spawn(const std::string &command)
{
static HANDLE job = INVALID_HANDLE_VALUE;
if (job == INVALID_HANDLE_VALUE) {
job = CreateJobObject(NULL, NULL);
JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
ZeroMemory(&jeli, sizeof(jeli));
jeli.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
SetInformationJobObject(job, JobObjectExtendedLimitInformation, &jeli, sizeof(jeli));
}
Process *p = new Process;
STARTUPINFO si;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
PROCESS_INFORMATION pi;
BOOL r = CreateProcess(
NULL,
const_cast<LPSTR>(command.c_str()),
NULL,
NULL,
FALSE,
0,
NULL,
NULL,
&si,
&pi);
if (not r) {
throw RtlException(Exception_file$PathNotFound, command.c_str());
}
AssignProcessToJobObject(job, pi.hProcess);
p->process = pi.hProcess;
CloseHandle(pi.hThread);
return p;
}
Number os$wait(Cell **process)
{
DWORD r;
{
Process **pp = reinterpret_cast<Process **>(process);
WaitForSingleObject((*pp)->process, INFINITE);
GetExitCodeProcess((*pp)->process, &r);
CloseHandle((*pp)->process);
(*pp)->process = INVALID_HANDLE_VALUE;
delete *pp;
*pp = NULL;
}
return number_from_uint32(r);
}
}
<|endoftext|> |
<commit_before>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, development version *
* (c) 2006-2016 INRIA, USTL, UJF, CNRS, MGH *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: [email protected] *
******************************************************************************/
#define SOFA_COMPONENT_CONSTRAINTSET_UNCOUPLEDCONSTRAINTCORRECTION_CPP
#include "UncoupledConstraintCorrection.inl"
#include <sofa/defaulttype/Vec3Types.h>
#include <sofa/core/ObjectFactory.h>
#include <sofa/defaulttype/RigidTypes.h>
#include <sofa/simulation/Node.h>
#include <sofa/simulation/MechanicalVisitor.h>
#include <SofaBaseLinearSolver/FullMatrix.h>
#include <SofaBaseMechanics/UniformMass.h>
namespace sofa
{
namespace component
{
namespace constraintset
{
using namespace sofa::defaulttype;
template<>
SOFA_CONSTRAINT_API UncoupledConstraintCorrection< sofa::defaulttype::Rigid3Types >::UncoupledConstraintCorrection(sofa::core::behavior::MechanicalState<sofa::defaulttype::Rigid3Types> *mm)
: Inherit(mm)
, compliance(initData(&compliance, "compliance", "Rigid compliance value: 1st value for translations, 6 others for upper-triangular part of symmetric 3x3 rotation compliance matrix"))
, defaultCompliance(initData(&defaultCompliance, (Real)0.00001, "defaultCompliance", "Default compliance value for new dof or if all should have the same (in which case compliance vector should be empty)"))
, f_verbose( initData(&f_verbose,false,"verbose","Dump the constraint matrix at each iteration") )
, d_handleTopologyChange(initData(&d_handleTopologyChange, false, "handleTopologyChange", "Enable support of topological changes for compliance vector (should be disabled for rigids)"))
, d_correctionVelocityFactor(initData(&d_correctionVelocityFactor, (Real)1.0, "correctionVelocityFactor", "Factor applied to the constraint forces when correcting the velocities"))
, d_correctionPositionFactor(initData(&d_correctionPositionFactor, (Real)1.0, "correctionPositionFactor", "Factor applied to the constraint forces when correcting the positions"))
{
}
template<>
SOFA_CONSTRAINT_API void UncoupledConstraintCorrection< defaulttype::Rigid3Types >::init()
{
Inherit::init();
double dt = this->getContext()->getDt();
const VecReal& comp = compliance.getValue();
VecReal usedComp;
if (comp.size() != 7)
{
using sofa::component::mass::UniformMass;
using sofa::defaulttype::Rigid3Types;
using sofa::defaulttype::Rigid3Mass;
using sofa::simulation::Node;
Node *node = dynamic_cast< Node * >(getContext());
Rigid3Mass massValue;
//Should use the BaseMatrix API to get the Mass
//void getElementMass(unsigned int index, defaulttype::BaseMatrix *m)
if (node != NULL)
{
core::behavior::BaseMass *m = node->mass;
UniformMass< Rigid3Types, Rigid3Mass > *um = dynamic_cast< UniformMass< Rigid3Types, Rigid3Mass >* > (m);
if (um)
massValue = um->getMass();
else
serr << "WARNING : no mass found" << sendl;
}
else
{
serr << "\n WARNING : node is not found => massValue could be incorrect in addComplianceInConstraintSpace function" << sendl;
}
const double dt2 = dt * dt;
usedComp.push_back(dt2 / massValue.mass);
usedComp.push_back(dt2 * massValue.invInertiaMassMatrix[0][0]);
usedComp.push_back(dt2 * massValue.invInertiaMassMatrix[0][1]);
usedComp.push_back(dt2 * massValue.invInertiaMassMatrix[0][2]);
usedComp.push_back(dt2 * massValue.invInertiaMassMatrix[1][1]);
usedComp.push_back(dt2 * massValue.invInertiaMassMatrix[1][2]);
usedComp.push_back(dt2 * massValue.invInertiaMassMatrix[2][2]);
compliance.setValue(usedComp);
}
else
{
sout << "COMPLIANCE VALUE FOUND" << sendl;
}
}
template<>
SOFA_CONSTRAINT_API void UncoupledConstraintCorrection< defaulttype::Rigid3Types >::getComplianceMatrix(defaulttype::BaseMatrix *m) const
{
const VecReal& comp = compliance.getValue();
const unsigned int dimension = defaulttype::DataTypeInfo<Deriv>::size();
const unsigned int numDofs = comp.size() / 7;
m->resize(dimension * numDofs, dimension * numDofs);
/// @todo Optimization
for (unsigned int d = 0; d < numDofs; ++d)
{
const unsigned int d6 = 6 * d;
const unsigned int d7 = 7 * d;
const SReal invM = comp[d7];
m->set(d6, d6, invM);
m->set(d6 + 1, d6 + 1, invM);
m->set(d6 + 2, d6 + 2, invM);
m->set(d6 + 3, d6 + 3, comp[d7 + 1]);
m->set(d6 + 3, d6 + 4, comp[d7 + 2]);
m->set(d6 + 4, d6 + 3, comp[d7 + 2]);
m->set(d6 + 3, d6 + 5, comp[d7 + 3]);
m->set(d6 + 5, d6 + 3, comp[d7 + 3]);
m->set(d6 + 4, d6 + 4, comp[d7 + 4]);
m->set(d6 + 4, d6 + 5, comp[d7 + 5]);
m->set(d6 + 5, d6 + 4, comp[d7 + 5]);
m->set(d6 + 5, d6 + 5, comp[d7 + 6]);
}
}
SOFA_DECL_CLASS(UncoupledConstraintCorrection)
int UncoupledConstraintCorrectionClass = core::RegisterObject("Component computing contact forces within a simulated body using the compliance method.")
#ifndef SOFA_FLOAT
.add< UncoupledConstraintCorrection< Vec1dTypes > >()
.add< UncoupledConstraintCorrection< Vec3dTypes > >()
.add< UncoupledConstraintCorrection< Rigid3dTypes > >()
#endif
#ifndef SOFA_DOUBLE
.add< UncoupledConstraintCorrection< Vec1fTypes > >()
.add< UncoupledConstraintCorrection< Vec3fTypes > >()
.add< UncoupledConstraintCorrection< Rigid3fTypes > >()
#endif
;
#ifndef SOFA_FLOAT
template class SOFA_CONSTRAINT_API UncoupledConstraintCorrection< Vec1dTypes >;
template class SOFA_CONSTRAINT_API UncoupledConstraintCorrection< Vec3dTypes >;
template class SOFA_CONSTRAINT_API UncoupledConstraintCorrection< Rigid3dTypes >;
#endif
#ifndef SOFA_DOUBLE
template class SOFA_CONSTRAINT_API UncoupledConstraintCorrection< Vec1fTypes >;
template class SOFA_CONSTRAINT_API UncoupledConstraintCorrection< Vec3fTypes >;
template class SOFA_CONSTRAINT_API UncoupledConstraintCorrection< Rigid3fTypes >;
#endif
} // namespace constraintset
} // namespace component
} // namespace sofa
<commit_msg>FIX: UncoupledConstraintCorrection for rigid in a 7 value vector. When using the default initialization of the compliance using the mass matrix of the rigid the linear part of the compliance was added twice. T900<commit_after>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, development version *
* (c) 2006-2016 INRIA, USTL, UJF, CNRS, MGH *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: [email protected] *
******************************************************************************/
#define SOFA_COMPONENT_CONSTRAINTSET_UNCOUPLEDCONSTRAINTCORRECTION_CPP
#include "UncoupledConstraintCorrection.inl"
#include <sofa/defaulttype/Vec3Types.h>
#include <sofa/core/ObjectFactory.h>
#include <sofa/defaulttype/RigidTypes.h>
#include <sofa/simulation/Node.h>
#include <sofa/simulation/MechanicalVisitor.h>
#include <SofaBaseLinearSolver/FullMatrix.h>
#include <SofaBaseMechanics/UniformMass.h>
namespace sofa
{
namespace component
{
namespace constraintset
{
using namespace sofa::defaulttype;
template<>
SOFA_CONSTRAINT_API UncoupledConstraintCorrection< sofa::defaulttype::Rigid3Types >::UncoupledConstraintCorrection(sofa::core::behavior::MechanicalState<sofa::defaulttype::Rigid3Types> *mm)
: Inherit(mm)
, compliance(initData(&compliance, "compliance", "Rigid compliance value: 1st value for translations, 6 others for upper-triangular part of symmetric 3x3 rotation compliance matrix"))
, defaultCompliance(initData(&defaultCompliance, (Real)0.00001, "defaultCompliance", "Default compliance value for new dof or if all should have the same (in which case compliance vector should be empty)"))
, f_verbose( initData(&f_verbose,false,"verbose","Dump the constraint matrix at each iteration") )
, d_handleTopologyChange(initData(&d_handleTopologyChange, false, "handleTopologyChange", "Enable support of topological changes for compliance vector (should be disabled for rigids)"))
, d_correctionVelocityFactor(initData(&d_correctionVelocityFactor, (Real)1.0, "correctionVelocityFactor", "Factor applied to the constraint forces when correcting the velocities"))
, d_correctionPositionFactor(initData(&d_correctionPositionFactor, (Real)1.0, "correctionPositionFactor", "Factor applied to the constraint forces when correcting the positions"))
{
}
template<>
SOFA_CONSTRAINT_API void UncoupledConstraintCorrection< defaulttype::Rigid3Types >::init()
{
Inherit::init();
double dt = this->getContext()->getDt();
const VecReal& comp = compliance.getValue();
VecReal usedComp;
if (comp.size() != 7)
{
using sofa::component::mass::UniformMass;
using sofa::defaulttype::Rigid3Types;
using sofa::defaulttype::Rigid3Mass;
using sofa::simulation::Node;
Node *node = dynamic_cast< Node * >(getContext());
Rigid3Mass massValue;
//Should use the BaseMatrix API to get the Mass
//void getElementMass(unsigned int index, defaulttype::BaseMatrix *m)
if (node != NULL)
{
core::behavior::BaseMass *m = node->mass;
UniformMass< Rigid3Types, Rigid3Mass > *um = dynamic_cast< UniformMass< Rigid3Types, Rigid3Mass >* > (m);
if (um)
massValue = um->getMass();
else
serr << "WARNING : no mass found" << sendl;
}
else
{
serr << "\n WARNING : node is not found => massValue could be incorrect in addComplianceInConstraintSpace function" << sendl;
}
const double dt2 = dt * dt;
usedComp.push_back(dt2 * massValue.invInertiaMassMatrix[0][0]);
usedComp.push_back(dt2 * massValue.invInertiaMassMatrix[0][1]);
usedComp.push_back(dt2 * massValue.invInertiaMassMatrix[0][2]);
usedComp.push_back(dt2 * massValue.invInertiaMassMatrix[1][1]);
usedComp.push_back(dt2 * massValue.invInertiaMassMatrix[1][2]);
usedComp.push_back(dt2 * massValue.invInertiaMassMatrix[2][2]);
compliance.setValue(usedComp);
}
else
{
sout << "COMPLIANCE VALUE FOUND" << sendl;
}
}
template<>
SOFA_CONSTRAINT_API void UncoupledConstraintCorrection< defaulttype::Rigid3Types >::getComplianceMatrix(defaulttype::BaseMatrix *m) const
{
const VecReal& comp = compliance.getValue();
const unsigned int dimension = defaulttype::DataTypeInfo<Deriv>::size();
const unsigned int numDofs = comp.size() / 7;
m->resize(dimension * numDofs, dimension * numDofs);
/// @todo Optimization
for (unsigned int d = 0; d < numDofs; ++d)
{
const unsigned int d6 = 6 * d;
const unsigned int d7 = 7 * d;
const SReal invM = comp[d7];
m->set(d6, d6, invM);
m->set(d6 + 1, d6 + 1, invM);
m->set(d6 + 2, d6 + 2, invM);
m->set(d6 + 3, d6 + 3, comp[d7 + 1]);
m->set(d6 + 3, d6 + 4, comp[d7 + 2]);
m->set(d6 + 4, d6 + 3, comp[d7 + 2]);
m->set(d6 + 3, d6 + 5, comp[d7 + 3]);
m->set(d6 + 5, d6 + 3, comp[d7 + 3]);
m->set(d6 + 4, d6 + 4, comp[d7 + 4]);
m->set(d6 + 4, d6 + 5, comp[d7 + 5]);
m->set(d6 + 5, d6 + 4, comp[d7 + 5]);
m->set(d6 + 5, d6 + 5, comp[d7 + 6]);
}
}
SOFA_DECL_CLASS(UncoupledConstraintCorrection)
int UncoupledConstraintCorrectionClass = core::RegisterObject("Component computing contact forces within a simulated body using the compliance method.")
#ifndef SOFA_FLOAT
.add< UncoupledConstraintCorrection< Vec1dTypes > >()
.add< UncoupledConstraintCorrection< Vec3dTypes > >()
.add< UncoupledConstraintCorrection< Rigid3dTypes > >()
#endif
#ifndef SOFA_DOUBLE
.add< UncoupledConstraintCorrection< Vec1fTypes > >()
.add< UncoupledConstraintCorrection< Vec3fTypes > >()
.add< UncoupledConstraintCorrection< Rigid3fTypes > >()
#endif
;
#ifndef SOFA_FLOAT
template class SOFA_CONSTRAINT_API UncoupledConstraintCorrection< Vec1dTypes >;
template class SOFA_CONSTRAINT_API UncoupledConstraintCorrection< Vec3dTypes >;
template class SOFA_CONSTRAINT_API UncoupledConstraintCorrection< Rigid3dTypes >;
#endif
#ifndef SOFA_DOUBLE
template class SOFA_CONSTRAINT_API UncoupledConstraintCorrection< Vec1fTypes >;
template class SOFA_CONSTRAINT_API UncoupledConstraintCorrection< Vec3fTypes >;
template class SOFA_CONSTRAINT_API UncoupledConstraintCorrection< Rigid3fTypes >;
#endif
} // namespace constraintset
} // namespace component
} // namespace sofa
<|endoftext|> |
<commit_before>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *
* (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: [email protected] *
******************************************************************************/
#ifndef SOFA_COMPONENT_COLLISION_BARYCENTRICPENALITYCONTACT_INL
#define SOFA_COMPONENT_COLLISION_BARYCENTRICPENALITYCONTACT_INL
#include <SofaMeshCollision/BarycentricPenalityContact.h>
#include <sofa/core/visual/VisualParams.h>
#include <SofaMeshCollision/RigidContactMapper.inl>
namespace sofa
{
namespace component
{
namespace collision
{
using namespace sofa::defaulttype;
using namespace core::collision;
template < class TCollisionModel1, class TCollisionModel2, class ResponseDataTypes >
BarycentricPenalityContact<TCollisionModel1,TCollisionModel2,ResponseDataTypes>::BarycentricPenalityContact(CollisionModel1* _model1, CollisionModel2* _model2, Intersection* _intersectionMethod)
: model1(_model1), model2(_model2), intersectionMethod(_intersectionMethod), ff(NULL), parent(NULL)
{
mapper1.setCollisionModel(model1);
mapper2.setCollisionModel(model2);
}
template < class TCollisionModel1, class TCollisionModel2, class ResponseDataTypes >
BarycentricPenalityContact<TCollisionModel1,TCollisionModel2,ResponseDataTypes>::~BarycentricPenalityContact()
{
}
template < class TCollisionModel1, class TCollisionModel2, class ResponseDataTypes >
void BarycentricPenalityContact<TCollisionModel1,TCollisionModel2,ResponseDataTypes>::cleanup()
{
if (ff!=NULL)
{
ff->cleanup();
if (parent!=NULL) parent->removeObject(ff);
//delete ff;
parent = NULL;
ff = NULL;
mapper1.cleanup();
mapper2.cleanup();
}
}
template < class TCollisionModel1, class TCollisionModel2, class ResponseDataTypes >
void BarycentricPenalityContact<TCollisionModel1,TCollisionModel2,ResponseDataTypes>::setDetectionOutputs(OutputVector* o)
{
TOutputVector& outputs = *static_cast<TOutputVector*>(o);
const bool printLog = this->f_printLog.getValue();
if (ff==NULL)
{
MechanicalState1* mstate1 = mapper1.createMapping();
MechanicalState2* mstate2 = mapper2.createMapping();
ff = sofa::core::objectmodel::New<ResponseForceField>(mstate1,mstate2);
ff->setName( getName() );
setInteractionTags(mstate1, mstate2);
ff->init();
#ifdef SOFA_SMP
ff->setPartition(mstate1->getPartition());
#endif
}
int insize = outputs.size();
// old index for each contact
// >0 indicate preexisting contact
// 0 indicate new contact
// -1 indicate ignored duplicate contact
std::vector<int> oldIndex(insize);
int nbnew = 0;
for (int i=0; i<insize; i++)
{
DetectionOutput* o = &outputs[i];
// find this contact in contactIndex, possibly creating a new entry initialized by 0
int& index = contactIndex[o->id];
if (index < 0) // duplicate contact
{
int i2 = -1-index;
DetectionOutput* o2 = &outputs[i2];
if (o2->value <= o->value)
{
// current contact is ignored
oldIndex[i] = -1;
continue;
}
else
{
// previous contact is replaced
oldIndex[i] = oldIndex[i2];
oldIndex[i2] = -1;
}
}
else
{
oldIndex[i] = index;
if (!index)
{
++nbnew;
if (printLog) sout << "BarycentricPenalityContact: New contact "<<o->id<<sendl;
}
}
index = -1-i; // save this index as a negative value in contactIndex map.
}
// compute new index of each contact
std::vector<int> newIndex(insize);
// number of final contacts used in the response
int size = 0;
for (int i=0; i<insize; i++)
{
if (oldIndex[i] >= 0)
{
++size;
newIndex[i] = size;
}
}
// update contactMap
for (ContactIndexMap::iterator it = contactIndex.begin(), itend = contactIndex.end(); it != itend; )
{
int& index = it->second;
if (index >= 0)
{
if (printLog) sout << "BarycentricPenalityContact: Removed contact "<<it->first<<sendl;
ContactIndexMap::iterator oldit = it;
++it;
contactIndex.erase(oldit);
}
else
{
index = newIndex[-1-index]; // write the final contact index
++it;
}
}
if (printLog) sout << "BarycentricPenalityContact: "<<insize<<" input contacts, "<<size<<" contacts used for response ("<<nbnew<<" new)."<<sendl;
//int size = contacts.size();
ff->clear(size);
mapper1.resize(size);
mapper2.resize(size);
//int i = 0;
const double d0 = intersectionMethod->getContactDistance() + model1->getProximity() + model2->getProximity(); // - 0.001;
//for (std::vector<DetectionOutput>::iterator it = outputs.begin(); it!=outputs.end(); it++)
//{
// DetectionOutput* o = &*it;
for (int i=0; i<insize; i++)
{
int index = oldIndex[i];
if (index < 0) continue; // this contact is ignored
DetectionOutput* o = &outputs[i];
CollisionElement1 elem1(o->elem.first);
CollisionElement2 elem2(o->elem.second);
int index1 = elem1.getIndex();
int index2 = elem2.getIndex();
typename DataTypes1::Real r1 = 0.0;
typename DataTypes2::Real r2 = 0.0;
// Just make it work, some changes have been done in rev 10382 so that BarycentricPenaltyContact doesn't
// map well the contact points because o->baryCoords is used ant not initialized. It means that
// the mapped contact point is random ! So I replaced addPointB by addPoint to make it work.
// Create mapping for first point
// index1 = mapper1.addPointB(o->point[0], index1, r1
//#ifdef DETECTIONOUTPUT_BARYCENTRICINFO
// , o->baryCoords[0]
//#endif
// );
index1 = mapper1.addPoint(o->point[0], index1, r1);
// Create mapping for second point
// index2 = mapper2.addPointB(o->point[1], index2, r2
//#ifdef DETECTIONOUTPUT_BARYCENTRICINFO
// , o->baryCoords[1]
//#endif
// );
index2 = mapper2.addPoint(o->point[1], index2, r2);
double distance = d0 + r1 + r2;
double stiffness = (elem1.getContactStiffness() * elem2.getContactStiffness());
if (distance != 0.0) stiffness /= distance;
double mu_v = (elem1.getContactFriction() + elem2.getContactFriction());
ff->addContact(index1, index2, elem1.getIndex(), elem2.getIndex(), o->normal, distance, stiffness, mu_v/* *distance */, mu_v, index);
}
// Update mappings
mapper1.update();
mapper2.update();
}
template < class TCollisionModel1, class TCollisionModel2, class ResponseDataTypes >
void BarycentricPenalityContact<TCollisionModel1,TCollisionModel2,ResponseDataTypes>::createResponse(core::objectmodel::BaseContext* group)
{
if (ff!=NULL)
{
if (parent!=NULL)
{
parent->removeObject(this);
parent->removeObject(ff);
}
parent = group;
if (parent!=NULL)
{
//sout << "Attaching contact response to "<<parent->getName()<<sendl;
parent->addObject(this);
parent->addObject(ff);
}
}
}
template < class TCollisionModel1, class TCollisionModel2, class ResponseDataTypes >
void BarycentricPenalityContact<TCollisionModel1,TCollisionModel2,ResponseDataTypes>::removeResponse()
{
if (ff!=NULL)
{
if (parent!=NULL)
{
//sout << "Removing contact response from "<<parent->getName()<<sendl;
parent->removeObject(this);
parent->removeObject(ff);
}
parent = NULL;
}
}
template < class TCollisionModel1, class TCollisionModel2, class ResponseDataTypes >
void BarycentricPenalityContact<TCollisionModel1,TCollisionModel2,ResponseDataTypes>::draw(const core::visual::VisualParams* )
{
// if (ff!=NULL)
// ff->draw(vparams);
}
template < class TCollisionModel1, class TCollisionModel2, class ResponseDataTypes >
void BarycentricPenalityContact<TCollisionModel1,TCollisionModel2,ResponseDataTypes>::setInteractionTags(MechanicalState1* mstate1, MechanicalState2* mstate2)
{
TagSet tagsm1 = mstate1->getTags();
TagSet tagsm2 = mstate2->getTags();
TagSet::iterator it;
for(it=tagsm1.begin(); it != tagsm1.end(); it++)
ff->addTag(*it);
for(it=tagsm2.begin(); it!=tagsm2.end(); it++)
ff->addTag(*it);
}
} // namespace collision
} // namespace component
} // namespace sofa
#endif
<commit_msg>FIX: SofaMeshCollision compilation<commit_after>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *
* (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: [email protected] *
******************************************************************************/
#ifndef SOFA_COMPONENT_COLLISION_BARYCENTRICPENALITYCONTACT_INL
#define SOFA_COMPONENT_COLLISION_BARYCENTRICPENALITYCONTACT_INL
#include <SofaMeshCollision/BarycentricPenalityContact.h>
#include <sofa/core/visual/VisualParams.h>
#include <SofaMeshCollision/RigidContactMapper.inl>
namespace sofa
{
namespace component
{
namespace collision
{
using namespace sofa::defaulttype;
using namespace core::collision;
template < class TCollisionModel1, class TCollisionModel2, class ResponseDataTypes >
BarycentricPenalityContact<TCollisionModel1,TCollisionModel2,ResponseDataTypes>::BarycentricPenalityContact(CollisionModel1* _model1, CollisionModel2* _model2, Intersection* _intersectionMethod)
: model1(_model1), model2(_model2), intersectionMethod(_intersectionMethod), ff(NULL), parent(NULL)
{
mapper1.setCollisionModel(model1);
mapper2.setCollisionModel(model2);
}
template < class TCollisionModel1, class TCollisionModel2, class ResponseDataTypes >
BarycentricPenalityContact<TCollisionModel1,TCollisionModel2,ResponseDataTypes>::~BarycentricPenalityContact()
{
}
template < class TCollisionModel1, class TCollisionModel2, class ResponseDataTypes >
void BarycentricPenalityContact<TCollisionModel1,TCollisionModel2,ResponseDataTypes>::cleanup()
{
if (ff!=NULL)
{
ff->cleanup();
if (parent!=NULL) parent->removeObject(ff);
//delete ff;
parent = NULL;
ff = NULL;
mapper1.cleanup();
mapper2.cleanup();
}
}
template < class TCollisionModel1, class TCollisionModel2, class ResponseDataTypes >
void BarycentricPenalityContact<TCollisionModel1,TCollisionModel2,ResponseDataTypes>::setDetectionOutputs(OutputVector* o)
{
TOutputVector& outputs = *static_cast<TOutputVector*>(o);
const bool printLog = this->f_printLog.getValue();
if (ff==NULL)
{
MechanicalState1* mstate1 = mapper1.createMapping();
MechanicalState2* mstate2 = mapper2.createMapping();
ff = sofa::core::objectmodel::New<ResponseForceField>(mstate1,mstate2);
ff->setName( getName() );
setInteractionTags(mstate1, mstate2);
ff->init();
#ifdef SOFA_SMP
ff->setPartition(mstate1->getPartition());
#endif
}
int insize = outputs.size();
// old index for each contact
// >0 indicate preexisting contact
// 0 indicate new contact
// -1 indicate ignored duplicate contact
std::vector<int> oldIndex(insize);
int nbnew = 0;
for (int i=0; i<insize; i++)
{
DetectionOutput* o = &outputs[i];
// find this contact in contactIndex, possibly creating a new entry initialized by 0
int& index = contactIndex[o->id];
if (index < 0) // duplicate contact
{
int i2 = -1-index;
DetectionOutput* o2 = &outputs[i2];
if (o2->value <= o->value)
{
// current contact is ignored
oldIndex[i] = -1;
continue;
}
else
{
// previous contact is replaced
oldIndex[i] = oldIndex[i2];
oldIndex[i2] = -1;
}
}
else
{
oldIndex[i] = index;
if (!index)
{
++nbnew;
if (printLog) sout << "BarycentricPenalityContact: New contact "<<o->id<<sendl;
}
}
index = -1-i; // save this index as a negative value in contactIndex map.
}
// compute new index of each contact
std::vector<int> newIndex(insize);
// number of final contacts used in the response
int size = 0;
for (int i=0; i<insize; i++)
{
if (oldIndex[i] >= 0)
{
++size;
newIndex[i] = size;
}
}
// update contactMap
for (ContactIndexMap::iterator it = contactIndex.begin(), itend = contactIndex.end(); it != itend; )
{
int& index = it->second;
if (index >= 0)
{
if (printLog) sout << "BarycentricPenalityContact: Removed contact "<<it->first<<sendl;
ContactIndexMap::iterator oldit = it;
++it;
contactIndex.erase(oldit);
}
else
{
index = newIndex[-1-index]; // write the final contact index
++it;
}
}
if (printLog) sout << "BarycentricPenalityContact: "<<insize<<" input contacts, "<<size<<" contacts used for response ("<<nbnew<<" new)."<<sendl;
//int size = contacts.size();
ff->clear(size);
mapper1.resize(size);
mapper2.resize(size);
//int i = 0;
const double d0 = intersectionMethod->getContactDistance() + model1->getProximity() + model2->getProximity(); // - 0.001;
//for (std::vector<DetectionOutput>::iterator it = outputs.begin(); it!=outputs.end(); it++)
//{
// DetectionOutput* o = &*it;
for (int i=0; i<insize; i++)
{
int index = oldIndex[i];
if (index < 0) continue; // this contact is ignored
DetectionOutput* o = &outputs[i];
CollisionElement1 elem1(o->elem.first);
CollisionElement2 elem2(o->elem.second);
int index1 = elem1.getIndex();
int index2 = elem2.getIndex();
typename DataTypes1::Real r1 = 0.0;
typename DataTypes2::Real r2 = 0.0;
// Just make it work, some changes have been done in rev 10382 so that BarycentricPenaltyContact doesn't
// map well the contact points because o->baryCoords is used ant not initialized. It means that
// the mapped contact point is random ! So I replaced addPointB by addPoint to make it work.
// Create mapping for first point
// index1 = mapper1.addPointB(o->point[0], index1, r1
//#ifdef DETECTIONOUTPUT_BARYCENTRICINFO
// , o->baryCoords[0]
//#endif
// );
index1 = mapper1.addPoint(o->point[0], index1, r1);
// Create mapping for second point
// index2 = mapper2.addPointB(o->point[1], index2, r2
//#ifdef DETECTIONOUTPUT_BARYCENTRICINFO
// , o->baryCoords[1]
//#endif
// );
index2 = mapper2.addPoint(o->point[1], index2, r2);
double distance = d0 + r1 + r2;
double stiffness = (elem1.getContactStiffness() * elem2.getContactStiffness());
if (distance != 0.0) stiffness /= distance;
double mu_v = (elem1.getContactFriction() + elem2.getContactFriction());
ff->addContact(index1, index2, elem1.getIndex(), elem2.getIndex(), o->normal, distance, stiffness, mu_v/* *distance */, mu_v, index);
}
// Update mappings
mapper1.update();
mapper2.update();
}
template < class TCollisionModel1, class TCollisionModel2, class ResponseDataTypes >
void BarycentricPenalityContact<TCollisionModel1,TCollisionModel2,ResponseDataTypes>::createResponse(core::objectmodel::BaseContext* group)
{
if (ff!=NULL)
{
if (parent!=NULL)
{
parent->removeObject(this);
parent->removeObject(ff);
}
parent = group;
if (parent!=NULL)
{
//sout << "Attaching contact response to "<<parent->getName()<<sendl;
parent->addObject(this);
parent->addObject(ff);
}
}
}
template < class TCollisionModel1, class TCollisionModel2, class ResponseDataTypes >
void BarycentricPenalityContact<TCollisionModel1,TCollisionModel2,ResponseDataTypes>::removeResponse()
{
if (ff!=NULL)
{
if (parent!=NULL)
{
//sout << "Removing contact response from "<<parent->getName()<<sendl;
parent->removeObject(this);
parent->removeObject(ff);
}
parent = NULL;
}
}
template < class TCollisionModel1, class TCollisionModel2, class ResponseDataTypes >
void BarycentricPenalityContact<TCollisionModel1,TCollisionModel2,ResponseDataTypes>::draw(const core::visual::VisualParams* )
{
// if (ff!=NULL)
// ff->draw(vparams);
}
template < class TCollisionModel1, class TCollisionModel2, class ResponseDataTypes >
void BarycentricPenalityContact<TCollisionModel1,TCollisionModel2,ResponseDataTypes>::setInteractionTags(MechanicalState1* mstate1, MechanicalState2* mstate2)
{
sofa::core::objectmodel::TagSet tagsm1 = mstate1->getTags();
sofa::core::objectmodel::TagSet tagsm2 = mstate2->getTags();
sofa::core::objectmodel::TagSet::iterator it;
for(it=tagsm1.begin(); it != tagsm1.end(); it++)
ff->addTag(*it);
for(it=tagsm2.begin(); it!=tagsm2.end(); it++)
ff->addTag(*it);
}
} // namespace collision
} // namespace component
} // namespace sofa
#endif
<|endoftext|> |
<commit_before>// Illustrates the advantages of a TH1K histogram
//Author: Victor Perevovchikov
void padRefresh(TPad *pad,int flag=0);
void hksimple()
{
// Create a new canvas.
c1 = new TCanvas("c1","Dynamic Filling Example",200,10,600,900);
c1->SetFillColor(42);
// Create a normal histogram and two TH1K histograms
TH1 *hpx[3];
hpx[0] = new TH1F("hp0","Normal histogram",1000,-4,4);
hpx[1] = new TH1K("hk1","Nearest Neighboor of order 3",1000,-4,4);
hpx[2] = new TH1K("hk2","Nearest Neighboor of order 16",1000,-4,4,16);
c1->Divide(1,3);
Int_t j;
for (j=0;j<3;j++) {
c1->cd(j+1);
gPad->SetFrameFillColor(33);
hpx[j]->SetFillColor(48);
hpx[j]->Draw();
}
// Fill histograms randomly
gRandom->SetSeed();
Float_t px, py, pz;
const Int_t kUPDATE = 10;
for (Int_t i = 0; i <= 300; i++) {
gRandom->Rannor(px,py);
for (j=0;j<3;j++) {hpx[j]->Fill(px);}
if (i && (i%kUPDATE) == 0) {
padRefresh(c1);
}
}
for (j=0;j<3;j++) hpx[j]->Fit("gaus");
padRefresh(c1);
}
void padRefresh(TPad *pad,int flag)
{
if (!pad) return;
pad->Modified();
pad->Update();
TList *tl = pad->GetListOfPrimitives();
if (!tl) return;
TListIter next(tl);
TObject *to;
while ((to=next())) {
if (to->InheritsFrom(TPad::Class())) padRefresh((TPad*)to,1);}
if (flag) return;
gSystem->ProcessEvents();
}
<commit_msg>spelling<commit_after>// Illustrates the advantages of a TH1K histogram
//Author: Victor Perevovchikov
void padRefresh(TPad *pad,int flag=0);
void hksimple()
{
// Create a new canvas.
c1 = new TCanvas("c1","Dynamic Filling Example",200,10,600,900);
c1->SetFillColor(42);
// Create a normal histogram and two TH1K histograms
TH1 *hpx[3];
hpx[0] = new TH1F("hp0","Normal histogram",1000,-4,4);
hpx[1] = new TH1K("hk1","Nearest Neighbor of order 3",1000,-4,4);
hpx[2] = new TH1K("hk2","Nearest Neighbor of order 16",1000,-4,4,16);
c1->Divide(1,3);
Int_t j;
for (j=0;j<3;j++) {
c1->cd(j+1);
gPad->SetFrameFillColor(33);
hpx[j]->SetFillColor(48);
hpx[j]->Draw();
}
// Fill histograms randomly
gRandom->SetSeed();
Float_t px, py, pz;
const Int_t kUPDATE = 10;
for (Int_t i = 0; i <= 300; i++) {
gRandom->Rannor(px,py);
for (j=0;j<3;j++) {hpx[j]->Fill(px);}
if (i && (i%kUPDATE) == 0) {
padRefresh(c1);
}
}
for (j=0;j<3;j++) hpx[j]->Fit("gaus");
padRefresh(c1);
}
void padRefresh(TPad *pad,int flag)
{
if (!pad) return;
pad->Modified();
pad->Update();
TList *tl = pad->GetListOfPrimitives();
if (!tl) return;
TListIter next(tl);
TObject *to;
while ((to=next())) {
if (to->InheritsFrom(TPad::Class())) padRefresh((TPad*)to,1);}
if (flag) return;
gSystem->ProcessEvents();
}
<|endoftext|> |
<commit_before>#include <isl/set.h>
#include <isl/union_map.h>
#include <isl/union_set.h>
#include <isl/ast_build.h>
#include <isl/schedule.h>
#include <isl/schedule_node.h>
#include <tiramisu/debug.h>
#include <tiramisu/core.h>
#include <string.h>
#include <Halide.h>
#include "halide_image_io.h"
/* Halide code for matrix multiplication.
Func matmul(Input A, Input B, Output C) {
Halide::Func A, B, C;
Halide::Var x, y;
Halide::RDom r(0, N);
C(x,y) = C(x,y) + A(x,r) * B(r,y);
C.realize(N, N);
}
*/
#define SIZE0 1000
using namespace tiramisu;
int main(int argc, char **argv)
{
// Set default tiramisu options.
global::set_default_tiramisu_options();
global::set_loop_iterator_type(p_int32);
// -------------------------------------------------------
// Layer I
// -------------------------------------------------------
/*
* Declare a function matmul.
* Declare two arguments (tiramisu buffers) for the function: b_A and b_B
* Declare an invariant for the function.
*/
function matmul("matmul");
constant p0("N", expr((int32_t) SIZE0), p_int32, true, NULL, 0, &matmul);
// Declare a computation c_A that represents a binding to the buffer b_A
computation c_A("[N]->{c_A[i,j]: 0<=i<N and 0<=j<N}", expr(), false, p_uint8, &matmul);
// Declare a computation c_B that represents a binding to the buffer b_B
computation c_B("[N]->{c_B[i,j]: 0<=i<N and 0<=j<N}", expr(), false, p_uint8, &matmul);
// Indices
var i = var("i");
var j = var("j");
var k = var("k");
// Declare a computation c_C
computation c_C("[N]->{c_C[i,j,0]: 0<=i<N and 0<=j<N}", expr((uint8_t) 0), true, p_uint8, &matmul);
c_C.add_definitions("[N]->{c_C[i,j,k]: 0<=i<N and 0<=j<N and 0<=k<N}", expr(),
true, p_uint8, &matmul);
expr e1 = c_C(i, j, k - 1) + c_A(i, k) * c_B(k, j);
c_C.get_update(1).set_expression(e1);
// -------------------------------------------------------
// Layer II
// -------------------------------------------------------
// Set the schedule of each computation.
// The identity schedule means that the program order is not modified
// (i.e. no optimization is applied).
c_C.get_update(1).after(c_C, var("j"));
c_C.tile(var("i"), var("j"), 32, 32, var("i0"), var("j0"), var("i1"), var("j1"));
c_C.get_update(1).tile(var("i"), var("j"), 32, 32, var("i0"), var("j0"), var("i1"), var("j1"));
c_C.get_update(1).tag_parallel_level(var("i0"));
// -------------------------------------------------------
// Layer III
// -------------------------------------------------------
buffer b_A("b_A", {tiramisu::expr(SIZE0), tiramisu::expr(SIZE0)}, p_uint8, a_input, &matmul);
buffer b_B("b_B", {tiramisu::expr(SIZE0), tiramisu::expr(SIZE0)}, p_uint8, a_input, &matmul);
buffer b_C("b_C", {tiramisu::expr(SIZE0), tiramisu::expr(SIZE0)}, p_uint8, a_output, &matmul);
// Map the computations to a buffer.
c_A.set_access("{c_A[i,j]->b_A[i,j]}");
c_B.set_access("{c_B[i,j]->b_B[i,j]}");
c_C.set_access("{c_C[i,j,k]->b_C[i,j]}");
c_C.get_update(1).set_access("{c_C[i,j,k]->b_C[i,j]}");
// -------------------------------------------------------
// Code Generation
// -------------------------------------------------------
// Set the arguments to blurxy
matmul.set_arguments({&b_A, &b_B, &b_C});
// Generate code
matmul.gen_time_space_domain();
matmul.gen_isl_ast();
matmul.gen_halide_stmt();
matmul.gen_halide_obj("build/generated_fct_tutorial_03.o");
// Some debugging
matmul.dump_iteration_domain();
matmul.dump_halide_stmt();
// Dump all the fields of the blurxy class.
matmul.dump(true);
return 0;
}
<commit_msg>Update tutorial_03.cpp<commit_after>#include <isl/set.h>
#include <isl/union_map.h>
#include <isl/union_set.h>
#include <isl/ast_build.h>
#include <isl/schedule.h>
#include <isl/schedule_node.h>
#include <tiramisu/debug.h>
#include <tiramisu/core.h>
#include <string.h>
#include <Halide.h>
#include "halide_image_io.h"
/* Halide code for matrix multiplication.
Func matmul(Input A, Input B, Output C) {
Halide::Func A, B, C;
Halide::Var x, y;
Halide::RDom r(0, N);
C(x,y) = C(x,y) + A(x,r) * B(r,y);
C.realize(N, N);
}
*/
#define SIZE0 1000
using namespace tiramisu;
int main(int argc, char **argv)
{
// Set default tiramisu options.
global::set_default_tiramisu_options();
// -------------------------------------------------------
// Layer I
// -------------------------------------------------------
/*
* Declare a function matmul.
* Declare two arguments (tiramisu buffers) for the function: b_A and b_B
* Declare an invariant for the function.
*/
function matmul("matmul");
constant p0("N", expr((int32_t) SIZE0), p_int32, true, NULL, 0, &matmul);
// Declare a computation c_A that represents a binding to the buffer b_A
computation c_A("[N]->{c_A[i,j]: 0<=i<N and 0<=j<N}", expr(), false, p_uint8, &matmul);
// Declare a computation c_B that represents a binding to the buffer b_B
computation c_B("[N]->{c_B[i,j]: 0<=i<N and 0<=j<N}", expr(), false, p_uint8, &matmul);
// Indices
var i = var("i");
var j = var("j");
var k = var("k");
// Declare a computation c_C
computation c_C("[N]->{c_C[i,j,0]: 0<=i<N and 0<=j<N}", expr((uint8_t) 0), true, p_uint8, &matmul);
c_C.add_definitions("[N]->{c_C[i,j,k]: 0<=i<N and 0<=j<N and 0<=k<N}", expr(),
true, p_uint8, &matmul);
expr e1 = c_C(i, j, k - 1) + c_A(i, k) * c_B(k, j);
c_C.get_update(1).set_expression(e1);
// -------------------------------------------------------
// Layer II
// -------------------------------------------------------
// Set the schedule of each computation.
// The identity schedule means that the program order is not modified
// (i.e. no optimization is applied).
c_C.get_update(1).after(c_C, var("j"));
c_C.tile(var("i"), var("j"), 32, 32, var("i0"), var("j0"), var("i1"), var("j1"));
c_C.get_update(1).tile(var("i"), var("j"), 32, 32, var("i0"), var("j0"), var("i1"), var("j1"));
c_C.get_update(1).tag_parallel_level(var("i0"));
// -------------------------------------------------------
// Layer III
// -------------------------------------------------------
buffer b_A("b_A", {tiramisu::expr(SIZE0), tiramisu::expr(SIZE0)}, p_uint8, a_input, &matmul);
buffer b_B("b_B", {tiramisu::expr(SIZE0), tiramisu::expr(SIZE0)}, p_uint8, a_input, &matmul);
buffer b_C("b_C", {tiramisu::expr(SIZE0), tiramisu::expr(SIZE0)}, p_uint8, a_output, &matmul);
// Map the computations to a buffer.
c_A.set_access("{c_A[i,j]->b_A[i,j]}");
c_B.set_access("{c_B[i,j]->b_B[i,j]}");
c_C.set_access("{c_C[i,j,k]->b_C[i,j]}");
c_C.get_update(1).set_access("{c_C[i,j,k]->b_C[i,j]}");
// -------------------------------------------------------
// Code Generation
// -------------------------------------------------------
// Set the arguments to blurxy
matmul.set_arguments({&b_A, &b_B, &b_C});
// Generate code
matmul.gen_time_space_domain();
matmul.gen_isl_ast();
matmul.gen_halide_stmt();
matmul.gen_halide_obj("build/generated_fct_tutorial_03.o");
// Some debugging
matmul.dump_iteration_domain();
matmul.dump_halide_stmt();
// Dump all the fields of the blurxy class.
matmul.dump(true);
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>Made it possible to disable auto-import of lib-file.<commit_after><|endoftext|> |
<commit_before>#include "AliAnalysisTaskSEXicTopKpi.h"
#include "AliAnalysisManager.h"
#include "TFile.h"
#include "AliAnalysisDataContainer.h"
#include "TChain.h"
AliAnalysisTaskSEXicTopKpi *AddTaskSEXicTopKpi(Bool_t readMC=kFALSE,
Int_t system=0/*0=pp,1=PbPb*/,
Float_t minC=0, Float_t maxC=0,
TString finDirname="",
TString finname="",TString finObjname="D0toKpiCuts",TString strLcCutFile="",TString strLcCutObjName="")
{
//
// AddTask for the AliAnalysisTaskSE for D0 candidates
// invariant mass histogram and association with MC truth
// (using MC info in AOD) and cut variables distributions
// C.Bianchin [email protected]
//
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskD0Distr", "No analysis manager to connect to.");
return NULL;
}
TString filename="",out1name="", out2name="", out3name="",inname="";
filename = AliAnalysisManager::GetCommonFileName();
filename += ":PWG3_D2H_";
filename+="XicpKpi";
out1name="entriesHisto";
//AliNormalizationCounter
out2name="normalizationCounter";
out3name="outputList";
inname="cinputmassD0_1";
inname += finDirname.Data();
//setting my cut values
//cuts order
// printf(" |M-MD0| [GeV] < %f\n",fD0toKpiCuts[0]);
// printf(" dca [cm] < %f\n",fD0toKpiCuts[1]);
// printf(" cosThetaStar < %f\n",fD0toKpiCuts[2]);
// printf(" pTK [GeV/c] > %f\n",fD0toKpiCuts[3]);
// printf(" pTpi [GeV/c] > %f\n",fD0toKpiCuts[4]);
// printf(" |d0K| [cm] < %f\n",fD0toKpiCuts[5]);
// printf(" |d0pi| [cm] < %f\n",fD0toKpiCuts[6]);
// printf(" d0d0 [cm^2] < %f\n",fD0toKpiCuts[7]);
// printf(" cosThetaPoint > %f\n",fD0toKpiCuts[8]);
TFile* filecuts;
Printf("Opening file %s",finname.Data());
filecuts=TFile::Open(finname.Data());
if(!filecuts ||(filecuts&& !filecuts->IsOpen())){
::Fatal("AddTaskXictopKpi", "Input file not found : check your cut object");
}
AliRDHFCutsD0toKpi* RDHFD0toKpi=new AliRDHFCutsD0toKpi();
RDHFD0toKpi = (AliRDHFCutsD0toKpi*)filecuts->Get(finObjname.Data());
if(!RDHFD0toKpi){
::Fatal("AddTaskD0Mass", "Specific AliRDHFCuts not found");
return NULL;
}
if(minC!=0 && maxC!=0) { //if centrality 0 and 0 leave the values in the cut object
RDHFD0toKpi->SetMinCentrality(minC);
RDHFD0toKpi->SetMaxCentrality(maxC);
}
// RDHFD0toKpi->SetName(Form("D0toKpiCuts%d",flag));
TString centr="";
if(minC!=0 && maxC!=0) centr = Form("%.0f%.0f",minC,maxC);
else centr = Form("%.0f%.0f",RDHFD0toKpi->GetMinCentrality(),RDHFD0toKpi->GetMaxCentrality());
out1name+=centr;
inname+=centr;
// Aanalysis task
TString taskname="XicPkPiMassAndDistrAnalysis";
AliAnalysisTaskSEXicTopKpi *massXicTask = new AliAnalysisTaskSEXicTopKpi(taskname.Data(),RDHFD0toKpi);
massXicTask->SetDebugLevel(-1);
massXicTask->SetReadMC(readMC);
massXicTask->SetSystem(system); //0=pp, 1=pPb, 2=PbPb
massXicTask->SetUseLcTrackFilteringCut(kTRUE);
massXicTask->SetMaxPtSPDkFirst(kTRUE,1.);
//massXicTask->SetFillTree(2); // moved in RunAnalysis (i.e.: macro customization)
massXicTask->SetMaxChi2Cut(1.5);
if(!strLcCutFile.IsNull()){
TFile *flc=TFile::Open(strLcCutFile.Data(),"READ");
if(!flc){
Printf("Wrong file for Lc cuts");
return 0x0;
}
AliRDHFCutsLctopKpi* cutsLc=(AliRDHFCutsLctopKpi*)flc->Get(strLcCutObjName.Data());
if(!cutsLc){
Printf("Wrong object name for Lc cuts");
return 0x0;
}
massXicTask->SetLcCuts(cutsLc);
}
if(system==0){
massXicTask->SetRecalcOwnPrimVtx(kTRUE);
}
// massXicTask->SetAODMismatchProtection(AODProtection);
// massD0Task->SetRejectSDDClusters(kTRUE);
// massD0Task->SetWriteVariableTree(kTRUE);
mgr->AddTask(massXicTask);
//
// Create containers for input/output
AliAnalysisDataContainer *cinputmass = mgr->CreateContainer(inname,TChain::Class(),
AliAnalysisManager::kInputContainer);
AliAnalysisDataContainer *coutputmass1 = mgr->CreateContainer(out1name,TH1F::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //mass
// AliAnalysisDataContainer *coutputmassD04 = mgr->CreateContainer(out4name,AliRDHFCutsD0toKpi::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //cuts
AliAnalysisDataContainer *coutputmass2 = mgr->CreateContainer(out2name,AliNormalizationCounter::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //counter
AliAnalysisDataContainer *coutputmass3 = mgr->CreateContainer(out3name,TList::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //counter
mgr->ConnectInput(massXicTask,0,mgr->GetCommonInputContainer());
mgr->ConnectOutput(massXicTask,1,coutputmass1);
mgr->ConnectOutput(massXicTask,2,coutputmass2);
mgr->ConnectOutput(massXicTask,3,coutputmass3);
return massXicTask;
}
<commit_msg>Adding ifded CLING protenction for header inclusion in AddTaskSEXicTopKpi.C<commit_after>#if !defined (__CINT__) || defined (__CLING__)
#include "AliAnalysisTaskSEXicTopKpi.h"
#include "AliAnalysisManager.h"
#include "TFile.h"
#include "AliAnalysisDataContainer.h"
#include "TChain.h"
#endif
AliAnalysisTaskSEXicTopKpi *AddTaskSEXicTopKpi(Bool_t readMC=kFALSE,
Int_t system=0/*0=pp,1=PbPb*/,
Float_t minC=0, Float_t maxC=0,
TString finDirname="",
TString finname="",TString finObjname="D0toKpiCuts",TString strLcCutFile="",TString strLcCutObjName="")
{
//
// AddTask for the AliAnalysisTaskSE for D0 candidates
// invariant mass histogram and association with MC truth
// (using MC info in AOD) and cut variables distributions
// C.Bianchin [email protected]
//
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskD0Distr", "No analysis manager to connect to.");
return NULL;
}
TString filename="",out1name="", out2name="", out3name="",inname="";
filename = AliAnalysisManager::GetCommonFileName();
filename += ":PWG3_D2H_";
filename+="XicpKpi";
out1name="entriesHisto";
//AliNormalizationCounter
out2name="normalizationCounter";
out3name="outputList";
inname="cinputmassD0_1";
inname += finDirname.Data();
//setting my cut values
//cuts order
// printf(" |M-MD0| [GeV] < %f\n",fD0toKpiCuts[0]);
// printf(" dca [cm] < %f\n",fD0toKpiCuts[1]);
// printf(" cosThetaStar < %f\n",fD0toKpiCuts[2]);
// printf(" pTK [GeV/c] > %f\n",fD0toKpiCuts[3]);
// printf(" pTpi [GeV/c] > %f\n",fD0toKpiCuts[4]);
// printf(" |d0K| [cm] < %f\n",fD0toKpiCuts[5]);
// printf(" |d0pi| [cm] < %f\n",fD0toKpiCuts[6]);
// printf(" d0d0 [cm^2] < %f\n",fD0toKpiCuts[7]);
// printf(" cosThetaPoint > %f\n",fD0toKpiCuts[8]);
TFile* filecuts;
Printf("Opening file %s",finname.Data());
filecuts=TFile::Open(finname.Data());
if(!filecuts ||(filecuts&& !filecuts->IsOpen())){
::Fatal("AddTaskXictopKpi", "Input file not found : check your cut object");
}
AliRDHFCutsD0toKpi* RDHFD0toKpi=new AliRDHFCutsD0toKpi();
RDHFD0toKpi = (AliRDHFCutsD0toKpi*)filecuts->Get(finObjname.Data());
if(!RDHFD0toKpi){
::Fatal("AddTaskD0Mass", "Specific AliRDHFCuts not found");
return NULL;
}
if(minC!=0 && maxC!=0) { //if centrality 0 and 0 leave the values in the cut object
RDHFD0toKpi->SetMinCentrality(minC);
RDHFD0toKpi->SetMaxCentrality(maxC);
}
// RDHFD0toKpi->SetName(Form("D0toKpiCuts%d",flag));
TString centr="";
if(minC!=0 && maxC!=0) centr = Form("%.0f%.0f",minC,maxC);
else centr = Form("%.0f%.0f",RDHFD0toKpi->GetMinCentrality(),RDHFD0toKpi->GetMaxCentrality());
out1name+=centr;
inname+=centr;
// Aanalysis task
TString taskname="XicPkPiMassAndDistrAnalysis";
AliAnalysisTaskSEXicTopKpi *massXicTask = new AliAnalysisTaskSEXicTopKpi(taskname.Data(),RDHFD0toKpi);
massXicTask->SetDebugLevel(-1);
massXicTask->SetReadMC(readMC);
massXicTask->SetSystem(system); //0=pp, 1=pPb, 2=PbPb
massXicTask->SetUseLcTrackFilteringCut(kTRUE);
massXicTask->SetMaxPtSPDkFirst(kTRUE,1.);
//massXicTask->SetFillTree(2); // moved in RunAnalysis (i.e.: macro customization)
massXicTask->SetMaxChi2Cut(1.5);
if(!strLcCutFile.IsNull()){
TFile *flc=TFile::Open(strLcCutFile.Data(),"READ");
if(!flc){
Printf("Wrong file for Lc cuts");
return 0x0;
}
AliRDHFCutsLctopKpi* cutsLc=(AliRDHFCutsLctopKpi*)flc->Get(strLcCutObjName.Data());
if(!cutsLc){
Printf("Wrong object name for Lc cuts");
return 0x0;
}
massXicTask->SetLcCuts(cutsLc);
}
if(system==0){
massXicTask->SetRecalcOwnPrimVtx(kTRUE);
}
// massXicTask->SetAODMismatchProtection(AODProtection);
// massD0Task->SetRejectSDDClusters(kTRUE);
// massD0Task->SetWriteVariableTree(kTRUE);
mgr->AddTask(massXicTask);
//
// Create containers for input/output
AliAnalysisDataContainer *cinputmass = mgr->CreateContainer(inname,TChain::Class(),
AliAnalysisManager::kInputContainer);
AliAnalysisDataContainer *coutputmass1 = mgr->CreateContainer(out1name,TH1F::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //mass
// AliAnalysisDataContainer *coutputmassD04 = mgr->CreateContainer(out4name,AliRDHFCutsD0toKpi::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //cuts
AliAnalysisDataContainer *coutputmass2 = mgr->CreateContainer(out2name,AliNormalizationCounter::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //counter
AliAnalysisDataContainer *coutputmass3 = mgr->CreateContainer(out3name,TList::Class(),AliAnalysisManager::kOutputContainer, filename.Data()); //counter
mgr->ConnectInput(massXicTask,0,mgr->GetCommonInputContainer());
mgr->ConnectOutput(massXicTask,1,coutputmass1);
mgr->ConnectOutput(massXicTask,2,coutputmass2);
mgr->ConnectOutput(massXicTask,3,coutputmass3);
return massXicTask;
}
<|endoftext|> |
<commit_before>#ifndef __RIGID_BODY_HPP__
#define __RIGID_BODY_HPP__
#include <btBulletDynamicsCommon.h>
#include <Components/Component.hh>
#include "Utils/SmartPointer.hh"
#include <Entities/EntityData.hh>
#include <Entities/Entity.hh>
#include <Core/Engine.hh>
#include <ResourceManager/ResourceManager.hh>
#include <ResourceManager/SharedMesh.hh>
#include <Managers/BulletDynamicManager.hpp>
#include "BulletCollision/CollisionShapes/btShapeHull.h"
#include <hacdHACD.h>
#include <Utils/BtConversion.hpp>
#include <Utils/MatrixConversion.hpp>
namespace Component
{
ATTRIBUTE_ALIGNED16(struct) RigidBody : public Component::ComponentBase<RigidBody>
{
BT_DECLARE_ALIGNED_ALLOCATOR();
typedef enum
{
SPHERE,
BOX,
MESH,
CONCAVE_STATIC_MESH,
UNDEFINED
} CollisionShape;
RigidBody()
: ComponentBase(),
_manager(nullptr),
shapeType(UNDEFINED),
mass(0.0f),
inertia(btVector3(0.0f, 0.0f, 0.0f)),
rotationConstraint(glm::vec3(1,1,1)),
transformConstraint(glm::vec3(1,1,1)),
meshName(""),
_collisionShape(nullptr),
_motionState(nullptr),
_rigidBody(nullptr)
{
}
void init(float _mass = 1.0f)
{
_manager = dynamic_cast<BulletDynamicManager*>(&_entity->getScene()->getEngine().getInstance<BulletCollisionManager>());
assert(_manager != nullptr);
mass = _mass;
}
virtual void reset()
{
if (_rigidBody != nullptr)
{
_manager->getWorld()->removeRigidBody(_rigidBody);
delete _rigidBody;
_rigidBody = nullptr;
}
if (_motionState != nullptr)
{
delete _motionState;
_motionState = nullptr;
}
if (_collisionShape != nullptr)
{
delete _collisionShape;
_collisionShape = nullptr;
}
shapeType = UNDEFINED;
mass = 0.0f;
inertia = btVector3(0.0f, 0.0f, 0.0f);
rotationConstraint = glm::vec3(1, 1, 1);
transformConstraint = glm::vec3(1, 1, 1);
}
btMotionState &getMotionState()
{
assert(_motionState != nullptr && "Motion state is NULL, RigidBody error. Tips : Have you setAcollisionShape to Component ?.");
return *_motionState;
}
btCollisionShape &getShape()
{
assert(_collisionShape != nullptr && "Shape is NULL, RigidBody error. Tips : Have you setAcollisionShape to Component ?.");
return *_collisionShape;
}
btRigidBody &getBody()
{
assert(_rigidBody != nullptr && "RigidBody is NULL. Tips : Have you setAcollisionShape to Component ?.");
return *_rigidBody;
}
void setMass(float mass)
{
mass = btScalar(mass);
}
void setInertia(btVector3 const &v)
{
inertia = v;
}
void setCollisionShape(CollisionShape c, const std::string &_meshName = "")
{
if (c == UNDEFINED)
return;
meshName = _meshName;
_reset();
shapeType = c;
btTransform transform;
glm::vec3 position = posFromMat4(_entity->getLocalTransform());
glm::vec3 scale = scaleFromMat4(_entity->getLocalTransform());
std::cout << scale.x << " " << scale.y << " " << scale.z << std::endl;
glm::vec3 rot = rotFromMat4(_entity->getLocalTransform(), true);
transform.setIdentity();
transform.setOrigin(convertGLMVectorToBullet(position));
transform.setRotation(btQuaternion(rot.x, rot.y, rot.z));
_motionState = new btDefaultMotionState(transform);
if (c == BOX)
{
_collisionShape = new btBoxShape(btVector3(0.5, 0.5, 0.5));//new btBoxShape(halfScale);
}
else if (c == SPHERE)
{
_collisionShape = new btSphereShape(0.5);//new btSphereShape(scale.x);
}
else if (c == MESH)
{
// THERE IS SOME LEAKS BECAUSE THAT'S TEMPORARY
SmartPointer<Resources::SharedMesh> mesh = _entity->getScene()->getEngine().getInstance<Resources::ResourceManager>().getResource(meshName);
auto group = new btCompoundShape();
auto &geos = mesh->getGeometry();
for (unsigned int i = 0; i < geos.size(); ++i)
{
const Resources::Geometry &geo = geos[i]; // DIRTY HACK TEMPORARY
// NEED TO REPLACE MESH BY MESH GROUP !
btScalar *t = new btScalar[geo.vertices.size() * 3]();
for (unsigned int it = 0; it < geo.vertices.size(); ++it)
{
t[it * 3] = geo.vertices[it].x;
t[it * 3 + 1] = geo.vertices[it].y;
t[it * 3 + 2] = geo.vertices[it].z;
}
btConvexHullShape *tmp = new btConvexHullShape(t, geo.vertices.size(), 3 * sizeof(btScalar));
btShapeHull *hull = new btShapeHull(tmp);
btScalar margin = tmp->getMargin();
hull->buildHull(margin);
tmp->setUserPointer(hull);
btConvexHullShape *s = new btConvexHullShape();
for (int it = 0; it < hull->numVertices(); ++it)
{
s->addPoint(hull->getVertexPointer()[it], false);
}
s->recalcLocalAabb();
btTransform localTrans;
localTrans.setIdentity();
_collisionShape = s;
group->addChildShape(localTrans,s);
delete[] t;
delete hull;
delete tmp;
}
_collisionShape = group;
}
else if (c == CONCAVE_STATIC_MESH) // dont work
{
SmartPointer<Resources::SharedMesh> mesh = _entity->getScene()->getEngine().getInstance<Resources::ResourceManager>().getResource(meshName);
auto trimesh = new btTriangleMesh();
auto &geos = mesh->getGeometry();
for (unsigned int j = 0; j < geos.size(); ++j)
{
const Resources::Geometry &geo = geos[j];
for (unsigned int i = 2; i < geo.vertices.size(); i += 3)
{
trimesh->addTriangle(btVector3(geo.vertices[i - 2].x, geo.vertices[i - 2].y, geo.vertices[i - 2].z)
, btVector3(geo.vertices[i - 1].x, geo.vertices[i - 1].y, geo.vertices[i - 1].z)
, btVector3(geo.vertices[i].x, geo.vertices[i].y, geo.vertices[i].z));
}
}
auto bvh = new btBvhTriangleMeshShape(trimesh, true);
bvh->buildOptimizedBvh();
bool isit = bvh->isConcave();
_collisionShape = bvh;
}
if (mass != 0)
_collisionShape->calculateLocalInertia(mass, inertia);
_collisionShape->setLocalScaling(convertGLMVectorToBullet(scale));
_rigidBody = new btRigidBody(mass, _motionState, _collisionShape, inertia);
_rigidBody->setUserPointer(&_entity);
_rigidBody->setAngularFactor(convertGLMVectorToBullet(rotationConstraint));
_rigidBody->setLinearFactor(convertGLMVectorToBullet(transformConstraint));
if (_rigidBody->isStaticObject())
{
_rigidBody->setActivationState(DISABLE_SIMULATION);
}
_manager->getWorld()->addRigidBody(_rigidBody);
}
void setRotationConstraint(bool x, bool y, bool z)
{
rotationConstraint = glm::vec3(static_cast<unsigned int>(x),
static_cast<unsigned int>(y),
static_cast<unsigned int>(z));
if (!_rigidBody)
return;
_rigidBody->setAngularFactor(convertGLMVectorToBullet(rotationConstraint));
}
void setTransformConstraint(bool x, bool y, bool z)
{
transformConstraint = glm::vec3(static_cast<unsigned int>(x),
static_cast<unsigned int>(y),
static_cast<unsigned int>(z));
if (!_rigidBody)
return;
_rigidBody->setLinearFactor(convertGLMVectorToBullet(transformConstraint));
}
virtual ~RigidBody(void)
{
if (_rigidBody)
{
_manager->getWorld()->removeRigidBody(_rigidBody);
delete _rigidBody;
}
if (_motionState)
delete _motionState;
if (_collisionShape)
delete _collisionShape;
}
//////
////
// Serialization
template <typename Archive>
Base *unserialize(Archive &ar, Entity e)
{
auto res = new RigidBody();
res->setEntity(e);
ar(*res);
return res;
}
template <typename Archive>
void save(Archive &ar) const
{
}
template <typename Archive>
void load(Archive &ar)
{
}
// !Serialization
////
//////
BulletDynamicManager *_manager;
CollisionShape shapeType;
btScalar mass;
btVector3 inertia;
glm::vec3 rotationConstraint;
glm::vec3 transformConstraint;
std::string meshName;
btCollisionShape *_collisionShape;
btMotionState *_motionState;
btRigidBody *_rigidBody;
private:
RigidBody(RigidBody const &);
RigidBody &operator=(RigidBody const &);
void _reset()
{
if (_rigidBody != nullptr)
{
_manager->getWorld()->removeRigidBody(_rigidBody);
delete _rigidBody;
}
if (_motionState != nullptr)
{
delete _motionState;
}
if (_collisionShape != nullptr)
{
delete _collisionShape;
}
}
};
}
#endif //!__RIGID_BODY_HPP__<commit_msg>Rigid body fixed + Demo spaceship functionnal<commit_after>#ifndef __RIGID_BODY_HPP__
#define __RIGID_BODY_HPP__
#include <btBulletDynamicsCommon.h>
#include <Components/Component.hh>
#include "Utils/SmartPointer.hh"
#include <Entities/EntityData.hh>
#include <Entities/Entity.hh>
#include <Core/Engine.hh>
#include <ResourceManager/ResourceManager.hh>
#include <ResourceManager/SharedMesh.hh>
#include <Managers/BulletDynamicManager.hpp>
#include "BulletCollision/CollisionShapes/btShapeHull.h"
#include <hacdHACD.h>
#include <Utils/BtConversion.hpp>
#include <Utils/MatrixConversion.hpp>
namespace Component
{
ATTRIBUTE_ALIGNED16(struct) RigidBody : public Component::ComponentBase<RigidBody>
{
BT_DECLARE_ALIGNED_ALLOCATOR();
typedef enum
{
SPHERE,
BOX,
MESH,
CONCAVE_STATIC_MESH,
UNDEFINED
} CollisionShape;
RigidBody()
: ComponentBase(),
_manager(nullptr),
shapeType(UNDEFINED),
mass(0.0f),
inertia(btVector3(0.0f, 0.0f, 0.0f)),
rotationConstraint(glm::vec3(1,1,1)),
transformConstraint(glm::vec3(1,1,1)),
meshName(""),
_collisionShape(nullptr),
_motionState(nullptr),
_rigidBody(nullptr)
{
}
void init(float _mass = 1.0f)
{
_manager = dynamic_cast<BulletDynamicManager*>(&_entity->getScene()->getEngine().getInstance<BulletCollisionManager>());
assert(_manager != nullptr);
mass = _mass;
}
virtual void reset()
{
if (_rigidBody != nullptr)
{
_manager->getWorld()->removeRigidBody(_rigidBody);
delete _rigidBody;
_rigidBody = nullptr;
}
if (_motionState != nullptr)
{
delete _motionState;
_motionState = nullptr;
}
if (_collisionShape != nullptr)
{
delete _collisionShape;
_collisionShape = nullptr;
}
shapeType = UNDEFINED;
mass = 0.0f;
inertia = btVector3(0.0f, 0.0f, 0.0f);
rotationConstraint = glm::vec3(1, 1, 1);
transformConstraint = glm::vec3(1, 1, 1);
}
btMotionState &getMotionState()
{
assert(_motionState != nullptr && "Motion state is NULL, RigidBody error. Tips : Have you setAcollisionShape to Component ?.");
return *_motionState;
}
btCollisionShape &getShape()
{
assert(_collisionShape != nullptr && "Shape is NULL, RigidBody error. Tips : Have you setAcollisionShape to Component ?.");
return *_collisionShape;
}
btRigidBody &getBody()
{
assert(_rigidBody != nullptr && "RigidBody is NULL. Tips : Have you setAcollisionShape to Component ?.");
return *_rigidBody;
}
void setMass(float _mass)
{
mass = btScalar(_mass);
}
void setInertia(btVector3 const &v)
{
inertia = v;
}
void setCollisionShape(CollisionShape c, const std::string &_meshName = "")
{
if (c == UNDEFINED)
return;
meshName = _meshName;
_reset();
shapeType = c;
btTransform transform;
glm::vec3 position = posFromMat4(_entity->getLocalTransform());
glm::vec3 scale = scaleFromMat4(_entity->getLocalTransform());
std::cout << scale.x << " " << scale.y << " " << scale.z << std::endl;
glm::vec3 rot = rotFromMat4(_entity->getLocalTransform(), true);
transform.setIdentity();
transform.setOrigin(convertGLMVectorToBullet(position));
transform.setRotation(btQuaternion(rot.x, rot.y, rot.z));
_motionState = new btDefaultMotionState(transform);
if (c == BOX)
{
_collisionShape = new btBoxShape(btVector3(0.5, 0.5, 0.5));//new btBoxShape(halfScale);
}
else if (c == SPHERE)
{
_collisionShape = new btSphereShape(0.5);//new btSphereShape(scale.x);
}
else if (c == MESH)
{
// THERE IS SOME LEAKS BECAUSE THAT'S TEMPORARY
SmartPointer<Resources::SharedMesh> mesh = _entity->getScene()->getEngine().getInstance<Resources::ResourceManager>().getResource(meshName);
auto group = new btCompoundShape();
auto &geos = mesh->getGeometry();
for (unsigned int i = 0; i < geos.size(); ++i)
{
const Resources::Geometry &geo = geos[i]; // DIRTY HACK TEMPORARY
// NEED TO REPLACE MESH BY MESH GROUP !
btScalar *t = new btScalar[geo.vertices.size() * 3]();
for (unsigned int it = 0; it < geo.vertices.size(); ++it)
{
t[it * 3] = geo.vertices[it].x;
t[it * 3 + 1] = geo.vertices[it].y;
t[it * 3 + 2] = geo.vertices[it].z;
}
btConvexHullShape *tmp = new btConvexHullShape(t, geo.vertices.size(), 3 * sizeof(btScalar));
btShapeHull *hull = new btShapeHull(tmp);
btScalar margin = tmp->getMargin();
hull->buildHull(margin);
tmp->setUserPointer(hull);
btConvexHullShape *s = new btConvexHullShape();
for (int it = 0; it < hull->numVertices(); ++it)
{
s->addPoint(hull->getVertexPointer()[it], false);
}
s->recalcLocalAabb();
btTransform localTrans;
localTrans.setIdentity();
_collisionShape = s;
group->addChildShape(localTrans,s);
delete[] t;
delete hull;
delete tmp;
}
_collisionShape = group;
}
else if (c == CONCAVE_STATIC_MESH) // dont work
{
SmartPointer<Resources::SharedMesh> mesh = _entity->getScene()->getEngine().getInstance<Resources::ResourceManager>().getResource(meshName);
auto trimesh = new btTriangleMesh();
auto &geos = mesh->getGeometry();
for (unsigned int j = 0; j < geos.size(); ++j)
{
const Resources::Geometry &geo = geos[j];
for (unsigned int i = 2; i < geo.vertices.size(); i += 3)
{
trimesh->addTriangle(btVector3(geo.vertices[i - 2].x, geo.vertices[i - 2].y, geo.vertices[i - 2].z)
, btVector3(geo.vertices[i - 1].x, geo.vertices[i - 1].y, geo.vertices[i - 1].z)
, btVector3(geo.vertices[i].x, geo.vertices[i].y, geo.vertices[i].z));
}
}
auto bvh = new btBvhTriangleMeshShape(trimesh, true);
bvh->buildOptimizedBvh();
bool isit = bvh->isConcave();
_collisionShape = bvh;
}
if (mass != 0)
_collisionShape->calculateLocalInertia(mass, inertia);
_collisionShape->setLocalScaling(convertGLMVectorToBullet(scale));
_rigidBody = new btRigidBody(mass, _motionState, _collisionShape, inertia);
_rigidBody->setUserPointer(&_entity);
_rigidBody->setAngularFactor(convertGLMVectorToBullet(rotationConstraint));
_rigidBody->setLinearFactor(convertGLMVectorToBullet(transformConstraint));
if (_rigidBody->isStaticObject())
{
_rigidBody->setActivationState(DISABLE_SIMULATION);
}
_manager->getWorld()->addRigidBody(_rigidBody);
}
void setRotationConstraint(bool x, bool y, bool z)
{
rotationConstraint = glm::vec3(static_cast<unsigned int>(x),
static_cast<unsigned int>(y),
static_cast<unsigned int>(z));
if (!_rigidBody)
return;
_rigidBody->setAngularFactor(convertGLMVectorToBullet(rotationConstraint));
}
void setTransformConstraint(bool x, bool y, bool z)
{
transformConstraint = glm::vec3(static_cast<unsigned int>(x),
static_cast<unsigned int>(y),
static_cast<unsigned int>(z));
if (!_rigidBody)
return;
_rigidBody->setLinearFactor(convertGLMVectorToBullet(transformConstraint));
}
virtual ~RigidBody(void)
{
if (_rigidBody)
{
_manager->getWorld()->removeRigidBody(_rigidBody);
delete _rigidBody;
}
if (_motionState)
delete _motionState;
if (_collisionShape)
delete _collisionShape;
}
//////
////
// Serialization
template <typename Archive>
Base *unserialize(Archive &ar, Entity e)
{
auto res = new RigidBody();
res->setEntity(e);
ar(*res);
return res;
}
template <typename Archive>
void save(Archive &ar) const
{
}
template <typename Archive>
void load(Archive &ar)
{
}
// !Serialization
////
//////
BulletDynamicManager *_manager;
CollisionShape shapeType;
btScalar mass;
btVector3 inertia;
glm::vec3 rotationConstraint;
glm::vec3 transformConstraint;
std::string meshName;
btCollisionShape *_collisionShape;
btMotionState *_motionState;
btRigidBody *_rigidBody;
private:
RigidBody(RigidBody const &);
RigidBody &operator=(RigidBody const &);
void _reset()
{
if (_rigidBody != nullptr)
{
_manager->getWorld()->removeRigidBody(_rigidBody);
delete _rigidBody;
}
if (_motionState != nullptr)
{
delete _motionState;
}
if (_collisionShape != nullptr)
{
delete _collisionShape;
}
}
};
}
#endif //!__RIGID_BODY_HPP__<|endoftext|> |
<commit_before>/******************************************************************************/
/* */
/* X r d S e c P r o t o c o l s s l . h h */
/* */
/* (c) 2007 by the Board of Trustees of the Leland Stanford, Jr., University */
/* All Rights Reserved */
/* Produced by Andrew Hanushevsky for Stanford University under contract */
/* DE-AC02-76-SFO0515 with the Department of Energy */
/******************************************************************************/
// $Id$
#include <unistd.h>
#include <ctype.h>
#include <errno.h>
#include <iostream>
#include <stdlib.h>
#include <strings.h>
#include <grp.h>
#include <pwd.h>
#define OPENSSL_THREAD_DEFINES
#include <openssl/opensslconf.h>
#include <openssl/crypto.h>
#include <openssl/x509v3.h>
#include <openssl/ssl.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/file.h>
#include <fcntl.h>
#include <pwd.h>
#include <grp.h>
#include "XrdNet/XrdNetDNS.hh"
#include "XrdOuc/XrdOucErrInfo.hh"
#include "XrdOuc/XrdOucHash.hh"
#include "XrdOuc/XrdOucString.hh"
#include "XrdOuc/XrdOucTrace.hh"
#include "XrdOuc/XrdOucTokenizer.hh"
#include "XrdSys/XrdSysPthread.hh"
#include "XrdSys/XrdSysLogger.hh"
#include "XrdSec/XrdSecInterface.hh"
#include "XrdSec/XrdSecTLayer.hh"
#include "XrdSecssl/XrdSecProtocolsslTrace.hh"
#include "XrdSecssl/XrdSecProtocolsslProc.hh"
#include "libsslGridSite/grst_verifycallback.h"
#include "libsslGridSite/gridsite.h"
#define EXPORTKEYSTRENGTH 10
#define PROTOCOLSSL_MAX_CRYPTO_MUTEX 256
// fix for SSL 098 stuff and g++
#ifdef R__SSL_GE_098
#undef PEM_read_SSL_SESSION
#undef PEM_write_SSL_SESSION
#define PEM_read_SSL_SESSION(fp,x,cb,u) (SSL_SESSION *)PEM_ASN1_read( (void *(*)(void **, const unsigned char **, long int))d2i_SSL_SESSION,PEM_STRING_SSL_SESSION,fp,(void **)x,cb,u)
#define PEM_write_SSL_SESSION(fp,x) PEM_ASN1_write((int (*)(void*, unsigned char**))i2d_SSL_SESSION, PEM_STRING_SSL_SESSION,fp, (char *)x, NULL,NULL,0,NULL,NULL)
#else
#ifdef defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_5)
#undef PEM_read_SSL_SESSION
#undef PEM_write_SSL_SESSION
#define PEM_read_SSL_SESSION(fp,x,cb,u) (SSL_SESSION *)PEM_ASN1_read( (char *(*)(...))d2i_SSL_SESSION,PEM_STRING_SSL_SESSION,fp,(char **)x ,cb,u)
#define PEM_write_SSL_SESSION(fp,x) PEM_ASN1_write((int(*)(...))i2d_SSL_SESSION, PEM_STRING_SSL_SESSION,fp, (char *)x,NULL,NULL,0,NULL,NULL)
#endif
#endif
#define l2n(l,c) (*((c)++)=(unsigned char)(((l)>>24)&0xff), \
*((c)++)=(unsigned char)(((l)>>16)&0xff), \
*((c)++)=(unsigned char)(((l)>> 8)&0xff), \
*((c)++)=(unsigned char)(((l) )&0xff))
#ifdef SUNCC
#define __FUNCTION__ "-unknown-"
#endif
static XrdOucTrace *SSLxTrace=0;
class XrdSecProtocolssl;
#define MAX_SESSION_ID_ATTEMPTS 10
/******************************************************************************/
/* X r d S e c P r o t o c o l s s l C l a s s */
/******************************************************************************/
class XrdSecsslSessionLock {
private:
static XrdSysMutex sessionmutex;
int sessionfd;
public:
XrdSecsslSessionLock() {sessionfd=0;}
bool SoftLock() { sessionmutex.Lock();return true;}
bool SoftUnLock() {sessionmutex.UnLock();return true;}
#ifdef SUNCC
bool HardLock(const char* path) {return true;}
bool HardUnLock() {return true;}
~XrdSecsslSessionLock() {sessionmutex.UnLock();}
#else
bool HardLock(const char* path) {sessionfd = open(path,O_RDWR); if ( (sessionfd>0) && (!flock(sessionfd,LOCK_EX)))return true;return false;}
bool HardUnLock() {if (sessionfd>0) {flock(sessionfd,LOCK_UN);close(sessionfd);sessionfd=0;}return true;}
~XrdSecsslSessionLock() {if (sessionfd>0) {flock(sessionfd,LOCK_UN);close(sessionfd);};}
#endif
};
class XrdSecProtocolssl : public XrdSecTLayer
{
public:
friend class XrdSecProtocolDummy; // Avoid stupid gcc warnings about destructor
XrdSecProtocolssl(const char* hostname, const struct sockaddr *ipaddr) : XrdSecTLayer("ssl",XrdSecTLayer::isClient) {
credBuff = 0;
ssl = 0;
Entity.name = 0;
Entity.grps = 0;
Entity.endorsements = 0;
host = hostname;
if (ipaddr)
Entity.host = (XrdNetDNS::getHostName((sockaddr&)*ipaddr));
else
Entity.host = strdup("");
proxyBuff[0]=0;
client_cert=0;
server_cert=0;
ssl = 0 ;
clientctx = 0;
terminate = 0;
}
virtual void secClient(int theFD, XrdOucErrInfo *einfo);
virtual void secServer(int theFD, XrdOucErrInfo *einfo=0);
// triggers purging of expired SecTLayer threads
static int dummy(const char* key, XrdSecProtocolssl *ssl, void* Arg) { return 0;}
// delayed garbage collection
virtual void Delete() { terminate = true; if (secTid) XrdSysThread::Join(secTid,NULL); secTid=0; delete this; }
static int GenerateSession(const SSL* ssl, unsigned char *id, unsigned int *id_len);
static int NewSession(SSL* ssl, SSL_SESSION *pNew);
static int GetSession(SSL* ssl, SSL_SESSION *pNew);
static char* SessionIdContext ;
static char* sslcadir;
static char* sslvomsdir;
static char* sslserverkeyfile;
static char* sslkeyfile;
static char* sslcertfile;
static char* sslproxyexportdir;
static bool sslproxyexportplain;
static char sslserverexportpassword[EXPORTKEYSTRENGTH+1];
static int threadsinuse;
static char* gridmapfile;
static char* vomsmapfile;
static bool mapuser;
static bool mapnobody;
static bool mapgroup;
static bool mapcerncertificates;
static int debug;
static time_t sslsessionlifetime;
static int sslselecttimeout;
static int sslsessioncachesize;
static char* procdir;
static XrdSecProtocolsslProc* proc;
static int errortimeout;
static int errorverify;
static int errorqueue;
static int erroraccept;
static int errorabort;
static int errorread;
static int forwardedproxies;
static bool isServer;
static bool forwardProxy;
static bool allowSessions;
static X509_STORE* store;
static X509_LOOKUP* lookup;
static int verifydepth;
static int verifyindex;
int sessionfd;
X509* client_cert;
X509* server_cert;
XrdOucString host;
// User/Group mapping
static void ReloadGridMapFile();
static void ReloadVomsMapFile();
static bool VomsMapGroups(const char* groups, XrdOucString& allgroups, XrdOucString& defaultgroup);
static void GetEnvironment();
static XrdOucHash<XrdOucString> gridmapstore;
static XrdOucHash<XrdOucString> vomsmapstore;
static XrdOucHash<XrdOucString> stringstore;
static XrdSysMutex StoreMutex;
static XrdSysMutex VomsMapMutex;
static XrdSysMutex GridMapMutex;
static XrdSysMutex* CryptoMutexPool[PROTOCOLSSL_MAX_CRYPTO_MUTEX];
static XrdSysMutex ThreadsInUseMutex;
static XrdSysMutex ErrorMutex;
// for error logging and tracing
static XrdSysLogger Logger;
static XrdSysError ssleDest;
static time_t storeLoadTime;
typedef struct {
int verbose_mode;
int verify_depth;
int always_continue;
} sslverify_t;
char proxyBuff[16384];
static SSL_CTX* ctx;
SSL_CTX* clientctx;
XrdSysMutex SSLMutex;
bool terminate;
~XrdSecProtocolssl() {
if (credBuff) free(credBuff);
if (Entity.name) free(Entity.name);
if (Entity.grps) free(Entity.grps);
if (Entity.role) free(Entity.role);
if (Entity.host) free(Entity.host);
SSLMutex.Lock();
if (ssl) SSL_free(ssl);ssl=0;
if (client_cert) X509_free(client_cert);
if (server_cert) X509_free(server_cert);
SSLMutex.UnLock();
}
static int Fatal(XrdOucErrInfo *erp, const char* msg, int rc);
struct sockaddr hostaddr; // Client-side only
char *credBuff; // Credentials buffer (server)
int Step; // Indicates step in authentication
int sd;
int listen_sd;
struct sockaddr_in sa_serv;
struct sockaddr_in sa_cli;
SSL* ssl;
};
extern "C"
{
char *XrdSecProtocolsslInit(const char mode,
const char *parms,
XrdOucErrInfo *erp);
}
class XrdSecsslThreadInUse {
public:
XrdSecsslThreadInUse() {XrdSecProtocolssl::ThreadsInUseMutex.Lock();XrdSecProtocolssl::threadsinuse++;XrdSecProtocolssl::ThreadsInUseMutex.UnLock();}
~XrdSecsslThreadInUse() {XrdSecProtocolssl::ThreadsInUseMutex.Lock();XrdSecProtocolssl::threadsinuse--;XrdSecProtocolssl::ThreadsInUseMutex.UnLock();}
};
<commit_msg>Fix cut&paste mistake in the previous patch<commit_after>/******************************************************************************/
/* */
/* X r d S e c P r o t o c o l s s l . h h */
/* */
/* (c) 2007 by the Board of Trustees of the Leland Stanford, Jr., University */
/* All Rights Reserved */
/* Produced by Andrew Hanushevsky for Stanford University under contract */
/* DE-AC02-76-SFO0515 with the Department of Energy */
/******************************************************************************/
// $Id$
#include <unistd.h>
#include <ctype.h>
#include <errno.h>
#include <iostream>
#include <stdlib.h>
#include <strings.h>
#include <grp.h>
#include <pwd.h>
#define OPENSSL_THREAD_DEFINES
#include <openssl/opensslconf.h>
#include <openssl/crypto.h>
#include <openssl/x509v3.h>
#include <openssl/ssl.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/file.h>
#include <fcntl.h>
#include <pwd.h>
#include <grp.h>
#include "XrdNet/XrdNetDNS.hh"
#include "XrdOuc/XrdOucErrInfo.hh"
#include "XrdOuc/XrdOucHash.hh"
#include "XrdOuc/XrdOucString.hh"
#include "XrdOuc/XrdOucTrace.hh"
#include "XrdOuc/XrdOucTokenizer.hh"
#include "XrdSys/XrdSysPthread.hh"
#include "XrdSys/XrdSysLogger.hh"
#include "XrdSec/XrdSecInterface.hh"
#include "XrdSec/XrdSecTLayer.hh"
#include "XrdSecssl/XrdSecProtocolsslTrace.hh"
#include "XrdSecssl/XrdSecProtocolsslProc.hh"
#include "libsslGridSite/grst_verifycallback.h"
#include "libsslGridSite/gridsite.h"
#define EXPORTKEYSTRENGTH 10
#define PROTOCOLSSL_MAX_CRYPTO_MUTEX 256
// fix for SSL 098 stuff and g++
#ifdef R__SSL_GE_098
#undef PEM_read_SSL_SESSION
#undef PEM_write_SSL_SESSION
#define PEM_read_SSL_SESSION(fp,x,cb,u) (SSL_SESSION *)PEM_ASN1_read( (void *(*)(void **, const unsigned char **, long int))d2i_SSL_SESSION,PEM_STRING_SSL_SESSION,fp,(void **)x,cb,u)
#define PEM_write_SSL_SESSION(fp,x) PEM_ASN1_write((int (*)(void*, unsigned char**))i2d_SSL_SESSION, PEM_STRING_SSL_SESSION,fp, (char *)x, NULL,NULL,0,NULL,NULL)
#else
#if defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_5)
#undef PEM_read_SSL_SESSION
#undef PEM_write_SSL_SESSION
#define PEM_read_SSL_SESSION(fp,x,cb,u) (SSL_SESSION *)PEM_ASN1_read( (char *(*)(...))d2i_SSL_SESSION,PEM_STRING_SSL_SESSION,fp,(char **)x ,cb,u)
#define PEM_write_SSL_SESSION(fp,x) PEM_ASN1_write((int(*)(...))i2d_SSL_SESSION, PEM_STRING_SSL_SESSION,fp, (char *)x,NULL,NULL,0,NULL,NULL)
#endif
#endif
#define l2n(l,c) (*((c)++)=(unsigned char)(((l)>>24)&0xff), \
*((c)++)=(unsigned char)(((l)>>16)&0xff), \
*((c)++)=(unsigned char)(((l)>> 8)&0xff), \
*((c)++)=(unsigned char)(((l) )&0xff))
#ifdef SUNCC
#define __FUNCTION__ "-unknown-"
#endif
static XrdOucTrace *SSLxTrace=0;
class XrdSecProtocolssl;
#define MAX_SESSION_ID_ATTEMPTS 10
/******************************************************************************/
/* X r d S e c P r o t o c o l s s l C l a s s */
/******************************************************************************/
class XrdSecsslSessionLock {
private:
static XrdSysMutex sessionmutex;
int sessionfd;
public:
XrdSecsslSessionLock() {sessionfd=0;}
bool SoftLock() { sessionmutex.Lock();return true;}
bool SoftUnLock() {sessionmutex.UnLock();return true;}
#ifdef SUNCC
bool HardLock(const char* path) {return true;}
bool HardUnLock() {return true;}
~XrdSecsslSessionLock() {sessionmutex.UnLock();}
#else
bool HardLock(const char* path) {sessionfd = open(path,O_RDWR); if ( (sessionfd>0) && (!flock(sessionfd,LOCK_EX)))return true;return false;}
bool HardUnLock() {if (sessionfd>0) {flock(sessionfd,LOCK_UN);close(sessionfd);sessionfd=0;}return true;}
~XrdSecsslSessionLock() {if (sessionfd>0) {flock(sessionfd,LOCK_UN);close(sessionfd);};}
#endif
};
class XrdSecProtocolssl : public XrdSecTLayer
{
public:
friend class XrdSecProtocolDummy; // Avoid stupid gcc warnings about destructor
XrdSecProtocolssl(const char* hostname, const struct sockaddr *ipaddr) : XrdSecTLayer("ssl",XrdSecTLayer::isClient) {
credBuff = 0;
ssl = 0;
Entity.name = 0;
Entity.grps = 0;
Entity.endorsements = 0;
host = hostname;
if (ipaddr)
Entity.host = (XrdNetDNS::getHostName((sockaddr&)*ipaddr));
else
Entity.host = strdup("");
proxyBuff[0]=0;
client_cert=0;
server_cert=0;
ssl = 0 ;
clientctx = 0;
terminate = 0;
}
virtual void secClient(int theFD, XrdOucErrInfo *einfo);
virtual void secServer(int theFD, XrdOucErrInfo *einfo=0);
// triggers purging of expired SecTLayer threads
static int dummy(const char* key, XrdSecProtocolssl *ssl, void* Arg) { return 0;}
// delayed garbage collection
virtual void Delete() { terminate = true; if (secTid) XrdSysThread::Join(secTid,NULL); secTid=0; delete this; }
static int GenerateSession(const SSL* ssl, unsigned char *id, unsigned int *id_len);
static int NewSession(SSL* ssl, SSL_SESSION *pNew);
static int GetSession(SSL* ssl, SSL_SESSION *pNew);
static char* SessionIdContext ;
static char* sslcadir;
static char* sslvomsdir;
static char* sslserverkeyfile;
static char* sslkeyfile;
static char* sslcertfile;
static char* sslproxyexportdir;
static bool sslproxyexportplain;
static char sslserverexportpassword[EXPORTKEYSTRENGTH+1];
static int threadsinuse;
static char* gridmapfile;
static char* vomsmapfile;
static bool mapuser;
static bool mapnobody;
static bool mapgroup;
static bool mapcerncertificates;
static int debug;
static time_t sslsessionlifetime;
static int sslselecttimeout;
static int sslsessioncachesize;
static char* procdir;
static XrdSecProtocolsslProc* proc;
static int errortimeout;
static int errorverify;
static int errorqueue;
static int erroraccept;
static int errorabort;
static int errorread;
static int forwardedproxies;
static bool isServer;
static bool forwardProxy;
static bool allowSessions;
static X509_STORE* store;
static X509_LOOKUP* lookup;
static int verifydepth;
static int verifyindex;
int sessionfd;
X509* client_cert;
X509* server_cert;
XrdOucString host;
// User/Group mapping
static void ReloadGridMapFile();
static void ReloadVomsMapFile();
static bool VomsMapGroups(const char* groups, XrdOucString& allgroups, XrdOucString& defaultgroup);
static void GetEnvironment();
static XrdOucHash<XrdOucString> gridmapstore;
static XrdOucHash<XrdOucString> vomsmapstore;
static XrdOucHash<XrdOucString> stringstore;
static XrdSysMutex StoreMutex;
static XrdSysMutex VomsMapMutex;
static XrdSysMutex GridMapMutex;
static XrdSysMutex* CryptoMutexPool[PROTOCOLSSL_MAX_CRYPTO_MUTEX];
static XrdSysMutex ThreadsInUseMutex;
static XrdSysMutex ErrorMutex;
// for error logging and tracing
static XrdSysLogger Logger;
static XrdSysError ssleDest;
static time_t storeLoadTime;
typedef struct {
int verbose_mode;
int verify_depth;
int always_continue;
} sslverify_t;
char proxyBuff[16384];
static SSL_CTX* ctx;
SSL_CTX* clientctx;
XrdSysMutex SSLMutex;
bool terminate;
~XrdSecProtocolssl() {
if (credBuff) free(credBuff);
if (Entity.name) free(Entity.name);
if (Entity.grps) free(Entity.grps);
if (Entity.role) free(Entity.role);
if (Entity.host) free(Entity.host);
SSLMutex.Lock();
if (ssl) SSL_free(ssl);ssl=0;
if (client_cert) X509_free(client_cert);
if (server_cert) X509_free(server_cert);
SSLMutex.UnLock();
}
static int Fatal(XrdOucErrInfo *erp, const char* msg, int rc);
struct sockaddr hostaddr; // Client-side only
char *credBuff; // Credentials buffer (server)
int Step; // Indicates step in authentication
int sd;
int listen_sd;
struct sockaddr_in sa_serv;
struct sockaddr_in sa_cli;
SSL* ssl;
};
extern "C"
{
char *XrdSecProtocolsslInit(const char mode,
const char *parms,
XrdOucErrInfo *erp);
}
class XrdSecsslThreadInUse {
public:
XrdSecsslThreadInUse() {XrdSecProtocolssl::ThreadsInUseMutex.Lock();XrdSecProtocolssl::threadsinuse++;XrdSecProtocolssl::ThreadsInUseMutex.UnLock();}
~XrdSecsslThreadInUse() {XrdSecProtocolssl::ThreadsInUseMutex.Lock();XrdSecProtocolssl::threadsinuse--;XrdSecProtocolssl::ThreadsInUseMutex.UnLock();}
};
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "QmitkRenderWindow.h"
#include <QCursor>
#include <QMouseEvent>
#include <QWheelEvent>
#include <QKeyEvent>
#include <QResizeEvent>
#include <QTimer>
#include "QmitkEventAdapter.h"
#include "QmitkRenderWindowMenu.h"
QmitkRenderWindow::QmitkRenderWindow(QWidget *parent, QString name, mitk::VtkPropRenderer* /*renderer*/, mitk::RenderingManager* renderingManager )
: QVTKWidget(parent)
, m_ResendQtEvents(true)
, m_MenuWidget(NULL)
, m_MenuWidgetActivated(false)
, m_LayoutIndex(0)
{
Initialize( renderingManager, name.toStdString().c_str() ); // Initialize mitkRenderWindowBase
setFocusPolicy(Qt::StrongFocus);
setMouseTracking(true);
}
QmitkRenderWindow::~QmitkRenderWindow()
{
Destroy(); // Destroy mitkRenderWindowBase
}
void QmitkRenderWindow::SetResendQtEvents(bool resend)
{
m_ResendQtEvents = resend;
}
void QmitkRenderWindow::SetLayoutIndex( unsigned int layoutIndex )
{
m_LayoutIndex = layoutIndex;
if( m_MenuWidget )
m_MenuWidget->SetLayoutIndex(layoutIndex);
}
unsigned int QmitkRenderWindow::GetLayoutIndex()
{
if( m_MenuWidget )
return m_MenuWidget->GetLayoutIndex();
else
return NULL;
}
void QmitkRenderWindow::LayoutDesignListChanged( int layoutDesignIndex )
{
if( m_MenuWidget )
m_MenuWidget->UpdateLayoutDesignList( layoutDesignIndex );
}
void QmitkRenderWindow::mousePressEvent(QMouseEvent *me)
{
mitk::MouseEvent myevent(QmitkEventAdapter::AdaptMouseEvent(m_Renderer, me));
this->mousePressMitkEvent(&myevent);
QVTKWidget::mousePressEvent(me);
if (m_ResendQtEvents) me->ignore();
}
void QmitkRenderWindow::mouseReleaseEvent(QMouseEvent *me)
{
mitk::MouseEvent myevent(QmitkEventAdapter::AdaptMouseEvent(m_Renderer, me));
this->mouseReleaseMitkEvent(&myevent);
QVTKWidget::mouseReleaseEvent(me);
if (m_ResendQtEvents) me->ignore();
}
void QmitkRenderWindow::mouseMoveEvent(QMouseEvent *me)
{
this->AdjustRenderWindowMenuVisibility( me->pos() );
mitk::MouseEvent myevent(QmitkEventAdapter::AdaptMouseEvent(m_Renderer, me));
this->mouseMoveMitkEvent(&myevent);
QVTKWidget::mouseMoveEvent(me);
//if (m_ResendQtEvents) me->ignore();
////Show/Hide Menu Widget
//if( m_MenuWidgetActivated )
//{
// //Show Menu Widget when mouse is inside of the define region of the top right corner
// if( m_MenuWidget->GetLayoutIndex() <= QmitkRenderWindowMenu::CORONAL
// && me->pos().x() >= 0
// && me->pos().y() <= m_MenuWidget->height() + 20 )
// {
// m_MenuWidget->MoveWidgetToCorrectPos(1.0);
// m_MenuWidget->show();
// m_MenuWidget->update();
// }
// else if( m_MenuWidget->GetLayoutIndex() == QmitkRenderWindowMenu::THREE_D
// && me->pos().x() >= this->width() - m_MenuWidget->width() - 20
// && me->pos().y() <= m_MenuWidget->height() + 20 )
// {
// m_MenuWidget->MoveWidgetToCorrectPos(1.0);
// m_MenuWidget->show();
// m_MenuWidget->update();
// }
// //Hide Menu Widget when mouse is outside of the define region of the the right corner
// else if( !m_MenuWidget->GetSettingsMenuVisibilty() )
// {
// m_MenuWidget->hide();
// }
//}
}
void QmitkRenderWindow::wheelEvent(QWheelEvent *we)
{
mitk::WheelEvent myevent(QmitkEventAdapter::AdaptWheelEvent(m_Renderer, we));
this->wheelMitkEvent(&myevent);
QVTKWidget::wheelEvent(we);
if (m_ResendQtEvents)
we->ignore();
}
void QmitkRenderWindow::keyPressEvent(QKeyEvent *ke)
{
QPoint cp = mapFromGlobal(QCursor::pos());
mitk::KeyEvent mke(QmitkEventAdapter::AdaptKeyEvent(m_Renderer, ke, cp));
this->keyPressMitkEvent(&mke);
ke->accept();
QVTKWidget::keyPressEvent(ke);
if (m_ResendQtEvents) ke->ignore();
}
void QmitkRenderWindow::enterEvent( QEvent *e )
{
MITK_DEBUG << "rw enter Event";
QVTKWidget::enterEvent(e);
}
void QmitkRenderWindow::DeferredHideMenu( )
{
MITK_DEBUG << "QmitkRenderWindow::DeferredHideMenu";
if( m_MenuWidget )
m_MenuWidget->HideMenu();
}
void QmitkRenderWindow::leaveEvent( QEvent *e )
{
MITK_DEBUG << "QmitkRenderWindow::leaveEvent";
if( m_MenuWidget )
m_MenuWidget->smoothHide();
QVTKWidget::leaveEvent(e);
}
void QmitkRenderWindow::paintEvent(QPaintEvent* /*event*/)
{
//We are using our own interaction and thus have to call the rendering manually.
mitk::RenderingManager::GetInstance()->RequestUpdate(GetRenderWindow());
}
void QmitkRenderWindow::resizeEvent(QResizeEvent* event)
{
this->resizeMitkEvent(event->size().width(), event->size().height());
QVTKWidget::resizeEvent(event);
emit resized();
}
void QmitkRenderWindow::moveEvent( QMoveEvent* event )
{
QVTKWidget::moveEvent( event );
// after a move the overlays need to be positioned
emit moved();
}
void QmitkRenderWindow::showEvent( QShowEvent* event )
{
QVTKWidget::showEvent( event );
// this singleshot is necessary to have the overlays positioned correctly after initial show
// simple call of moved() is no use here!!
QTimer::singleShot(0, this ,SIGNAL( moved() ) );
}
void QmitkRenderWindow::ActivateMenuWidget( bool state )
{
m_MenuWidgetActivated = state;
if(!m_MenuWidgetActivated && m_MenuWidget)
{
//disconnect Signal/Slot Connection
disconnect( m_MenuWidget, SIGNAL( SignalChangeLayoutDesign(int) ), this, SLOT(OnChangeLayoutDesign(int)) );
disconnect( m_MenuWidget, SIGNAL( ResetView() ), this, SIGNAL( ResetView()) );
disconnect( m_MenuWidget, SIGNAL( ChangeCrosshairRotationMode(int) ), this, SIGNAL( ChangeCrosshairRotationMode(int)) );
delete m_MenuWidget;
m_MenuWidget = 0;
}
else if(m_MenuWidgetActivated && !m_MenuWidget )
{
//create render window MenuBar for split, close Window or set new setting.
m_MenuWidget = new QmitkRenderWindowMenu(this,0,m_Renderer);
m_MenuWidget->SetLayoutIndex( m_LayoutIndex );
//create Signal/Slot Connection
connect( m_MenuWidget, SIGNAL( SignalChangeLayoutDesign(int) ), this, SLOT(OnChangeLayoutDesign(int)) );
connect( m_MenuWidget, SIGNAL( ResetView() ), this, SIGNAL( ResetView()) );
connect( m_MenuWidget, SIGNAL( ChangeCrosshairRotationMode(int) ), this, SIGNAL( ChangeCrosshairRotationMode(int)) );
}
}
void QmitkRenderWindow::AdjustRenderWindowMenuVisibility( const QPoint& /*pos*/ )
{
if( m_MenuWidget )
{
m_MenuWidget->ShowMenu();
m_MenuWidget->MoveWidgetToCorrectPos(1.0f);
}
}
void QmitkRenderWindow::HideRenderWindowMenu( )
{
// DEPRECATED METHOD
}
void QmitkRenderWindow::OnChangeLayoutDesign( int layoutDesignIndex )
{
emit SignalLayoutDesignChanged( layoutDesignIndex );
}
void QmitkRenderWindow::OnWidgetPlaneModeChanged( int mode )
{
if( m_MenuWidget )
m_MenuWidget->NotifyNewWidgetPlanesMode( mode );
}
void QmitkRenderWindow::FullScreenMode(bool state)
{
if( m_MenuWidget )
m_MenuWidget->ChangeFullScreenMode( state );
}
<commit_msg>requesting update from correct instance of renderingManager<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "QmitkRenderWindow.h"
#include <QCursor>
#include <QMouseEvent>
#include <QWheelEvent>
#include <QKeyEvent>
#include <QResizeEvent>
#include <QTimer>
#include "QmitkEventAdapter.h"
#include "QmitkRenderWindowMenu.h"
QmitkRenderWindow::QmitkRenderWindow(QWidget *parent, QString name, mitk::VtkPropRenderer* /*renderer*/, mitk::RenderingManager* renderingManager )
: QVTKWidget(parent)
, m_ResendQtEvents(true)
, m_MenuWidget(NULL)
, m_MenuWidgetActivated(false)
, m_LayoutIndex(0)
{
Initialize( renderingManager, name.toStdString().c_str() ); // Initialize mitkRenderWindowBase
setFocusPolicy(Qt::StrongFocus);
setMouseTracking(true);
}
QmitkRenderWindow::~QmitkRenderWindow()
{
Destroy(); // Destroy mitkRenderWindowBase
}
void QmitkRenderWindow::SetResendQtEvents(bool resend)
{
m_ResendQtEvents = resend;
}
void QmitkRenderWindow::SetLayoutIndex( unsigned int layoutIndex )
{
m_LayoutIndex = layoutIndex;
if( m_MenuWidget )
m_MenuWidget->SetLayoutIndex(layoutIndex);
}
unsigned int QmitkRenderWindow::GetLayoutIndex()
{
if( m_MenuWidget )
return m_MenuWidget->GetLayoutIndex();
else
return NULL;
}
void QmitkRenderWindow::LayoutDesignListChanged( int layoutDesignIndex )
{
if( m_MenuWidget )
m_MenuWidget->UpdateLayoutDesignList( layoutDesignIndex );
}
void QmitkRenderWindow::mousePressEvent(QMouseEvent *me)
{
mitk::MouseEvent myevent(QmitkEventAdapter::AdaptMouseEvent(m_Renderer, me));
this->mousePressMitkEvent(&myevent);
QVTKWidget::mousePressEvent(me);
if (m_ResendQtEvents) me->ignore();
}
void QmitkRenderWindow::mouseReleaseEvent(QMouseEvent *me)
{
mitk::MouseEvent myevent(QmitkEventAdapter::AdaptMouseEvent(m_Renderer, me));
this->mouseReleaseMitkEvent(&myevent);
QVTKWidget::mouseReleaseEvent(me);
if (m_ResendQtEvents) me->ignore();
}
void QmitkRenderWindow::mouseMoveEvent(QMouseEvent *me)
{
this->AdjustRenderWindowMenuVisibility( me->pos() );
mitk::MouseEvent myevent(QmitkEventAdapter::AdaptMouseEvent(m_Renderer, me));
this->mouseMoveMitkEvent(&myevent);
QVTKWidget::mouseMoveEvent(me);
//if (m_ResendQtEvents) me->ignore();
////Show/Hide Menu Widget
//if( m_MenuWidgetActivated )
//{
// //Show Menu Widget when mouse is inside of the define region of the top right corner
// if( m_MenuWidget->GetLayoutIndex() <= QmitkRenderWindowMenu::CORONAL
// && me->pos().x() >= 0
// && me->pos().y() <= m_MenuWidget->height() + 20 )
// {
// m_MenuWidget->MoveWidgetToCorrectPos(1.0);
// m_MenuWidget->show();
// m_MenuWidget->update();
// }
// else if( m_MenuWidget->GetLayoutIndex() == QmitkRenderWindowMenu::THREE_D
// && me->pos().x() >= this->width() - m_MenuWidget->width() - 20
// && me->pos().y() <= m_MenuWidget->height() + 20 )
// {
// m_MenuWidget->MoveWidgetToCorrectPos(1.0);
// m_MenuWidget->show();
// m_MenuWidget->update();
// }
// //Hide Menu Widget when mouse is outside of the define region of the the right corner
// else if( !m_MenuWidget->GetSettingsMenuVisibilty() )
// {
// m_MenuWidget->hide();
// }
//}
}
void QmitkRenderWindow::wheelEvent(QWheelEvent *we)
{
mitk::WheelEvent myevent(QmitkEventAdapter::AdaptWheelEvent(m_Renderer, we));
this->wheelMitkEvent(&myevent);
QVTKWidget::wheelEvent(we);
if (m_ResendQtEvents)
we->ignore();
}
void QmitkRenderWindow::keyPressEvent(QKeyEvent *ke)
{
QPoint cp = mapFromGlobal(QCursor::pos());
mitk::KeyEvent mke(QmitkEventAdapter::AdaptKeyEvent(m_Renderer, ke, cp));
this->keyPressMitkEvent(&mke);
ke->accept();
QVTKWidget::keyPressEvent(ke);
if (m_ResendQtEvents) ke->ignore();
}
void QmitkRenderWindow::enterEvent( QEvent *e )
{
MITK_DEBUG << "rw enter Event";
QVTKWidget::enterEvent(e);
}
void QmitkRenderWindow::DeferredHideMenu( )
{
MITK_DEBUG << "QmitkRenderWindow::DeferredHideMenu";
if( m_MenuWidget )
m_MenuWidget->HideMenu();
}
void QmitkRenderWindow::leaveEvent( QEvent *e )
{
MITK_DEBUG << "QmitkRenderWindow::leaveEvent";
if( m_MenuWidget )
m_MenuWidget->smoothHide();
QVTKWidget::leaveEvent(e);
}
void QmitkRenderWindow::paintEvent(QPaintEvent* /*event*/)
{
//We are using our own interaction and thus have to call the rendering manually.
this->GetRenderer()->GetRenderingManager()->RequestUpdate(GetRenderWindow());
}
void QmitkRenderWindow::resizeEvent(QResizeEvent* event)
{
this->resizeMitkEvent(event->size().width(), event->size().height());
QVTKWidget::resizeEvent(event);
emit resized();
}
void QmitkRenderWindow::moveEvent( QMoveEvent* event )
{
QVTKWidget::moveEvent( event );
// after a move the overlays need to be positioned
emit moved();
}
void QmitkRenderWindow::showEvent( QShowEvent* event )
{
QVTKWidget::showEvent( event );
// this singleshot is necessary to have the overlays positioned correctly after initial show
// simple call of moved() is no use here!!
QTimer::singleShot(0, this ,SIGNAL( moved() ) );
}
void QmitkRenderWindow::ActivateMenuWidget( bool state )
{
m_MenuWidgetActivated = state;
if(!m_MenuWidgetActivated && m_MenuWidget)
{
//disconnect Signal/Slot Connection
disconnect( m_MenuWidget, SIGNAL( SignalChangeLayoutDesign(int) ), this, SLOT(OnChangeLayoutDesign(int)) );
disconnect( m_MenuWidget, SIGNAL( ResetView() ), this, SIGNAL( ResetView()) );
disconnect( m_MenuWidget, SIGNAL( ChangeCrosshairRotationMode(int) ), this, SIGNAL( ChangeCrosshairRotationMode(int)) );
delete m_MenuWidget;
m_MenuWidget = 0;
}
else if(m_MenuWidgetActivated && !m_MenuWidget )
{
//create render window MenuBar for split, close Window or set new setting.
m_MenuWidget = new QmitkRenderWindowMenu(this,0,m_Renderer);
m_MenuWidget->SetLayoutIndex( m_LayoutIndex );
//create Signal/Slot Connection
connect( m_MenuWidget, SIGNAL( SignalChangeLayoutDesign(int) ), this, SLOT(OnChangeLayoutDesign(int)) );
connect( m_MenuWidget, SIGNAL( ResetView() ), this, SIGNAL( ResetView()) );
connect( m_MenuWidget, SIGNAL( ChangeCrosshairRotationMode(int) ), this, SIGNAL( ChangeCrosshairRotationMode(int)) );
}
}
void QmitkRenderWindow::AdjustRenderWindowMenuVisibility( const QPoint& /*pos*/ )
{
if( m_MenuWidget )
{
m_MenuWidget->ShowMenu();
m_MenuWidget->MoveWidgetToCorrectPos(1.0f);
}
}
void QmitkRenderWindow::HideRenderWindowMenu( )
{
// DEPRECATED METHOD
}
void QmitkRenderWindow::OnChangeLayoutDesign( int layoutDesignIndex )
{
emit SignalLayoutDesignChanged( layoutDesignIndex );
}
void QmitkRenderWindow::OnWidgetPlaneModeChanged( int mode )
{
if( m_MenuWidget )
m_MenuWidget->NotifyNewWidgetPlanesMode( mode );
}
void QmitkRenderWindow::FullScreenMode(bool state)
{
if( m_MenuWidget )
m_MenuWidget->ChangeFullScreenMode( state );
}
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef itkFlipImageFilter_hxx
#define itkFlipImageFilter_hxx
#include "itkFlipImageFilter.h"
#include "itkImageScanlineIterator.h"
#include "itkProgressReporter.h"
namespace itk
{
template< typename TImage >
FlipImageFilter< TImage >
::FlipImageFilter() :
m_FlipAboutOrigin( true )
{
m_FlipAxes.Fill(false);
}
template< typename TImage >
void
FlipImageFilter< TImage >
::GenerateOutputInformation()
{
// Call the superclass's implementation of this method
Superclass::GenerateOutputInformation();
// Get pointers to the input and output
InputImagePointer inputPtr =
const_cast< TImage * >( this->GetInput() );
OutputImagePointer outputPtr = this->GetOutput();
if ( !inputPtr || !outputPtr )
{
return;
}
const typename TImage::DirectionType & inputDirection = inputPtr->GetDirection();
const typename TImage::SizeType & inputSize =
inputPtr->GetLargestPossibleRegion().GetSize();
const typename TImage::IndexType & inputStartIndex =
inputPtr->GetLargestPossibleRegion().GetIndex();
typename TImage::PointType outputOrigin;
typename TImage::IndexType newIndex = inputStartIndex;
unsigned int j;
typename TImage::DirectionType flipMatrix;
flipMatrix.SetIdentity();
// Need the coordinate of the pixel that will become the first pixel
// and need a matrix to model the flip
for ( j = 0; j < ImageDimension; j++ )
{
if ( m_FlipAxes[j] )
{
// If flipping the axis, then we need to know the last pixel in
// that dimension
newIndex[j] += ( inputSize[j] - 1 );
// What we really want is the index padded out past this point
// by the amount the start index is from [0,0,0] (because the
// output regions have the same index layout as the input
// regions)
newIndex[j] += inputStartIndex[j];
// Only flip the directions if we are NOT flipping about the
// origin (when flipping about the origin, the pixels are
// ordered in the same direction as the input directions. when
// NOT flipping about the origin, the pixels traverse space in
// the opposite direction. when flipping about the origin,
// increasing indices traverse space in the same direction as
// the original data.).
if ( !m_FlipAboutOrigin )
{
flipMatrix[j][j] = -1.0;
}
}
}
inputPtr->TransformIndexToPhysicalPoint(newIndex, outputOrigin);
// Finally, flip about the origin if needed
if ( m_FlipAboutOrigin )
{
for ( j = 0; j < ImageDimension; j++ )
{
if ( m_FlipAxes[j] )
{
outputOrigin[j] *= -1;
}
}
}
outputPtr->SetDirection(inputDirection * flipMatrix);
outputPtr->SetOrigin(outputOrigin);
}
template< typename TImage >
void
FlipImageFilter< TImage >
::GenerateInputRequestedRegion()
{
// Call the superclass's implementation of this method
Superclass::GenerateInputRequestedRegion();
// Get pointers to the input and output
InputImagePointer inputPtr =
const_cast< TImage * >( this->GetInput() );
OutputImagePointer outputPtr = this->GetOutput();
if ( !inputPtr || !outputPtr )
{
return;
}
const typename TImage::SizeType & outputRequestedSize =
outputPtr->GetRequestedRegion().GetSize();
const typename TImage::IndexType & outputRequestedIndex =
outputPtr->GetRequestedRegion().GetIndex();
const typename TImage::SizeType & outputLargestPossibleSize =
outputPtr->GetLargestPossibleRegion().GetSize();
const typename TImage::IndexType & outputLargestPossibleIndex =
outputPtr->GetLargestPossibleRegion().GetIndex();
IndexType inputRequestedIndex(outputRequestedIndex);
unsigned int j;
for ( j = 0; j < ImageDimension; j++ )
{
if ( m_FlipAxes[j] )
{
inputRequestedIndex[j] =
2 * outputLargestPossibleIndex[j]
+ static_cast< IndexValueType >( outputLargestPossibleSize[j] )
- static_cast< IndexValueType >( outputRequestedSize[j] )
- outputRequestedIndex[j];
}
}
typename TImage::RegionType inputRequestedRegion( inputRequestedIndex, outputRequestedSize);
inputPtr->SetRequestedRegion(inputRequestedRegion);
}
template< typename TImage >
void
FlipImageFilter< TImage >
::ThreadedGenerateData(const OutputImageRegionType & outputRegionForThread,
ThreadIdType threadId)
{
// Get the input and output pointers
InputImageConstPointer inputPtr = this->GetInput();
OutputImagePointer outputPtr = this->GetOutput();
// Support progress methods/callbacks
const typename OutputImageRegionType::SizeType ®ionSize = outputRegionForThread.GetSize();
const size_t numberOfLinesToProcess = outputRegionForThread.GetNumberOfPixels() / regionSize[0];
ProgressReporter progress( this, threadId, static_cast<SizeValueType>( numberOfLinesToProcess ) );
const typename TImage::SizeType & outputLargestPossibleSize =
outputPtr->GetLargestPossibleRegion().GetSize();
const typename TImage::IndexType & outputLargestPossibleIndex =
outputPtr->GetLargestPossibleRegion().GetIndex();
// Compute the input region the output region maps to
typename TImage::RegionType inputReginForThread( outputRegionForThread );
for ( unsigned int j = 0; j < ImageDimension; j++ )
{
if ( m_FlipAxes[j] )
{
const IndexValueType idx =
2 * outputLargestPossibleIndex[j]
+ static_cast< IndexValueType >( outputLargestPossibleSize[j] )
- static_cast< IndexValueType >( outputRegionForThread.GetSize(j) )
- outputRegionForThread.GetIndex(j);
inputReginForThread.SetIndex(j, idx);
}
}
// Setup output region iterator
ImageScanlineIterator< TImage > outputIt(outputPtr, outputRegionForThread);
ImageScanlineConstIterator< TImage > inputIter(inputPtr, inputReginForThread);
IndexValueType offset[ImageDimension];
for ( unsigned int j = 0; j < ImageDimension; j++ )
{
if ( m_FlipAxes[j] )
{
offset[j] = 2 * outputLargestPossibleIndex[j]
+ static_cast< IndexValueType >( outputLargestPossibleSize[j] ) - 1;
}
else
{
offset[j] = 0;
}
}
outputIt.GoToBegin();
while ( !outputIt.IsAtEnd() )
{
// Determine the index of the output line
const typename TImage::IndexType outputIndex = outputIt.GetIndex();
// Determine the input pixel location associated with the start of
// the line
typename TImage::IndexType inputIndex(outputIndex);
for ( unsigned int j = 0; j < ImageDimension; ++j )
{
if ( m_FlipAxes[j] )
{
inputIndex[j] = -1 * outputIndex[j] + offset[j];
}
}
inputIter.SetIndex(inputIndex);
if ( m_FlipAxes[0] )
{
// Move the across the output scanline
while ( !outputIt.IsAtEndOfLine() )
{
// Copy the input pixel to the output
outputIt.Set( inputIter.Get() );
++outputIt;
// Read the input scaneline in reverse
--inputIter;
}
}
else
{
// Move the across the output scanline
while ( !outputIt.IsAtEndOfLine() )
{
// Copy the input pixel to the output
outputIt.Set( inputIter.Get() );
++outputIt;
++inputIter;
}
}
outputIt.NextLine();
progress.CompletedPixel();
}
}
template< typename TImage >
void
FlipImageFilter< TImage >
::PrintSelf(std::ostream & os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "FlipAxes: " << m_FlipAxes << std::endl;
os << indent << "FlipAboutOrigin: " << m_FlipAboutOrigin << std::endl;
}
} // namespace itk
#endif
<commit_msg>STYLE: Limit itkFlipImageFilter methods' loops variables' scope.<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef itkFlipImageFilter_hxx
#define itkFlipImageFilter_hxx
#include "itkFlipImageFilter.h"
#include "itkImageScanlineIterator.h"
#include "itkProgressReporter.h"
namespace itk
{
template< typename TImage >
FlipImageFilter< TImage >
::FlipImageFilter() :
m_FlipAboutOrigin( true )
{
m_FlipAxes.Fill(false);
}
template< typename TImage >
void
FlipImageFilter< TImage >
::GenerateOutputInformation()
{
// Call the superclass's implementation of this method
Superclass::GenerateOutputInformation();
// Get pointers to the input and output
InputImagePointer inputPtr =
const_cast< TImage * >( this->GetInput() );
OutputImagePointer outputPtr = this->GetOutput();
if ( !inputPtr || !outputPtr )
{
return;
}
const typename TImage::DirectionType & inputDirection = inputPtr->GetDirection();
const typename TImage::SizeType & inputSize =
inputPtr->GetLargestPossibleRegion().GetSize();
const typename TImage::IndexType & inputStartIndex =
inputPtr->GetLargestPossibleRegion().GetIndex();
typename TImage::PointType outputOrigin;
typename TImage::IndexType newIndex = inputStartIndex;
typename TImage::DirectionType flipMatrix;
flipMatrix.SetIdentity();
// Need the coordinate of the pixel that will become the first pixel
// and need a matrix to model the flip
for ( unsigned int j = 0; j < ImageDimension; j++ )
{
if ( m_FlipAxes[j] )
{
// If flipping the axis, then we need to know the last pixel in
// that dimension
newIndex[j] += ( inputSize[j] - 1 );
// What we really want is the index padded out past this point
// by the amount the start index is from [0,0,0] (because the
// output regions have the same index layout as the input
// regions)
newIndex[j] += inputStartIndex[j];
// Only flip the directions if we are NOT flipping about the
// origin (when flipping about the origin, the pixels are
// ordered in the same direction as the input directions. when
// NOT flipping about the origin, the pixels traverse space in
// the opposite direction. when flipping about the origin,
// increasing indices traverse space in the same direction as
// the original data.).
if ( !m_FlipAboutOrigin )
{
flipMatrix[j][j] = -1.0;
}
}
}
inputPtr->TransformIndexToPhysicalPoint(newIndex, outputOrigin);
// Finally, flip about the origin if needed
if ( m_FlipAboutOrigin )
{
for ( unsigned int j = 0; j < ImageDimension; j++ )
{
if ( m_FlipAxes[j] )
{
outputOrigin[j] *= -1;
}
}
}
outputPtr->SetDirection(inputDirection * flipMatrix);
outputPtr->SetOrigin(outputOrigin);
}
template< typename TImage >
void
FlipImageFilter< TImage >
::GenerateInputRequestedRegion()
{
// Call the superclass's implementation of this method
Superclass::GenerateInputRequestedRegion();
// Get pointers to the input and output
InputImagePointer inputPtr =
const_cast< TImage * >( this->GetInput() );
OutputImagePointer outputPtr = this->GetOutput();
if ( !inputPtr || !outputPtr )
{
return;
}
const typename TImage::SizeType & outputRequestedSize =
outputPtr->GetRequestedRegion().GetSize();
const typename TImage::IndexType & outputRequestedIndex =
outputPtr->GetRequestedRegion().GetIndex();
const typename TImage::SizeType & outputLargestPossibleSize =
outputPtr->GetLargestPossibleRegion().GetSize();
const typename TImage::IndexType & outputLargestPossibleIndex =
outputPtr->GetLargestPossibleRegion().GetIndex();
IndexType inputRequestedIndex(outputRequestedIndex);
for ( unsigned int j = 0; j < ImageDimension; j++ )
{
if ( m_FlipAxes[j] )
{
inputRequestedIndex[j] =
2 * outputLargestPossibleIndex[j]
+ static_cast< IndexValueType >( outputLargestPossibleSize[j] )
- static_cast< IndexValueType >( outputRequestedSize[j] )
- outputRequestedIndex[j];
}
}
typename TImage::RegionType inputRequestedRegion( inputRequestedIndex, outputRequestedSize);
inputPtr->SetRequestedRegion(inputRequestedRegion);
}
template< typename TImage >
void
FlipImageFilter< TImage >
::ThreadedGenerateData(const OutputImageRegionType & outputRegionForThread,
ThreadIdType threadId)
{
// Get the input and output pointers
InputImageConstPointer inputPtr = this->GetInput();
OutputImagePointer outputPtr = this->GetOutput();
// Support progress methods/callbacks
const typename OutputImageRegionType::SizeType ®ionSize = outputRegionForThread.GetSize();
const size_t numberOfLinesToProcess = outputRegionForThread.GetNumberOfPixels() / regionSize[0];
ProgressReporter progress( this, threadId, static_cast<SizeValueType>( numberOfLinesToProcess ) );
const typename TImage::SizeType & outputLargestPossibleSize =
outputPtr->GetLargestPossibleRegion().GetSize();
const typename TImage::IndexType & outputLargestPossibleIndex =
outputPtr->GetLargestPossibleRegion().GetIndex();
// Compute the input region the output region maps to
typename TImage::RegionType inputReginForThread( outputRegionForThread );
for ( unsigned int j = 0; j < ImageDimension; j++ )
{
if ( m_FlipAxes[j] )
{
const IndexValueType idx =
2 * outputLargestPossibleIndex[j]
+ static_cast< IndexValueType >( outputLargestPossibleSize[j] )
- static_cast< IndexValueType >( outputRegionForThread.GetSize(j) )
- outputRegionForThread.GetIndex(j);
inputReginForThread.SetIndex(j, idx);
}
}
// Setup output region iterator
ImageScanlineIterator< TImage > outputIt(outputPtr, outputRegionForThread);
ImageScanlineConstIterator< TImage > inputIter(inputPtr, inputReginForThread);
IndexValueType offset[ImageDimension];
for ( unsigned int j = 0; j < ImageDimension; j++ )
{
if ( m_FlipAxes[j] )
{
offset[j] = 2 * outputLargestPossibleIndex[j]
+ static_cast< IndexValueType >( outputLargestPossibleSize[j] ) - 1;
}
else
{
offset[j] = 0;
}
}
outputIt.GoToBegin();
while ( !outputIt.IsAtEnd() )
{
// Determine the index of the output line
const typename TImage::IndexType outputIndex = outputIt.GetIndex();
// Determine the input pixel location associated with the start of
// the line
typename TImage::IndexType inputIndex(outputIndex);
for ( unsigned int j = 0; j < ImageDimension; ++j )
{
if ( m_FlipAxes[j] )
{
inputIndex[j] = -1 * outputIndex[j] + offset[j];
}
}
inputIter.SetIndex(inputIndex);
if ( m_FlipAxes[0] )
{
// Move the across the output scanline
while ( !outputIt.IsAtEndOfLine() )
{
// Copy the input pixel to the output
outputIt.Set( inputIter.Get() );
++outputIt;
// Read the input scaneline in reverse
--inputIter;
}
}
else
{
// Move the across the output scanline
while ( !outputIt.IsAtEndOfLine() )
{
// Copy the input pixel to the output
outputIt.Set( inputIter.Get() );
++outputIt;
++inputIter;
}
}
outputIt.NextLine();
progress.CompletedPixel();
}
}
template< typename TImage >
void
FlipImageFilter< TImage >
::PrintSelf(std::ostream & os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "FlipAxes: " << m_FlipAxes << std::endl;
os << indent << "FlipAboutOrigin: " << m_FlipAboutOrigin << std::endl;
}
} // namespace itk
#endif
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015-2017 Daniel Nicoletti <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "sql.h"
#include <QtCore/QLoggingCategory>
#include <QThread>
#include <QtSql/QSqlQuery>
#include <QtSql/QSqlError>
#include <QtSql/QSqlRecord>
Q_LOGGING_CATEGORY(C_SQL, "cutelyst.utils.sql")
using namespace Cutelyst;
QVariantHash Sql::queryToHashObject(QSqlQuery &query)
{
QVariantHash ret;
if (query.next()) {
int columns = query.record().count();
for (int i = 0; i < columns; ++i) {
ret.insert(query.record().fieldName(i), query.value(i));
}
}
return ret;
}
QVariantList Sql::queryToHashList(QSqlQuery &query)
{
QVariantList ret;
int columns = query.record().count();
QStringList cols;
for (int i = 0; i < columns; ++i) {
cols.append(query.record().fieldName(i));
}
while (query.next()) {
QVariantHash line;
for (int i = 0; i < columns; ++i) {
line.insert(cols.at(i), query.value(i));
}
ret.append(line);
}
return ret;
}
QVariantMap Sql::queryToMapObject(QSqlQuery &query)
{
QVariantMap ret;
if (query.next()) {
int columns = query.record().count();
for (int i = 0; i < columns; ++i) {
ret.insert(query.record().fieldName(i), query.value(i));
}
}
return ret;
}
QVariantList Sql::queryToMapList(QSqlQuery &query)
{
QVariantList ret;
int columns = query.record().count();
QStringList cols;
for (int i = 0; i < columns; ++i) {
cols.append(query.record().fieldName(i));
}
while (query.next()) {
QVariantMap line;
for (int i = 0; i < columns; ++i) {
line.insert(cols.at(i), query.value(i));
}
ret.append(line);
}
return ret;
}
QVariantHash Sql::queryToIndexedHash(QSqlQuery &query, const QString &key)
{
QVariantHash ret;
QSqlRecord record = query.record();
if (!record.contains(key)) {
qCCritical(C_SQL) << "Field Name " << key <<
" not found in result set";
return ret;
}
int columns = record.count();
QStringList cols;
for (int i = 0; i < columns; ++i) {
cols.append(record.fieldName(i));
}
while (query.next()) {
QVariantHash line;
for (int i = 0; i < columns; ++i) {
line.insertMulti(cols.at(i),query.value(i));
}
ret.insertMulti(query.value(key).toString(), line);
}
return ret;
}
void Sql::bindParamsToQuery(QSqlQuery &query, const Cutelyst::ParamsMultiMap ¶ms, bool htmlEscaped)
{
auto it = params.constBegin();
if (htmlEscaped) {
while (it != params.constEnd()) {
if (it.value().isNull()) {
query.bindValue(QLatin1Char(':') + it.key(), QVariant());
} else {
query.bindValue(QLatin1Char(':') + it.key(), it.value().toHtmlEscaped());
}
++it;
}
} else {
while (it != params.constEnd()) {
if (it.value().isNull()) {
query.bindValue(QLatin1Char(':') + it.key(), QVariant());
} else {
query.bindValue(QLatin1Char(':') + it.key(), it.value());
}
++it;
}
}
}
QSqlQuery Sql::preparedQuery(const QString &query, QSqlDatabase db, bool forwardOnly)
{
QSqlQuery sqlQuery(db);
sqlQuery.setForwardOnly(forwardOnly);
if (!sqlQuery.prepare(query)) {
qCCritical(C_SQL) << "Failed to prepare query:" << query << sqlQuery.lastError().databaseText();
}
return sqlQuery;
}
QSqlQuery Sql::preparedQueryThread(const QString &query, const QString &dbName, bool forwardOnly)
{
QSqlQuery sqlQuery(QSqlDatabase::database(databaseNameThread(dbName)));
sqlQuery.setForwardOnly(forwardOnly);
if (!sqlQuery.prepare(query)) {
qCCritical(C_SQL) << "Failed to prepare query:" << query << sqlQuery.lastError().databaseText();
}
return sqlQuery;
}
QString Sql::databaseNameThread(const QString &dbName)
{
return dbName + QLatin1Char('-') + QThread::currentThread()->objectName();
}
<commit_msg>Changes in Sql utils functions in sql.cpp. The changes ensure that the querying of the record will be done only once.<commit_after>/*
* Copyright (C) 2015-2017 Daniel Nicoletti <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "sql.h"
#include <QtCore/QLoggingCategory>
#include <QThread>
#include <QtSql/QSqlQuery>
#include <QtSql/QSqlError>
#include <QtSql/QSqlRecord>
Q_LOGGING_CATEGORY(C_SQL, "cutelyst.utils.sql")
using namespace Cutelyst;
QVariantHash Sql::queryToHashObject(QSqlQuery &query)
{
QVariantHash ret;
if (query.next()) {
QSqlRecord record = query.record();
int columns = record.count();
for (int i = 0; i < columns; ++i) {
ret.insert(record.fieldName(i), query.value(i));
}
}
return ret;
}
QVariantList Sql::queryToHashList(QSqlQuery &query)
{
QVariantList ret;
QSqlRecord record = query.record();
int columns = record.count();
QStringList cols;
for (int i = 0; i < columns; ++i) {
cols.append(record.fieldName(i));
}
while (query.next()) {
QVariantHash line;
for (int i = 0; i < columns; ++i) {
line.insert(cols.at(i), query.value(i));
}
ret.append(line);
}
return ret;
}
QVariantMap Sql::queryToMapObject(QSqlQuery &query)
{
QVariantMap ret;
if (query.next()) {
QSqlRecord record = query.record();
int columns = record.count();
for (int i = 0; i < columns; ++i) {
ret.insert(record.fieldName(i), query.value(i));
}
}
return ret;
}
QVariantList Sql::queryToMapList(QSqlQuery &query)
{
QVariantList ret;
QSqlRecord record = query.record();
int columns = record.count();
QStringList cols;
for (int i = 0; i < columns; ++i) {
cols.append(record.fieldName(i));
}
while (query.next()) {
QVariantMap line;
for (int i = 0; i < columns; ++i) {
line.insert(cols.at(i), query.value(i));
}
ret.append(line);
}
return ret;
}
QVariantHash Sql::queryToIndexedHash(QSqlQuery &query, const QString &key)
{
QVariantHash ret;
QSqlRecord record = query.record();
if (!record.contains(key)) {
qCCritical(C_SQL) << "Field Name " << key <<
" not found in result set";
return ret;
}
int columns = record.count();
QStringList cols;
for (int i = 0; i < columns; ++i) {
cols.append(record.fieldName(i));
}
while (query.next()) {
QVariantHash line;
for (int i = 0; i < columns; ++i) {
line.insertMulti(cols.at(i),query.value(i));
}
ret.insertMulti(query.value(key).toString(), line);
}
return ret;
}
void Sql::bindParamsToQuery(QSqlQuery &query, const Cutelyst::ParamsMultiMap ¶ms, bool htmlEscaped)
{
auto it = params.constBegin();
if (htmlEscaped) {
while (it != params.constEnd()) {
if (it.value().isNull()) {
query.bindValue(QLatin1Char(':') + it.key(), QVariant());
} else {
query.bindValue(QLatin1Char(':') + it.key(), it.value().toHtmlEscaped());
}
++it;
}
} else {
while (it != params.constEnd()) {
if (it.value().isNull()) {
query.bindValue(QLatin1Char(':') + it.key(), QVariant());
} else {
query.bindValue(QLatin1Char(':') + it.key(), it.value());
}
++it;
}
}
}
QSqlQuery Sql::preparedQuery(const QString &query, QSqlDatabase db, bool forwardOnly)
{
QSqlQuery sqlQuery(db);
sqlQuery.setForwardOnly(forwardOnly);
if (!sqlQuery.prepare(query)) {
qCCritical(C_SQL) << "Failed to prepare query:" << query << sqlQuery.lastError().databaseText();
}
return sqlQuery;
}
QSqlQuery Sql::preparedQueryThread(const QString &query, const QString &dbName, bool forwardOnly)
{
QSqlQuery sqlQuery(QSqlDatabase::database(databaseNameThread(dbName)));
sqlQuery.setForwardOnly(forwardOnly);
if (!sqlQuery.prepare(query)) {
qCCritical(C_SQL) << "Failed to prepare query:" << query << sqlQuery.lastError().databaseText();
}
return sqlQuery;
}
QString Sql::databaseNameThread(const QString &dbName)
{
return dbName + QLatin1Char('-') + QThread::currentThread()->objectName();
}
<|endoftext|> |
<commit_before><commit_msg>背景の再描画はInvalidateRect()で指示するようにした<commit_after><|endoftext|> |
<commit_before>#pragma once
#include <sstream>
#include "rapidcheck/Show.hpp"
#include "ImplicitParam.hpp"
#include "RandomEngine.hpp"
namespace rc {
namespace detail {
//! Represents the structure of value generation where large complex values are
//! generated from small simple values. This also means that large values often
//! can be shrunk by shrinking the small values individually.
class RoseNode
{
public:
//! Constructs a new root \c RoseNode.
RoseNode() : RoseNode(nullptr) {}
//! Returns an atom. If one has already been generated, it's reused. If not,
//! a new one is generated.
RandomEngine::Atom atom()
{
if (!m_hasAtom) {
ImplicitParam<param::RandomEngine> randomEngine;
m_atom = randomEngine->nextAtom();
m_hasAtom = true;
}
return m_atom;
}
//! Outputs a string representation of this node and all its children.
void print(std::ostream &os)
{
for (int i = 0; i < depth(); i++)
os << " ";
os << "- " << description() << std::endl;
for (auto &child : m_children)
child.print(os);
}
//! Generates a value in this node using the given generator.
template<typename Gen>
typename Gen::GeneratedType generate(const Gen &generator)
{
typedef typename Gen::GeneratedType T;
ImplicitParam<ShrunkNode> shrunkNode;
if (!isFrozen())
m_originalGenerator = UntypedGeneratorUP(new Gen(generator));
if (shrunkNode.hasBinding() && (*shrunkNode == nullptr)) {
if (!m_shrinkIterator) {
T value(regenerate<T>());
// Did children shrink before us?
if (*shrunkNode != nullptr)
return value;
m_shrinkIterator = generator.shrink(value);
// We need a fallback accepted generator if shrinking fails
if (!m_acceptedGenerator)
m_acceptedGenerator = UntypedGeneratorUP(new Gen(generator));
}
if (m_shrinkIterator->hasNext()) {
auto typedIterator =
dynamic_cast<ShrinkIterator<T> *>(m_shrinkIterator.get());
assert(typedIterator != nullptr);
m_currentGenerator = UntypedGeneratorUP(
new Constant<T>(typedIterator->next()));
*shrunkNode = this;
} else {
// Shrinking exhausted
m_currentGenerator = nullptr;
}
}
return regenerate<T>();
}
//! Picks a value using the given generator in the context of the current
//! node.
template<typename Gen>
typename Gen::GeneratedType pick(const Gen &generator)
{
ImplicitParam<NextChildIndex> nextChildIndex;
if (*nextChildIndex >= m_children.size())
m_children.push_back(RoseNode(this));
(*nextChildIndex)++;
return m_children[*nextChildIndex - 1].generate(generator);
}
//! Returns a list of \c ValueDescriptions from the immediate children of
//! this node.
std::vector<std::string> example()
{
std::vector<std::string> values;
values.reserve(m_children.size());
for (auto &child : m_children)
values.push_back(child.stringValue());
return values;
}
//! Returns a string representation of the value of this node or an empty
//! if one hasn't been decided.
std::string stringValue()
{
ImplicitParam<CurrentNode> currentNode;
currentNode.let(this);
ImplicitParam<NextChildIndex> nextChildIndex;
nextChildIndex.let(0);
UntypedGenerator *generator = activeGenerator();
if (generator != nullptr)
return generator->generateString();
else
return std::string();
}
//! Tries to find an immediate shrink that yields \c false for the given
//! generator.
//!
//! @return A tuple where the first value tells whether the shrinking was
//! successful and the second how many shrinks were tried,
//! regardless of success.
template<typename Gen>
std::tuple<bool, int> shrink(const Gen &generator)
{
ImplicitParam<ShrunkNode> shrunkNode;
int numTries = 0;
bool result = true;
while (result) {
numTries++;
shrunkNode.let(nullptr);
result = generate(generator);
if (*shrunkNode == nullptr)
return std::make_tuple(false, numTries);
}
(*shrunkNode)->acceptShrink();
return std::make_tuple(true, numTries);
}
//! Returns true if this node is frozen. If a node is frozen, the generator
//! passed to \c generate will only be used to infer the type, the actual
//! value will come from shrinking or similar.
bool isFrozen() const
{
return bool(m_acceptedGenerator);
}
//! Move constructor.
RoseNode(RoseNode &&other)
: m_parent(other.m_parent)
, m_children(std::move(other.m_children))
, m_hasAtom(other.m_hasAtom)
, m_atom(other.m_atom)
, m_originalGenerator(std::move(other.m_originalGenerator))
, m_acceptedGenerator(std::move(other.m_acceptedGenerator))
, m_currentGenerator(std::move(other.m_currentGenerator))
, m_shrinkIterator(std::move(other.m_shrinkIterator))
{
adoptChildren();
}
//! Move assignment
RoseNode &operator=(RoseNode &&rhs)
{
m_parent = rhs.m_parent;
m_children = std::move(rhs.m_children);
m_hasAtom = rhs.m_hasAtom;
m_atom = rhs.m_atom;
m_originalGenerator = std::move(rhs.m_originalGenerator);
m_acceptedGenerator = std::move(rhs.m_acceptedGenerator);
m_currentGenerator = std::move(rhs.m_currentGenerator);
m_shrinkIterator = std::move(rhs.m_shrinkIterator);
adoptChildren();
return *this;
}
void printExample()
{
for (const auto &desc : example())
std::cout << desc << std::endl;
}
//! Returns a reference to the current node.
static RoseNode ¤t()
{ return **ImplicitParam<CurrentNode>(); }
private:
RC_DISABLE_COPY(RoseNode)
// Implicit parameters, see ImplicitParam
struct CurrentNode { typedef RoseNode *ValueType; };
struct NextChildIndex { typedef size_t ValueType; };
struct ShrunkNode { typedef RoseNode *ValueType; };
//! Constructs a new \c RoseNode with the given parent or \c 0 if it should
//! have no parent, i.e. is root.
explicit RoseNode(RoseNode *parent) : m_parent(parent) {}
//! Returns the depth of this node.
int depth() const
{
if (m_parent == nullptr)
return 0;
return m_parent->depth() + 1;
}
//! Sets the parent of all children to this node.
void adoptChildren()
{
for (auto &child : m_children)
child.m_parent = this;
}
//! Returns a description of this node.
std::string description() const
{
return generatorName();
}
//! Returns the index of this node among its sibilings. Returns \c -1 if
//! node is root.
std::ptrdiff_t index() const
{
if (m_parent == nullptr)
return -1;
auto &siblings = m_parent->m_children;
auto it = std::find_if(
siblings.begin(),
siblings.end(),
[this](const RoseNode &node){ return &node == this; });
return it - siblings.begin();
}
//! Returns a string describing the path to this node from the root node.
std::string path()
{
if (m_parent == nullptr)
return "/ " + description();
else
return m_parent->path() + " / " + description();
}
//! Returns the active generator.
UntypedGenerator *activeGenerator() const
{
if (m_currentGenerator)
return m_currentGenerator.get();
else if (m_acceptedGenerator)
return m_acceptedGenerator.get();
else if (m_originalGenerator)
return m_originalGenerator.get();
else
return nullptr;
}
//! Returns the name of the active generator
std::string generatorName() const
{
auto gen = activeGenerator();
if (gen == nullptr)
return std::string();
else
return demangle(typeid(*gen).name());
}
//! Returns the active generator cast to a generator of the given type or
//! \c default if there is none or if there is a type mismatch.
template<typename T>
T regenerate()
{
ImplicitParam<CurrentNode> currentNode;
currentNode.let(this);
ImplicitParam<NextChildIndex> nextChildIndex;
nextChildIndex.let(0);
return (*dynamic_cast<Generator<T> *>(activeGenerator()))();
}
//! Accepts the current shrink value
void acceptShrink()
{
if (!m_currentGenerator)
return;
m_acceptedGenerator = std::move(m_currentGenerator);
m_shrinkIterator = nullptr;
}
typedef std::vector<RoseNode> Children;
RoseNode *m_parent;
Children m_children;
bool m_hasAtom = false;
RandomEngine::Atom m_atom;
UntypedGeneratorUP m_originalGenerator;
UntypedGeneratorUP m_acceptedGenerator;
UntypedGeneratorUP m_currentGenerator;
UntypedShrinkIteratorUP m_shrinkIterator;
};
} // namespace detail
} // namespace rc
<commit_msg>Some more refactoring<commit_after>#pragma once
#include <sstream>
#include "rapidcheck/Show.hpp"
#include "ImplicitParam.hpp"
#include "RandomEngine.hpp"
namespace rc {
namespace detail {
//! Represents the structure of value generation where large complex values are
//! generated from small simple values. This also means that large values often
//! can be shrunk by shrinking the small values individually.
class RoseNode
{
public:
//! Constructs a new root \c RoseNode.
RoseNode() : RoseNode(nullptr) {}
//! Returns an atom. If one has already been generated, it's reused. If not,
//! a new one is generated.
RandomEngine::Atom atom()
{
if (!m_hasAtom) {
ImplicitParam<param::RandomEngine> randomEngine;
m_atom = randomEngine->nextAtom();
m_hasAtom = true;
}
return m_atom;
}
//! Outputs the tree structure to the given output stream for debugging.
void print(std::ostream &os)
{
for (int i = 0; i < depth(); i++)
os << " ";
os << "- " << description() << std::endl;
for (auto &child : m_children)
child.print(os);
}
//! Generates a value in this node using the given generator.
template<typename Gen>
typename Gen::GeneratedType generate(const Gen &generator)
{
typedef typename Gen::GeneratedType T;
ImplicitParam<ShrunkNode> shrunkNode;
if (!isFrozen())
m_originalGenerator = UntypedGeneratorUP(new Gen(generator));
if (shrunkNode.hasBinding() && (*shrunkNode == nullptr)) {
if (!m_shrinkIterator) {
T value(regenerate<T>());
// Did children shrink before us?
if (*shrunkNode != nullptr)
return value;
m_shrinkIterator = generator.shrink(value);
// We need a fallback accepted generator if shrinking fails
if (!m_acceptedGenerator)
m_acceptedGenerator = UntypedGeneratorUP(new Gen(generator));
}
if (m_shrinkIterator->hasNext()) {
auto typedIterator =
dynamic_cast<ShrinkIterator<T> *>(m_shrinkIterator.get());
assert(typedIterator != nullptr);
m_currentGenerator = UntypedGeneratorUP(
new Constant<T>(typedIterator->next()));
*shrunkNode = this;
} else {
// Shrinking exhausted
m_currentGenerator = nullptr;
}
}
return regenerate<T>();
}
//! Picks a value using the given generator in the context of the current
//! node.
template<typename Gen>
typename Gen::GeneratedType pick(const Gen &generator)
{
ImplicitParam<NextChildIndex> nextChildIndex;
if (*nextChildIndex >= m_children.size())
m_children.push_back(RoseNode(this));
(*nextChildIndex)++;
return m_children[*nextChildIndex - 1].generate(generator);
}
//! Returns a list of \c ValueDescriptions from the immediate children of
//! this node.
std::vector<std::string> example()
{
std::vector<std::string> values;
values.reserve(m_children.size());
for (auto &child : m_children)
values.push_back(child.regenerateString());
return values;
}
//! Regenerates a string representation of the value of this node or an empty
//! if one hasn't been decided.
std::string regenerateString()
{
ImplicitParam<CurrentNode> currentNode;
currentNode.let(this);
ImplicitParam<NextChildIndex> nextChildIndex;
nextChildIndex.let(0);
UntypedGenerator *generator = activeGenerator();
if (generator != nullptr)
return generator->generateString();
else
return std::string();
}
//! Tries to find an immediate shrink that yields \c false for the given
//! generator.
//!
//! @return A tuple where the first value tells whether the shrinking was
//! successful and the second how many shrinks were tried,
//! regardless of success.
template<typename Gen>
std::tuple<bool, int> shrink(const Gen &generator)
{
ImplicitParam<ShrunkNode> shrunkNode;
int numTries = 0;
bool result = true;
while (result) {
numTries++;
shrunkNode.let(nullptr);
result = generate(generator);
if (*shrunkNode == nullptr)
return std::make_tuple(false, numTries);
}
(*shrunkNode)->acceptShrink();
return std::make_tuple(true, numTries);
}
//! Returns true if this node is frozen. If a node is frozen, the generator
//! passed to \c generate will only be used to infer the type, the actual
//! value will come from shrinking or similar.
bool isFrozen() const
{
return bool(m_acceptedGenerator);
}
//! Move constructor.
RoseNode(RoseNode &&other)
: m_parent(other.m_parent)
, m_children(std::move(other.m_children))
, m_hasAtom(other.m_hasAtom)
, m_atom(other.m_atom)
, m_originalGenerator(std::move(other.m_originalGenerator))
, m_acceptedGenerator(std::move(other.m_acceptedGenerator))
, m_currentGenerator(std::move(other.m_currentGenerator))
, m_shrinkIterator(std::move(other.m_shrinkIterator))
{
adoptChildren();
}
//! Move assignment
RoseNode &operator=(RoseNode &&rhs)
{
m_parent = rhs.m_parent;
m_children = std::move(rhs.m_children);
m_hasAtom = rhs.m_hasAtom;
m_atom = rhs.m_atom;
m_originalGenerator = std::move(rhs.m_originalGenerator);
m_acceptedGenerator = std::move(rhs.m_acceptedGenerator);
m_currentGenerator = std::move(rhs.m_currentGenerator);
m_shrinkIterator = std::move(rhs.m_shrinkIterator);
adoptChildren();
return *this;
}
//! Returns a reference to the current node.
static RoseNode ¤t()
{ return **ImplicitParam<CurrentNode>(); }
private:
RC_DISABLE_COPY(RoseNode)
// Implicit parameters, see ImplicitParam
struct CurrentNode { typedef RoseNode *ValueType; };
struct NextChildIndex { typedef size_t ValueType; };
struct ShrunkNode { typedef RoseNode *ValueType; };
//! Constructs a new \c RoseNode with the given parent or \c 0 if it should
//! have no parent, i.e. is root.
explicit RoseNode(RoseNode *parent) : m_parent(parent) {}
//! Returns the depth of this node.
int depth() const
{
if (m_parent == nullptr)
return 0;
return m_parent->depth() + 1;
}
//! Sets the parent of all children to this node.
void adoptChildren()
{
for (auto &child : m_children)
child.m_parent = this;
}
//! Returns a description of this node.
std::string description() const
{
std::string desc(generatorName());
if (m_parent != nullptr)
desc += "[" + std::toString(index()) + "]";
return desc;
}
//! Returns the index of this node among its sibilings. Returns \c -1 if
//! node is root.
std::ptrdiff_t index() const
{
if (m_parent == nullptr)
return -1;
auto &siblings = m_parent->m_children;
auto it = std::find_if(
siblings.begin(),
siblings.end(),
[this](const RoseNode &node){ return &node == this; });
return it - siblings.begin();
}
//! Returns a string describing the path to this node from the root node.
std::string path()
{
if (m_parent == nullptr)
return "/ " + description();
else
return m_parent->path() + " / " + description();
}
//! Returns the active generator.
UntypedGenerator *activeGenerator() const
{
if (m_currentGenerator)
return m_currentGenerator.get();
else if (m_acceptedGenerator)
return m_acceptedGenerator.get();
else if (m_originalGenerator)
return m_originalGenerator.get();
else
return nullptr;
}
//! Returns the name of the active generator
std::string generatorName() const
{
auto gen = activeGenerator();
if (gen == nullptr)
return std::string();
else
return demangle(typeid(*gen).name());
}
//! Returns the active generator cast to a generator of the given type or
//! \c default if there is none or if there is a type mismatch.
template<typename T>
T regenerate()
{
ImplicitParam<CurrentNode> currentNode;
currentNode.let(this);
ImplicitParam<NextChildIndex> nextChildIndex;
nextChildIndex.let(0);
return (*dynamic_cast<Generator<T> *>(activeGenerator()))();
}
//! Accepts the current shrink value
void acceptShrink()
{
if (!m_currentGenerator)
return;
m_acceptedGenerator = std::move(m_currentGenerator);
m_shrinkIterator = nullptr;
}
typedef std::vector<RoseNode> Children;
RoseNode *m_parent;
Children m_children;
bool m_hasAtom = false;
RandomEngine::Atom m_atom;
UntypedGeneratorUP m_originalGenerator;
UntypedGeneratorUP m_acceptedGenerator;
UntypedGeneratorUP m_currentGenerator;
UntypedShrinkIteratorUP m_shrinkIterator;
};
} // namespace detail
} // namespace rc
<|endoftext|> |
<commit_before>/** @file gsTrilinosSolvers.cpp
@brief Wrappers for Trilinos solvers
This file is part of the G+Smo library.
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
Author(s): A. Mantzaflaris
*/
#include <gsTrilinos/gsTrilinosSolvers.h>
#include "gsTrilinosHeaders.h"
#include "Amesos.h"
#include "Amesos_BaseSolver.h"
#include "AztecOO.h"
#include "AztecOO_Version.h"
//#include "Ifpack_ConfigDefs.h"
//#include "Ifpack.h"
//#include "Ifpack_AdditiveSchwarz.h"
//#include "Amesos_Superlu.h"
#include "gsTrilinosHeaders.h"
#include "BelosConfigDefs.hpp"
#include "BelosLinearProblem.hpp"
#include "BelosEpetraAdapter.hpp"
#include "BelosBlockGmresSolMgr.hpp"
#include "BelosBlockCGSolMgr.hpp"
namespace gismo
{
namespace trilinos
{
namespace solver
{
struct AbstractSolverPrivate
{
typedef real_t Scalar;
typedef conditional<util::is_same<Scalar,double>::value, Epetra_MultiVector,
Tpetra::MultiVector<Scalar,int,int> >::type MVector;
typedef conditional<util::is_same<Scalar,double>::value,Epetra_Operator,
Tpetra::Operator<Scalar,int,int> >::type Operator;
// Problem
Epetra_LinearProblem Problem;
// Solution vector
Vector solution;
};
AbstractSolver::AbstractSolver() : my(NULL)
{
}
AbstractSolver::AbstractSolver(const SparseMatrix & A)
: my(new AbstractSolverPrivate)
{
my->Problem.SetOperator(A.get());
my->solution.setFrom(A); // i.e. A.get()->OperatorDomainMap()
my->Problem.SetLHS(my->solution.get());
}
AbstractSolver::~AbstractSolver()
{
delete my;
}
const Vector & AbstractSolver::solve(const Vector & b)
{
my->Problem.SetRHS(b.get());
solveProblem(); // virtual call
return my->solution;
}
void AbstractSolver::getSolution( gsVector<real_t> & sol, const int rank) const
{
my->solution.copyTo(sol, rank);
}
void GMRES::solveProblem()
{
/* 1. Preconditionner */
/*
// allocates an IFPACK factory. No data is associated
Ifpack Factory;
// create the preconditioner. For valid PrecType values,
// please check the documentation
std::string PrecType = "ILU"; // incomplete LU
int OverlapLevel = 1; // must be >= 0. ignored for Comm.NumProc() == 1
Teuchos::RCP<Ifpack_Preconditioner> Prec = Teuchos::rcp( Factory.Create(PrecType, &*A, OverlapLevel) );
assert(Prec != Teuchos::null);
// specify parameters for ILU
List.set("fact: drop tolerance", 1e-9);
List.set("fact: level-of-fill", 1);
// the combine mode is on the following:
// "Add", "Zero", "Insert", "InsertAdd", "Average", "AbsMax"
// Their meaning is as defined in file Epetra_CombineMode.h
List.set("schwarz: combine mode", "Add");
// sets the parameters
IFPACK_CHK_ERR(Prec->SetParameters(List));
// initialize the preconditioner. At this point the matrix must
// have been FillComplete()'d, but actual values are ignored.
IFPACK_CHK_ERR(Prec->Initialize());
// Builds the preconditioners, by looking for the values of
// the matrix.
IFPACK_CHK_ERR(Prec->Compute());
*/
/* 2. AztecOO solver / GMRES*/
AztecOO Solver;
Solver.SetProblem(my->Problem);
Solver.SetAztecOption(AZ_solver, AZ_gmres);
Solver.SetAztecOption(AZ_output,AZ_none);//32
//Solver.SetPrecOperator(Prec);
Solver.Iterate(m_maxIter, m_tolerance);
}
void KLU::solveProblem()
{
static const char * SolverType = "Klu";
static Amesos Factory;
const bool IsAvailable = Factory.Query(SolverType);
GISMO_ENSURE(IsAvailable, "Amesos KLU is not available.\n");
Amesos_BaseSolver * Solver = Factory.Create(SolverType, my->Problem);
Solver->SymbolicFactorization();
Solver->NumericFactorization();
Solver->Solve();
}
void SuperLU::solveProblem()
{
// Amesos_Superlu Solver(my->Problem);
// Solver.SymbolicFactorization();
// Solver.NumericFactorization();
// Solver.Solve();
}
/* --- Belos--- */
struct BelosTypes // General types for use in all solvers
{
typedef real_t Scalar;
typedef conditional<util::is_same<Scalar,double>::value, Epetra_MultiVector,
Tpetra::MultiVector<Scalar,int,int> >::type MVector;
typedef conditional<util::is_same<Scalar,double>::value,Epetra_Operator,
Tpetra::Operator<Scalar,int,int> >::type Operator;
typedef Belos::SolverManager<Scalar, MVector, Operator> SolManager;
typedef Belos::LinearProblem<Scalar, MVector, Operator> LinearProblem;
};
template<int mode> // mode values define different solvers
struct BelosSolManager { BelosSolManager() {GISMO_STATIC_ASSERT(mode!=mode,INCONSISTENT_INSTANTIZATION)} };
template<>
struct BelosSolManager<BlockCG>
{ typedef Belos::BlockCGSolMgr<BelosTypes::Scalar , BelosTypes::MVector, BelosTypes::Operator> type; };
template<>
struct BelosSolManager<BlockGmres>
{ typedef Belos::BlockGmresSolMgr<BelosTypes::Scalar , BelosTypes::MVector, BelosTypes::Operator> type; };
struct BelosSolverPrivate
{
Teuchos::RCP<BelosTypes::SolManager> Solver;
Teuchos::ParameterList belosList;
BelosTypes::LinearProblem Problem;
};
template<int mode>
BelosSolver<mode>::BelosSolver(const SparseMatrix & A
//, const std::string solver_teuchosUser
)
: Base(A), myBelos(new BelosSolverPrivate), blocksize(1), maxiters(500)
{
// Note: By default the string variable SolverTeuchosUser = "Belos".
// This can be adapted to get different values if other solvers with
// similar implementation structures are considered later on.
//SolverTeuchosUser = solver_teuchosUser;
myBelos->Problem.setOperator(A.getRCP());
myBelos->Problem.setLHS(my->solution.getRCP());
// If the matrix is symmetric, specify this in the linear problem.
// my->Problem->setHermitian();
}
template<int mode>
BelosSolver<mode>::~BelosSolver()
{
delete myBelos;
}
template<int mode>
void BelosSolver<mode>::solveProblem()
{
// Grab right-hand side
myBelos->Problem.setRHS( Teuchos::rcp(my->Problem.GetRHS(), false) );
// Tell the program that setting of the linear problem is done.
// Throw an error if failed.
bool err_set = myBelos->Problem.setProblem();
GISMO_ASSERT(true == err_set, "Error: Belos Problem couldn't be"
" initialized.");
// Teuchos::ScalarTraits<double>::magnitudeType tol = 1.0e-5;
double tol = 1.0e-5;
myBelos->belosList.set( "Block Size", blocksize ); // Blocksize to be used by iterative solver
myBelos->belosList.set( "Maximum Iterations", maxiters ); // Maximum number of iterations allowed
myBelos->belosList.set( "Convergence Tolerance", tol ); // Relative convergence tolerance requested
// Create an iterative solver manager.
myBelos->Solver = Teuchos::rcp( new typename BelosSolManager<mode>::type );
myBelos->Solver->setProblem (Teuchos::rcp(&myBelos->Problem , false));
myBelos->Solver->setParameters(Teuchos::rcp(&myBelos->belosList, false));
// Perform solve
Belos::ReturnType ret = myBelos->Solver->solve();
// Get the number of iterations for this solve.
// int numIters = myBelos->Solver->getNumIters();
// // Compute actual residuals.
// bool badRes = false;
// std::vector<double> actual_resids( numrhs );
// std::vector<double> rhs_norm( numrhs );
// MVector resid(*Map, numrhs);
GISMO_ENSURE(ret == Belos::Converged , "Error: Belos Problem couldn't be"
" initialized.");
}
CLASS_TEMPLATE_INST BelosSolver<BlockGmres>;
CLASS_TEMPLATE_INST BelosSolver<BlockCG>;
};// namespace solver
};// namespace trilinos
};// namespace gismo
<commit_msg>minor changes<commit_after>/** @file gsTrilinosSolvers.cpp
@brief Wrappers for Trilinos solvers
This file is part of the G+Smo library.
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
Author(s): A. Mantzaflaris
*/
#include <gsTrilinos/gsTrilinosSolvers.h>
#include "gsTrilinosHeaders.h"
#include "Amesos.h"
#include "Amesos_BaseSolver.h"
#include "AztecOO.h"
#include "AztecOO_Version.h"
//#include "Ifpack_ConfigDefs.h"
//#include "Ifpack.h"
//#include "Ifpack_AdditiveSchwarz.h"
//#include "Amesos_Superlu.h"
#include "gsTrilinosHeaders.h"
#include "BelosConfigDefs.hpp"
#include "BelosLinearProblem.hpp"
#include "BelosEpetraAdapter.hpp"
#include "BelosBlockGmresSolMgr.hpp"
#include "BelosBlockCGSolMgr.hpp"
namespace gismo
{
namespace trilinos
{
struct DataTypes // General types for use in all solvers
{
typedef real_t Scalar;
typedef conditional<util::is_same<Scalar,double>::value, Epetra_MultiVector,
Tpetra::MultiVector<Scalar,int,int> >::type MVector;
typedef conditional<util::is_same<Scalar,double>::value,Epetra_Operator,
Tpetra::Operator<Scalar,int,int> >::type Operator;
typedef Belos::SolverManager<Scalar, MVector, Operator> SolManager;
typedef Belos::LinearProblem<Scalar, MVector, Operator> BelosLp;
typedef Epetra_LinearProblem EpetraLp;
//typedef Teuchos::ParameterList
};
namespace solver
{
struct AbstractSolverPrivate
{
// Problem
DataTypes::EpetraLp Problem;
// Solution vector
Vector solution;
};
AbstractSolver::AbstractSolver() : my(NULL)
{
}
AbstractSolver::AbstractSolver(const SparseMatrix & A)
: my(new AbstractSolverPrivate)
{
my->Problem.SetOperator(A.get());
my->solution.setFrom(A); // i.e. A.get()->OperatorDomainMap()
my->Problem.SetLHS(my->solution.get());
}
AbstractSolver::~AbstractSolver()
{
delete my;
}
const Vector & AbstractSolver::solve(const Vector & b)
{
my->Problem.SetRHS(b.get());
solveProblem(); // virtual call
return my->solution;
}
void AbstractSolver::getSolution( gsVector<real_t> & sol, const int rank) const
{
my->solution.copyTo(sol, rank);
}
void GMRES::solveProblem()
{
/* 1. Preconditionner */
/*
// allocates an IFPACK factory. No data is associated
Ifpack Factory;
// create the preconditioner. For valid PrecType values,
// please check the documentation
std::string PrecType = "ILU"; // incomplete LU
int OverlapLevel = 1; // must be >= 0. ignored for Comm.NumProc() == 1
Teuchos::RCP<Ifpack_Preconditioner> Prec = Teuchos::rcp( Factory.Create(PrecType, &*A, OverlapLevel) );
assert(Prec != Teuchos::null);
// specify parameters for ILU
List.set("fact: drop tolerance", 1e-9);
List.set("fact: level-of-fill", 1);
// the combine mode is on the following:
// "Add", "Zero", "Insert", "InsertAdd", "Average", "AbsMax"
// Their meaning is as defined in file Epetra_CombineMode.h
List.set("schwarz: combine mode", "Add");
// sets the parameters
IFPACK_CHK_ERR(Prec->SetParameters(List));
// initialize the preconditioner. At this point the matrix must
// have been FillComplete()'d, but actual values are ignored.
IFPACK_CHK_ERR(Prec->Initialize());
// Builds the preconditioners, by looking for the values of
// the matrix.
IFPACK_CHK_ERR(Prec->Compute());
*/
/* 2. AztecOO solver / GMRES*/
AztecOO Solver;
Solver.SetProblem(my->Problem);
Solver.SetAztecOption(AZ_solver, AZ_gmres);
Solver.SetAztecOption(AZ_output,AZ_none);//32
//Solver.SetPrecOperator(Prec);
Solver.Iterate(m_maxIter, m_tolerance);
}
void KLU::solveProblem()
{
static const char * SolverType = "Klu";
static Amesos Factory;
const bool IsAvailable = Factory.Query(SolverType);
GISMO_ENSURE(IsAvailable, "Amesos KLU is not available.\n");
Amesos_BaseSolver * Solver = Factory.Create(SolverType, my->Problem);
Solver->SymbolicFactorization();
Solver->NumericFactorization();
Solver->Solve();
}
void SuperLU::solveProblem()
{
// Amesos_Superlu Solver(my->Problem);
// Solver.SymbolicFactorization();
// Solver.NumericFactorization();
// Solver.Solve();
}
/* --- Belos--- */
// mode values define different solvers
template<int mode> struct BelosSolManager { };
template<>
struct BelosSolManager<BlockCG>
{ typedef Belos::BlockCGSolMgr<DataTypes::Scalar , DataTypes::MVector, DataTypes::Operator> type; };
template<>
struct BelosSolManager<BlockGmres>
{ typedef Belos::BlockGmresSolMgr<DataTypes::Scalar , DataTypes::MVector, DataTypes::Operator> type; };
struct BelosSolverPrivate
{
Teuchos::RCP<DataTypes::SolManager> Solver;
Teuchos::ParameterList belosList;
DataTypes::BelosLp Problem;
};
template<int mode>
BelosSolver<mode>::BelosSolver(const SparseMatrix & A
//, const std::string solver_teuchosUser
)
: Base(A), myBelos(new BelosSolverPrivate), blocksize(1), maxiters(500)
{
// Note: By default the string variable SolverTeuchosUser = "Belos".
// This can be adapted to get different values if other solvers with
// similar implementation structures are considered later on.
//SolverTeuchosUser = solver_teuchosUser;
// Initialize solver manager
myBelos->Solver = Teuchos::rcp( new typename BelosSolManager<mode>::type );
myBelos->Problem.setOperator(A.getRCP());
myBelos->Problem.setLHS(my->solution.getRCP());
// If the matrix is symmetric, specify this in the linear problem.
// my->Problem->setHermitian();
}
template<int mode>
BelosSolver<mode>::~BelosSolver()
{
delete myBelos;
}
template<int mode>
void BelosSolver<mode>::solveProblem()
{
// Grab right-hand side
myBelos->Problem.setRHS( Teuchos::rcp(my->Problem.GetRHS(), false) );
// Tell the program that setting of the linear problem is done.
// Throw an error if failed.
bool err_set = myBelos->Problem.setProblem();
GISMO_ASSERT(true == err_set, "Error: Belos Problem couldn't be"
" initialized.");
// Teuchos::ScalarTraits<double>::magnitudeType tol = 1.0e-5;
double tol = 1.0e-5;
myBelos->belosList.set( "Block Size", blocksize ); // Blocksize to be used by iterative solver
myBelos->belosList.set( "Maximum Iterations", maxiters ); // Maximum number of iterations allowed
myBelos->belosList.set( "Convergence Tolerance", tol ); // Relative convergence tolerance requested
// Set the solver manager data.
myBelos->Solver->setProblem (Teuchos::rcp(&myBelos->Problem , false));
myBelos->Solver->setParameters(Teuchos::rcp(&myBelos->belosList, false));
// Perform solve
Belos::ReturnType ret = myBelos->Solver->solve();
// Get the number of iterations for this solve.
// int numIters = myBelos->Solver->getNumIters();
// // Compute actual residuals.
// bool badRes = false;
// std::vector<double> actual_resids( numrhs );
// std::vector<double> rhs_norm( numrhs );
// MVector resid(*Map, numrhs);
GISMO_ENSURE(ret == Belos::Converged , "Error: Belos Problem couldn't be"
" initialized.");
}
CLASS_TEMPLATE_INST BelosSolver<BlockGmres>;
CLASS_TEMPLATE_INST BelosSolver<BlockCG>;
};// namespace solver
};// namespace trilinos
};// namespace gismo
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2003 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#endif
#include "common.h"
#include "ShotUpdate.h"
//
// ShotUpdate
//
void* ShotUpdate::pack(void* buf) const
{
buf = nboPackUByte(buf, player);
buf = nboPackUShort(buf, id);
buf = nboPackVector(buf, pos);
buf = nboPackVector(buf, vel);
buf = nboPackFloat(buf, dt);
buf = nboPackShort(buf, team);
return buf;
}
void* ShotUpdate::unpack(void* buf)
{
buf = nboUnpackUByte(buf, player);
buf = nboUnpackUShort(buf, id);
buf = nboUnpackVector(buf, pos);
buf = nboUnpackVector(buf, vel);
buf = nboUnpackFloat(buf, dt);
short temp = team;
buf = nboUnpackShort(buf, temp);
return buf;
}
//
// FiringInfo
//
FiringInfo::FiringInfo()
{
// do nothing -- must be prepared before use by unpack() or assignment
}
void* FiringInfo::pack(void* buf) const
{
buf = shot.pack(buf);
buf = flagType->pack(buf);
buf = nboPackFloat(buf, lifetime);
return buf;
}
void* FiringInfo::unpack(void* buf)
{
buf = shot.unpack(buf);
buf = FlagType::unpack(buf, flagType);
buf = nboUnpackFloat(buf, lifetime);
return buf;
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>Yeah, this shoud explain killed by teammate, problem with rabbit and others<commit_after>/* bzflag
* Copyright (c) 1993 - 2003 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#endif
#include "common.h"
#include "ShotUpdate.h"
//
// ShotUpdate
//
void* ShotUpdate::pack(void* buf) const
{
buf = nboPackUByte(buf, player);
buf = nboPackUShort(buf, id);
buf = nboPackVector(buf, pos);
buf = nboPackVector(buf, vel);
buf = nboPackFloat(buf, dt);
buf = nboPackShort(buf, team);
return buf;
}
void* ShotUpdate::unpack(void* buf)
{
buf = nboUnpackUByte(buf, player);
buf = nboUnpackUShort(buf, id);
buf = nboUnpackVector(buf, pos);
buf = nboUnpackVector(buf, vel);
buf = nboUnpackFloat(buf, dt);
short temp;
buf = nboUnpackShort(buf, temp);
team = (TeamColor)temp;
return buf;
}
//
// FiringInfo
//
FiringInfo::FiringInfo()
{
// do nothing -- must be prepared before use by unpack() or assignment
}
void* FiringInfo::pack(void* buf) const
{
buf = shot.pack(buf);
buf = flagType->pack(buf);
buf = nboPackFloat(buf, lifetime);
return buf;
}
void* FiringInfo::unpack(void* buf)
{
buf = shot.unpack(buf);
buf = FlagType::unpack(buf, flagType);
buf = nboUnpackFloat(buf, lifetime);
return buf;
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>/*
* ThreadPool.cpp
* OpenLieroX
*
* Created by Albert Zeyer on 08.02.09.
* code under LGPL
*
*/
#include <SDL_thread.h>
#include "ThreadPool.h"
#include "Debug.h"
static const unsigned int THREADNUM = 20;
ThreadPool::ThreadPool() {
nextAction = NULL; nextIsHeadless = false; nextData = NULL;
mutex = SDL_CreateMutex();
awakeThread = SDL_CreateCond();
threadStartedWork = SDL_CreateCond();
threadFinishedWork = SDL_CreateCond();
startMutex = SDL_CreateMutex();
SDL_mutexP(mutex);
notes << "ThreadPool: creating " << THREADNUM << " threads ..." << endl;
while(availableThreads.size() < THREADNUM)
prepareNewThread();
SDL_mutexV(mutex);
}
ThreadPool::~ThreadPool() {
waitAll();
// this is the hint for all available threads to break
nextAction = NULL;
SDL_CondBroadcast(awakeThread);
for(std::set<ThreadPoolItem*>::iterator i = availableThreads.begin(); i != availableThreads.end(); ++i) {
SDL_WaitThread((*i)->thread, NULL);
SDL_DestroyCond((*i)->finishedSignal);
SDL_DestroyCond((*i)->readyForNewWork);
delete *i;
}
availableThreads.clear();
SDL_DestroyMutex(startMutex);
SDL_DestroyCond(threadStartedWork);
SDL_DestroyCond(threadFinishedWork);
SDL_DestroyCond(awakeThread);
SDL_DestroyMutex(mutex);
}
void ThreadPool::prepareNewThread() {
ThreadPoolItem* t = new ThreadPoolItem();
t->pool = this;
t->finishedSignal = SDL_CreateCond();
t->readyForNewWork = SDL_CreateCond();
t->finished = false;
t->working = false;
availableThreads.insert(t);
t->thread = SDL_CreateThread(threadWrapper, t);
}
int ThreadPool::threadWrapper(void* param) {
ThreadPoolItem* data = (ThreadPoolItem*)param;
SDL_mutexP(data->pool->mutex);
while(true) {
if(data->pool->nextAction == NULL)
SDL_CondWait(data->pool->awakeThread, data->pool->mutex);
if(data->pool->nextAction == NULL) break;
data->pool->usedThreads.insert(data);
data->pool->availableThreads.erase(data);
Action* act = data->pool->nextAction; data->pool->nextAction = NULL;
data->headless = data->pool->nextIsHeadless;
data->name = data->pool->nextName;
data->finished = false;
data->working = true;
data->pool->nextData = data;
SDL_mutexV(data->pool->mutex);
SDL_CondSignal(data->pool->threadStartedWork);
data->ret = act->handle();
delete act;
SDL_mutexP(data->pool->mutex);
data->finished = true;
if(!data->headless) { // headless means that we just can clean it up right now without waiting
SDL_CondSignal(data->finishedSignal);
while(data->working) SDL_CondWait(data->readyForNewWork, data->pool->mutex);
} else
data->working = false;
data->pool->usedThreads.erase(data);
data->pool->availableThreads.insert(data);
SDL_CondSignal(data->pool->threadFinishedWork);
}
SDL_mutexV(data->pool->mutex);
return 0;
}
ThreadPoolItem* ThreadPool::start(Action* act, const std::string& name, bool headless) {
SDL_mutexP(startMutex); // If start() method will be called from different threads without mutex, hard-to-find crashes will occur
SDL_mutexP(mutex);
if(availableThreads.size() == 0) {
warnings << "no available thread in ThreadPool for " << name << ", creating new one..." << endl;
prepareNewThread();
}
assert(nextAction == NULL);
nextAction = act;
nextIsHeadless = headless;
nextName = name;
assert(nextData == NULL);
SDL_mutexV(mutex);
int ret = SDL_CondSignal(awakeThread);
SDL_mutexP(mutex);
while(nextData == NULL) SDL_CondWait(threadStartedWork, mutex);
ThreadPoolItem* data = nextData; nextData = NULL;
SDL_mutexV(mutex);
SDL_mutexV(startMutex);
return data;
}
ThreadPoolItem* ThreadPool::start(ThreadFunc fct, void* param, const std::string& name) {
struct StaticAction : Action {
ThreadFunc fct; void* param;
int handle() { return (*fct) (param); }
};
StaticAction* act = new StaticAction();
act->fct = fct;
act->param = param;
ThreadPoolItem* item = start(act, name);
if(item) return item;
delete act;
return NULL;
}
bool ThreadPool::wait(ThreadPoolItem* thread, int* status) {
if(!thread) return false;
SDL_mutexP(mutex);
if(!thread->working) {
warnings << "given thread " << thread->name << " is not working anymore" << endl;
SDL_mutexV(mutex);
return false;
}
while(!thread->finished) SDL_CondWait(thread->finishedSignal, mutex);
if(status) *status = thread->ret;
thread->working = false;
SDL_mutexV(mutex);
SDL_CondSignal(thread->readyForNewWork);
return true;
}
bool ThreadPool::waitAll() {
SDL_mutexP(mutex);
while(usedThreads.size() > 0) {
warnings << "ThreadPool: waiting for " << usedThreads.size() << " threads to finish:" << endl;
for(std::set<ThreadPoolItem*>::iterator i = usedThreads.begin(); i != usedThreads.end(); ++i) {
if((*i)->working && (*i)->finished) {
warnings << "thread " << (*i)->name << " is ready but was not cleaned up" << endl;
(*i)->working = false;
SDL_CondSignal((*i)->readyForNewWork);
}
else if((*i)->working && !(*i)->finished) {
warnings << "thread " << (*i)->name << " is still working" << endl;
}
else {
warnings << "thread " << (*i)->name << " is in an invalid state" << endl;
}
}
SDL_CondWait(threadFinishedWork, mutex);
}
SDL_mutexV(mutex);
return true;
}
ThreadPool* threadPool = NULL;
void InitThreadPool() {
if(!threadPool)
threadPool = new ThreadPool();
else
errors << "ThreadPool inited twice" << endl;
}
void UnInitThreadPool() {
if(threadPool) {
delete threadPool;
threadPool = NULL;
} else
errors << "ThreadPool already uninited" << endl;
}
<commit_msg>removed obsolte mutex locks<commit_after>/*
* ThreadPool.cpp
* OpenLieroX
*
* Created by Albert Zeyer on 08.02.09.
* code under LGPL
*
*/
#include <SDL_thread.h>
#include "ThreadPool.h"
#include "Debug.h"
static const unsigned int THREADNUM = 20;
ThreadPool::ThreadPool() {
nextAction = NULL; nextIsHeadless = false; nextData = NULL;
mutex = SDL_CreateMutex();
awakeThread = SDL_CreateCond();
threadStartedWork = SDL_CreateCond();
threadFinishedWork = SDL_CreateCond();
startMutex = SDL_CreateMutex();
notes << "ThreadPool: creating " << THREADNUM << " threads ..." << endl;
while(availableThreads.size() < THREADNUM)
prepareNewThread();
}
ThreadPool::~ThreadPool() {
waitAll();
// this is the hint for all available threads to break
nextAction = NULL;
SDL_CondBroadcast(awakeThread);
for(std::set<ThreadPoolItem*>::iterator i = availableThreads.begin(); i != availableThreads.end(); ++i) {
SDL_WaitThread((*i)->thread, NULL);
SDL_DestroyCond((*i)->finishedSignal);
SDL_DestroyCond((*i)->readyForNewWork);
delete *i;
}
availableThreads.clear();
SDL_DestroyMutex(startMutex);
SDL_DestroyCond(threadStartedWork);
SDL_DestroyCond(threadFinishedWork);
SDL_DestroyCond(awakeThread);
SDL_DestroyMutex(mutex);
}
void ThreadPool::prepareNewThread() {
ThreadPoolItem* t = new ThreadPoolItem();
t->pool = this;
t->finishedSignal = SDL_CreateCond();
t->readyForNewWork = SDL_CreateCond();
t->finished = false;
t->working = false;
availableThreads.insert(t);
t->thread = SDL_CreateThread(threadWrapper, t);
}
int ThreadPool::threadWrapper(void* param) {
ThreadPoolItem* data = (ThreadPoolItem*)param;
SDL_mutexP(data->pool->mutex);
while(true) {
if(data->pool->nextAction == NULL)
SDL_CondWait(data->pool->awakeThread, data->pool->mutex);
if(data->pool->nextAction == NULL) break;
data->pool->usedThreads.insert(data);
data->pool->availableThreads.erase(data);
Action* act = data->pool->nextAction; data->pool->nextAction = NULL;
data->headless = data->pool->nextIsHeadless;
data->name = data->pool->nextName;
data->finished = false;
data->working = true;
data->pool->nextData = data;
SDL_mutexV(data->pool->mutex);
SDL_CondSignal(data->pool->threadStartedWork);
data->ret = act->handle();
delete act;
SDL_mutexP(data->pool->mutex);
data->finished = true;
if(!data->headless) { // headless means that we just can clean it up right now without waiting
SDL_CondSignal(data->finishedSignal);
while(data->working) SDL_CondWait(data->readyForNewWork, data->pool->mutex);
} else
data->working = false;
data->pool->usedThreads.erase(data);
data->pool->availableThreads.insert(data);
SDL_CondSignal(data->pool->threadFinishedWork);
}
SDL_mutexV(data->pool->mutex);
return 0;
}
ThreadPoolItem* ThreadPool::start(Action* act, const std::string& name, bool headless) {
SDL_mutexP(startMutex); // If start() method will be called from different threads without mutex, hard-to-find crashes will occur
SDL_mutexP(mutex);
if(availableThreads.size() == 0) {
warnings << "no available thread in ThreadPool for " << name << ", creating new one..." << endl;
prepareNewThread();
}
assert(nextAction == NULL);
assert(nextData == NULL);
nextAction = act;
nextIsHeadless = headless;
nextName = name;
SDL_CondSignal(awakeThread);
while(nextData == NULL) SDL_CondWait(threadStartedWork, mutex);
ThreadPoolItem* data = nextData; nextData = NULL;
SDL_mutexV(mutex);
SDL_mutexV(startMutex);
return data;
}
ThreadPoolItem* ThreadPool::start(ThreadFunc fct, void* param, const std::string& name) {
struct StaticAction : Action {
ThreadFunc fct; void* param;
int handle() { return (*fct) (param); }
};
StaticAction* act = new StaticAction();
act->fct = fct;
act->param = param;
ThreadPoolItem* item = start(act, name);
if(item) return item;
delete act;
return NULL;
}
bool ThreadPool::wait(ThreadPoolItem* thread, int* status) {
if(!thread) return false;
SDL_mutexP(mutex);
if(!thread->working) {
warnings << "given thread " << thread->name << " is not working anymore" << endl;
SDL_mutexV(mutex);
return false;
}
while(!thread->finished) SDL_CondWait(thread->finishedSignal, mutex);
if(status) *status = thread->ret;
thread->working = false;
SDL_mutexV(mutex);
SDL_CondSignal(thread->readyForNewWork);
return true;
}
bool ThreadPool::waitAll() {
SDL_mutexP(mutex);
while(usedThreads.size() > 0) {
warnings << "ThreadPool: waiting for " << usedThreads.size() << " threads to finish:" << endl;
for(std::set<ThreadPoolItem*>::iterator i = usedThreads.begin(); i != usedThreads.end(); ++i) {
if((*i)->working && (*i)->finished) {
warnings << "thread " << (*i)->name << " is ready but was not cleaned up" << endl;
(*i)->working = false;
SDL_CondSignal((*i)->readyForNewWork);
}
else if((*i)->working && !(*i)->finished) {
warnings << "thread " << (*i)->name << " is still working" << endl;
}
else {
warnings << "thread " << (*i)->name << " is in an invalid state" << endl;
}
}
SDL_CondWait(threadFinishedWork, mutex);
}
SDL_mutexV(mutex);
return true;
}
ThreadPool* threadPool = NULL;
void InitThreadPool() {
if(!threadPool)
threadPool = new ThreadPool();
else
errors << "ThreadPool inited twice" << endl;
}
void UnInitThreadPool() {
if(threadPool) {
delete threadPool;
threadPool = NULL;
} else
errors << "ThreadPool already uninited" << endl;
}
<|endoftext|> |
<commit_before>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2010 Dreamhost
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include "auth/AuthSupported.h"
#include "auth/KeyRing.h"
#include "common/safe_io.h"
#include "config.h"
#include "common/common_init.h"
#include "common/errno.h"
#include "common/signal.h"
#include "include/color.h"
/* Set foreground logging
*
* Forces the process to log only to stderr, overriding whatever was in the ceph.conf.
*
* TODO: make this configurable by a command line switch or environment variable, if users want
* an unusual logging setup for their foreground process.
*/
void set_foreground_logging()
{
free((void*)g_conf.log_file);
g_conf.log_file = NULL;
free((void*)g_conf.log_dir);
g_conf.log_dir = NULL;
free((void*)g_conf.log_sym_dir);
g_conf.log_sym_dir = NULL;
g_conf.log_sym_history = 0;
g_conf.log_to_stderr = LOG_TO_STDERR_ALL;
g_conf.log_to_syslog = false;
g_conf.log_per_instance = false;
g_conf.log_to_file = false;
}
void common_set_defaults(bool daemon)
{
if (daemon) {
cout << TEXT_YELLOW << " ** WARNING: Ceph is still under heavy development, and is only suitable for **" << TEXT_NORMAL << std::endl;
cout << TEXT_YELLOW << " ** testing and review. Do not trust it with important data. **" << TEXT_NORMAL << std::endl;
g_conf.daemonize = true;
} else {
g_conf.pid_file = 0;
}
}
static void keyring_init(const char *filesearch)
{
const char *filename = filesearch;
string keyring_search = g_conf.keyring;
string new_keyring;
if (ceph_resolve_file_search(keyring_search, new_keyring)) {
filename = new_keyring.c_str();
}
int ret = g_keyring.load(filename);
if (ret) {
derr << "keyring_init: failed to load " << filename << dendl;
return;
}
if (g_conf.key && g_conf.key[0]) {
string k = g_conf.key;
EntityAuth ea;
ea.key.decode_base64(k);
g_keyring.add(*g_conf.entity_name, ea);
} else if (g_conf.keyfile && g_conf.keyfile[0]) {
char buf[100];
int fd = ::open(g_conf.keyfile, O_RDONLY);
if (fd < 0) {
int err = errno;
derr << "unable to open " << g_conf.keyfile << ": "
<< cpp_strerror(err) << dendl;
ceph_abort();
}
memset(buf, 0, sizeof(buf));
int len = safe_read(fd, buf, sizeof(buf) - 1);
if (len < 0) {
derr << "unable to read key from " << g_conf.keyfile << ": "
<< cpp_strerror(len) << dendl;
TEMP_FAILURE_RETRY(::close(fd));
ceph_abort();
}
TEMP_FAILURE_RETRY(::close(fd));
buf[len] = 0;
string k = buf;
EntityAuth ea;
ea.key.decode_base64(k);
g_keyring.add(*g_conf.entity_name, ea);
}
}
void common_init(std::vector<const char*>& args, const char *module_type, int flags)
{
parse_startup_config_options(args, module_type, flags);
parse_config_options(args);
install_standard_sighandlers();
#ifdef HAVE_LIBTCMALLOC
if (g_conf.tcmalloc_profiler_run && g_conf.tcmalloc_have) {
char profile_name[PATH_MAX];
sprintf(profile_name, "%s/%s", g_conf.log_dir, g_conf.name);
char *val = new char[sizeof(int)*8+1];
sprintf(val, "%i", g_conf.profiler_allocation_interval);
setenv("HEAP_PROFILE_ALLOCATION_INTERVAL", val, g_conf.profiler_allocation_interval);
sprintf(val, "%i", g_conf.profiler_highwater_interval);
setenv("HEAP_PROFILE_INUSE_INTERVAL", val, g_conf.profiler_highwater_interval);
generic_dout(0) << "turning on heap profiler with prefix " << profile_name << dendl;
g_conf.profiler_start(profile_name);
}
#endif //HAVE_LIBTCMALLOC
if (flags & STARTUP_FLAG_INIT_KEYS) {
if (is_supported_auth(CEPH_AUTH_CEPHX))
keyring_init(g_conf.keyring);
}
}
<commit_msg>keyring_init: g_conf.keyring is not a list<commit_after>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2010 Dreamhost
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include "auth/AuthSupported.h"
#include "auth/KeyRing.h"
#include "common/safe_io.h"
#include "config.h"
#include "common/common_init.h"
#include "common/errno.h"
#include "common/signal.h"
#include "include/color.h"
/* Set foreground logging
*
* Forces the process to log only to stderr, overriding whatever was in the ceph.conf.
*
* TODO: make this configurable by a command line switch or environment variable, if users want
* an unusual logging setup for their foreground process.
*/
void set_foreground_logging()
{
free((void*)g_conf.log_file);
g_conf.log_file = NULL;
free((void*)g_conf.log_dir);
g_conf.log_dir = NULL;
free((void*)g_conf.log_sym_dir);
g_conf.log_sym_dir = NULL;
g_conf.log_sym_history = 0;
g_conf.log_to_stderr = LOG_TO_STDERR_ALL;
g_conf.log_to_syslog = false;
g_conf.log_per_instance = false;
g_conf.log_to_file = false;
}
void common_set_defaults(bool daemon)
{
if (daemon) {
cout << TEXT_YELLOW << " ** WARNING: Ceph is still under heavy development, and is only suitable for **" << TEXT_NORMAL << std::endl;
cout << TEXT_YELLOW << " ** testing and review. Do not trust it with important data. **" << TEXT_NORMAL << std::endl;
g_conf.daemonize = true;
} else {
g_conf.pid_file = 0;
}
}
static void keyring_init(const char *filesearch)
{
int ret = g_keyring.load(g_conf.keyring);
if (ret) {
derr << "keyring_init: failed to load " << g_conf.keyring << dendl;
return;
}
if (g_conf.key && g_conf.key[0]) {
string k = g_conf.key;
EntityAuth ea;
ea.key.decode_base64(k);
g_keyring.add(*g_conf.entity_name, ea);
} else if (g_conf.keyfile && g_conf.keyfile[0]) {
char buf[100];
int fd = ::open(g_conf.keyfile, O_RDONLY);
if (fd < 0) {
int err = errno;
derr << "unable to open " << g_conf.keyfile << ": "
<< cpp_strerror(err) << dendl;
ceph_abort();
}
memset(buf, 0, sizeof(buf));
int len = safe_read(fd, buf, sizeof(buf) - 1);
if (len < 0) {
derr << "unable to read key from " << g_conf.keyfile << ": "
<< cpp_strerror(len) << dendl;
TEMP_FAILURE_RETRY(::close(fd));
ceph_abort();
}
TEMP_FAILURE_RETRY(::close(fd));
buf[len] = 0;
string k = buf;
EntityAuth ea;
ea.key.decode_base64(k);
g_keyring.add(*g_conf.entity_name, ea);
}
}
void common_init(std::vector<const char*>& args, const char *module_type, int flags)
{
parse_startup_config_options(args, module_type, flags);
parse_config_options(args);
install_standard_sighandlers();
#ifdef HAVE_LIBTCMALLOC
if (g_conf.tcmalloc_profiler_run && g_conf.tcmalloc_have) {
char profile_name[PATH_MAX];
sprintf(profile_name, "%s/%s", g_conf.log_dir, g_conf.name);
char *val = new char[sizeof(int)*8+1];
sprintf(val, "%i", g_conf.profiler_allocation_interval);
setenv("HEAP_PROFILE_ALLOCATION_INTERVAL", val, g_conf.profiler_allocation_interval);
sprintf(val, "%i", g_conf.profiler_highwater_interval);
setenv("HEAP_PROFILE_INUSE_INTERVAL", val, g_conf.profiler_highwater_interval);
generic_dout(0) << "turning on heap profiler with prefix " << profile_name << dendl;
g_conf.profiler_start(profile_name);
}
#endif //HAVE_LIBTCMALLOC
if (flags & STARTUP_FLAG_INIT_KEYS) {
if (is_supported_auth(CEPH_AUTH_CEPHX))
keyring_init(g_conf.keyring);
}
}
<|endoftext|> |
<commit_before>#pragma once
#include <cmath>
#include <set>
#include <algorithm>
#include <vector>
namespace ncv
{
///
/// \brief search for a 1D parameter that minimizes a given operator,
/// using a greedy approach on the logarithmic scale in the range [minlog, maxlog].
///
/// \returns the result associated with the optimum (log) paramerer.
///
template
<
typename toperator, ///< toperator(tscalar param) returns the optimal result for that parameter
typename tscalar,
typename tsize
>
auto log_min_search(const toperator& op, tscalar minlog, tscalar maxlog, tscalar epslog, tsize splits)
-> decltype(op(tscalar(0)))
{
typedef decltype(op(tscalar(0))) tresult;
typedef std::pair<tresult, tscalar> tvalue;
std::set<tvalue> history;
splits = std::max(tsize(4), splits);
for ( tscalar varlog = (maxlog - minlog) / tscalar(splits - 1);
(maxlog - minlog) > epslog && epslog > tscalar(0);
varlog = varlog / splits)
{
for (tsize i = 0; i < splits; i ++)
{
const tscalar log = minlog + i * varlog;
history.insert(std::make_pair(op(std::exp(log)), log));
}
const tvalue& optimum = *history.begin();
minlog = optimum.second - varlog * tscalar(splits - 1) / tscalar(splits);
maxlog = optimum.second + varlog * tscalar(splits - 1) / tscalar(splits);
}
return history.empty() ? tresult() : history.begin()->first;
}
///
/// \brief multi-threaded search for a 1D parameter that minimizes a given operator,
/// using a greedy approach on the logarithmic scale in the range [minlog, maxlog].
///
/// \returns the result associated with the optimum (log) paramerer.
///
template
<
typename toperator, ///< toperator(tscalar param) returns the optimal result for that parameter
typename tpool, ///< thread pool
typename tscalar,
typename tsize
>
auto log_min_search_mt(const toperator& op, tpool& pool, tscalar minlog, tscalar maxlog, tscalar epslog, tsize splits)
-> decltype(op(tscalar(0)))
{
typedef decltype(op(tscalar(0))) tresult;
typedef std::pair<tresult, tscalar> tvalue;
std::set<tvalue> history;
std::vector<tvalue> results(splits);
splits = std::max(tsize(4), splits);
for ( tscalar varlog = (maxlog - minlog) / tscalar(splits - 1);
(maxlog - minlog) > epslog && epslog > tscalar(0);
varlog = varlog / splits)
{
for (tsize i = 0; i < splits; i ++)
{
const tscalar log = minlog + i * varlog;
pool.enqueue([=,&results,&op]()
{
results[i] = std::make_pair(op(std::exp(log)), log);
});
}
pool.wait(); // synchronize
history.insert(results.begin(), results.end()); // update history
const tvalue& optimum = *history.begin();
minlog = optimum.second - varlog * tscalar(splits - 1) / tscalar(splits);
maxlog = optimum.second + varlog * tscalar(splits - 1) / tscalar(splits);
}
return history.empty() ? tresult() : history.begin()->first;
}
}
<commit_msg>fix issue with the address sanitizer<commit_after>#pragma once
#include <cmath>
#include <set>
#include <algorithm>
#include <vector>
namespace ncv
{
///
/// \brief search for a 1D parameter that minimizes a given operator,
/// using a greedy approach on the logarithmic scale in the range [minlog, maxlog].
///
/// \returns the result associated with the optimum (log) paramerer.
///
template
<
typename toperator, ///< toperator(tscalar param) returns the optimal result for that parameter
typename tscalar,
typename tsize
>
auto log_min_search(const toperator& op, tscalar minlog, tscalar maxlog, tscalar epslog, tsize splits)
-> decltype(op(tscalar(0)))
{
typedef decltype(op(tscalar(0))) tresult;
typedef std::pair<tresult, tscalar> tvalue;
std::set<tvalue> history;
splits = std::max(tsize(4), splits);
for ( tscalar varlog = (maxlog - minlog) / tscalar(splits - 1);
(maxlog - minlog) > epslog && epslog > tscalar(0);
varlog = varlog / splits)
{
for (tsize i = 0; i < splits; i ++)
{
const tscalar log = minlog + i * varlog;
const tresult result = op(std::exp(log));
history.insert(std::make_pair(result, log));
}
const tvalue& optimum = *history.begin();
minlog = optimum.second - varlog * tscalar(splits - 1) / tscalar(splits);
maxlog = optimum.second + varlog * tscalar(splits - 1) / tscalar(splits);
}
return history.empty() ? tresult() : history.begin()->first;
}
///
/// \brief multi-threaded search for a 1D parameter that minimizes a given operator,
/// using a greedy approach on the logarithmic scale in the range [minlog, maxlog].
///
/// \returns the result associated with the optimum (log) paramerer.
///
template
<
typename toperator, ///< toperator(tscalar param) returns the optimal result for that parameter
typename tpool, ///< thread pool
typename tscalar,
typename tsize
>
auto log_min_search_mt(const toperator& op, tpool& pool, tscalar minlog, tscalar maxlog, tscalar epslog, tsize splits)
-> decltype(op(tscalar(0)))
{
typedef decltype(op(tscalar(0))) tresult;
typedef std::pair<tresult, tscalar> tvalue;
typedef typename tpool::mutex_t tmutex;
typedef typename tpool::lock_t tlock;
std::set<tvalue> history;
tmutex mutex;
splits = std::max(tsize(4), splits);
for ( tscalar varlog = (maxlog - minlog) / tscalar(splits - 1);
(maxlog - minlog) > epslog && epslog > tscalar(0);
varlog = varlog / splits)
{
for (tsize i = 0; i < splits; i ++)
{
pool.enqueue([=,&history,&mutex,&op]()
{
const tscalar log = minlog + i * varlog;
const tresult result = op(std::exp(log));
// synchronize per thread
const tlock lock(mutex);
history.insert(std::make_pair(result, log));
});
}
// synchronize per search step
pool.wait();
const tvalue& optimum = *history.begin();
minlog = optimum.second - varlog * tscalar(splits - 1) / tscalar(splits);
maxlog = optimum.second + varlog * tscalar(splits - 1) / tscalar(splits);
}
return history.empty() ? tresult() : history.begin()->first;
}
}
<|endoftext|> |
<commit_before>#include "module_handcontrol.h"
#include "module_thruster.h"
#include "module_thrustercontrolloop.h"
#include "handcontrol_form.h"
#include "server.h"
Module_HandControl::Module_HandControl(QString id, Module_ThrusterControlLoop *tcl, Module_Thruster *thrusterLeft, Module_Thruster *thrusterRight, Module_Thruster *thrusterDown)
: RobotModule(id)
{
this->controlLoop = tcl,
this->thrusterDown = thrusterDown;
this->thrusterLeft = thrusterLeft;
this->thrusterRight = thrusterRight;
setDefaultValue("port",1234);
setDefaultValue("receiver","thruster");
setDefaultValue("divisor",127);
server = new Server();
connect(server,SIGNAL(newMessage(int,int,int)), this, SLOT(newMessage(int,int,int)));
connect(server, SIGNAL(healthProblem(QString)), this, SLOT(serverReportedError(QString)));
reset();
}
QList<RobotModule*> Module_HandControl::getDependencies()
{
QList<RobotModule*> ret;
ret.append(thrusterDown);
ret.append(thrusterLeft);
ret.append(thrusterRight);
ret.append(controlLoop);
return ret;
}
QWidget* Module_HandControl::createView(QWidget* parent)
{
return new HandControl_Form(this, parent);
}
void Module_HandControl::terminate()
{
server->close();
}
void Module_HandControl::reset()
{
server->close();
server->open(settings.value("port").toInt());
}
void Module_HandControl::newMessage(int forwardSpeed, int angularSpeed, int speedUpDown)
{
if (!getSettings().value("enabled").toBool())
return;
data["forwardSpeed"] = forwardSpeed;
data["angularSpeed"] = angularSpeed;
data["speedUpDown"] = speedUpDown;
float div = settings.value("divisor").toFloat();
if (settings.value("receiver").toString()=="thruster") {
float left = (float)(forwardSpeed-angularSpeed) / div;
float right = (float)(forwardSpeed+angularSpeed) / div;
float updown = (float)speedUpDown / div;
thrusterDown->setSpeed(updown);
thrusterLeft->setSpeed(left);
thrusterRight->setSpeed(right);
} else {
// TODO: find sutable factors once the control loop interface is fixed.
controlLoop->setAngularSpeed(angularSpeed/div);
controlLoop->setForwardSpeed(forwardSpeed/div);
controlLoop->setDepth(speedUpDown/div);
}
// seems to be working..
setHealthToOk();
}
void Module_HandControl::serverReportedError(QString error)
{
setHealthToSick(error);
}
<commit_msg>fix orientation during handcontrol<commit_after>#include "module_handcontrol.h"
#include "module_thruster.h"
#include "module_thrustercontrolloop.h"
#include "handcontrol_form.h"
#include "server.h"
Module_HandControl::Module_HandControl(QString id, Module_ThrusterControlLoop *tcl, Module_Thruster *thrusterLeft, Module_Thruster *thrusterRight, Module_Thruster *thrusterDown)
: RobotModule(id)
{
this->controlLoop = tcl,
this->thrusterDown = thrusterDown;
this->thrusterLeft = thrusterLeft;
this->thrusterRight = thrusterRight;
setDefaultValue("port",1234);
setDefaultValue("receiver","thruster");
setDefaultValue("divisor",127);
server = new Server();
connect(server,SIGNAL(newMessage(int,int,int)), this, SLOT(newMessage(int,int,int)));
connect(server, SIGNAL(healthProblem(QString)), this, SLOT(serverReportedError(QString)));
reset();
}
QList<RobotModule*> Module_HandControl::getDependencies()
{
QList<RobotModule*> ret;
ret.append(thrusterDown);
ret.append(thrusterLeft);
ret.append(thrusterRight);
ret.append(controlLoop);
return ret;
}
QWidget* Module_HandControl::createView(QWidget* parent)
{
return new HandControl_Form(this, parent);
}
void Module_HandControl::terminate()
{
server->close();
}
void Module_HandControl::reset()
{
server->close();
server->open(settings.value("port").toInt());
}
void Module_HandControl::newMessage(int forwardSpeed, int angularSpeed, int speedUpDown)
{
if (!getSettings().value("enabled").toBool())
return;
data["forwardSpeed"] = forwardSpeed;
data["angularSpeed"] = angularSpeed;
data["speedUpDown"] = speedUpDown;
float div = settings.value("divisor").toFloat();
if (settings.value("receiver").toString()=="thruster") {
float left = (float)(forwardSpeed+angularSpeed) / div;
float right = (float)(forwardSpeed-angularSpeed) / div;
float updown = (float)speedUpDown / div;
thrusterDown->setSpeed(updown);
thrusterLeft->setSpeed(left);
thrusterRight->setSpeed(right);
} else {
// TODO: find sutable factors once the control loop interface is fixed.
controlLoop->setAngularSpeed(angularSpeed/div);
controlLoop->setForwardSpeed(forwardSpeed/div);
controlLoop->setDepth(speedUpDown/div);
}
// seems to be working..
setHealthToOk();
}
void Module_HandControl::serverReportedError(QString error)
{
setHealthToSick(error);
}
<|endoftext|> |
<commit_before>#include "ReleaseBuilder.h"
namespace project {
ReleaseBuilder::ReleaseBuilder(double _value, Account* _account, string _releaseType,
string _paymentType, string _description, string _operation, string _date) :
value(_value),
account(_account),
releaseType(_releaseType),
paymentType(_paymentType),
description(_description),
operation(_operation),
date(_date)
{
}
ReleaseBuilder::~ReleaseBuilder()
{
}
bool ReleaseBuilder::isValid()
{
return (account != nullptr) && !releaseType.empty() &&
!paymentType.empty() && !date.empty() &&
((operation == "in") || (operation == "out"));
}
Release * ReleaseBuilder::build()
{
if (!isValid())
throw std::out_of_range("Os parâmetros para a criação não são validos!");
return new Release(value, account, releaseType, paymentType, description, operation, date);
}
}
<commit_msg>Corrigido: Adicionando novo lancamento se nao tiver tipo de lancamento ou pagamento<commit_after>#include "ReleaseBuilder.h"
namespace project {
ReleaseBuilder::ReleaseBuilder(double _value, Account* _account, string _releaseType,
string _paymentType, string _description, string _operation, string _date) :
value(_value),
account(_account),
releaseType(_releaseType),
paymentType(_paymentType),
description(_description),
operation(_operation),
date(_date)
{
}
ReleaseBuilder::~ReleaseBuilder()
{
}
bool ReleaseBuilder::isValid()
{
return (account != nullptr) && !date.empty() &&
!releaseType.empty() && (releaseType != "Tipo de Lancamento") &&
!paymentType.empty() && (paymentType != "Tipo de Pagamento") &&
((operation == "in") || (operation == "out"));
}
Release * ReleaseBuilder::build()
{
if (!isValid())
throw std::out_of_range("Os parâmetros para a criação não são validos!");
return new Release(value, account, releaseType, paymentType, description, operation, date);
}
}
<|endoftext|> |
<commit_before>// MIT License
//
// Copyright © 2017 Michael J Simms. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include "IsolationForest.h"
#include <stdlib.h>
#include <inttypes.h>
#include <iostream>
#include <fstream>
using namespace IsolationForest;
int main(int argc, const char * argv[])
{
const size_t NUM_TRAINING_SAMPLES = 100;
const size_t NUM_TEST_SAMPLES = 10;
const size_t NUM_TREES_IN_FOREST = 10;
const size_t SUBSAMPLING_SIZE = 10;
std::ofstream outStream;
// Parse the command line arguments.
for (int i = 1; i < argc; ++i)
{
if ((strstr(argv[i], "outfile") == 0) && (i + 1 < argc))
{
outStream.open(argv[i + 1]);
}
}
Forest forest(NUM_TREES_IN_FOREST, SUBSAMPLING_SIZE);
srand((unsigned int)time(NULL));
// Create some training samples.
for (size_t i = 0; i < NUM_TRAINING_SAMPLES; ++i)
{
Sample sample("training");
FeaturePtrList features;
uint32_t x = rand() % 25;
uint32_t y = rand() % 25;
features.push_back(new Feature("x", x));
features.push_back(new Feature("y", y));
sample.AddFeatures(features);
forest.AddSample(sample);
if (outStream.is_open())
{
outStream << "training," << x << "," << y << std::endl;
}
}
// Create the isolation forest.
forest.Create();
// Test samples (similar to training samples).
std::cout << "Test samples that are similar to the training set." << std::endl;
std::cout << "--------------------------------------------------" << std::endl;
double avgNormalScore = (double)0.0;
for (size_t i = 0; i < NUM_TEST_SAMPLES; ++i)
{
Sample sample("normal sample");
FeaturePtrList features;
uint32_t x = rand() % 25;
uint32_t y = rand() % 25;
features.push_back(new Feature("x", x));
features.push_back(new Feature("y", y));
sample.AddFeatures(features);
// Run a test with the sample that doesn't contain outliers.
double score = forest.Score(sample);
std::cout << "Normal test sample " << i << ": " << score << std::endl;
if (outStream.is_open())
{
outStream << "normal," << x << "," << y << std::endl;
}
avgNormalScore += score;
}
std::cout << std::endl;
// Outlier samples (different from training samples).
std::cout << "Test samples that are different from the training set." << std::endl;
std::cout << "------------------------------------------------------" << std::endl;
double avgOutlierScore = (double)0.0;
for (size_t i = 0; i < NUM_TEST_SAMPLES; ++i)
{
Sample sample("outlier sample");
FeaturePtrList features;
uint32_t x = 20 + (rand() % 25);
uint32_t y = 20 + (rand() % 25);
features.push_back(new Feature("x", x));
features.push_back(new Feature("y", y));
sample.AddFeatures(features);
// Run a test with the sample that contains outliers.
double score = forest.Score(sample);
std::cout << "Outlier test sample " << i << ": " << score << std::endl;
if (outStream.is_open())
{
outStream << "outlier," << x << "," << y << std::endl;
}
avgOutlierScore += score;
}
std::cout << std::endl;
if (outStream.is_open())
{
outStream.close();
}
return 0;
}
<commit_msg>Added performance measurements to the C++ implementation.<commit_after>// MIT License
//
// Copyright © 2017 Michael J Simms. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include "IsolationForest.h"
#include <stdlib.h>
#include <inttypes.h>
#include <iostream>
#include <fstream>
#include <chrono>
using namespace IsolationForest;
void test(std::ofstream& outStream, size_t numTrainingSamples, size_t numTestSamples, uint32_t numTrees, uint32_t subSamplingSize)
{
Forest forest(numTrees, subSamplingSize);
std::chrono::high_resolution_clock::time_point startTime = std::chrono::high_resolution_clock::now();
// Create some training samples.
for (size_t i = 0; i < numTrainingSamples; ++i)
{
Sample sample("training");
FeaturePtrList features;
uint32_t x = rand() % 25;
uint32_t y = rand() % 25;
features.push_back(new Feature("x", x));
features.push_back(new Feature("y", y));
sample.AddFeatures(features);
forest.AddSample(sample);
if (outStream.is_open())
{
outStream << "training," << x << "," << y << std::endl;
}
}
// Create the isolation forest.
forest.Create();
// Test samples (similar to training samples).
double avgNormalScore = (double)0.0;
for (size_t i = 0; i < numTestSamples; ++i)
{
Sample sample("normal sample");
FeaturePtrList features;
uint32_t x = rand() % 25;
uint32_t y = rand() % 25;
features.push_back(new Feature("x", x));
features.push_back(new Feature("y", y));
sample.AddFeatures(features);
// Run a test with the sample that doesn't contain outliers.
double score = forest.Score(sample);
avgNormalScore += score;
if (outStream.is_open())
{
outStream << "normal," << x << "," << y << std::endl;
}
}
// Outlier samples (different from training samples).
double avgOutlierScore = (double)0.0;
for (size_t i = 0; i < numTestSamples; ++i)
{
Sample sample("outlier sample");
FeaturePtrList features;
uint32_t x = 20 + (rand() % 25);
uint32_t y = 20 + (rand() % 25);
features.push_back(new Feature("x", x));
features.push_back(new Feature("y", y));
sample.AddFeatures(features);
// Run a test with the sample that contains outliers.
double score = forest.Score(sample);
avgOutlierScore += score;
if (outStream.is_open())
{
outStream << "outlier," << x << "," << y << std::endl;
}
}
std::chrono::high_resolution_clock::time_point endTime = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsedTime = std::chrono::duration_cast<std::chrono::duration<double>>(endTime - startTime);
std::cout << "Average of normal test samples: " << avgNormalScore << std::endl;
std::cout << "Average of outlier test samples: " << avgOutlierScore << std::endl;
std::cout << "Total time for Test 1: " << elapsedTime.count() << " seconds." << std::endl;
}
int main(int argc, const char * argv[])
{
const size_t NUM_TRAINING_SAMPLES = 100;
const size_t NUM_TEST_SAMPLES = 10;
const uint32_t NUM_TREES_IN_FOREST = 10;
const uint32_t SUBSAMPLING_SIZE = 10;
std::ofstream outStream;
// Parse the command line arguments.
for (int i = 1; i < argc; ++i)
{
if ((strstr(argv[i], "outfile") == 0) && (i + 1 < argc))
{
outStream.open(argv[i + 1]);
}
}
srand((unsigned int)time(NULL));
std::cout << "Test 1:" << std::endl;
std::cout << "-------" << std::endl;
test(outStream, NUM_TRAINING_SAMPLES, NUM_TEST_SAMPLES, NUM_TREES_IN_FOREST, SUBSAMPLING_SIZE);
std::cout << std::endl;
std::cout << "Test 2:" << std::endl;
std::cout << "-------" << std::endl;
test(outStream, NUM_TRAINING_SAMPLES * 10, NUM_TEST_SAMPLES * 10, NUM_TREES_IN_FOREST * 10, SUBSAMPLING_SIZE * 10);
std::cout << std::endl;
if (outStream.is_open())
{
outStream.close();
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id$
*
*/
#include <gtest/gtest.h>
#include <pcl/common/common.h>
#include <pcl/common/distances.h>
#include <pcl/common/eigen.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
using namespace pcl;
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, PointXYZRGB)
{
PointXYZRGB p;
uint8_t r = 127, g = 64, b = 254;
uint32_t rgb = ((uint32_t)r << 16 | (uint32_t)g << 8 | (uint32_t)b);
p.rgb = *reinterpret_cast<float*>(&rgb);
rgb = *reinterpret_cast<int*>(&p.rgb);
uint8_t rr = (rgb >> 16) & 0x0000ff;
uint8_t gg = (rgb >> 8) & 0x0000ff;
uint8_t bb = (rgb) & 0x0000ff;
EXPECT_EQ (r, rr);
EXPECT_EQ (g, gg);
EXPECT_EQ (b, bb);
EXPECT_EQ (rr, 127);
EXPECT_EQ (gg, 64);
EXPECT_EQ (bb, 254);
p.r = 0; p.g = 127; p.b = 0;
rgb = *reinterpret_cast<int*>(&p.rgb);
rr = (rgb >> 16) & 0x0000ff;
gg = (rgb >> 8) & 0x0000ff;
bb = (rgb) & 0x0000ff;
EXPECT_EQ (rr, 0);
EXPECT_EQ (gg, 127);
EXPECT_EQ (bb, 0);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, PointXYZRGBNormal)
{
PointXYZRGBNormal p;
uint8_t r = 127, g = 64, b = 254;
uint32_t rgb = ((uint32_t)r << 16 | (uint32_t)g << 8 | (uint32_t)b);
p.rgb = *reinterpret_cast<float*>(&rgb);
rgb = *reinterpret_cast<int*>(&p.rgb);
uint8_t rr = (rgb >> 16) & 0x0000ff;
uint8_t gg = (rgb >> 8) & 0x0000ff;
uint8_t bb = (rgb) & 0x0000ff;
EXPECT_EQ (r, rr);
EXPECT_EQ (g, gg);
EXPECT_EQ (b, bb);
EXPECT_EQ (rr, 127);
EXPECT_EQ (gg, 64);
EXPECT_EQ (bb, 254);
p.r = 0; p.g = 127; p.b = 0;
rgb = *reinterpret_cast<int*>(&p.rgb);
rr = (rgb >> 16) & 0x0000ff;
gg = (rgb >> 8) & 0x0000ff;
bb = (rgb) & 0x0000ff;
EXPECT_EQ (rr, 0);
EXPECT_EQ (gg, 127);
EXPECT_EQ (bb, 0);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, Common)
{
PointXYZ p1, p2, p3;
p1.x = 1; p1.y = p1.z = 0;
p2.y = 1; p2.x = p2.z = 0;
p3.z = 1; p3.x = p3.y = 0;
double radius = getCircumcircleRadius (p1, p2, p3);
EXPECT_NEAR (radius, 0.816497, 1e-4);
Eigen::Vector4f pt (1,0,0,0), line_pt (0,0,0,0), line_dir (1,1,0,0);
double point2line_disance = sqrt (sqrPointToLineDistance (pt, line_pt, line_dir));
EXPECT_NEAR (point2line_disance, sqrt(2.0)/2, 1e-4);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, Eigen)
{
Eigen::Matrix3f mat, vec;
mat << 0.000536227, -1.56178e-05, -9.47391e-05, -1.56178e-05, 0.000297322, -0.000148785, -9.47391e-05, -0.000148785, 9.7827e-05;
Eigen::Vector3f val;
eigen33 (mat, vec, val);
EXPECT_NEAR (fabs (vec (0, 0)), 0.168841, 1e-4); EXPECT_NEAR (fabs (vec (0, 1)), 0.161623, 1e-4); EXPECT_NEAR (fabs (vec (0, 2)), 0.972302, 1e-4);
EXPECT_NEAR (fabs (vec (1, 0)), 0.451632, 1e-4); EXPECT_NEAR (fabs (vec (1, 1)), 0.889498, 1e-4); EXPECT_NEAR (fabs (vec (1, 2)), 0.0694328, 1e-4);
EXPECT_NEAR (fabs (vec (2, 0)), 0.876082, 1e-4); EXPECT_NEAR (fabs (vec (2, 1)), 0.4274, 1e-4); EXPECT_NEAR (fabs (vec (2, 2)), 0.223178, 1e-4);
EXPECT_NEAR (val (0), 2.86806e-06, 1e-4); EXPECT_NEAR (val (1), 0.00037165, 1e-4); EXPECT_NEAR (val (2), 0.000556858, 1e-4);
Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> eig (mat);
EXPECT_NEAR (eig.eigenvectors () (0, 0), -0.168841, 1e-4); EXPECT_NEAR (eig.eigenvectors () (0, 1), 0.161623, 1e-4); EXPECT_NEAR (eig.eigenvectors () (0, 2), 0.972302, 1e-4);
EXPECT_NEAR (eig.eigenvectors () (1, 0), -0.451632, 1e-4); EXPECT_NEAR (eig.eigenvectors () (1, 1), -0.889498, 1e-4); EXPECT_NEAR (eig.eigenvectors () (1, 2), 0.0694328, 1e-4);
EXPECT_NEAR (eig.eigenvectors () (2, 0), -0.876083, 1e-4); EXPECT_NEAR (eig.eigenvectors () (2, 1), 0.4274, 1e-4); EXPECT_NEAR (eig.eigenvectors () (2, 2), -0.223178, 1e-4);
EXPECT_NEAR (eig.eigenvalues () (0), 2.86806e-06, 1e-4); EXPECT_NEAR (eig.eigenvalues () (1), 0.00037165, 1e-4); EXPECT_NEAR (eig.eigenvalues () (2), 0.000556858, 1e-4);
Eigen::Vector3f eivals = mat.selfadjointView<Eigen::Lower>().eigenvalues ();
EXPECT_NEAR (eivals (0), 2.86806e-06, 1e-4); EXPECT_NEAR (eivals (1), 0.00037165, 1e-4); EXPECT_NEAR (eivals (2), 0.000556858, 1e-4);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, PointCloud)
{
PointCloud<PointXYZ> cloud;
cloud.width = 640;
cloud.height = 480;
EXPECT_EQ (cloud.isOrganized (), true);
cloud.height = 1;
EXPECT_EQ (cloud.isOrganized (), false);
cloud.width = 10;
for (uint32_t i = 0; i < cloud.width*cloud.height; ++i)
cloud.points.push_back (PointXYZ (3*i+0,3*i+1,3*i+2));
Eigen::MatrixXf mat_xyz1 = cloud.getMatrixXfMap();
EXPECT_EQ (mat_xyz1.rows (), 4);
EXPECT_EQ (mat_xyz1.cols (), cloud.width);
EXPECT_EQ (mat_xyz1 (0,0), 0);
EXPECT_EQ (mat_xyz1 (2,cloud.width-1), 3*cloud.width-1);
Eigen::MatrixXf mat_xyz = cloud.getMatrixXfMap(3,4,0);
EXPECT_EQ (mat_xyz.rows (), 3);
EXPECT_EQ (mat_xyz.cols (), cloud.width);
EXPECT_EQ (mat_xyz (0,0), 0);
EXPECT_EQ (mat_xyz (2,cloud.width-1), 3*cloud.width-1);
Eigen::MatrixXf mat_yz = cloud.getMatrixXfMap(2,4,1);
EXPECT_EQ (mat_yz.rows (), 2);
EXPECT_EQ (mat_yz.cols (), cloud.width);
EXPECT_EQ (mat_yz (0,0), 1);
EXPECT_EQ (mat_yz (1,cloud.width-1), 3*cloud.width-1);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, PointTypes)
{
EXPECT_EQ (sizeof (PointXYZ), 16);
EXPECT_EQ (__alignof (PointXYZ), 16);
EXPECT_EQ (sizeof (PointXYZI), 32);
EXPECT_EQ (__alignof (PointXYZI), 16);
EXPECT_EQ (sizeof (PointXYZRGB), 32);
EXPECT_EQ (__alignof (PointXYZRGB), 16);
EXPECT_EQ (sizeof (PointXYZRGBA), 32);
EXPECT_EQ (__alignof (PointXYZRGBA), 16);
EXPECT_EQ (sizeof (Normal), 32);
EXPECT_EQ (__alignof (Normal), 16);
EXPECT_EQ (sizeof (PointNormal), 48);
EXPECT_EQ (__alignof (PointNormal), 16);
EXPECT_EQ (sizeof (PointXYZRGBNormal), 48);
EXPECT_EQ (__alignof (PointXYZRGBNormal), 16);
}
/* ---[ */
int
main (int argc, char** argv)
{
testing::InitGoogleTest (&argc, argv);
return (RUN_ALL_TESTS ());
}
/* ]--- */
<commit_msg>the map test fails in debug mode with an assertion error. we need to fix this<commit_after>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id$
*
*/
#include <gtest/gtest.h>
#include <pcl/common/common.h>
#include <pcl/common/distances.h>
#include <pcl/common/eigen.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
using namespace pcl;
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, PointXYZRGB)
{
PointXYZRGB p;
uint8_t r = 127, g = 64, b = 254;
uint32_t rgb = ((uint32_t)r << 16 | (uint32_t)g << 8 | (uint32_t)b);
p.rgb = *reinterpret_cast<float*>(&rgb);
rgb = *reinterpret_cast<int*>(&p.rgb);
uint8_t rr = (rgb >> 16) & 0x0000ff;
uint8_t gg = (rgb >> 8) & 0x0000ff;
uint8_t bb = (rgb) & 0x0000ff;
EXPECT_EQ (r, rr);
EXPECT_EQ (g, gg);
EXPECT_EQ (b, bb);
EXPECT_EQ (rr, 127);
EXPECT_EQ (gg, 64);
EXPECT_EQ (bb, 254);
p.r = 0; p.g = 127; p.b = 0;
rgb = *reinterpret_cast<int*>(&p.rgb);
rr = (rgb >> 16) & 0x0000ff;
gg = (rgb >> 8) & 0x0000ff;
bb = (rgb) & 0x0000ff;
EXPECT_EQ (rr, 0);
EXPECT_EQ (gg, 127);
EXPECT_EQ (bb, 0);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, PointXYZRGBNormal)
{
PointXYZRGBNormal p;
uint8_t r = 127, g = 64, b = 254;
uint32_t rgb = ((uint32_t)r << 16 | (uint32_t)g << 8 | (uint32_t)b);
p.rgb = *reinterpret_cast<float*>(&rgb);
rgb = *reinterpret_cast<int*>(&p.rgb);
uint8_t rr = (rgb >> 16) & 0x0000ff;
uint8_t gg = (rgb >> 8) & 0x0000ff;
uint8_t bb = (rgb) & 0x0000ff;
EXPECT_EQ (r, rr);
EXPECT_EQ (g, gg);
EXPECT_EQ (b, bb);
EXPECT_EQ (rr, 127);
EXPECT_EQ (gg, 64);
EXPECT_EQ (bb, 254);
p.r = 0; p.g = 127; p.b = 0;
rgb = *reinterpret_cast<int*>(&p.rgb);
rr = (rgb >> 16) & 0x0000ff;
gg = (rgb >> 8) & 0x0000ff;
bb = (rgb) & 0x0000ff;
EXPECT_EQ (rr, 0);
EXPECT_EQ (gg, 127);
EXPECT_EQ (bb, 0);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, Common)
{
PointXYZ p1, p2, p3;
p1.x = 1; p1.y = p1.z = 0;
p2.y = 1; p2.x = p2.z = 0;
p3.z = 1; p3.x = p3.y = 0;
double radius = getCircumcircleRadius (p1, p2, p3);
EXPECT_NEAR (radius, 0.816497, 1e-4);
Eigen::Vector4f pt (1,0,0,0), line_pt (0,0,0,0), line_dir (1,1,0,0);
double point2line_disance = sqrt (sqrPointToLineDistance (pt, line_pt, line_dir));
EXPECT_NEAR (point2line_disance, sqrt(2.0)/2, 1e-4);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, Eigen)
{
Eigen::Matrix3f mat, vec;
mat << 0.000536227, -1.56178e-05, -9.47391e-05, -1.56178e-05, 0.000297322, -0.000148785, -9.47391e-05, -0.000148785, 9.7827e-05;
Eigen::Vector3f val;
eigen33 (mat, vec, val);
EXPECT_NEAR (fabs (vec (0, 0)), 0.168841, 1e-4); EXPECT_NEAR (fabs (vec (0, 1)), 0.161623, 1e-4); EXPECT_NEAR (fabs (vec (0, 2)), 0.972302, 1e-4);
EXPECT_NEAR (fabs (vec (1, 0)), 0.451632, 1e-4); EXPECT_NEAR (fabs (vec (1, 1)), 0.889498, 1e-4); EXPECT_NEAR (fabs (vec (1, 2)), 0.0694328, 1e-4);
EXPECT_NEAR (fabs (vec (2, 0)), 0.876082, 1e-4); EXPECT_NEAR (fabs (vec (2, 1)), 0.4274, 1e-4); EXPECT_NEAR (fabs (vec (2, 2)), 0.223178, 1e-4);
EXPECT_NEAR (val (0), 2.86806e-06, 1e-4); EXPECT_NEAR (val (1), 0.00037165, 1e-4); EXPECT_NEAR (val (2), 0.000556858, 1e-4);
Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> eig (mat);
EXPECT_NEAR (eig.eigenvectors () (0, 0), -0.168841, 1e-4); EXPECT_NEAR (eig.eigenvectors () (0, 1), 0.161623, 1e-4); EXPECT_NEAR (eig.eigenvectors () (0, 2), 0.972302, 1e-4);
EXPECT_NEAR (eig.eigenvectors () (1, 0), -0.451632, 1e-4); EXPECT_NEAR (eig.eigenvectors () (1, 1), -0.889498, 1e-4); EXPECT_NEAR (eig.eigenvectors () (1, 2), 0.0694328, 1e-4);
EXPECT_NEAR (eig.eigenvectors () (2, 0), -0.876083, 1e-4); EXPECT_NEAR (eig.eigenvectors () (2, 1), 0.4274, 1e-4); EXPECT_NEAR (eig.eigenvectors () (2, 2), -0.223178, 1e-4);
EXPECT_NEAR (eig.eigenvalues () (0), 2.86806e-06, 1e-4); EXPECT_NEAR (eig.eigenvalues () (1), 0.00037165, 1e-4); EXPECT_NEAR (eig.eigenvalues () (2), 0.000556858, 1e-4);
Eigen::Vector3f eivals = mat.selfadjointView<Eigen::Lower>().eigenvalues ();
EXPECT_NEAR (eivals (0), 2.86806e-06, 1e-4); EXPECT_NEAR (eivals (1), 0.00037165, 1e-4); EXPECT_NEAR (eivals (2), 0.000556858, 1e-4);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, PointCloud)
{
PointCloud<PointXYZ> cloud;
cloud.width = 640;
cloud.height = 480;
EXPECT_EQ (cloud.isOrganized (), true);
cloud.height = 1;
EXPECT_EQ (cloud.isOrganized (), false);
cloud.width = 10;
for (uint32_t i = 0; i < cloud.width*cloud.height; ++i)
cloud.points.push_back (PointXYZ (3*i+0,3*i+1,3*i+2));
Eigen::MatrixXf mat_xyz1 = cloud.getMatrixXfMap();
EXPECT_EQ (mat_xyz1.rows (), 4);
EXPECT_EQ (mat_xyz1.cols (), cloud.width);
EXPECT_EQ (mat_xyz1 (0,0), 0);
EXPECT_EQ (mat_xyz1 (2,cloud.width-1), 3*cloud.width-1);
Eigen::MatrixXf mat_xyz = cloud.getMatrixXfMap(3,4,0);
EXPECT_EQ (mat_xyz.rows (), 3);
EXPECT_EQ (mat_xyz.cols (), cloud.width);
EXPECT_EQ (mat_xyz (0,0), 0);
EXPECT_EQ (mat_xyz (2,cloud.width-1), 3*cloud.width-1);
#ifdef NDEBUG
Eigen::MatrixXf mat_yz = cloud.getMatrixXfMap(2,4,1);
EXPECT_EQ (mat_yz.rows (), 2);
EXPECT_EQ (mat_yz.cols (), cloud.width);
EXPECT_EQ (mat_yz (0,0), 1);
EXPECT_EQ (mat_yz (1,cloud.width-1), 3*cloud.width-1);
#endif
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, PointTypes)
{
EXPECT_EQ (sizeof (PointXYZ), 16);
EXPECT_EQ (__alignof (PointXYZ), 16);
EXPECT_EQ (sizeof (PointXYZI), 32);
EXPECT_EQ (__alignof (PointXYZI), 16);
EXPECT_EQ (sizeof (PointXYZRGB), 32);
EXPECT_EQ (__alignof (PointXYZRGB), 16);
EXPECT_EQ (sizeof (PointXYZRGBA), 32);
EXPECT_EQ (__alignof (PointXYZRGBA), 16);
EXPECT_EQ (sizeof (Normal), 32);
EXPECT_EQ (__alignof (Normal), 16);
EXPECT_EQ (sizeof (PointNormal), 48);
EXPECT_EQ (__alignof (PointNormal), 16);
EXPECT_EQ (sizeof (PointXYZRGBNormal), 48);
EXPECT_EQ (__alignof (PointXYZRGBNormal), 16);
}
/* ---[ */
int
main (int argc, char** argv)
{
testing::InitGoogleTest (&argc, argv);
return (RUN_ALL_TESTS ());
}
/* ]--- */
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id$
*
*/
#include <gtest/gtest.h>
#include <pcl/common/common.h>
#include <pcl/common/distances.h>
#include <pcl/common/eigen.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
using pcl::PointXYZ;
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, PointXYZRGB)
{
pcl::PointXYZRGB p;
uint8_t r = 127, g = 64, b = 254;
uint32_t rgb = ((uint32_t)r << 16 | (uint32_t)g << 8 | (uint32_t)b);
p.rgb = *reinterpret_cast<float*>(&rgb);
rgb = *reinterpret_cast<int*>(&p.rgb);
uint8_t rr = (rgb >> 16) & 0x0000ff;
uint8_t gg = (rgb >> 8) & 0x0000ff;
uint8_t bb = (rgb) & 0x0000ff;
EXPECT_EQ (r, rr);
EXPECT_EQ (g, gg);
EXPECT_EQ (b, bb);
EXPECT_EQ (rr, 127);
EXPECT_EQ (gg, 64);
EXPECT_EQ (bb, 254);
p.r = 0; p.g = 127; p.b = 0;
rgb = *reinterpret_cast<int*>(&p.rgb);
rr = (rgb >> 16) & 0x0000ff;
gg = (rgb >> 8) & 0x0000ff;
bb = (rgb) & 0x0000ff;
EXPECT_EQ (rr, 0);
EXPECT_EQ (gg, 127);
EXPECT_EQ (bb, 0);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, PointXYZRGBNormal)
{
pcl::PointXYZRGBNormal p;
uint8_t r = 127, g = 64, b = 254;
uint32_t rgb = ((uint32_t)r << 16 | (uint32_t)g << 8 | (uint32_t)b);
p.rgb = *reinterpret_cast<float*>(&rgb);
rgb = *reinterpret_cast<int*>(&p.rgb);
uint8_t rr = (rgb >> 16) & 0x0000ff;
uint8_t gg = (rgb >> 8) & 0x0000ff;
uint8_t bb = (rgb) & 0x0000ff;
EXPECT_EQ (r, rr);
EXPECT_EQ (g, gg);
EXPECT_EQ (b, bb);
EXPECT_EQ (rr, 127);
EXPECT_EQ (gg, 64);
EXPECT_EQ (bb, 254);
p.r = 0; p.g = 127; p.b = 0;
rgb = *reinterpret_cast<int*>(&p.rgb);
rr = (rgb >> 16) & 0x0000ff;
gg = (rgb >> 8) & 0x0000ff;
bb = (rgb) & 0x0000ff;
EXPECT_EQ (rr, 0);
EXPECT_EQ (gg, 127);
EXPECT_EQ (bb, 0);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, Common)
{
PointXYZ p1, p2, p3;
p1.x = 1; p1.y = p1.z = 0;
p2.y = 1; p2.x = p2.z = 0;
p3.z = 1; p3.x = p3.y = 0;
double radius = getCircumcircleRadius (p1, p2, p3);
EXPECT_NEAR (radius, 0.816497, 1e-4);
Eigen::Vector4f pt (1,0,0,0), line_pt (0,0,0,0), line_dir (1,1,0,0);
double point2line_disance = sqrt (pcl::sqrPointToLineDistance (pt, line_pt, line_dir));
EXPECT_NEAR (point2line_disance, sqrt(2.0)/2, 1e-4);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, Eigen)
{
Eigen::Matrix3f mat, vec;
mat << 0.000536227, -1.56178e-05, -9.47391e-05, -1.56178e-05, 0.000297322, -0.000148785, -9.47391e-05, -0.000148785, 9.7827e-05;
Eigen::Vector3f val;
pcl::eigen33 (mat, vec, val);
EXPECT_NEAR (fabs (vec (0, 0)), 0.168841, 1e-4); EXPECT_NEAR (fabs (vec (0, 1)), 0.161623, 1e-4); EXPECT_NEAR (fabs (vec (0, 2)), 0.972302, 1e-4);
EXPECT_NEAR (fabs (vec (1, 0)), 0.451632, 1e-4); EXPECT_NEAR (fabs (vec (1, 1)), 0.889498, 1e-4); EXPECT_NEAR (fabs (vec (1, 2)), 0.0694328, 1e-4);
EXPECT_NEAR (fabs (vec (2, 0)), 0.876082, 1e-4); EXPECT_NEAR (fabs (vec (2, 1)), 0.4274, 1e-4); EXPECT_NEAR (fabs (vec (2, 2)), 0.223178, 1e-4);
EXPECT_NEAR (val (0), 2.86806e-06, 1e-4); EXPECT_NEAR (val (1), 0.00037165, 1e-4); EXPECT_NEAR (val (2), 0.000556858, 1e-4);
Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> eig (mat);
EXPECT_NEAR (eig.eigenvectors () (0, 0), -0.168841, 1e-4); EXPECT_NEAR (eig.eigenvectors () (0, 1), 0.161623, 1e-4); EXPECT_NEAR (eig.eigenvectors () (0, 2), 0.972302, 1e-4);
EXPECT_NEAR (eig.eigenvectors () (1, 0), -0.451632, 1e-4); EXPECT_NEAR (eig.eigenvectors () (1, 1), -0.889498, 1e-4); EXPECT_NEAR (eig.eigenvectors () (1, 2), 0.0694328, 1e-4);
EXPECT_NEAR (eig.eigenvectors () (2, 0), -0.876083, 1e-4); EXPECT_NEAR (eig.eigenvectors () (2, 1), 0.4274, 1e-4); EXPECT_NEAR (eig.eigenvectors () (2, 2), -0.223178, 1e-4);
EXPECT_NEAR (eig.eigenvalues () (0), 2.86806e-06, 1e-4); EXPECT_NEAR (eig.eigenvalues () (1), 0.00037165, 1e-4); EXPECT_NEAR (eig.eigenvalues () (2), 0.000556858, 1e-4);
Eigen::Vector3f eivals = mat.selfadjointView<Eigen::Lower>().eigenvalues ();
EXPECT_NEAR (eivals (0), 2.86806e-06, 1e-4); EXPECT_NEAR (eivals (1), 0.00037165, 1e-4); EXPECT_NEAR (eivals (2), 0.000556858, 1e-4);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, PointCloud)
{
pcl::PointCloud<PointXYZ> cloud;
cloud.width = 640;
cloud.height = 480;
EXPECT_EQ (cloud.isOrganized (), true);
cloud.height = 1;
EXPECT_EQ (cloud.isOrganized (), false);
}
/* ---[ */
int
main (int argc, char** argv)
{
testing::InitGoogleTest (&argc, argv);
return (RUN_ALL_TESTS ());
}
/* ]--- */
<commit_msg>testing new sizeof/__alignof + unix2dos<commit_after>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id$
*
*/
#include <gtest/gtest.h>
#include <pcl/common/common.h>
#include <pcl/common/distances.h>
#include <pcl/common/eigen.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
using namespace pcl;
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, PointXYZRGB)
{
PointXYZRGB p;
uint8_t r = 127, g = 64, b = 254;
uint32_t rgb = ((uint32_t)r << 16 | (uint32_t)g << 8 | (uint32_t)b);
p.rgb = *reinterpret_cast<float*>(&rgb);
rgb = *reinterpret_cast<int*>(&p.rgb);
uint8_t rr = (rgb >> 16) & 0x0000ff;
uint8_t gg = (rgb >> 8) & 0x0000ff;
uint8_t bb = (rgb) & 0x0000ff;
EXPECT_EQ (r, rr);
EXPECT_EQ (g, gg);
EXPECT_EQ (b, bb);
EXPECT_EQ (rr, 127);
EXPECT_EQ (gg, 64);
EXPECT_EQ (bb, 254);
p.r = 0; p.g = 127; p.b = 0;
rgb = *reinterpret_cast<int*>(&p.rgb);
rr = (rgb >> 16) & 0x0000ff;
gg = (rgb >> 8) & 0x0000ff;
bb = (rgb) & 0x0000ff;
EXPECT_EQ (rr, 0);
EXPECT_EQ (gg, 127);
EXPECT_EQ (bb, 0);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, PointXYZRGBNormal)
{
PointXYZRGBNormal p;
uint8_t r = 127, g = 64, b = 254;
uint32_t rgb = ((uint32_t)r << 16 | (uint32_t)g << 8 | (uint32_t)b);
p.rgb = *reinterpret_cast<float*>(&rgb);
rgb = *reinterpret_cast<int*>(&p.rgb);
uint8_t rr = (rgb >> 16) & 0x0000ff;
uint8_t gg = (rgb >> 8) & 0x0000ff;
uint8_t bb = (rgb) & 0x0000ff;
EXPECT_EQ (r, rr);
EXPECT_EQ (g, gg);
EXPECT_EQ (b, bb);
EXPECT_EQ (rr, 127);
EXPECT_EQ (gg, 64);
EXPECT_EQ (bb, 254);
p.r = 0; p.g = 127; p.b = 0;
rgb = *reinterpret_cast<int*>(&p.rgb);
rr = (rgb >> 16) & 0x0000ff;
gg = (rgb >> 8) & 0x0000ff;
bb = (rgb) & 0x0000ff;
EXPECT_EQ (rr, 0);
EXPECT_EQ (gg, 127);
EXPECT_EQ (bb, 0);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, Common)
{
PointXYZ p1, p2, p3;
p1.x = 1; p1.y = p1.z = 0;
p2.y = 1; p2.x = p2.z = 0;
p3.z = 1; p3.x = p3.y = 0;
double radius = getCircumcircleRadius (p1, p2, p3);
EXPECT_NEAR (radius, 0.816497, 1e-4);
Eigen::Vector4f pt (1,0,0,0), line_pt (0,0,0,0), line_dir (1,1,0,0);
double point2line_disance = sqrt (sqrPointToLineDistance (pt, line_pt, line_dir));
EXPECT_NEAR (point2line_disance, sqrt(2.0)/2, 1e-4);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, Eigen)
{
Eigen::Matrix3f mat, vec;
mat << 0.000536227, -1.56178e-05, -9.47391e-05, -1.56178e-05, 0.000297322, -0.000148785, -9.47391e-05, -0.000148785, 9.7827e-05;
Eigen::Vector3f val;
eigen33 (mat, vec, val);
EXPECT_NEAR (fabs (vec (0, 0)), 0.168841, 1e-4); EXPECT_NEAR (fabs (vec (0, 1)), 0.161623, 1e-4); EXPECT_NEAR (fabs (vec (0, 2)), 0.972302, 1e-4);
EXPECT_NEAR (fabs (vec (1, 0)), 0.451632, 1e-4); EXPECT_NEAR (fabs (vec (1, 1)), 0.889498, 1e-4); EXPECT_NEAR (fabs (vec (1, 2)), 0.0694328, 1e-4);
EXPECT_NEAR (fabs (vec (2, 0)), 0.876082, 1e-4); EXPECT_NEAR (fabs (vec (2, 1)), 0.4274, 1e-4); EXPECT_NEAR (fabs (vec (2, 2)), 0.223178, 1e-4);
EXPECT_NEAR (val (0), 2.86806e-06, 1e-4); EXPECT_NEAR (val (1), 0.00037165, 1e-4); EXPECT_NEAR (val (2), 0.000556858, 1e-4);
Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> eig (mat);
EXPECT_NEAR (eig.eigenvectors () (0, 0), -0.168841, 1e-4); EXPECT_NEAR (eig.eigenvectors () (0, 1), 0.161623, 1e-4); EXPECT_NEAR (eig.eigenvectors () (0, 2), 0.972302, 1e-4);
EXPECT_NEAR (eig.eigenvectors () (1, 0), -0.451632, 1e-4); EXPECT_NEAR (eig.eigenvectors () (1, 1), -0.889498, 1e-4); EXPECT_NEAR (eig.eigenvectors () (1, 2), 0.0694328, 1e-4);
EXPECT_NEAR (eig.eigenvectors () (2, 0), -0.876083, 1e-4); EXPECT_NEAR (eig.eigenvectors () (2, 1), 0.4274, 1e-4); EXPECT_NEAR (eig.eigenvectors () (2, 2), -0.223178, 1e-4);
EXPECT_NEAR (eig.eigenvalues () (0), 2.86806e-06, 1e-4); EXPECT_NEAR (eig.eigenvalues () (1), 0.00037165, 1e-4); EXPECT_NEAR (eig.eigenvalues () (2), 0.000556858, 1e-4);
Eigen::Vector3f eivals = mat.selfadjointView<Eigen::Lower>().eigenvalues ();
EXPECT_NEAR (eivals (0), 2.86806e-06, 1e-4); EXPECT_NEAR (eivals (1), 0.00037165, 1e-4); EXPECT_NEAR (eivals (2), 0.000556858, 1e-4);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, PointCloud)
{
PointCloud<PointXYZ> cloud;
cloud.width = 640;
cloud.height = 480;
EXPECT_EQ (cloud.isOrganized (), true);
cloud.height = 1;
EXPECT_EQ (cloud.isOrganized (), false);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, PointTypes)
{
EXPECT_EQ (sizeof (PointXYZ), 16); EXPECT_EQ (__alignof (PointXYZ), 16);
EXPECT_EQ (sizeof (PointXYZRGB), 32); EXPECT_EQ (__alignof (PointXYZRGB), 16);
}
/* ---[ */
int
main (int argc, char** argv)
{
testing::InitGoogleTest (&argc, argv);
return (RUN_ALL_TESTS ());
}
/* ]--- */
<|endoftext|> |
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "sal/config.h"
#include "boost/noncopyable.hpp"
#include "com/sun/star/beans/PropertyState.hpp"
#include "com/sun/star/beans/PropertyValue.hpp"
#include "com/sun/star/document/MacroExecMode.hpp"
#include "com/sun/star/frame/DispatchResultEvent.hpp"
#include "com/sun/star/frame/DispatchResultState.hpp"
#include "com/sun/star/frame/XComponentLoader.hpp"
#include "com/sun/star/frame/XController.hpp"
#include "com/sun/star/frame/XDispatchProvider.hpp"
#include "com/sun/star/frame/XDispatchResultListener.hpp"
#include "com/sun/star/frame/XModel.hpp"
#include "com/sun/star/frame/XNotifyingDispatch.hpp"
#include "com/sun/star/lang/EventObject.hpp"
#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/RuntimeException.hpp"
#include "com/sun/star/uno/Sequence.hxx"
#include "com/sun/star/util/URL.hpp"
#include "cppuhelper/implbase1.hxx"
#include "cppunit/TestAssert.h"
#include "cppunit/TestFixture.h"
#include "cppunit/extensions/HelperMacros.h"
#include "cppunit/plugin/TestPlugIn.h"
#include "osl/conditn.hxx"
#include "osl/diagnose.h"
#include "rtl/ustring.h"
#include "rtl/ustring.hxx"
#include "test/getargument.hxx"
#include "test/officeconnection.hxx"
#include "test/oustringostreaminserter.hxx"
#include "test/toabsolutefileurl.hxx"
namespace {
namespace css = com::sun::star;
struct Result: private boost::noncopyable {
osl::Condition condition;
bool success;
rtl::OUString result;
};
class Listener:
public cppu::WeakImplHelper1< css::frame::XDispatchResultListener >
{
public:
Listener(Result * result): result_(result) { OSL_ASSERT(result != 0); }
private:
virtual void SAL_CALL disposing(css::lang::EventObject const &)
throw (css::uno::RuntimeException) {}
virtual void SAL_CALL dispatchFinished(
css::frame::DispatchResultEvent const & Result)
throw (css::uno::RuntimeException);
Result * result_;
};
void Listener::dispatchFinished(css::frame::DispatchResultEvent const & Result)
throw (css::uno::RuntimeException)
{
result_->success =
(Result.State == css::frame::DispatchResultState::SUCCESS) &&
(Result.Result >>= result_->result);
result_->condition.set();
}
class Test: public CppUnit::TestFixture {
public:
virtual void setUp();
virtual void tearDown();
private:
CPPUNIT_TEST_SUITE(Test);
CPPUNIT_TEST(test);
CPPUNIT_TEST_SUITE_END();
void test();
test::OfficeConnection connection_;
};
void Test::setUp() {
connection_.setUp();
}
void Test::tearDown() {
connection_.tearDown();
}
void Test::test() {
rtl::OUString doc;
CPPUNIT_ASSERT(
test::getArgument(
rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("doc")), &doc));
css::uno::Sequence< css::beans::PropertyValue > args(1);
args[0].Name = rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM("MacroExecutionMode"));
args[0].Handle = -1;
args[0].Value <<=
com::sun::star::document::MacroExecMode::ALWAYS_EXECUTE_NO_WARN;
args[0].State = css::beans::PropertyState_DIRECT_VALUE;
css::util::URL url;
url.Complete = rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM(
"vnd.sun.star.script:Standard.Global.StartTestWithDefaultOptions?"
"language=Basic&location=document"));
Result result;
css::uno::Reference< css::frame::XNotifyingDispatch >(
css::uno::Reference< css::frame::XDispatchProvider >(
css::uno::Reference< css::frame::XController >(
css::uno::Reference< css::frame::XModel >(
css::uno::Reference< css::frame::XComponentLoader >(
connection_.getFactory()->createInstance(
rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM(
"com.sun.star.frame.Desktop"))),
css::uno::UNO_QUERY_THROW)->loadComponentFromURL(
test::toAbsoluteFileUrl(doc),
rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM("_default")),
0, args),
css::uno::UNO_QUERY_THROW)->getCurrentController(),
css::uno::UNO_SET_THROW)->getFrame(),
css::uno::UNO_QUERY_THROW)->queryDispatch(
url, rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("_self")), 0),
css::uno::UNO_QUERY_THROW)->dispatchWithNotification(
url, css::uno::Sequence< css::beans::PropertyValue >(),
new Listener(&result));
result.condition.wait();
CPPUNIT_ASSERT(result.success);
CPPUNIT_ASSERT_EQUAL(rtl::OUString(), result.result);
}
CPPUNIT_TEST_SUITE_REGISTRATION(Test);
}
CPPUNIT_PLUGIN_IMPLEMENT();
<commit_msg>sb128: #i112986# shifted relevant smoketest work to OOo main thread to work around potential deadlocks (transplanted from 5dc61b93c5ef2ed21e3d9532325b35a70fef18da)<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "sal/config.h"
#include "boost/noncopyable.hpp"
#include "com/sun/star/awt/XCallback.hpp"
#include "com/sun/star/awt/XRequestCallback.hpp"
#include "com/sun/star/beans/PropertyState.hpp"
#include "com/sun/star/beans/PropertyValue.hpp"
#include "com/sun/star/document/MacroExecMode.hpp"
#include "com/sun/star/frame/DispatchResultEvent.hpp"
#include "com/sun/star/frame/DispatchResultState.hpp"
#include "com/sun/star/frame/XComponentLoader.hpp"
#include "com/sun/star/frame/XController.hpp"
#include "com/sun/star/frame/XDispatchProvider.hpp"
#include "com/sun/star/frame/XDispatchResultListener.hpp"
#include "com/sun/star/frame/XModel.hpp"
#include "com/sun/star/frame/XNotifyingDispatch.hpp"
#include "com/sun/star/lang/EventObject.hpp"
#include "com/sun/star/uno/Any.hxx"
#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/RuntimeException.hpp"
#include "com/sun/star/uno/Sequence.hxx"
#include "com/sun/star/util/URL.hpp"
#include "cppuhelper/implbase1.hxx"
#include "cppunit/TestAssert.h"
#include "cppunit/TestFixture.h"
#include "cppunit/extensions/HelperMacros.h"
#include "cppunit/plugin/TestPlugIn.h"
#include "osl/conditn.hxx"
#include "osl/diagnose.h"
#include "rtl/ustring.h"
#include "rtl/ustring.hxx"
#include "test/getargument.hxx"
#include "test/officeconnection.hxx"
#include "test/oustringostreaminserter.hxx"
#include "test/toabsolutefileurl.hxx"
namespace {
namespace css = com::sun::star;
struct Result: private boost::noncopyable {
osl::Condition condition;
bool success;
rtl::OUString result;
};
class Listener:
public cppu::WeakImplHelper1< css::frame::XDispatchResultListener >
{
public:
Listener(Result * result): result_(result) { OSL_ASSERT(result != 0); }
private:
virtual void SAL_CALL disposing(css::lang::EventObject const &)
throw (css::uno::RuntimeException) {}
virtual void SAL_CALL dispatchFinished(
css::frame::DispatchResultEvent const & Result)
throw (css::uno::RuntimeException);
Result * result_;
};
void Listener::dispatchFinished(css::frame::DispatchResultEvent const & Result)
throw (css::uno::RuntimeException)
{
result_->success =
(Result.State == css::frame::DispatchResultState::SUCCESS) &&
(Result.Result >>= result_->result);
result_->condition.set();
}
class Callback: public cppu::WeakImplHelper1< css::awt::XCallback > {
public:
Callback(
css::uno::Reference< css::frame::XNotifyingDispatch > const & dispatch,
css::util::URL const & url,
css::uno::Sequence< css::beans::PropertyValue > const & arguments,
css::uno::Reference< css::frame::XDispatchResultListener > const &
listener):
dispatch_(dispatch), url_(url), arguments_(arguments),
listener_(listener)
{ OSL_ASSERT(dispatch.is()); }
private:
virtual void SAL_CALL notify(css::uno::Any const &)
throw (css::uno::RuntimeException)
{ dispatch_->dispatchWithNotification(url_, arguments_, listener_); }
css::uno::Reference< css::frame::XNotifyingDispatch > dispatch_;
css::util::URL url_;
css::uno::Sequence< css::beans::PropertyValue > arguments_;
css::uno::Reference< css::frame::XDispatchResultListener > listener_;
};
class Test: public CppUnit::TestFixture {
public:
virtual void setUp();
virtual void tearDown();
private:
CPPUNIT_TEST_SUITE(Test);
CPPUNIT_TEST(test);
CPPUNIT_TEST_SUITE_END();
void test();
test::OfficeConnection connection_;
};
void Test::setUp() {
connection_.setUp();
}
void Test::tearDown() {
connection_.tearDown();
}
void Test::test() {
rtl::OUString doc;
CPPUNIT_ASSERT(
test::getArgument(
rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("doc")), &doc));
css::uno::Sequence< css::beans::PropertyValue > args(1);
args[0].Name = rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM("MacroExecutionMode"));
args[0].Handle = -1;
args[0].Value <<=
com::sun::star::document::MacroExecMode::ALWAYS_EXECUTE_NO_WARN;
args[0].State = css::beans::PropertyState_DIRECT_VALUE;
css::util::URL url;
url.Complete = rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM(
"vnd.sun.star.script:Standard.Global.StartTestWithDefaultOptions?"
"language=Basic&location=document"));
css::uno::Reference< css::frame::XNotifyingDispatch > disp(
css::uno::Reference< css::frame::XDispatchProvider >(
css::uno::Reference< css::frame::XController >(
css::uno::Reference< css::frame::XModel >(
css::uno::Reference< css::frame::XComponentLoader >(
connection_.getFactory()->createInstance(
rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM(
"com.sun.star.frame.Desktop"))),
css::uno::UNO_QUERY_THROW)->loadComponentFromURL(
test::toAbsoluteFileUrl(doc),
rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM("_default")),
0, args),
css::uno::UNO_QUERY_THROW)->getCurrentController(),
css::uno::UNO_SET_THROW)->getFrame(),
css::uno::UNO_QUERY_THROW)->queryDispatch(
url, rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("_self")), 0),
css::uno::UNO_QUERY_THROW);
Result result;
// Shifted to main thread to work around potential deadlocks (i112867):
css::uno::Reference< css::awt::XRequestCallback >(
connection_.getFactory()->createInstance( //TODO: AsyncCallback ctor
rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM("com.sun.star.awt.AsyncCallback"))),
css::uno::UNO_QUERY_THROW)->addCallback(
new Callback(
disp, url, css::uno::Sequence< css::beans::PropertyValue >(),
new Listener(&result)),
css::uno::Any());
result.condition.wait();
CPPUNIT_ASSERT(result.success);
CPPUNIT_ASSERT_EQUAL(rtl::OUString(), result.result);
}
CPPUNIT_TEST_SUITE_REGISTRATION(Test);
}
CPPUNIT_PLUGIN_IMPLEMENT();
<|endoftext|> |
<commit_before>/*
* ImageJFind
* A Diamond application for interoperating with ImageJ
* Version 1
*
* Copyright (c) 2002-2005 Intel Corporation
* Copyright (c) 2008 Carnegie Mellon University
* All Rights Reserved.
*
* This software is distributed under the terms of the Eclipse Public
* License, Version 1.0 which can be found in the file named LICENSE.
* ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS SOFTWARE CONSTITUTES
* RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT
*/
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <glib.h>
#include <gtk/gtk.h>
#include <assert.h>
#include <string.h>
#include <errno.h>
#include <sys/queue.h>
#include "lib_results.h"
#include "rgb.h"
#include "imagej_search.h"
#include "factory.h"
#include "quick_tar.h"
#define MAX_DISPLAY_NAME 64
/* config file tokens that we write out */
#define SEARCH_NAME "imagej_search"
#define EVAL_FUNCTION_ID "EVAL_FUNCTION"
#define THRESHOLD_ID "THRESHOLD"
#define SOURCE_FOLDER_ID "SOURCE_FOLDER"
extern "C" {
void search_init();
}
/*
* Initialization function that creates the factory and registers
* it with the rest of the UI.
*/
void
search_init()
{
imagej_factory *fac;
fac = new imagej_factory;
imagej_codec_factory *fac2;
fac2 = new imagej_codec_factory;
factory_register(fac);
// factory_register_codec(fac2); // also does codec
}
imagej_search::imagej_search(const char *name, char *descr)
: img_search(name, descr)
{
eval_function = strdup("eval");
threshold = strdup("0");
source_folder = strdup(".");
edit_window = NULL;
return;
}
imagej_search::~imagej_search()
{
if (eval_function) {
free(eval_function);
}
if (threshold) {
free(threshold);
}
if (source_folder) {
free(source_folder);
}
free(get_auxiliary_data());
return;
}
int
imagej_search::handle_config(int nconf, char **data)
{
int err;
if (strcmp(EVAL_FUNCTION_ID, data[0]) == 0) {
assert(nconf > 1);
eval_function = strdup(data[1]);
assert(eval_function != NULL);
err = 0;
} else if (strcmp(THRESHOLD_ID, data[0]) == 0) {
assert(nconf > 1);
threshold = strdup(data[1]);
assert(threshold != NULL);
err = 0;
} else if (strcmp(SOURCE_FOLDER_ID, data[0]) == 0) {
assert(nconf > 1);
source_folder = strdup(data[1]);
assert(source_folder != NULL);
err = 0;
} else {
err = img_search::handle_config(nconf, data);
}
return(err);
}
static void
cb_edit_done(GtkButton *item, gpointer data)
{
GtkWidget * widget = (GtkWidget *)data;
gtk_widget_destroy(widget);
}
static void
cb_close_edit_window(GtkWidget* item, gpointer data)
{
imagej_search * search;
search = (imagej_search *)data;
search->close_edit_win();
}
void
imagej_search::edit_search()
{
GtkWidget * widget;
GtkWidget * box;
GtkWidget * hbox;
GtkWidget * table;
char name[MAX_DISPLAY_NAME];
/* see if it already exists */
if (edit_window != NULL) {
/* raise to top ??? */
gdk_window_raise(GTK_WIDGET(edit_window)->window);
return;
}
edit_window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
snprintf(name, MAX_DISPLAY_NAME - 1, "Edit %s", get_name());
name[MAX_DISPLAY_NAME -1] = '\0';
gtk_window_set_title(GTK_WINDOW(edit_window), name);
g_signal_connect(G_OBJECT(edit_window), "destroy",
G_CALLBACK(cb_close_edit_window), this);
box = gtk_vbox_new(FALSE, 10);
gtk_container_add(GTK_CONTAINER(edit_window), box);
hbox = gtk_hbox_new(FALSE, 10);
gtk_box_pack_start(GTK_BOX(box), hbox, FALSE, TRUE, 0);
widget = gtk_button_new_with_label("Close");
g_signal_connect(G_OBJECT(widget), "clicked",
G_CALLBACK(cb_edit_done), edit_window);
GTK_WIDGET_SET_FLAGS(widget, GTK_CAN_DEFAULT);
gtk_box_pack_start(GTK_BOX(hbox), widget, FALSE, TRUE, 0);
/*
* Get the controls from the img_search.
*/
widget = img_search_display();
gtk_box_pack_start(GTK_BOX(box), widget, FALSE, TRUE, 0);
/*
* To make the layout look a little cleaner we use a table
* to place all the fields. This will make them be nicely
* aligned.
*/
table = gtk_table_new(4, 2, FALSE);
gtk_table_set_row_spacings(GTK_TABLE(table), 2);
gtk_table_set_col_spacings(GTK_TABLE(table), 4);
gtk_container_set_border_width(GTK_CONTAINER(table), 10);
gtk_box_pack_start(GTK_BOX(box), table, FALSE, TRUE, 0);
/* set the first row label and text entry for the eval function */
widget = gtk_label_new("Macro name");
gtk_label_set_justify(GTK_LABEL(widget), GTK_JUSTIFY_LEFT);
gtk_table_attach_defaults(GTK_TABLE(table), widget, 0, 1, 0, 1);
eval_function_entry = gtk_entry_new();
gtk_table_attach_defaults(GTK_TABLE(table), eval_function_entry, 1, 2, 0, 1);
if (eval_function != NULL) {
char *s = strdup(eval_function);
// convert '_' to ' '
for (int i = 0; i < strlen(s); i++) {
if (s[i] == '_') {
s[i] = ' ';
}
}
gtk_entry_set_text(GTK_ENTRY(eval_function_entry), s);
free(s);
}
/* set the third row label and text entry for the threshold */
widget = gtk_label_new("Threshold");
gtk_label_set_justify(GTK_LABEL(widget), GTK_JUSTIFY_LEFT);
gtk_table_attach_defaults(GTK_TABLE(table), widget, 0, 1, 2, 3);
threshold_entry = gtk_entry_new();
gtk_table_attach_defaults(GTK_TABLE(table), threshold_entry, 1, 2, 2, 3);
if (threshold != NULL) {
gtk_entry_set_text(GTK_ENTRY(threshold_entry), threshold);
}
/* set the fourth row label and file chooser button for the source directory */
widget = gtk_label_new("Source folder");
gtk_label_set_justify(GTK_LABEL(widget), GTK_JUSTIFY_LEFT);
gtk_table_attach_defaults(GTK_TABLE(table), widget, 0, 1, 3, 4);
source_folder_button = gtk_file_chooser_button_new("Select a Folder",
GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER);
gtk_table_attach_defaults(GTK_TABLE(table), source_folder_button, 1, 2, 3, 4);
if (source_folder != NULL) {
gtk_file_chooser_set_filename(GTK_FILE_CHOOSER(source_folder_button), source_folder);
}
/* make everything visible */
gtk_widget_show_all(edit_window);
return;
}
/*
* This method reads the values from the current edit
* window if there is an active one.
*/
void
imagej_search::save_edits()
{
int fd;
int blob_len;
gchar *name_used;
gboolean success;
gchar *blob_data;
if (edit_window == NULL) {
return;
}
if (eval_function != NULL) {
free(eval_function);
}
if (threshold != NULL) {
free(threshold);
}
if (source_folder != NULL) {
free(source_folder);
}
eval_function = strdup(gtk_entry_get_text(GTK_ENTRY(eval_function_entry)));
assert(eval_function != NULL);
// convert ' ' to '_'
for (int i = 0; i < strlen(eval_function); i++) {
if (eval_function[i] == ' ') {
eval_function[i] = '_';
}
}
threshold = strdup(gtk_entry_get_text(GTK_ENTRY(threshold_entry)));
assert(threshold != NULL);
source_folder = strdup(gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(source_folder_button)));
assert(source_folder != NULL);
/* blob */
free(get_auxiliary_data());
fd = g_file_open_tmp(NULL, &name_used, NULL);
g_assert(fd >= 0);
// printf("quick tar: %s\n", source_folder);
blob_len = tar_blob(source_folder, fd);
g_assert(blob_len >= 0);
success = g_file_get_contents(name_used, &blob_data, NULL, NULL);
g_assert(success);
set_auxiliary_data(blob_data);
set_auxiliary_data_length(blob_len);
// printf(" blob length: %d\n", blob_len);
// save name
img_search::save_edits();
}
void
imagej_search::close_edit_win()
{
save_edits();
/* call parent to give them a chance to cleanup */
img_search::close_edit_win();
edit_window = NULL;
}
/*
* This write the relevant section of the filter specification file
* for this search.
*/
void
imagej_search::write_fspec(FILE *ostream)
{
if (strcmp("RGB", get_name()) == 0) {
fprintf(ostream, "FILTER RGB\n");
} else {
fprintf(ostream, "FILTER %s # dependencies \n", get_name());
fprintf(ostream, "REQUIRES RGB\n");
}
fprintf(ostream, "\n");
fprintf(ostream, "THRESHOLD %s\n", threshold);
fprintf(ostream, "MERIT 10000\n");
fprintf(ostream, "EVAL_FUNCTION f_eval_imagej_exec # eval function \n");
fprintf(ostream, "INIT_FUNCTION f_init_imagej_exec # init function \n");
fprintf(ostream, "FINI_FUNCTION f_fini_imagej_exec # fini function \n");
fprintf(ostream, "ARG %s\n", eval_function );
fprintf(ostream, "\n");
fprintf(ostream, "\n");
}
void
imagej_search::write_config(FILE *ostream, const char *dirname)
{
fprintf(ostream, "SEARCH %s %s\n", SEARCH_NAME, get_name());
fprintf(ostream, "%s %s\n", EVAL_FUNCTION_ID, eval_function);
fprintf(ostream, "%s %s \n", THRESHOLD_ID, threshold);
fprintf(ostream, "%s %s \n", SOURCE_FOLDER_ID, source_folder);
}
/* Region match isn't meaningful for this search */
void
imagej_search::region_match(RGBImage *img, bbox_list_t *blist)
{
return;
}
bool
imagej_search::is_editable(void)
{
return true;
}
<commit_msg>Don't modify the eval_function anymore in snapfind<commit_after>/*
* ImageJFind
* A Diamond application for interoperating with ImageJ
* Version 1
*
* Copyright (c) 2002-2005 Intel Corporation
* Copyright (c) 2008 Carnegie Mellon University
* All Rights Reserved.
*
* This software is distributed under the terms of the Eclipse Public
* License, Version 1.0 which can be found in the file named LICENSE.
* ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS SOFTWARE CONSTITUTES
* RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT
*/
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <glib.h>
#include <gtk/gtk.h>
#include <assert.h>
#include <string.h>
#include <errno.h>
#include <sys/queue.h>
#include "lib_results.h"
#include "rgb.h"
#include "imagej_search.h"
#include "factory.h"
#include "quick_tar.h"
#define MAX_DISPLAY_NAME 64
/* config file tokens that we write out */
#define SEARCH_NAME "imagej_search"
#define EVAL_FUNCTION_ID "EVAL_FUNCTION"
#define THRESHOLD_ID "THRESHOLD"
#define SOURCE_FOLDER_ID "SOURCE_FOLDER"
extern "C" {
void search_init();
}
/*
* Initialization function that creates the factory and registers
* it with the rest of the UI.
*/
void
search_init()
{
imagej_factory *fac;
fac = new imagej_factory;
imagej_codec_factory *fac2;
fac2 = new imagej_codec_factory;
factory_register(fac);
// factory_register_codec(fac2); // also does codec
}
imagej_search::imagej_search(const char *name, char *descr)
: img_search(name, descr)
{
eval_function = strdup("eval");
threshold = strdup("0");
source_folder = strdup(".");
edit_window = NULL;
return;
}
imagej_search::~imagej_search()
{
if (eval_function) {
free(eval_function);
}
if (threshold) {
free(threshold);
}
if (source_folder) {
free(source_folder);
}
free(get_auxiliary_data());
return;
}
int
imagej_search::handle_config(int nconf, char **data)
{
int err;
if (strcmp(EVAL_FUNCTION_ID, data[0]) == 0) {
assert(nconf > 1);
eval_function = strdup(data[1]);
assert(eval_function != NULL);
err = 0;
} else if (strcmp(THRESHOLD_ID, data[0]) == 0) {
assert(nconf > 1);
threshold = strdup(data[1]);
assert(threshold != NULL);
err = 0;
} else if (strcmp(SOURCE_FOLDER_ID, data[0]) == 0) {
assert(nconf > 1);
source_folder = strdup(data[1]);
assert(source_folder != NULL);
err = 0;
} else {
err = img_search::handle_config(nconf, data);
}
return(err);
}
static void
cb_edit_done(GtkButton *item, gpointer data)
{
GtkWidget * widget = (GtkWidget *)data;
gtk_widget_destroy(widget);
}
static void
cb_close_edit_window(GtkWidget* item, gpointer data)
{
imagej_search * search;
search = (imagej_search *)data;
search->close_edit_win();
}
void
imagej_search::edit_search()
{
GtkWidget * widget;
GtkWidget * box;
GtkWidget * hbox;
GtkWidget * table;
char name[MAX_DISPLAY_NAME];
/* see if it already exists */
if (edit_window != NULL) {
/* raise to top ??? */
gdk_window_raise(GTK_WIDGET(edit_window)->window);
return;
}
edit_window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
snprintf(name, MAX_DISPLAY_NAME - 1, "Edit %s", get_name());
name[MAX_DISPLAY_NAME -1] = '\0';
gtk_window_set_title(GTK_WINDOW(edit_window), name);
g_signal_connect(G_OBJECT(edit_window), "destroy",
G_CALLBACK(cb_close_edit_window), this);
box = gtk_vbox_new(FALSE, 10);
gtk_container_add(GTK_CONTAINER(edit_window), box);
hbox = gtk_hbox_new(FALSE, 10);
gtk_box_pack_start(GTK_BOX(box), hbox, FALSE, TRUE, 0);
widget = gtk_button_new_with_label("Close");
g_signal_connect(G_OBJECT(widget), "clicked",
G_CALLBACK(cb_edit_done), edit_window);
GTK_WIDGET_SET_FLAGS(widget, GTK_CAN_DEFAULT);
gtk_box_pack_start(GTK_BOX(hbox), widget, FALSE, TRUE, 0);
/*
* Get the controls from the img_search.
*/
widget = img_search_display();
gtk_box_pack_start(GTK_BOX(box), widget, FALSE, TRUE, 0);
/*
* To make the layout look a little cleaner we use a table
* to place all the fields. This will make them be nicely
* aligned.
*/
table = gtk_table_new(4, 2, FALSE);
gtk_table_set_row_spacings(GTK_TABLE(table), 2);
gtk_table_set_col_spacings(GTK_TABLE(table), 4);
gtk_container_set_border_width(GTK_CONTAINER(table), 10);
gtk_box_pack_start(GTK_BOX(box), table, FALSE, TRUE, 0);
/* set the first row label and text entry for the eval function */
widget = gtk_label_new("Macro name");
gtk_label_set_justify(GTK_LABEL(widget), GTK_JUSTIFY_LEFT);
gtk_table_attach_defaults(GTK_TABLE(table), widget, 0, 1, 0, 1);
eval_function_entry = gtk_entry_new();
gtk_table_attach_defaults(GTK_TABLE(table), eval_function_entry, 1, 2, 0, 1);
if (eval_function != NULL) {
gtk_entry_set_text(GTK_ENTRY(eval_function_entry), eval_function);
}
/* set the third row label and text entry for the threshold */
widget = gtk_label_new("Threshold");
gtk_label_set_justify(GTK_LABEL(widget), GTK_JUSTIFY_LEFT);
gtk_table_attach_defaults(GTK_TABLE(table), widget, 0, 1, 2, 3);
threshold_entry = gtk_entry_new();
gtk_table_attach_defaults(GTK_TABLE(table), threshold_entry, 1, 2, 2, 3);
if (threshold != NULL) {
gtk_entry_set_text(GTK_ENTRY(threshold_entry), threshold);
}
/* set the fourth row label and file chooser button for the source directory */
widget = gtk_label_new("Source folder");
gtk_label_set_justify(GTK_LABEL(widget), GTK_JUSTIFY_LEFT);
gtk_table_attach_defaults(GTK_TABLE(table), widget, 0, 1, 3, 4);
source_folder_button = gtk_file_chooser_button_new("Select a Folder",
GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER);
gtk_table_attach_defaults(GTK_TABLE(table), source_folder_button, 1, 2, 3, 4);
if (source_folder != NULL) {
gtk_file_chooser_set_filename(GTK_FILE_CHOOSER(source_folder_button), source_folder);
}
/* make everything visible */
gtk_widget_show_all(edit_window);
return;
}
/*
* This method reads the values from the current edit
* window if there is an active one.
*/
void
imagej_search::save_edits()
{
int fd;
int blob_len;
gchar *name_used;
gboolean success;
gchar *blob_data;
if (edit_window == NULL) {
return;
}
if (eval_function != NULL) {
free(eval_function);
}
if (threshold != NULL) {
free(threshold);
}
if (source_folder != NULL) {
free(source_folder);
}
eval_function = strdup(gtk_entry_get_text(GTK_ENTRY(eval_function_entry)));
assert(eval_function != NULL);
threshold = strdup(gtk_entry_get_text(GTK_ENTRY(threshold_entry)));
assert(threshold != NULL);
source_folder = strdup(gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(source_folder_button)));
assert(source_folder != NULL);
/* blob */
free(get_auxiliary_data());
fd = g_file_open_tmp(NULL, &name_used, NULL);
g_assert(fd >= 0);
// printf("quick tar: %s\n", source_folder);
blob_len = tar_blob(source_folder, fd);
g_assert(blob_len >= 0);
success = g_file_get_contents(name_used, &blob_data, NULL, NULL);
g_assert(success);
set_auxiliary_data(blob_data);
set_auxiliary_data_length(blob_len);
// printf(" blob length: %d\n", blob_len);
// save name
img_search::save_edits();
}
void
imagej_search::close_edit_win()
{
save_edits();
/* call parent to give them a chance to cleanup */
img_search::close_edit_win();
edit_window = NULL;
}
/*
* This write the relevant section of the filter specification file
* for this search.
*/
void
imagej_search::write_fspec(FILE *ostream)
{
if (strcmp("RGB", get_name()) == 0) {
fprintf(ostream, "FILTER RGB\n");
} else {
fprintf(ostream, "FILTER %s # dependencies \n", get_name());
fprintf(ostream, "REQUIRES RGB\n");
}
fprintf(ostream, "\n");
fprintf(ostream, "THRESHOLD %s\n", threshold);
fprintf(ostream, "MERIT 10000\n");
fprintf(ostream, "EVAL_FUNCTION f_eval_imagej_exec # eval function \n");
fprintf(ostream, "INIT_FUNCTION f_init_imagej_exec # init function \n");
fprintf(ostream, "FINI_FUNCTION f_fini_imagej_exec # fini function \n");
fprintf(ostream, "ARG %s\n", eval_function );
fprintf(ostream, "\n");
fprintf(ostream, "\n");
}
void
imagej_search::write_config(FILE *ostream, const char *dirname)
{
fprintf(ostream, "SEARCH %s %s\n", SEARCH_NAME, get_name());
fprintf(ostream, "%s %s\n", EVAL_FUNCTION_ID, eval_function);
fprintf(ostream, "%s %s \n", THRESHOLD_ID, threshold);
fprintf(ostream, "%s %s \n", SOURCE_FOLDER_ID, source_folder);
}
/* Region match isn't meaningful for this search */
void
imagej_search::region_match(RGBImage *img, bbox_list_t *blist)
{
return;
}
bool
imagej_search::is_editable(void)
{
return true;
}
<|endoftext|> |
<commit_before>#include "hirestimer.hpp"
#ifdef __APPLE__
#include <mach/mach.h>
#include <mach/mach_time.h>
HiResTimer::HiResTimer()
: elapsedTicks(0), running(0), startTicks(0)
{
}
void HiResTimer::start()
{
if (++running == 1)
startTicks = mach_absolute_time();
}
void HiResTimer::stop()
{
if (--running == 0) {
unsigned long long end = mach_absolute_time();
elapsedTicks += (end - startTicks);
}
}
unsigned long long HiResTimer::elapsedNanos()
{
static mach_timebase_info_data_t timeBaseInfo;
if (timeBaseInfo.denom == 0) {
mach_timebase_info(&timeBaseInfo);
}
return elapsedTicks * timeBaseInfo.numer / timeBaseInfo.denom;
}
#else // __APPLE__
HiResTimer::HiResTimer() {}
void HiResTimer::start() {}
void HiResTimer::stop() {}
unsigned long long HiResTimer::elapsedNanos() {}
#endif // __APPLE__
<commit_msg>fix compile error on non-apple platforms.<commit_after>#include "hirestimer.hpp"
#ifdef __APPLE__
#include <mach/mach.h>
#include <mach/mach_time.h>
HiResTimer::HiResTimer()
: elapsedTicks(0), running(0), startTicks(0)
{
}
void HiResTimer::start()
{
if (++running == 1)
startTicks = mach_absolute_time();
}
void HiResTimer::stop()
{
if (--running == 0) {
unsigned long long end = mach_absolute_time();
elapsedTicks += (end - startTicks);
}
}
unsigned long long HiResTimer::elapsedNanos()
{
static mach_timebase_info_data_t timeBaseInfo;
if (timeBaseInfo.denom == 0) {
mach_timebase_info(&timeBaseInfo);
}
return elapsedTicks * timeBaseInfo.numer / timeBaseInfo.denom;
}
#else // __APPLE__
HiResTimer::HiResTimer() {}
void HiResTimer::start() {}
void HiResTimer::stop() {}
unsigned long long HiResTimer::elapsedNanos() { return 0; }
#endif // __APPLE__
<|endoftext|> |
<commit_before>#include "../../../shared/SystemImplBase.h"
#include "common/RhoConf.h"
#include "logging/RhoLog.h"
#include "../../platform/shared/qt/rhodes/impl/MainWindowImpl.h"
#include "../../platform/shared/qt/rhodes/RhoSimulator.h"
#undef null
#include <qwebkitglobal.h>
#include <QLocale>
#include <QDesktopServices>
#include <QUrl>
#undef DEFAULT_LOGCATEGORY
#define DEFAULT_LOGCATEGORY "System"
namespace rho {
using namespace apiGenerator;
class CSystemImpl: public CSystemImplBase
{
public:
CSystemImpl(): CSystemImplBase(){}
virtual void getScreenWidth(CMethodResult& oResult);
virtual void getScreenHeight(CMethodResult& oResult);
virtual void getScreenOrientation(CMethodResult& oResult);
virtual void getPpiX(CMethodResult& oResult);
virtual void getPpiY(CMethodResult& oResult);
virtual void getPhoneId(CMethodResult& oResult);
virtual void getDeviceName(CMethodResult& oResult);
virtual void getOsVersion(CMethodResult& oResult);
virtual void getIsMotorolaDevice(CMethodResult& oResult);
virtual void getLocale(CMethodResult& oResult);
virtual void getCountry(CMethodResult& oResult);
virtual void getIsEmulator(CMethodResult& oResult);
virtual void getHasCalendar(CMethodResult& oResult);
virtual void getOemInfo(CMethodResult& oResult);
virtual void getUuid(CMethodResult& oResult);
virtual void getHttpProxyURI(CMethodResult& oResult);
virtual void setHttpProxyURI( const rho::String& value, CMethodResult& oResult);
virtual void getLockWindowSize(CMethodResult& oResult);
virtual void setLockWindowSize( bool value, CMethodResult& oResult);
//virtual void getKeyboardState(CMethodResult& oResult);
//virtual void setKeyboardState( const rho::String& value, CMethodResult& oResult);
virtual void getFullScreen(CMethodResult& oResult);
virtual void setFullScreen( bool value, CMethodResult& oResult);
virtual void getScreenAutoRotate(CMethodResult& oResult);
virtual void setScreenAutoRotate( bool value, CMethodResult& oResult);
virtual void getHasTouchscreen(rho::apiGenerator::CMethodResult& oResult);
virtual void getScreenSleeping(rho::apiGenerator::CMethodResult& oResult);
virtual void setScreenSleeping( bool value, rho::apiGenerator::CMethodResult& oResult);
virtual void applicationInstall( const rho::String& applicationUrl, CMethodResult& oResult);
virtual void isApplicationInstalled( const rho::String& applicationName, CMethodResult& oResult);
virtual void applicationUninstall( const rho::String& applicationName, CMethodResult& oResult);
virtual void openUrl( const rho::String& url, CMethodResult& oResult);
virtual void setRegistrySetting( int hive, int type, const rho::String& subKey, const rho::String& setting, const rho::String& value, rho::apiGenerator::CMethodResult& oResult);
virtual void getRegistrySetting( int hive, const rho::String& subKey, const rho::String& setting, rho::apiGenerator::CMethodResult& oResult);
virtual void setWindowFrame( int x, int y, int width, int height, CMethodResult& oResult);
virtual void setWindowPosition( int x, int y, CMethodResult& oResult);
virtual void setWindowSize( int width, int height, rho::apiGenerator::CMethodResult& oResult);
virtual void getWebviewFramework(rho::apiGenerator::CMethodResult& oResult);
virtual void bringToFront(rho::apiGenerator::CMethodResult& oResult);
virtual void runApplication( const rho::String& appName, const rho::String& params, bool blockingCall, rho::apiGenerator::CMethodResult& oResult);
virtual void set_http_proxy_url( const rho::String& proxyURI, rho::apiGenerator::CMethodResult& oResult);
virtual void unset_http_proxy(rho::apiGenerator::CMethodResult& oResult);
};
void CSystemImpl::getOsVersion(CMethodResult& oResult)
{
oResult.set(String(RHOSIMULATOR_NAME " v" RHOSIMULATOR_VERSION));
}
void CSystemImpl::getIsEmulator(CMethodResult& oResult)
{
oResult.set(true);
}
void CSystemImpl::getScreenWidth(CMethodResult& oResult)
{
oResult.set(CMainWindow::getScreenWidth());
}
void CSystemImpl::getScreenHeight(CMethodResult& oResult)
{
oResult.set(CMainWindow::getScreenHeight());
}
void CSystemImpl::getScreenOrientation(CMethodResult& oResult)
{
oResult.set(StringW(CMainWindow::getScreenWidth() <= CMainWindow::getScreenHeight() ? L"portrait" : L"landscape"));
}
void CSystemImpl::getPpiX(CMethodResult& oResult)
{
oResult.set(CMainWindow::getInstance()->getLogicalDpiX());
}
void CSystemImpl::getPpiY(CMethodResult& oResult)
{
oResult.set(CMainWindow::getInstance()->getLogicalDpiY());
}
void CSystemImpl::getPhoneId(CMethodResult& oResult)
{
//oResult.set(...);
getOsVersion(oResult);
}
void CSystemImpl::getDeviceName(CMethodResult& oResult)
{
oResult.set(String("Qt"));
}
void CSystemImpl::getLocale(CMethodResult& oResult)
{
oResult.set(String(QLocale::system().name().left(2).toStdString().c_str()));
}
void CSystemImpl::getCountry(CMethodResult& oResult)
{
oResult.set(String(QLocale::system().name().right(2).toStdString().c_str()));
}
void CSystemImpl::getHasCalendar(CMethodResult& oResult)
{
oResult.set(true);
}
void CSystemImpl::getIsMotorolaDevice(CMethodResult& oResult)
{
oResult.set(false);
}
void CSystemImpl::getOemInfo(CMethodResult& oResult)
{
//oResult.set(...);
}
void CSystemImpl::getUuid(CMethodResult& oResult)
{
//oResult.set(...);
}
void CSystemImpl::getLockWindowSize(CMethodResult& oResult){}
void CSystemImpl::setLockWindowSize( bool value, CMethodResult& oResult){}
//void CSystemImpl::getKeyboardState(CMethodResult& oResult){}
//void CSystemImpl::setKeyboardState( const rho::String& value, CMethodResult& oResult){}
void CSystemImpl::getFullScreen(CMethodResult& oResult)
{
//all apps working in full screen mode on WP8
oResult.set(CMainWindow::getInstance()->getFullScreen());
}
void CSystemImpl::setFullScreen(bool value, CMethodResult& oResult)
{
CMainWindow::getInstance()->fullscreenCommand(value);
}
void CSystemImpl::getScreenAutoRotate(CMethodResult& oResult)
{
oResult.set(false);
}
void CSystemImpl::setScreenAutoRotate( bool value, CMethodResult& oResult)
{
// TODO: impolement auto rotate
}
void CSystemImpl::applicationInstall( const rho::String& applicationUrl, CMethodResult& oResult)
{
}
void CSystemImpl::isApplicationInstalled( const rho::String& applicationName, CMethodResult& oResult)
{
oResult.set(false);
}
void CSystemImpl::applicationUninstall( const rho::String& applicationName, CMethodResult& oResult)
{
}
void CSystemImpl::openUrl( const rho::String& url, CMethodResult& oResult)
{
QString sUrl = QString::fromStdString(url);
if (sUrl.startsWith("/"))
sUrl.prepend("file://");
QDesktopServices::openUrl(QUrl(sUrl));
}
void CSystemImpl::runApplication( const rho::String& appName, const rho::String& params, bool blockingCall, CMethodResult& oResult)
{
//unsupported
}
void CSystemImpl::setRegistrySetting( int hive, int type, const rho::String& subKey, const rho::String& setting, const rho::String& value, rho::apiGenerator::CMethodResult& oResult)
{
//unsupported
}
void CSystemImpl::getRegistrySetting( int hive, const rho::String& subKey, const rho::String& setting, rho::apiGenerator::CMethodResult& oResult)
{
//unsupported
}
void CSystemImpl::setWindowFrame(int x, int y, int width, int height, CMethodResult& oResult)
{
CMainWindow::getInstance()->setFrame(x, y, width, height);
}
void CSystemImpl::setWindowPosition( int x, int y, CMethodResult& oResult)
{
CMainWindow::getInstance()->setPosition(x, y);
}
void CSystemImpl::getWebviewFramework(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set(String("WEBKIT/" QTWEBKIT_VERSION_STR));
}
void CSystemImpl::bringToFront(rho::apiGenerator::CMethodResult& oResult)
{
CMainWindow::getInstance()->bringToFront();
}
extern "C" const char* rho_sys_get_http_proxy_url();
extern "C" void rho_sys_set_http_proxy_url(const char* url);
extern "C" void rho_sys_unset_http_proxy();
void CSystemImpl::getHttpProxyURI(CMethodResult& oResult)
{
oResult.set(rho_sys_get_http_proxy_url());
}
void CSystemImpl::setHttpProxyURI( const rho::String& value, CMethodResult& oResult)
{
if ( value.length() )
rho_sys_set_http_proxy_url( value.c_str() );
else
rho_sys_unset_http_proxy();
}
void CSystemImpl::getHasTouchscreen(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set(true);
}
void CSystemImpl::getScreenSleeping(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set(false);
}
void CSystemImpl::setScreenSleeping( bool value, rho::apiGenerator::CMethodResult& oResult)
{
//unsupported
}
void CSystemImpl::setWindowSize( int width, int height, rho::apiGenerator::CMethodResult& oResult)
{
CMainWindow::getInstance()->setSize(width, height);
}
void CSystemImpl::set_http_proxy_url( const rho::String& proxyURI, rho::apiGenerator::CMethodResult& oResult)
{
rho_sys_set_http_proxy_url( proxyURI.c_str() );
}
void CSystemImpl::unset_http_proxy(rho::apiGenerator::CMethodResult& oResult)
{
rho_sys_unset_http_proxy();
}
////////////////////////////////////////////////////////////////////////
class CSystemSingleton: public CModuleSingletonBase<ISystemSingleton>
{
public:
~CSystemSingleton(){}
rho::StringW getInitialDefaultID(){return L"1";}
rho::StringW getDefaultID(){return L"1";}
void setDefaultID(const rho::StringW& strI){}
};
class CSystemFactory: public CSystemFactoryBase
{
public:
~CSystemFactory(){}
ISystemSingleton* createModuleSingleton(){ return new CSystemImpl(); }
};
extern "C" void Init_System()
{
CSystemFactory::setInstance( new CSystemFactory() );
Init_System_API();
}
}
<commit_msg>rhosimulator/osx: ruby debugging fixed<commit_after>#include "../../../shared/SystemImplBase.h"
#include "common/RhoConf.h"
#include "logging/RhoLog.h"
#include "../../platform/shared/qt/rhodes/impl/MainWindowImpl.h"
#include "../../platform/shared/qt/rhodes/RhoSimulator.h"
#undef null
#include <qwebkitglobal.h>
#include <QLocale>
#include <QDesktopServices>
#include <QUrl>
#undef DEFAULT_LOGCATEGORY
#define DEFAULT_LOGCATEGORY "System"
namespace rho {
using namespace apiGenerator;
class CSystemImpl: public CSystemImplBase
{
public:
CSystemImpl(): CSystemImplBase(){}
virtual void getScreenWidth(CMethodResult& oResult);
virtual void getScreenHeight(CMethodResult& oResult);
virtual void getScreenOrientation(CMethodResult& oResult);
virtual void getPpiX(CMethodResult& oResult);
virtual void getPpiY(CMethodResult& oResult);
virtual void getPhoneId(CMethodResult& oResult);
virtual void getDeviceName(CMethodResult& oResult);
virtual void getOsVersion(CMethodResult& oResult);
virtual void getIsMotorolaDevice(CMethodResult& oResult);
virtual void getLocale(CMethodResult& oResult);
virtual void getCountry(CMethodResult& oResult);
virtual void getIsEmulator(CMethodResult& oResult);
virtual void getHasCalendar(CMethodResult& oResult);
virtual void getOemInfo(CMethodResult& oResult);
virtual void getUuid(CMethodResult& oResult);
virtual void getHttpProxyURI(CMethodResult& oResult);
virtual void setHttpProxyURI( const rho::String& value, CMethodResult& oResult);
virtual void getLockWindowSize(CMethodResult& oResult);
virtual void setLockWindowSize( bool value, CMethodResult& oResult);
//virtual void getKeyboardState(CMethodResult& oResult);
//virtual void setKeyboardState( const rho::String& value, CMethodResult& oResult);
virtual void getFullScreen(CMethodResult& oResult);
virtual void setFullScreen( bool value, CMethodResult& oResult);
virtual void getScreenAutoRotate(CMethodResult& oResult);
virtual void setScreenAutoRotate( bool value, CMethodResult& oResult);
virtual void getHasTouchscreen(rho::apiGenerator::CMethodResult& oResult);
virtual void getScreenSleeping(rho::apiGenerator::CMethodResult& oResult);
virtual void setScreenSleeping( bool value, rho::apiGenerator::CMethodResult& oResult);
virtual void applicationInstall( const rho::String& applicationUrl, CMethodResult& oResult);
virtual void isApplicationInstalled( const rho::String& applicationName, CMethodResult& oResult);
virtual void applicationUninstall( const rho::String& applicationName, CMethodResult& oResult);
virtual void openUrl( const rho::String& url, CMethodResult& oResult);
virtual void setRegistrySetting( int hive, int type, const rho::String& subKey, const rho::String& setting, const rho::String& value, rho::apiGenerator::CMethodResult& oResult);
virtual void getRegistrySetting( int hive, const rho::String& subKey, const rho::String& setting, rho::apiGenerator::CMethodResult& oResult);
virtual void setWindowFrame( int x, int y, int width, int height, CMethodResult& oResult);
virtual void setWindowPosition( int x, int y, CMethodResult& oResult);
virtual void setWindowSize( int width, int height, rho::apiGenerator::CMethodResult& oResult);
virtual void getWebviewFramework(rho::apiGenerator::CMethodResult& oResult);
virtual void bringToFront(rho::apiGenerator::CMethodResult& oResult);
virtual void runApplication( const rho::String& appName, const rho::String& params, bool blockingCall, rho::apiGenerator::CMethodResult& oResult);
virtual void getMain_window_closed(rho::apiGenerator::CMethodResult& oResult);
virtual void set_http_proxy_url( const rho::String& proxyURI, rho::apiGenerator::CMethodResult& oResult);
virtual void unset_http_proxy(rho::apiGenerator::CMethodResult& oResult);
};
void CSystemImpl::getOsVersion(CMethodResult& oResult)
{
oResult.set(String(RHOSIMULATOR_NAME " v" RHOSIMULATOR_VERSION));
}
void CSystemImpl::getIsEmulator(CMethodResult& oResult)
{
oResult.set(true);
}
void CSystemImpl::getScreenWidth(CMethodResult& oResult)
{
oResult.set(CMainWindow::getScreenWidth());
}
void CSystemImpl::getScreenHeight(CMethodResult& oResult)
{
oResult.set(CMainWindow::getScreenHeight());
}
void CSystemImpl::getScreenOrientation(CMethodResult& oResult)
{
oResult.set(StringW(CMainWindow::getScreenWidth() <= CMainWindow::getScreenHeight() ? L"portrait" : L"landscape"));
}
void CSystemImpl::getPpiX(CMethodResult& oResult)
{
oResult.set(CMainWindow::getInstance()->getLogicalDpiX());
}
void CSystemImpl::getPpiY(CMethodResult& oResult)
{
oResult.set(CMainWindow::getInstance()->getLogicalDpiY());
}
void CSystemImpl::getPhoneId(CMethodResult& oResult)
{
//oResult.set(...);
getOsVersion(oResult);
}
void CSystemImpl::getDeviceName(CMethodResult& oResult)
{
oResult.set(String("Qt"));
}
void CSystemImpl::getLocale(CMethodResult& oResult)
{
oResult.set(String(QLocale::system().name().left(2).toStdString().c_str()));
}
void CSystemImpl::getCountry(CMethodResult& oResult)
{
oResult.set(String(QLocale::system().name().right(2).toStdString().c_str()));
}
void CSystemImpl::getHasCalendar(CMethodResult& oResult)
{
oResult.set(true);
}
void CSystemImpl::getIsMotorolaDevice(CMethodResult& oResult)
{
oResult.set(false);
}
void CSystemImpl::getOemInfo(CMethodResult& oResult)
{
//oResult.set(...);
}
void CSystemImpl::getUuid(CMethodResult& oResult)
{
//oResult.set(...);
}
void CSystemImpl::getLockWindowSize(CMethodResult& oResult){}
void CSystemImpl::setLockWindowSize( bool value, CMethodResult& oResult){}
//void CSystemImpl::getKeyboardState(CMethodResult& oResult){}
//void CSystemImpl::setKeyboardState( const rho::String& value, CMethodResult& oResult){}
void CSystemImpl::getFullScreen(CMethodResult& oResult)
{
//all apps working in full screen mode on WP8
oResult.set(CMainWindow::getInstance()->getFullScreen());
}
void CSystemImpl::setFullScreen(bool value, CMethodResult& oResult)
{
CMainWindow::getInstance()->fullscreenCommand(value);
}
void CSystemImpl::getScreenAutoRotate(CMethodResult& oResult)
{
oResult.set(false);
}
void CSystemImpl::setScreenAutoRotate( bool value, CMethodResult& oResult)
{
// TODO: impolement auto rotate
}
void CSystemImpl::applicationInstall( const rho::String& applicationUrl, CMethodResult& oResult)
{
}
void CSystemImpl::isApplicationInstalled( const rho::String& applicationName, CMethodResult& oResult)
{
oResult.set(false);
}
void CSystemImpl::applicationUninstall( const rho::String& applicationName, CMethodResult& oResult)
{
}
void CSystemImpl::openUrl( const rho::String& url, CMethodResult& oResult)
{
QString sUrl = QString::fromStdString(url);
if (sUrl.startsWith("/"))
sUrl.prepend("file://");
QDesktopServices::openUrl(QUrl(sUrl));
}
void CSystemImpl::getMain_window_closed(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set(CMainWindow::mainWindowClosed);
}
void CSystemImpl::runApplication( const rho::String& appName, const rho::String& params, bool blockingCall, CMethodResult& oResult)
{
//unsupported
}
void CSystemImpl::setRegistrySetting( int hive, int type, const rho::String& subKey, const rho::String& setting, const rho::String& value, rho::apiGenerator::CMethodResult& oResult)
{
//unsupported
}
void CSystemImpl::getRegistrySetting( int hive, const rho::String& subKey, const rho::String& setting, rho::apiGenerator::CMethodResult& oResult)
{
//unsupported
}
void CSystemImpl::setWindowFrame(int x, int y, int width, int height, CMethodResult& oResult)
{
CMainWindow::getInstance()->setFrame(x, y, width, height);
}
void CSystemImpl::setWindowPosition( int x, int y, CMethodResult& oResult)
{
CMainWindow::getInstance()->setPosition(x, y);
}
void CSystemImpl::getWebviewFramework(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set(String("WEBKIT/" QTWEBKIT_VERSION_STR));
}
void CSystemImpl::bringToFront(rho::apiGenerator::CMethodResult& oResult)
{
CMainWindow::getInstance()->bringToFront();
}
extern "C" const char* rho_sys_get_http_proxy_url();
extern "C" void rho_sys_set_http_proxy_url(const char* url);
extern "C" void rho_sys_unset_http_proxy();
void CSystemImpl::getHttpProxyURI(CMethodResult& oResult)
{
oResult.set(rho_sys_get_http_proxy_url());
}
void CSystemImpl::setHttpProxyURI( const rho::String& value, CMethodResult& oResult)
{
if ( value.length() )
rho_sys_set_http_proxy_url( value.c_str() );
else
rho_sys_unset_http_proxy();
}
void CSystemImpl::getHasTouchscreen(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set(true);
}
void CSystemImpl::getScreenSleeping(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set(false);
}
void CSystemImpl::setScreenSleeping( bool value, rho::apiGenerator::CMethodResult& oResult)
{
//unsupported
}
void CSystemImpl::setWindowSize( int width, int height, rho::apiGenerator::CMethodResult& oResult)
{
CMainWindow::getInstance()->setSize(width, height);
}
void CSystemImpl::set_http_proxy_url( const rho::String& proxyURI, rho::apiGenerator::CMethodResult& oResult)
{
rho_sys_set_http_proxy_url( proxyURI.c_str() );
}
void CSystemImpl::unset_http_proxy(rho::apiGenerator::CMethodResult& oResult)
{
rho_sys_unset_http_proxy();
}
////////////////////////////////////////////////////////////////////////
class CSystemSingleton: public CModuleSingletonBase<ISystemSingleton>
{
public:
~CSystemSingleton(){}
rho::StringW getInitialDefaultID(){return L"1";}
rho::StringW getDefaultID(){return L"1";}
void setDefaultID(const rho::StringW& strI){}
};
class CSystemFactory: public CSystemFactoryBase
{
public:
~CSystemFactory(){}
ISystemSingleton* createModuleSingleton(){ return new CSystemImpl(); }
};
extern "C" void Init_System()
{
CSystemFactory::setInstance( new CSystemFactory() );
Init_System_API();
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2013-2014 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Andrew Bardsley
*/
/**
* @file
*
* The constructed pipeline. Kept out of MinorCPU to keep the interface
* between the CPU and its grubby implementation details clean.
*/
#ifndef __CPU_MINOR_PIPELINE_HH__
#define __CPU_MINOR_PIPELINE_HH__
#include "cpu/minor/activity.hh"
#include "cpu/minor/cpu.hh"
#include "cpu/minor/decode.hh"
#include "cpu/minor/execute.hh"
#include "cpu/minor/fetch1.hh"
#include "cpu/minor/fetch2.hh"
#include "params/MinorCPU.hh"
#include "sim/ticked_object.hh"
namespace Minor
{
/**
* @namespace Minor
*
* Minor contains all the definitions within the MinorCPU apart from the CPU
* class itself
*/
/** The constructed pipeline. Kept out of MinorCPU to keep the interface
* between the CPU and its grubby implementation details clean. */
class Pipeline : public Ticked
{
protected:
MinorCPU &cpu;
/** Allow cycles to be skipped when the pipeline is idle */
bool allow_idling;
Latch<ForwardLineData> f1ToF2;
Latch<BranchData> f2ToF1;
Latch<ForwardInstData> f2ToD;
Latch<ForwardInstData> dToE;
Latch<BranchData> eToF1;
Execute execute;
Decode decode;
Fetch2 fetch2;
Fetch1 fetch1;
/** Activity recording for the pipeline. This is access through the CPU
* by the pipeline stages but belongs to the Pipeline as it is the
* cleanest place to initialise it */
MinorActivityRecorder activityRecorder;
public:
/** Enumerated ids of the 'stages' for the activity recorder */
enum StageId
{
/* A stage representing wakeup of the whole processor */
CPUStageId = 0,
/* Real pipeline stages */
Fetch1StageId, Fetch2StageId, DecodeStageId, ExecuteStageId,
Num_StageId /* Stage count */
};
/** True after drain is called but draining isn't complete */
bool needToSignalDrained;
public:
Pipeline(MinorCPU &cpu_, MinorCPUParams ¶ms);
public:
/** Wake up the Fetch unit. This is needed on thread activation esp.
* after quiesce wakeup */
void wakeupFetch();
/** Try to drain the CPU */
unsigned int drain(DrainManager *manager);
void drainResume();
/** Test to see if the CPU is drained */
bool isDrained();
/** A custom evaluate allows report in the right place (between
* stages and pipeline advance) */
void evaluate();
void countCycles(Cycles delta) M5_ATTR_OVERRIDE
{
cpu.ppCycles->notify(delta);
}
void minorTrace() const;
/** Functions below here are BaseCPU operations passed on to pipeline
* stages */
/** Return the IcachePort belonging to Fetch1 for the CPU */
MinorCPU::MinorCPUPort &getInstPort();
/** Return the DcachePort belonging to Execute for the CPU */
MinorCPU::MinorCPUPort &getDataPort();
/** To give the activity recorder to the CPU */
MinorActivityRecorder *getActivityRecorder() { return &activityRecorder; }
};
}
#endif /* __CPU_MINOR_PIPELINE_HH__ */
<commit_msg>test.161211.2324<commit_after>/*
* Copyright (c) 2013-2014 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Andrew Bardsley
*/
/**
* @file
*
* The constructed pipeline. Kept out of MinorCPU to keep the interface
* between the CPU and its grubby implementation details clean.
*/
#ifndef __CPU_MINOR_PIPELINE_HH__
#define __CPU_MINOR_PIPELINE_HH__
#include "cpu/minor/activity.hh"
#include "cpu/minor/cpu.hh"
#include "cpu/minor/decode.hh"
#include "cpu/minor/execute.hh"
#include "cpu/minor/fetch1.hh"
#include "cpu/minor/fetch2.hh"
#include "params/MinorCPU.hh"
#include "sim/ticked_object.hh"
namespace Minor
{
/**
* @namespace Minor
*
* Minor contains all the definitions within the MinorCPU apart from the CPU
* class itself
*/
/** The constructed pipeline. Kept out of MinorCPU to keep the interface
* between the CPU and its grubby implementation details clean. */
class Pipeline : public Ticked
{
protected:
MinorCPU &cpu;
/** Allow cycles to be skipped when the pipeline is idle */
bool allow_idling;
Latch<ForwardLineData> f1ToF2;
Latch<BranchData> f2ToF1;
Latch<ForwardInstData> f2ToD;
Latch<ForwardInstData> dToE;
Latch<BranchData> eToF1;
Latch<BranchData> dToF;
Execute execute;
Decode decode;
Fetch2 fetch2;
Fetch1 fetch1;
/** Activity recording for the pipeline. This is access through the CPU
* by the pipeline stages but belongs to the Pipeline as it is the
* cleanest place to initialise it */
MinorActivityRecorder activityRecorder;
public:
/** Enumerated ids of the 'stages' for the activity recorder */
enum StageId
{
/* A stage representing wakeup of the whole processor */
CPUStageId = 0,
/* Real pipeline stages */
Fetch1StageId, Fetch2StageId, DecodeStageId, ExecuteStageId,
Num_StageId /* Stage count */
};
/** True after drain is called but draining isn't complete */
bool needToSignalDrained;
public:
Pipeline(MinorCPU &cpu_, MinorCPUParams ¶ms);
public:
/** Wake up the Fetch unit. This is needed on thread activation esp.
* after quiesce wakeup */
void wakeupFetch();
/** Try to drain the CPU */
unsigned int drain(DrainManager *manager);
void drainResume();
/** Test to see if the CPU is drained */
bool isDrained();
/** A custom evaluate allows report in the right place (between
* stages and pipeline advance) */
void evaluate();
void countCycles(Cycles delta) M5_ATTR_OVERRIDE
{
cpu.ppCycles->notify(delta);
}
void minorTrace() const;
/** Functions below here are BaseCPU operations passed on to pipeline
* stages */
/** Return the IcachePort belonging to Fetch1 for the CPU */
MinorCPU::MinorCPUPort &getInstPort();
/** Return the DcachePort belonging to Execute for the CPU */
MinorCPU::MinorCPUPort &getDataPort();
/** To give the activity recorder to the CPU */
MinorActivityRecorder *getActivityRecorder() { return &activityRecorder; }
};
}
#endif /* __CPU_MINOR_PIPELINE_HH__ */
<|endoftext|> |
<commit_before>
#include "numerics/quadrature.hpp"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "quantities/elementary_functions.hpp"
#include "testing_utilities/almost_equals.hpp"
#include "testing_utilities/is_near.hpp"
#include "testing_utilities/numerics_matchers.hpp"
namespace principia {
namespace numerics {
namespace quadrature {
using quantities::Angle;
using quantities::Cos;
using quantities::Sin;
using quantities::si::Radian;
using testing_utilities::AlmostEquals;
using testing_utilities::IsNear;
using testing_utilities::RelativeErrorFrom;
using testing_utilities::operator""_⑴;
class QuadratureTest : public ::testing::Test {};
TEST_F(QuadratureTest, Sin) {
auto const f = [](Angle const x) { return Sin(x); };
auto const ʃf = (Cos(2.0 * Radian) - Cos(5.0 * Radian)) * Radian;
EXPECT_THAT(GaussLegendre<1>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(10_⑴)));
EXPECT_THAT(GaussLegendre<2>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(3.3_⑴)));
EXPECT_THAT(GaussLegendre<3>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(4.0e-1_⑴)));
EXPECT_THAT(GaussLegendre<4>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(2.4e-2_⑴)));
EXPECT_THAT(GaussLegendre<5>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(8.6e-4_⑴)));
EXPECT_THAT(GaussLegendre<6>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(2.1e-5_⑴)));
EXPECT_THAT(GaussLegendre<7>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(3.6e-7_⑴)));
EXPECT_THAT(GaussLegendre<8>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(4.7e-9_⑴)));
EXPECT_THAT(GaussLegendre<9>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(4.8e-11_⑴)));
EXPECT_THAT(GaussLegendre<10>(f, -2.0 * Radian, 5.0 * Radian),
AlmostEquals(ʃf, 2498));
EXPECT_THAT(GaussLegendre<11>(f, -2.0 * Radian, 5.0 * Radian),
AlmostEquals(ʃf, 20));
EXPECT_THAT(GaussLegendre<12>(f, -2.0 * Radian, 5.0 * Radian),
AlmostEquals(ʃf, 6));
EXPECT_THAT(GaussLegendre<13>(f, -2.0 * Radian, 5.0 * Radian),
AlmostEquals(ʃf, 1));
EXPECT_THAT(GaussLegendre<14>(f, -2.0 * Radian, 5.0 * Radian),
AlmostEquals(ʃf, 1));
EXPECT_THAT(GaussLegendre<15>(f, -2.0 * Radian, 5.0 * Radian),
AlmostEquals(ʃf, 4));
}
TEST_F(QuadratureTest, Sin10) {
auto const f = [](Angle const x) { return Sin(2 * x); };
auto const ʃf = (Cos(4 * Radian) - Cos(10 * Radian)) / 2 * Radian;
EXPECT_THAT(GaussLegendre<1>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(9.7_⑴)));
EXPECT_THAT(GaussLegendre<2>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(7.6_⑴)));
EXPECT_THAT(GaussLegendre<3>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(7.6_⑴)));
EXPECT_THAT(GaussLegendre<4>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(2.4_⑴)));
EXPECT_THAT(GaussLegendre<5>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(4.2e-1_⑴)));
EXPECT_THAT(GaussLegendre<6>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(4.6e-2_⑴)));
EXPECT_THAT(GaussLegendre<7>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(3.5e-3_⑴)));
EXPECT_THAT(GaussLegendre<8>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(2.0e-4_⑴)));
EXPECT_THAT(GaussLegendre<9>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(8.5e-6_⑴)));
EXPECT_THAT(GaussLegendre<10>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(2.9e-7_⑴)));;
EXPECT_THAT(GaussLegendre<11>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(8.1e-9_⑴)));
EXPECT_THAT(GaussLegendre<12>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(1.9e-10_⑴)));
EXPECT_THAT(GaussLegendre<13>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(3.7e-12_⑴)));
EXPECT_THAT(GaussLegendre<14>(f, -2.0 * Radian, 5.0 * Radian),
AlmostEquals(ʃf, 422));
EXPECT_THAT(GaussLegendre<15>(f, -2.0 * Radian, 5.0 * Radian),
AlmostEquals(ʃf, 44));
EXPECT_THAT(GaussLegendre<16>(f, -2.0 * Radian, 5.0 * Radian),
AlmostEquals(ʃf, 152));
}
} // namespace quadrature
} // namespace numerics
} // namespace principia
<commit_msg>Tolerances for Linux and macOS.<commit_after>
#include "numerics/quadrature.hpp"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "quantities/elementary_functions.hpp"
#include "testing_utilities/almost_equals.hpp"
#include "testing_utilities/is_near.hpp"
#include "testing_utilities/numerics_matchers.hpp"
namespace principia {
namespace numerics {
namespace quadrature {
using quantities::Angle;
using quantities::Cos;
using quantities::Sin;
using quantities::si::Radian;
using testing_utilities::AlmostEquals;
using testing_utilities::IsNear;
using testing_utilities::RelativeErrorFrom;
using testing_utilities::operator""_⑴;
class QuadratureTest : public ::testing::Test {};
TEST_F(QuadratureTest, Sin) {
auto const f = [](Angle const x) { return Sin(x); };
auto const ʃf = (Cos(2.0 * Radian) - Cos(5.0 * Radian)) * Radian;
EXPECT_THAT(GaussLegendre<1>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(10_⑴)));
EXPECT_THAT(GaussLegendre<2>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(3.3_⑴)));
EXPECT_THAT(GaussLegendre<3>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(4.0e-1_⑴)));
EXPECT_THAT(GaussLegendre<4>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(2.4e-2_⑴)));
EXPECT_THAT(GaussLegendre<5>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(8.6e-4_⑴)));
EXPECT_THAT(GaussLegendre<6>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(2.1e-5_⑴)));
EXPECT_THAT(GaussLegendre<7>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(3.6e-7_⑴)));
EXPECT_THAT(GaussLegendre<8>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(4.7e-9_⑴)));
EXPECT_THAT(GaussLegendre<9>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(4.8e-11_⑴)));
EXPECT_THAT(GaussLegendre<10>(f, -2.0 * Radian, 5.0 * Radian),
AlmostEquals(ʃf, 2495, 2498));
EXPECT_THAT(GaussLegendre<11>(f, -2.0 * Radian, 5.0 * Radian),
AlmostEquals(ʃf, 20));
EXPECT_THAT(GaussLegendre<12>(f, -2.0 * Radian, 5.0 * Radian),
AlmostEquals(ʃf, 6, 7));
EXPECT_THAT(GaussLegendre<13>(f, -2.0 * Radian, 5.0 * Radian),
AlmostEquals(ʃf, 0, 1));
EXPECT_THAT(GaussLegendre<14>(f, -2.0 * Radian, 5.0 * Radian),
AlmostEquals(ʃf, 1, 2));
EXPECT_THAT(GaussLegendre<15>(f, -2.0 * Radian, 5.0 * Radian),
AlmostEquals(ʃf, 3, 4));
}
TEST_F(QuadratureTest, Sin10) {
auto const f = [](Angle const x) { return Sin(2 * x); };
auto const ʃf = (Cos(4 * Radian) - Cos(10 * Radian)) / 2 * Radian;
EXPECT_THAT(GaussLegendre<1>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(9.7_⑴)));
EXPECT_THAT(GaussLegendre<2>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(7.6_⑴)));
EXPECT_THAT(GaussLegendre<3>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(7.6_⑴)));
EXPECT_THAT(GaussLegendre<4>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(2.4_⑴)));
EXPECT_THAT(GaussLegendre<5>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(4.2e-1_⑴)));
EXPECT_THAT(GaussLegendre<6>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(4.6e-2_⑴)));
EXPECT_THAT(GaussLegendre<7>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(3.5e-3_⑴)));
EXPECT_THAT(GaussLegendre<8>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(2.0e-4_⑴)));
EXPECT_THAT(GaussLegendre<9>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(8.5e-6_⑴)));
EXPECT_THAT(GaussLegendre<10>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(2.9e-7_⑴)));;
EXPECT_THAT(GaussLegendre<11>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(8.1e-9_⑴)));
EXPECT_THAT(GaussLegendre<12>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(1.9e-10_⑴)));
EXPECT_THAT(GaussLegendre<13>(f, -2.0 * Radian, 5.0 * Radian),
RelativeErrorFrom(ʃf, IsNear(3.7e-12_⑴)));
EXPECT_THAT(GaussLegendre<14>(f, -2.0 * Radian, 5.0 * Radian),
AlmostEquals(ʃf, 422, 425));
EXPECT_THAT(GaussLegendre<15>(f, -2.0 * Radian, 5.0 * Radian),
AlmostEquals(ʃf, 36, 50));
EXPECT_THAT(GaussLegendre<16>(f, -2.0 * Radian, 5.0 * Radian),
AlmostEquals(ʃf, 152, 159));
}
} // namespace quadrature
} // namespace numerics
} // namespace principia
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/browser_action_test_util.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/extensions/user_script_master.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"
IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoNoScript) {
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
// Loads a simple extension which attempts to change the title of every page
// that loads to "modified".
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("incognito").AppendASCII("content_scripts")));
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
Browser* otr_browser = BrowserList::FindBrowserWithType(
browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
false);
TabContents* tab = otr_browser->GetSelectedTabContents();
// Verify the script didn't run.
bool result = false;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
tab->render_view_host(), L"",
L"window.domAutomationController.send(document.title == 'Unmodified')",
&result));
EXPECT_TRUE(result);
}
IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoYesScript) {
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
// Load a dummy extension. This just tests that we don't regress a
// crash fix when multiple incognito- and non-incognito-enabled extensions
// are mixed.
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("content_scripts").AppendASCII("all_frames")));
// Loads a simple extension which attempts to change the title of every page
// that loads to "modified".
ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_.AppendASCII("api_test")
.AppendASCII("incognito").AppendASCII("content_scripts")));
// Dummy extension #2.
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("content_scripts").AppendASCII("isolated_world1")));
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
Browser* otr_browser = BrowserList::FindBrowserWithType(
browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
false);
TabContents* tab = otr_browser->GetSelectedTabContents();
// Verify the script ran.
bool result = false;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
tab->render_view_host(), L"",
L"window.domAutomationController.send(document.title == 'modified')",
&result));
EXPECT_TRUE(result);
}
// Tests that an extension which is enabled for incognito mode doesn't
// accidentially create and incognito profile.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DontCreateIncognitoProfile) {
ASSERT_FALSE(browser()->profile()->HasOffTheRecordProfile());
ASSERT_TRUE(
RunExtensionTestIncognito("incognito/enumerate_tabs")) << message_;
ASSERT_FALSE(browser()->profile()->HasOffTheRecordProfile());
}
// Tests that the APIs in an incognito-enabled extension work properly.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Incognito) {
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
ResultCatcher catcher;
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
.AppendASCII("incognito").AppendASCII("apis")));
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
// Tests that the APIs in an incognito-enabled split-mode extension work
// properly.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoSplitMode) {
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
// We need 2 ResultCatchers because we'll be running the same test in both
// regular and incognito mode.
ResultCatcher catcher;
catcher.RestrictToProfile(browser()->profile());
ResultCatcher catcher_incognito;
catcher_incognito.RestrictToProfile(
browser()->profile()->GetOffTheRecordProfile());
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
.AppendASCII("incognito").AppendASCII("split")));
// Wait for both extensions to be ready before telling them to proceed.
ExtensionTestMessageListener listener("waiting", true);
EXPECT_TRUE(listener.WaitUntilSatisfied());
ExtensionTestMessageListener listener_incognito("waiting", true);
EXPECT_TRUE(listener_incognito.WaitUntilSatisfied());
listener.Reply("go");
listener_incognito.Reply("go");
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
EXPECT_TRUE(catcher_incognito.GetNextResult()) << catcher.message();
}
// Tests that the APIs in an incognito-disabled extension don't see incognito
// events or callbacks.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoDisabled) {
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
ResultCatcher catcher;
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
ASSERT_TRUE(LoadExtension(test_data_dir_
.AppendASCII("incognito").AppendASCII("apis_disabled")));
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
// Test that opening a popup from an incognito browser window works properly.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoPopup) {
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
ResultCatcher catcher;
ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
.AppendASCII("incognito").AppendASCII("popup")));
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
Browser* incognito_browser = BrowserList::FindBrowserWithType(
browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
false);
// Simulate the incognito's browser action being clicked.
BrowserActionTestUtil(incognito_browser).Press(0);
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
<commit_msg>Mark IncognitoSplitMode flaky again. Turns out it is still not fixed.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/browser_action_test_util.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/extensions/user_script_master.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"
IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoNoScript) {
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
// Loads a simple extension which attempts to change the title of every page
// that loads to "modified".
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("incognito").AppendASCII("content_scripts")));
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
Browser* otr_browser = BrowserList::FindBrowserWithType(
browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
false);
TabContents* tab = otr_browser->GetSelectedTabContents();
// Verify the script didn't run.
bool result = false;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
tab->render_view_host(), L"",
L"window.domAutomationController.send(document.title == 'Unmodified')",
&result));
EXPECT_TRUE(result);
}
IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoYesScript) {
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
// Load a dummy extension. This just tests that we don't regress a
// crash fix when multiple incognito- and non-incognito-enabled extensions
// are mixed.
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("content_scripts").AppendASCII("all_frames")));
// Loads a simple extension which attempts to change the title of every page
// that loads to "modified".
ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_.AppendASCII("api_test")
.AppendASCII("incognito").AppendASCII("content_scripts")));
// Dummy extension #2.
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("content_scripts").AppendASCII("isolated_world1")));
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
Browser* otr_browser = BrowserList::FindBrowserWithType(
browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
false);
TabContents* tab = otr_browser->GetSelectedTabContents();
// Verify the script ran.
bool result = false;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
tab->render_view_host(), L"",
L"window.domAutomationController.send(document.title == 'modified')",
&result));
EXPECT_TRUE(result);
}
// Tests that an extension which is enabled for incognito mode doesn't
// accidentially create and incognito profile.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DontCreateIncognitoProfile) {
ASSERT_FALSE(browser()->profile()->HasOffTheRecordProfile());
ASSERT_TRUE(
RunExtensionTestIncognito("incognito/enumerate_tabs")) << message_;
ASSERT_FALSE(browser()->profile()->HasOffTheRecordProfile());
}
// Tests that the APIs in an incognito-enabled extension work properly.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Incognito) {
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
ResultCatcher catcher;
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
.AppendASCII("incognito").AppendASCII("apis")));
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
// Hangs flakily on mac and linux: http://crbug.com/53991
#if defined(OS_MACOSX) || defined(OS_LINUX)
#define MAYBE_IncognitoSplitMode DISABLED_IncognitoSplitMode
#else
#define MAYBE_IncognitoSplitMode IncognitoSplitMode
#endif
// Tests that the APIs in an incognito-enabled split-mode extension work
// properly.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_IncognitoSplitMode) {
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
// We need 2 ResultCatchers because we'll be running the same test in both
// regular and incognito mode.
ResultCatcher catcher;
catcher.RestrictToProfile(browser()->profile());
ResultCatcher catcher_incognito;
catcher_incognito.RestrictToProfile(
browser()->profile()->GetOffTheRecordProfile());
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
.AppendASCII("incognito").AppendASCII("split")));
// Wait for both extensions to be ready before telling them to proceed.
ExtensionTestMessageListener listener("waiting", true);
EXPECT_TRUE(listener.WaitUntilSatisfied());
ExtensionTestMessageListener listener_incognito("waiting", true);
EXPECT_TRUE(listener_incognito.WaitUntilSatisfied());
listener.Reply("go");
listener_incognito.Reply("go");
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
EXPECT_TRUE(catcher_incognito.GetNextResult()) << catcher.message();
}
// Tests that the APIs in an incognito-disabled extension don't see incognito
// events or callbacks.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoDisabled) {
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
ResultCatcher catcher;
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
ASSERT_TRUE(LoadExtension(test_data_dir_
.AppendASCII("incognito").AppendASCII("apis_disabled")));
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
// Test that opening a popup from an incognito browser window works properly.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoPopup) {
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
ResultCatcher catcher;
ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
.AppendASCII("incognito").AppendASCII("popup")));
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
Browser* incognito_browser = BrowserList::FindBrowserWithType(
browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
false);
// Simulate the incognito's browser action being clicked.
BrowserActionTestUtil(incognito_browser).Press(0);
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
<|endoftext|> |
<commit_before><commit_msg>Disable IncognitoSplitMode everywhere, it's failing and hangy. Working on a fix.<commit_after><|endoftext|> |
<commit_before><commit_msg>Revert r49169 and r49170; they didn't fix the problem.<commit_after><|endoftext|> |
<commit_before>
#ifdef __linux__
#include <cassert>
#include <GL/glew.h>
#include <GL/glxew.h>
#include <GL/glx.h>
#include <glow/logging.h>
#include <glow/global.h>
#include <glow/Error.h>
#include "GLxContext.h"
namespace glow
{
Display * GLxContext::s_display = nullptr;
GLxContext::GLxContext(Context & context)
: AbstractNativeContext(context)
, m_display(nullptr)
, m_hWnd(0L)
, m_context(nullptr)
, m_id(-1)
{
}
GLxContext::~GLxContext()
{
release();
assert(nullptr == m_display);
assert(0L == m_hWnd);
assert(nullptr == m_context);
assert(-1 == m_id);
}
Display * GLxContext::getOrOpenDisplay()
{
if(s_display)
return s_display;
s_display = XOpenDisplay(NULL);
if (nullptr == s_display)
{
int dummy; // this is stupid! if a parameters is not required passing nullptr does not work.
if(!glXQueryExtension(s_display, &dummy, &dummy))
{
fatal() << "Cannot conntext to X server (XOpenDisplay).";
return nullptr;
}
}
return s_display;
}
void GLxContext::closeDisplay()
{
if(!s_display)
return;
XCloseDisplay(s_display);
s_display = nullptr;
}
// example: http://wili.cc/blog/ogl3-glx.html
bool GLxContext::create(
const int hWnd
, ContextFormat & format)
{
assert(!isValid());
m_hWnd = static_cast< ::Window>(hWnd);
m_display = getOrOpenDisplay();
if (nullptr == m_display)
return false;
const int screen = DefaultScreen(m_display);
// TODO: unused variable
//const ::Window root = DefaultRootWindow(m_display);
int viAttribs[] = { GLX_RGBA, GLX_USE_GL, GLX_DEPTH_SIZE, format.depthBufferSize(), GLX_RED_SIZE, 8, GLX_GREEN_SIZE, 8, GLX_BLUE_SIZE, 8
, (format.swapBehavior() == ContextFormat::DoubleBuffering ? (int)GLX_DOUBLEBUFFER : (int)None), None };
XVisualInfo * vi = glXChooseVisual(m_display, screen, viAttribs);
if (nullptr == vi)
{
fatal() << "Choosing a visual failed (glXChooseVisual).";
release();
return false;
}
// create temporary ogl context
::GLXContext tempContext = glXCreateContext(m_display, vi, None, GL_TRUE);
if (NULL == tempContext)
{
fatal() << "Creating temporary OpenGL context failed (glXCreateContext).";
release();
return false;
}
// check for GLX_ARB_create_context extension
if (!glXMakeCurrent(m_display, m_hWnd, tempContext))
{
fatal() << "Making temporary OpenGL context current failed (glXMakeCurrent).";
glXDestroyContext(m_display, tempContext);
release();
return false;
}
// http://www.opengl.org/wiki/Tutorial:_OpenGL_3.1_The_First_Triangle_(C%2B%2B/Win)
if (GLEW_OK != glewInit())
{
fatal() << "GLEW initialization failed (glewInit).";
CheckGLError();
glXDestroyContext(m_display, tempContext);
release();
return false;
}
if (!GLX_ARB_create_context)
{
fatal() << "Mandatory extension GLX_ARB_create_context not supported.";
glXDestroyContext(m_display, tempContext);
release();
return false;
}
// NOTE: this assumes that the driver creates a "defaulted" context with
// the highest available opengl version.
format.setVersionFallback(query::majorVersion(), query::minorVersion());
glXMakeCurrent(m_display, 0L, nullptr);
glXDestroyContext(m_display, tempContext);
if(fatalVersionDisclaimer(format.version()))
return false;
// create context
const int attributes[] =
{
GLX_CONTEXT_MAJOR_VERSION_ARB, static_cast<int>(format.majorVersion())
, GLX_CONTEXT_MINOR_VERSION_ARB, static_cast<int>(format.minorVersion())
, GLX_CONTEXT_PROFILE_MASK_ARB, format.profile() == ContextFormat::CoreProfile ?
GLX_CONTEXT_CORE_PROFILE_BIT_ARB : GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB
, GLX_CONTEXT_FLAGS_ARB, 0, None
};
int elemc;
GLXFBConfig * fbConfig = glXChooseFBConfig(m_display, screen, NULL, &elemc);
if (!fbConfig)
{
fatal() << "Choosing a Frame Buffer configuration failed (glXChooseFBConfig)";
release();
return false;
}
m_context = glXCreateContextAttribsARB(m_display, fbConfig[0], NULL, true, attributes);
if (NULL == m_context)
{
fatal() << "Creating OpenGL context with attributes failed (glXCreateContextAttribsARB).";
release();
return false;
}
if (!glXIsDirect(m_display, m_context))
warning() << "Direct rendering is not enabled (glXIsDirect).";
if (GLX_EXT_import_context)
{
m_id = glXGetContextIDEXT(m_context);
}
else
{
m_id = 1; // TODO: workaround
}
return true;
}
void GLxContext::release()
{
//~ assert(isValid());
if(m_context)
{
if(m_context == glXGetCurrentContext() && !glXMakeCurrent(m_display, 0L, nullptr))
warning() << "Release of context failed (glXMakeCurrent).";
glXDestroyContext(m_display, m_context);
}
m_display = nullptr;
m_hWnd = 0L;
m_context = nullptr;
m_id = -1;
}
void GLxContext::swap() const
{
assert(isValid());
if(ContextFormat::SingleBuffering == format().swapBehavior())
return;
glXSwapBuffers(m_display, m_hWnd);
}
int GLxContext::id() const
{
return m_id;
}
bool GLxContext::isValid() const
{
return m_context != nullptr;
}
bool GLxContext::setSwapInterval(Context::SwapInterval swapInterval) const
{
if (!GLX_EXT_swap_control)
{
warning() << "GLX_EXT_swap_control extension not found, ignoring swap interval set request";
return false;
}
glXSwapIntervalEXT(m_display, m_hWnd, swapInterval);
if (Error::get())
{
warning() << "Setting swap interval to " << Context::swapIntervalString(swapInterval)
<< " (" << swapInterval << ") failed.";
return false;
}
return true;
}
bool GLxContext::makeCurrent() const
{
const Bool result = glXMakeCurrent(m_display, m_hWnd, m_context);
CheckGLError();
if (!result)
fatal() << "Making the OpenGL context current failed (glXMakeCurrent).";
return True == result;
}
bool GLxContext::doneCurrent() const
{
const Bool result = glXMakeCurrent(m_display, 0L, nullptr);
if (!result)
warning() << "Release of RC failed (glXMakeCurrent).";
return True == result;
}
} // namespace glow
#endif
<commit_msg>Add more specific condition for Ubuntu/Linux 64bit NVidia-325<commit_after>
#ifdef __linux__
#include <cassert>
#include <GL/glew.h>
#include <GL/glxew.h>
#include <GL/glx.h>
#include <glow/logging.h>
#include <glow/global.h>
#include <glow/Error.h>
#include "GLxContext.h"
namespace glow
{
Display * GLxContext::s_display = nullptr;
GLxContext::GLxContext(Context & context)
: AbstractNativeContext(context)
, m_display(nullptr)
, m_hWnd(0L)
, m_context(nullptr)
, m_id(-1)
{
}
GLxContext::~GLxContext()
{
release();
assert(nullptr == m_display);
assert(0L == m_hWnd);
assert(nullptr == m_context);
assert(-1 == m_id);
}
Display * GLxContext::getOrOpenDisplay()
{
if(s_display)
return s_display;
s_display = XOpenDisplay(NULL);
if (nullptr == s_display)
{
int dummy; // this is stupid! if a parameters is not required passing nullptr does not work.
if(!glXQueryExtension(s_display, &dummy, &dummy))
{
fatal() << "Cannot conntext to X server (XOpenDisplay).";
return nullptr;
}
}
return s_display;
}
void GLxContext::closeDisplay()
{
if(!s_display)
return;
XCloseDisplay(s_display);
s_display = nullptr;
}
// example: http://wili.cc/blog/ogl3-glx.html
bool GLxContext::create(
const int hWnd
, ContextFormat & format)
{
assert(!isValid());
m_hWnd = static_cast< ::Window>(hWnd);
m_display = getOrOpenDisplay();
if (nullptr == m_display)
return false;
const int screen = DefaultScreen(m_display);
// TODO: unused variable
//const ::Window root = DefaultRootWindow(m_display);
int viAttribs[] = { GLX_RGBA, GLX_USE_GL, GLX_DEPTH_SIZE, format.depthBufferSize(), GLX_RED_SIZE, 8, GLX_GREEN_SIZE, 8, GLX_BLUE_SIZE, 8
, (format.swapBehavior() == ContextFormat::DoubleBuffering ? (int)GLX_DOUBLEBUFFER : (int)None), None };
XVisualInfo * vi = glXChooseVisual(m_display, screen, viAttribs);
if (nullptr == vi)
{
fatal() << "Choosing a visual failed (glXChooseVisual).";
release();
return false;
}
// create temporary ogl context
::GLXContext tempContext = glXCreateContext(m_display, vi, None, GL_TRUE);
if (NULL == tempContext)
{
fatal() << "Creating temporary OpenGL context failed (glXCreateContext).";
release();
return false;
}
// check for GLX_ARB_create_context extension
if (!glXMakeCurrent(m_display, m_hWnd, tempContext))
{
fatal() << "Making temporary OpenGL context current failed (glXMakeCurrent).";
glXDestroyContext(m_display, tempContext);
release();
return false;
}
// http://www.opengl.org/wiki/Tutorial:_OpenGL_3.1_The_First_Triangle_(C%2B%2B/Win)
if (GLEW_OK != glewInit())
{
fatal() << "GLEW initialization failed (glewInit).";
CheckGLError();
glXDestroyContext(m_display, tempContext);
release();
return false;
}
if (!GLX_ARB_create_context)
{
fatal() << "Mandatory extension GLX_ARB_create_context not supported.";
glXDestroyContext(m_display, tempContext);
release();
return false;
}
// NOTE: this assumes that the driver creates a "defaulted" context with
// the highest available opengl version.
format.setVersionFallback(query::majorVersion(), query::minorVersion());
glXMakeCurrent(m_display, 0L, nullptr);
glXDestroyContext(m_display, tempContext);
if(fatalVersionDisclaimer(format.version()))
return false;
// create context
const int attributes[] =
{
GLX_CONTEXT_MAJOR_VERSION_ARB, static_cast<int>(format.majorVersion())
, GLX_CONTEXT_MINOR_VERSION_ARB, static_cast<int>(format.minorVersion())
, GLX_CONTEXT_PROFILE_MASK_ARB, format.profile() == ContextFormat::CoreProfile ?
GLX_CONTEXT_CORE_PROFILE_BIT_ARB : GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB
, GLX_CONTEXT_FLAGS_ARB, 0, None
};
int elemc;
GLXFBConfig * fbConfig = glXChooseFBConfig(m_display, screen, NULL, &elemc);
if (!fbConfig)
{
fatal() << "Choosing a Frame Buffer configuration failed (glXChooseFBConfig)";
release();
return false;
}
if (GLX_ARB_create_context)
{
if (glXCreateContextAttribsARB)
{
m_context = glXCreateContextAttribsARB(m_display, fbConfig[0], NULL, true, attributes);
}
else
{
fatal() << "GLX_ARB_create_context present, but glXCreateContextAttribsARB missing.";
}
}
else
{
fatal() << "GLX_ARB_create_context not present.";
}
if (nullptr == m_context)
{
fatal() << "Creating OpenGL context with attributes failed (glXCreateContextAttribsARB).";
release();
return false;
}
if (!glXIsDirect(m_display, m_context))
warning() << "Direct rendering is not enabled (glXIsDirect).";
if (GLX_EXT_import_context && glXGetContextIDEXT)
{
m_id = glXGetContextIDEXT(m_context);
}
else
{
m_id = 1; // TODO: workaround
}
return true;
}
void GLxContext::release()
{
//~ assert(isValid());
if(m_context)
{
if(m_context == glXGetCurrentContext() && !glXMakeCurrent(m_display, 0L, nullptr))
warning() << "Release of context failed (glXMakeCurrent).";
glXDestroyContext(m_display, m_context);
}
m_display = nullptr;
m_hWnd = 0L;
m_context = nullptr;
m_id = -1;
}
void GLxContext::swap() const
{
assert(isValid());
if(ContextFormat::SingleBuffering == format().swapBehavior())
return;
glXSwapBuffers(m_display, m_hWnd);
}
int GLxContext::id() const
{
return m_id;
}
bool GLxContext::isValid() const
{
return m_context != nullptr;
}
bool GLxContext::setSwapInterval(Context::SwapInterval swapInterval) const
{
if (!GLX_EXT_swap_control || !glXSwapIntervalEXT)
{
warning() << "GLX_EXT_swap_control extension not found, ignoring swap interval set request";
return false;
}
glXSwapIntervalEXT(m_display, m_hWnd, swapInterval);
if (Error::get())
{
warning() << "Setting swap interval to " << Context::swapIntervalString(swapInterval)
<< " (" << swapInterval << ") failed.";
return false;
}
return true;
}
bool GLxContext::makeCurrent() const
{
const Bool result = glXMakeCurrent(m_display, m_hWnd, m_context);
CheckGLError();
if (!result)
fatal() << "Making the OpenGL context current failed (glXMakeCurrent).";
return True == result;
}
bool GLxContext::doneCurrent() const
{
const Bool result = glXMakeCurrent(m_display, 0L, nullptr);
if (!result)
warning() << "Release of RC failed (glXMakeCurrent).";
return True == result;
}
} // namespace glow
#endif
<|endoftext|> |
<commit_before>// This code is based on Sabberstone project.
// Copyright (c) 2017-2018 SabberStone Team, darkfriend77 & rnilva
// Hearthstone++ is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
#include <hspp/Tasks/PlayerTasks/CombatTask.hpp>
#include <hspp/Tasks/SimpleTasks/DestroyMinionTask.hpp>
#include <hspp/Tasks/SimpleTasks/DestroyWeaponTask.hpp>
#include <hspp/Tasks/SimpleTasks/FreezeTask.hpp>
#include <hspp/Tasks/SimpleTasks/PoisonousTask.hpp>
using namespace Hearthstonepp::SimpleTasks;
namespace Hearthstonepp::PlayerTasks
{
CombatTask::CombatTask(TaskAgent& agent, Entity* source, Entity* target)
: ITask(source, target), m_requirement(TaskID::SELECT_TARGET, agent)
{
// Do nothing
}
TaskID CombatTask::GetTaskID() const
{
return TaskID::COMBAT;
}
MetaData CombatTask::Impl(Player& player)
{
auto [sourceIndex, targetIndex] = CalculateIndex(player);
// Verify index of the source
// NOTE: 0 means hero, 1 ~ field.size() means minion
if (sourceIndex > player.GetField().GetNumOfMinions())
{
return MetaData::COMBAT_SRC_IDX_OUT_OF_RANGE;
}
// Verify index of the target
// NOTE: 0 means hero, 1 ~ field.size() means minion
if (targetIndex > player.GetOpponent().GetField().GetNumOfMinions())
{
return MetaData::COMBAT_DST_IDX_OUT_OF_RANGE;
}
auto source = (sourceIndex > 0)
? dynamic_cast<Character*>(
player.GetField().GetMinion(sourceIndex - 1))
: dynamic_cast<Character*>(player.GetHero());
auto target =
(targetIndex > 0)
? dynamic_cast<Character*>(
player.GetOpponent().GetField().GetMinion(targetIndex - 1))
: dynamic_cast<Character*>(player.GetOpponent().GetHero());
if (!source->CanAttack() ||
!source->IsValidCombatTarget(player.GetOpponent(), target))
{
return MetaData::COMBAT_SOURCE_CANT_ATTACK;
}
const size_t targetAttack = target->GetAttack();
const size_t sourceAttack = source->GetAttack();
const size_t targetDamage = target->TakeDamage(*source, sourceAttack);
const bool isTargetDamaged = targetDamage > 0;
// Destroy target if attacker is poisonous
if (isTargetDamaged && source->GetGameTag(GameTag::POISONOUS) == 1)
{
PoisonousTask(target).Run(player);
}
// Freeze target if attacker is freezer
if (isTargetDamaged && source->GetGameTag(GameTag::FREEZE) == 1)
{
FreezeTask(EntityType::TARGET, target).Run(player);
}
// Ignore damage from defenders with 0 attack
if (targetAttack > 0)
{
const size_t sourceDamage = source->TakeDamage(*target, targetAttack);
const bool isSourceDamaged = sourceDamage > 0;
// Destroy source if defender is poisonous
if (isSourceDamaged && target->GetGameTag(GameTag::POISONOUS) == 1)
{
PoisonousTask(source).Run(player);
}
// Freeze source if defender is freezer
if (isSourceDamaged && target->GetGameTag(GameTag::FREEZE) == 1)
{
FreezeTask(EntityType::SOURCE, source).Run(player);
}
}
// Remove stealth ability if attacker has it
if (source->GetGameTag(GameTag::STEALTH) == 1)
{
source->SetGameTag(GameTag::STEALTH, 0);
}
// Remove durability from weapon if hero attack
const Hero* hero = dynamic_cast<Hero*>(source);
if (hero != nullptr && hero->weapon != nullptr &&
hero->weapon->GetGameTag(GameTag::IMMUNE) == 0)
{
hero->weapon->SetDurability(hero->weapon->GetDurability() - 1);
// Destroy weapon if durability is 0
if (hero->weapon->GetDurability() <= 0)
{
DestroyWeaponTask().Run(player);
}
}
source->attackableCount--;
// Destroy source minion if health less than 0
if (source->health <= 0)
{
DestroyMinionTask(source).Run(player);
}
// Destroy target minion if health less than 0
if (target->health <= 0)
{
DestroyMinionTask(target).Run(player);
}
return MetaData::COMBAT_SUCCESS;
}
std::tuple<BYTE, BYTE> CombatTask::CalculateIndex(Player& player) const
{
if (m_source != nullptr && m_target != nullptr)
{
Minion* minionSource = dynamic_cast<Minion*>(m_source);
Minion* minionTarget = dynamic_cast<Minion*>(m_target);
BYTE sourceIndex, targetIndex;
if (m_source == player.GetHero())
{
sourceIndex = 0;
}
else
{
if (minionSource != nullptr)
{
sourceIndex = static_cast<BYTE>(
player.GetField().FindMinionPos(*minionSource).value());
}
}
Player& opponent = player.GetOpponent();
if (m_target == opponent.GetHero())
{
targetIndex = 0;
}
else
{
if (minionTarget != nullptr)
{
targetIndex = static_cast<BYTE>(
opponent.GetField().FindMinionPos(*minionTarget).value());
}
}
return std::make_tuple(sourceIndex, targetIndex);
}
TaskMeta serialized;
// Get targeting response from game interface
m_requirement.Interact(player.GetID(), serialized);
// Get the source and the target
const auto req = TaskMeta::ConvertTo<FlatData::ResponseTarget>(serialized);
return std::make_tuple(req->src(), req->dst());
}
} // namespace Hearthstonepp::PlayerTasks
<commit_msg>[ci skip] fix: Add statement that adds 1 to 'index' (consider offset)<commit_after>// This code is based on Sabberstone project.
// Copyright (c) 2017-2018 SabberStone Team, darkfriend77 & rnilva
// Hearthstone++ is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
#include <hspp/Tasks/PlayerTasks/CombatTask.hpp>
#include <hspp/Tasks/SimpleTasks/DestroyMinionTask.hpp>
#include <hspp/Tasks/SimpleTasks/DestroyWeaponTask.hpp>
#include <hspp/Tasks/SimpleTasks/FreezeTask.hpp>
#include <hspp/Tasks/SimpleTasks/PoisonousTask.hpp>
using namespace Hearthstonepp::SimpleTasks;
namespace Hearthstonepp::PlayerTasks
{
CombatTask::CombatTask(TaskAgent& agent, Entity* source, Entity* target)
: ITask(source, target), m_requirement(TaskID::SELECT_TARGET, agent)
{
// Do nothing
}
TaskID CombatTask::GetTaskID() const
{
return TaskID::COMBAT;
}
MetaData CombatTask::Impl(Player& player)
{
auto [sourceIndex, targetIndex] = CalculateIndex(player);
// Verify index of the source
// NOTE: 0 means hero, 1 ~ field.size() means minion
if (sourceIndex > player.GetField().GetNumOfMinions())
{
return MetaData::COMBAT_SRC_IDX_OUT_OF_RANGE;
}
// Verify index of the target
// NOTE: 0 means hero, 1 ~ field.size() means minion
if (targetIndex > player.GetOpponent().GetField().GetNumOfMinions())
{
return MetaData::COMBAT_DST_IDX_OUT_OF_RANGE;
}
auto source = (sourceIndex > 0)
? dynamic_cast<Character*>(
player.GetField().GetMinion(sourceIndex - 1))
: dynamic_cast<Character*>(player.GetHero());
auto target =
(targetIndex > 0)
? dynamic_cast<Character*>(
player.GetOpponent().GetField().GetMinion(targetIndex - 1))
: dynamic_cast<Character*>(player.GetOpponent().GetHero());
if (!source->CanAttack() ||
!source->IsValidCombatTarget(player.GetOpponent(), target))
{
return MetaData::COMBAT_SOURCE_CANT_ATTACK;
}
const size_t targetAttack = target->GetAttack();
const size_t sourceAttack = source->GetAttack();
const size_t targetDamage = target->TakeDamage(*source, sourceAttack);
const bool isTargetDamaged = targetDamage > 0;
// Destroy target if attacker is poisonous
if (isTargetDamaged && source->GetGameTag(GameTag::POISONOUS) == 1)
{
PoisonousTask(target).Run(player);
}
// Freeze target if attacker is freezer
if (isTargetDamaged && source->GetGameTag(GameTag::FREEZE) == 1)
{
FreezeTask(EntityType::TARGET, target).Run(player);
}
// Ignore damage from defenders with 0 attack
if (targetAttack > 0)
{
const size_t sourceDamage = source->TakeDamage(*target, targetAttack);
const bool isSourceDamaged = sourceDamage > 0;
// Destroy source if defender is poisonous
if (isSourceDamaged && target->GetGameTag(GameTag::POISONOUS) == 1)
{
PoisonousTask(source).Run(player);
}
// Freeze source if defender is freezer
if (isSourceDamaged && target->GetGameTag(GameTag::FREEZE) == 1)
{
FreezeTask(EntityType::SOURCE, source).Run(player);
}
}
// Remove stealth ability if attacker has it
if (source->GetGameTag(GameTag::STEALTH) == 1)
{
source->SetGameTag(GameTag::STEALTH, 0);
}
// Remove durability from weapon if hero attack
const Hero* hero = dynamic_cast<Hero*>(source);
if (hero != nullptr && hero->weapon != nullptr &&
hero->weapon->GetGameTag(GameTag::IMMUNE) == 0)
{
hero->weapon->SetDurability(hero->weapon->GetDurability() - 1);
// Destroy weapon if durability is 0
if (hero->weapon->GetDurability() <= 0)
{
DestroyWeaponTask().Run(player);
}
}
source->attackableCount--;
// Destroy source minion if health less than 0
if (source->health <= 0)
{
DestroyMinionTask(source).Run(player);
}
// Destroy target minion if health less than 0
if (target->health <= 0)
{
DestroyMinionTask(target).Run(player);
}
return MetaData::COMBAT_SUCCESS;
}
std::tuple<BYTE, BYTE> CombatTask::CalculateIndex(Player& player) const
{
if (m_source != nullptr && m_target != nullptr)
{
Minion* minionSource = dynamic_cast<Minion*>(m_source);
Minion* minionTarget = dynamic_cast<Minion*>(m_target);
BYTE sourceIndex, targetIndex;
if (m_source == player.GetHero())
{
sourceIndex = 0;
}
else
{
if (minionSource != nullptr)
{
sourceIndex = static_cast<BYTE>(
player.GetField().FindMinionPos(*minionSource).value());
sourceIndex += 1;
}
}
Player& opponent = player.GetOpponent();
if (m_target == opponent.GetHero())
{
targetIndex = 0;
}
else
{
if (minionTarget != nullptr)
{
targetIndex = static_cast<BYTE>(
opponent.GetField().FindMinionPos(*minionTarget).value());
targetIndex += 1;
}
}
return std::make_tuple(sourceIndex, targetIndex);
}
TaskMeta serialized;
// Get targeting response from game interface
m_requirement.Interact(player.GetID(), serialized);
// Get the source and the target
const auto req = TaskMeta::ConvertTo<FlatData::ResponseTarget>(serialized);
return std::make_tuple(req->src(), req->dst());
}
} // namespace Hearthstonepp::PlayerTasks
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 Pavel Kirienko <[email protected]>
*/
#include "board.hpp"
#include <cstring>
#include <unistd.h>
#include <ch.h>
#include <ch.hpp>
#include <hal.h>
#include <zubax_chibios/sys/sys.h>
/**
* GPIO config for ChibiOS PAL driver
*/
const PALConfig pal_default_config =
{
{ VAL_GPIOAODR, VAL_GPIOACRL, VAL_GPIOACRH },
{ VAL_GPIOBODR, VAL_GPIOBCRL, VAL_GPIOBCRH },
{ VAL_GPIOCODR, VAL_GPIOCCRL, VAL_GPIOCCRH },
{ VAL_GPIODODR, VAL_GPIODCRL, VAL_GPIODCRH },
{ VAL_GPIOEODR, VAL_GPIOECRL, VAL_GPIOECRH }
};
namespace board
{
void init()
{
halInit();
chibios_rt::System::init();
sdStart(&STDOUT_SD, UAVCAN_NULLPTR);
}
__attribute__((noreturn))
void die(int error)
{
lowsyslog("Fatal error %i\n", error);
while (1)
{
setLed(false);
::sleep(1);
setLed(true);
::sleep(1);
}
}
void setLed(bool state)
{
palWritePad(GPIO_PORT_LED, GPIO_PIN_LED, state);
}
void restart()
{
NVIC_SystemReset();
}
void readUniqueID(std::uint8_t bytes[UniqueIDSize])
{
std::memcpy(bytes, reinterpret_cast<const void*>(0x1FFFF7E8), UniqueIDSize);
}
}
/*
* Early init from ChibiOS
*/
extern "C"
{
void __early_init(void)
{
stm32_clock_init();
}
void boardInit(void)
{
AFIO->MAPR |=
AFIO_MAPR_CAN_REMAP_REMAP3 |
AFIO_MAPR_CAN2_REMAP |
AFIO_MAPR_USART2_REMAP;
/*
* Enabling the CAN controllers, then configuring GPIO functions for CAN_TX.
* Order matters, otherwise the CAN_TX pins will twitch, disturbing the CAN bus.
* This is why we can't perform this initialization using ChibiOS GPIO configuration.
*/
RCC->APB1ENR |= RCC_APB1ENR_CAN1EN;
palSetPadMode(GPIOD, 1, PAL_MODE_STM32_ALTERNATE_PUSHPULL);
#if UAVCAN_STM32_NUM_IFACES > 1
RCC->APB1ENR |= RCC_APB1ENR_CAN2EN;
palSetPadMode(GPIOB, 6, PAL_MODE_STM32_ALTERNATE_PUSHPULL);
#endif
}
}
<commit_msg>STM32 build fix<commit_after>/*
* Copyright (C) 2015 Pavel Kirienko <[email protected]>
*/
#include "board.hpp"
#include <cstring>
#include <unistd.h>
#include <ch.h>
#include <ch.hpp>
#include <hal.h>
#include <zubax_chibios/sys/sys.h>
/**
* GPIO config for ChibiOS PAL driver
*/
const PALConfig pal_default_config =
{
{ VAL_GPIOAODR, VAL_GPIOACRL, VAL_GPIOACRH },
{ VAL_GPIOBODR, VAL_GPIOBCRL, VAL_GPIOBCRH },
{ VAL_GPIOCODR, VAL_GPIOCCRL, VAL_GPIOCCRH },
{ VAL_GPIODODR, VAL_GPIODCRL, VAL_GPIODCRH },
{ VAL_GPIOEODR, VAL_GPIOECRL, VAL_GPIOECRH }
};
namespace board
{
void init()
{
halInit();
chibios_rt::System::init();
sdStart(&STDOUT_SD, nullptr);
}
__attribute__((noreturn))
void die(int error)
{
lowsyslog("Fatal error %i\n", error);
while (1)
{
setLed(false);
::sleep(1);
setLed(true);
::sleep(1);
}
}
void setLed(bool state)
{
palWritePad(GPIO_PORT_LED, GPIO_PIN_LED, state);
}
void restart()
{
NVIC_SystemReset();
}
void readUniqueID(std::uint8_t bytes[UniqueIDSize])
{
std::memcpy(bytes, reinterpret_cast<const void*>(0x1FFFF7E8), UniqueIDSize);
}
}
/*
* Early init from ChibiOS
*/
extern "C"
{
void __early_init(void)
{
stm32_clock_init();
}
void boardInit(void)
{
AFIO->MAPR |=
AFIO_MAPR_CAN_REMAP_REMAP3 |
AFIO_MAPR_CAN2_REMAP |
AFIO_MAPR_USART2_REMAP;
/*
* Enabling the CAN controllers, then configuring GPIO functions for CAN_TX.
* Order matters, otherwise the CAN_TX pins will twitch, disturbing the CAN bus.
* This is why we can't perform this initialization using ChibiOS GPIO configuration.
*/
RCC->APB1ENR |= RCC_APB1ENR_CAN1EN;
palSetPadMode(GPIOD, 1, PAL_MODE_STM32_ALTERNATE_PUSHPULL);
#if UAVCAN_STM32_NUM_IFACES > 1
RCC->APB1ENR |= RCC_APB1ENR_CAN2EN;
palSetPadMode(GPIOB, 6, PAL_MODE_STM32_ALTERNATE_PUSHPULL);
#endif
}
}
<|endoftext|> |
<commit_before>#include "musicsemaphoreeventloop.h"
#include <QThread>
#include <QApplication>
MusicSemaphoreEventLoop::MusicSemaphoreEventLoop(QObject* parent)
: QObject(parent), m_semaphore(0)
{
}
void MusicSemaphoreEventLoop::exec()
{
QMutexLocker locker(&m_mutex);
--m_semaphore;
while(m_semaphore)
{
QApplication::processEvents();
QThread::msleep(100);
}
}
void MusicSemaphoreEventLoop::quit()
{
++m_semaphore;
}
<commit_msg>fix compile error on qt4 [556213]<commit_after>#include "musicsemaphoreeventloop.h"
#include <QThread>
#include <QApplication>
#if defined Q_OS_UNIX || defined Q_CC_MINGW
# include <unistd.h>
#endif
MusicSemaphoreEventLoop::MusicSemaphoreEventLoop(QObject* parent)
: QObject(parent), m_semaphore(0)
{
}
void MusicSemaphoreEventLoop::exec()
{
QMutexLocker locker(&m_mutex);
--m_semaphore;
while(m_semaphore)
{
QApplication::processEvents();
#if defined Q_OS_WIN && defined MUSIC_QT_5
QThread::msleep(100);
#else
usleep(100*1000);
#endif
}
}
void MusicSemaphoreEventLoop::quit()
{
++m_semaphore;
}
<|endoftext|> |
<commit_before><commit_msg>Fix race condition in OCSPRequestSession.<commit_after><|endoftext|> |
<commit_before>#include <StdAfx.h>
#include <UI/Controls/PaneHeader/PaneHeader.h>
#include <UI/UIFunctions.h>
#include <core/utility/strings.h>
#include <UI/DoubleBuffer.h>
#include <core/utility/output.h>
namespace controls
{
static std::wstring CLASS = L"PaneHeader";
PaneHeader::~PaneHeader()
{
TRACE_DESTRUCTOR(CLASS);
CWnd::DestroyWindow();
}
void PaneHeader::Initialize(HWND hWnd, _In_opt_ HDC hdc, _In_ UINT nid)
{
m_hWndParent = hWnd;
// Assign a nID to the collapse button that is IDD_COLLAPSE more than the control's nID
m_nID = nid;
m_nIDCollapse = nid + IDD_COLLAPSE;
WNDCLASSEX wc = {};
const auto hInst = AfxGetInstanceHandle();
if (!::GetClassInfoEx(hInst, _T("PaneHeader"), &wc)) // STRING_OK
{
wc.cbSize = sizeof wc;
wc.style = 0; // not passing CS_VREDRAW | CS_HREDRAW fixes flicker
wc.lpszClassName = _T("PaneHeader"); // STRING_OK
wc.lpfnWndProc = ::DefWindowProc;
wc.hbrBackground = GetSysBrush(ui::uiColor::Background); // helps spot flashing
RegisterClassEx(&wc);
}
// WS_CLIPCHILDREN is used to reduce flicker
EC_B_S(CreateEx(
0,
_T("PaneHeader"), // STRING_OK
_T("PaneHeader"), // STRING_OK
WS_CHILD | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_VISIBLE,
0,
0,
0,
0,
m_hWndParent,
reinterpret_cast<HMENU>(static_cast<INT_PTR>(IDC_PANE_HEADER)),
nullptr));
// Necessary for TAB to work. Without this, all TABS get stuck on the control
// instead of passing to the children.
EC_B_S(ModifyStyleEx(0, WS_EX_CONTROLPARENT));
const auto sizeText = ui::GetTextExtentPoint32(hdc, m_szLabel);
m_iLabelWidth = sizeText.cx;
output::DebugPrint(
output::dbgLevel::Draw,
L"PaneHeader::Initialize m_iLabelWidth:%d \"%ws\"\n",
m_iLabelWidth,
m_szLabel.c_str());
}
BEGIN_MESSAGE_MAP(PaneHeader, CWnd)
ON_WM_SIZE()
ON_WM_PAINT()
ON_WM_CREATE()
END_MESSAGE_MAP()
int PaneHeader::OnCreate(LPCREATESTRUCT /*lpCreateStruct*/)
{
EC_B_S(m_leftLabel.Create(
WS_CHILD | WS_CLIPSIBLINGS | ES_READONLY | WS_VISIBLE | WS_TABSTOP, CRect(0, 0, 0, 0), this, m_nID));
::SetWindowTextW(m_leftLabel.m_hWnd, m_szLabel.c_str());
ui::SubclassLabel(m_leftLabel.m_hWnd);
if (m_bCollapsible)
{
StyleLabel(m_leftLabel.m_hWnd, ui::uiLabelStyle::PaneHeaderLabel);
}
EC_B_S(m_rightLabel.Create(
WS_CHILD | WS_CLIPSIBLINGS | ES_READONLY | WS_VISIBLE | WS_TABSTOP,
CRect(0, 0, 0, 0),
this,
IDD_COUNTLABEL));
ui::SubclassLabel(m_rightLabel.m_hWnd);
StyleLabel(m_rightLabel.m_hWnd, ui::uiLabelStyle::PaneHeaderText);
if (m_bCollapsible)
{
EC_B_S(m_CollapseButton.Create(
nullptr, WS_TABSTOP | WS_CHILD | WS_CLIPSIBLINGS | WS_VISIBLE, CRect(0, 0, 0, 0), this, m_nIDCollapse));
StyleButton(
m_CollapseButton.m_hWnd, m_bCollapsed ? ui::uiButtonStyle::UpArrow : ui::uiButtonStyle::DownArrow);
}
// If we need an action button, go ahead and create it
if (m_nIDAction)
{
EC_B_S(m_actionButton.Create(
strings::wstringTotstring(m_szActionButton).c_str(),
WS_TABSTOP | WS_CHILD | WS_CLIPSIBLINGS | WS_VISIBLE,
CRect(0, 0, 0, 0),
this,
m_nIDAction));
StyleButton(m_actionButton.m_hWnd, ui::uiButtonStyle::Unstyled);
}
m_bInitialized = true;
return 0;
}
LRESULT PaneHeader::WindowProc(const UINT message, const WPARAM wParam, const LPARAM lParam)
{
LRESULT lRes = 0;
if (ui::HandleControlUI(message, wParam, lParam, &lRes)) return lRes;
switch (message)
{
case WM_CLOSE:
::SendMessage(m_hWndParent, message, wParam, lParam);
return true;
case WM_HELP:
return true;
case WM_COMMAND:
{
const auto nCode = HIWORD(wParam);
if (EN_CHANGE == nCode || CBN_SELCHANGE == nCode || CBN_EDITCHANGE == nCode || BN_CLICKED == nCode)
{
::SendMessage(m_hWndParent, message, wParam, lParam);
}
break;
}
}
return CWnd::WindowProc(message, wParam, lParam);
}
void PaneHeader::OnSize(UINT /*nType*/, const int cx, const int cy)
{
auto hdwp = WC_D(HDWP, BeginDeferWindowPos(2));
if (hdwp)
{
hdwp = EC_D(HDWP, DeferWindowPos(hdwp, 0, 0, cx, cy));
EC_B_S(EndDeferWindowPos(hdwp));
}
}
// Draw our collapse button and label, if needed.
// Draws everything to GetFixedHeight()
HDWP PaneHeader::DeferWindowPos(
_In_ HDWP hWinPosInfo,
const _In_ int x,
const _In_ int y,
const _In_ int width,
const _In_ int height)
{
if (!m_bInitialized) return hWinPosInfo;
output::DebugPrint(
output::dbgLevel::Draw,
L"PaneHeader::DeferWindowPos x:%d y:%d width:%d height:%d v:%d\n",
x,
y,
width,
height,
IsWindowVisible());
InvalidateRect(CRect(x, y, width, height), false);
//hWinPosInfo = ui::DeferWindowPos(
// hWinPosInfo, GetSafeHwnd(), x, y, width, height, L"PaneHeader::DeferWindowPos", m_szLabel.c_str());
auto curX = x;
const auto actionButtonWidth = m_actionButtonWidth ? m_actionButtonWidth + 2 * m_iMargin : 0;
const auto actionButtonAndGutterWidth = actionButtonWidth ? actionButtonWidth + m_iSideMargin : 0;
if (m_bCollapsible)
{
hWinPosInfo = ui::DeferWindowPos(
hWinPosInfo,
m_CollapseButton.GetSafeHwnd(),
curX,
y,
width - actionButtonAndGutterWidth,
height,
L"PaneHeader::DeferWindowPos::collapseButton");
curX += m_iButtonHeight;
}
//hWinPosInfo = ui::DeferWindowPos(
// hWinPosInfo, GetSafeHwnd(), curX, y, m_iLabelWidth, height, L"PaneHeader::DeferWindowPos::leftLabel");
if (!m_bCollapsed)
{
// Drop the count on top of the label we drew above
if (m_rightLabel.GetSafeHwnd())
{
hWinPosInfo = ui::DeferWindowPos(
hWinPosInfo,
m_rightLabel.GetSafeHwnd(),
x + width - m_rightLabelWidth - actionButtonAndGutterWidth,
y,
m_rightLabelWidth,
height,
L"PaneHeader::DeferWindowPos::rightLabel");
}
}
if (m_nIDAction)
{
// Drop the action button next to the label we drew above
hWinPosInfo = ui::DeferWindowPos(
hWinPosInfo,
m_actionButton.GetSafeHwnd(),
x + width - actionButtonWidth,
y,
actionButtonWidth,
height,
L"PaneHeader::DeferWindowPos::actionButton");
}
output::DebugPrint(output::dbgLevel::Draw, L"PaneHeader::DeferWindowPos end\n");
return hWinPosInfo;
}
void PaneHeader::OnPaint()
{
auto ps = PAINTSTRUCT{};
::BeginPaint(m_hWnd, &ps);
if (ps.hdc)
{
auto rcWin = RECT{};
::GetClientRect(m_hWnd, &rcWin);
ui::CDoubleBuffer db;
auto hdc = ps.hdc;
db.Begin(hdc, rcWin);
FillRect(hdc, &rcWin, GetSysBrush(ui::uiColor::Background));
db.End(hdc);
}
::EndPaint(m_hWnd, &ps);
}
int PaneHeader::GetMinWidth()
{
auto cx = m_iLabelWidth;
if (m_bCollapsible) cx += m_iButtonHeight;
if (m_rightLabelWidth)
{
cx += m_iSideMargin;
cx += m_rightLabelWidth;
}
if (m_actionButtonWidth)
{
cx += m_iSideMargin;
cx += m_actionButtonWidth + 2 * m_iMargin;
}
return cx;
}
void PaneHeader::SetRightLabel(const std::wstring szLabel)
{
//if (!m_bInitialized) return;
EC_B_S(::SetWindowTextW(m_rightLabel.m_hWnd, szLabel.c_str()));
const auto hdc = ::GetDC(m_rightLabel.GetSafeHwnd());
const auto hfontOld = SelectObject(hdc, ui::GetSegoeFont());
const auto sizeText = ui::GetTextExtentPoint32(hdc, szLabel);
static_cast<void>(SelectObject(hdc, hfontOld));
::ReleaseDC(m_rightLabel.GetSafeHwnd(), hdc);
m_rightLabelWidth = sizeText.cx;
}
void PaneHeader::SetActionButton(const std::wstring szActionButton)
{
// Don't bother if we never enabled the button
if (m_nIDAction == 0) return;
EC_B_S(::SetWindowTextW(m_actionButton.GetSafeHwnd(), szActionButton.c_str()));
m_szActionButton = szActionButton;
const auto hdc = ::GetDC(m_actionButton.GetSafeHwnd());
const auto hfontOld = SelectObject(hdc, ui::GetSegoeFont());
const auto sizeText = ui::GetTextExtentPoint32(hdc, szActionButton);
static_cast<void>(SelectObject(hdc, hfontOld));
::ReleaseDC(m_actionButton.GetSafeHwnd(), hdc);
m_actionButtonWidth = sizeText.cx;
}
bool PaneHeader::HandleChange(UINT nID)
{
// Collapse buttons have a nID IDD_COLLAPSE higher than nID of the pane they toggle.
// So if we get asked about one that matches, we can assume it's time to toggle our collapse.
if (m_nIDCollapse == nID)
{
OnToggleCollapse();
return true;
}
return false;
}
void PaneHeader::OnToggleCollapse()
{
m_bCollapsed = !m_bCollapsed;
StyleButton(m_CollapseButton.m_hWnd, m_bCollapsed ? ui::uiButtonStyle::UpArrow : ui::uiButtonStyle::DownArrow);
WC_B_S(m_rightLabel.ShowWindow(m_bCollapsed ? SW_HIDE : SW_SHOW));
// Trigger a redraw
::PostMessage(m_hWndParent, WM_COMMAND, IDD_RECALCLAYOUT, NULL);
}
void PaneHeader::SetMargins(
int iMargin,
int iSideMargin,
int iLabelHeight, // Height of the label
int iButtonHeight) // Height of button
{
m_iMargin = iMargin;
m_iSideMargin = iSideMargin;
m_iLabelHeight = iLabelHeight;
m_iButtonHeight = iButtonHeight;
}
} // namespace controls<commit_msg>restore left label<commit_after>#include <StdAfx.h>
#include <UI/Controls/PaneHeader/PaneHeader.h>
#include <UI/UIFunctions.h>
#include <core/utility/strings.h>
#include <UI/DoubleBuffer.h>
#include <core/utility/output.h>
namespace controls
{
static std::wstring CLASS = L"PaneHeader";
PaneHeader::~PaneHeader()
{
TRACE_DESTRUCTOR(CLASS);
CWnd::DestroyWindow();
}
void PaneHeader::Initialize(HWND hWnd, _In_opt_ HDC hdc, _In_ UINT nid)
{
m_hWndParent = hWnd;
// Assign a nID to the collapse button that is IDD_COLLAPSE more than the control's nID
m_nID = nid;
m_nIDCollapse = nid + IDD_COLLAPSE;
WNDCLASSEX wc = {};
const auto hInst = AfxGetInstanceHandle();
if (!::GetClassInfoEx(hInst, _T("PaneHeader"), &wc)) // STRING_OK
{
wc.cbSize = sizeof wc;
wc.style = 0; // not passing CS_VREDRAW | CS_HREDRAW fixes flicker
wc.lpszClassName = _T("PaneHeader"); // STRING_OK
wc.lpfnWndProc = ::DefWindowProc;
wc.hbrBackground = GetSysBrush(ui::uiColor::Background); // helps spot flashing
RegisterClassEx(&wc);
}
// WS_CLIPCHILDREN is used to reduce flicker
EC_B_S(CreateEx(
0,
_T("PaneHeader"), // STRING_OK
_T("PaneHeader"), // STRING_OK
WS_CHILD | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_VISIBLE,
0,
0,
0,
0,
m_hWndParent,
reinterpret_cast<HMENU>(static_cast<INT_PTR>(IDC_PANE_HEADER)),
nullptr));
// Necessary for TAB to work. Without this, all TABS get stuck on the control
// instead of passing to the children.
EC_B_S(ModifyStyleEx(0, WS_EX_CONTROLPARENT));
const auto sizeText = ui::GetTextExtentPoint32(hdc, m_szLabel);
m_iLabelWidth = sizeText.cx;
output::DebugPrint(
output::dbgLevel::Draw,
L"PaneHeader::Initialize m_iLabelWidth:%d \"%ws\"\n",
m_iLabelWidth,
m_szLabel.c_str());
}
BEGIN_MESSAGE_MAP(PaneHeader, CWnd)
ON_WM_SIZE()
ON_WM_PAINT()
ON_WM_CREATE()
END_MESSAGE_MAP()
int PaneHeader::OnCreate(LPCREATESTRUCT /*lpCreateStruct*/)
{
EC_B_S(m_leftLabel.Create(
WS_CHILD | WS_CLIPSIBLINGS | ES_READONLY | WS_VISIBLE | WS_TABSTOP, CRect(0, 0, 0, 0), this, m_nID));
::SetWindowTextW(m_leftLabel.m_hWnd, m_szLabel.c_str());
ui::SubclassLabel(m_leftLabel.m_hWnd);
if (m_bCollapsible)
{
StyleLabel(m_leftLabel.m_hWnd, ui::uiLabelStyle::PaneHeaderLabel);
}
EC_B_S(m_rightLabel.Create(
WS_CHILD | WS_CLIPSIBLINGS | ES_READONLY | WS_VISIBLE | WS_TABSTOP,
CRect(0, 0, 0, 0),
this,
IDD_COUNTLABEL));
ui::SubclassLabel(m_rightLabel.m_hWnd);
StyleLabel(m_rightLabel.m_hWnd, ui::uiLabelStyle::PaneHeaderText);
if (m_bCollapsible)
{
EC_B_S(m_CollapseButton.Create(
nullptr, WS_TABSTOP | WS_CHILD | WS_CLIPSIBLINGS | WS_VISIBLE, CRect(0, 0, 0, 0), this, m_nIDCollapse));
StyleButton(
m_CollapseButton.m_hWnd, m_bCollapsed ? ui::uiButtonStyle::UpArrow : ui::uiButtonStyle::DownArrow);
}
// If we need an action button, go ahead and create it
if (m_nIDAction)
{
EC_B_S(m_actionButton.Create(
strings::wstringTotstring(m_szActionButton).c_str(),
WS_TABSTOP | WS_CHILD | WS_CLIPSIBLINGS | WS_VISIBLE,
CRect(0, 0, 0, 0),
this,
m_nIDAction));
StyleButton(m_actionButton.m_hWnd, ui::uiButtonStyle::Unstyled);
}
m_bInitialized = true;
return 0;
}
LRESULT PaneHeader::WindowProc(const UINT message, const WPARAM wParam, const LPARAM lParam)
{
LRESULT lRes = 0;
if (ui::HandleControlUI(message, wParam, lParam, &lRes)) return lRes;
switch (message)
{
case WM_CLOSE:
::SendMessage(m_hWndParent, message, wParam, lParam);
return true;
case WM_HELP:
return true;
case WM_COMMAND:
{
const auto nCode = HIWORD(wParam);
if (EN_CHANGE == nCode || CBN_SELCHANGE == nCode || CBN_EDITCHANGE == nCode || BN_CLICKED == nCode)
{
::SendMessage(m_hWndParent, message, wParam, lParam);
}
break;
}
}
return CWnd::WindowProc(message, wParam, lParam);
}
void PaneHeader::OnSize(UINT /*nType*/, const int cx, const int cy)
{
auto hdwp = WC_D(HDWP, BeginDeferWindowPos(2));
if (hdwp)
{
hdwp = EC_D(HDWP, DeferWindowPos(hdwp, 0, 0, cx, cy));
EC_B_S(EndDeferWindowPos(hdwp));
}
}
// Draw our collapse button and label, if needed.
// Draws everything to GetFixedHeight()
HDWP PaneHeader::DeferWindowPos(
_In_ HDWP hWinPosInfo,
const _In_ int x,
const _In_ int y,
const _In_ int width,
const _In_ int height)
{
if (!m_bInitialized) return hWinPosInfo;
output::DebugPrint(
output::dbgLevel::Draw,
L"PaneHeader::DeferWindowPos x:%d y:%d width:%d height:%d v:%d\n",
x,
y,
width,
height,
IsWindowVisible());
InvalidateRect(CRect(x, y, width, height), false);
//hWinPosInfo = ui::DeferWindowPos(
// hWinPosInfo, GetSafeHwnd(), x, y, width, height, L"PaneHeader::DeferWindowPos", m_szLabel.c_str());
auto curX = x;
const auto actionButtonWidth = m_actionButtonWidth ? m_actionButtonWidth + 2 * m_iMargin : 0;
const auto actionButtonAndGutterWidth = actionButtonWidth ? actionButtonWidth + m_iSideMargin : 0;
if (m_bCollapsible)
{
hWinPosInfo = ui::DeferWindowPos(
hWinPosInfo,
m_CollapseButton.GetSafeHwnd(),
curX,
y,
width - actionButtonAndGutterWidth,
height,
L"PaneHeader::DeferWindowPos::collapseButton");
curX += m_iButtonHeight;
}
hWinPosInfo = ui::DeferWindowPos(
hWinPosInfo,
m_leftLabel.GetSafeHwnd(),
curX,
y,
m_iLabelWidth,
height,
L"PaneHeader::DeferWindowPos::leftLabel");
if (!m_bCollapsed)
{
// Drop the count on top of the label we drew above
if (m_rightLabel.GetSafeHwnd())
{
hWinPosInfo = ui::DeferWindowPos(
hWinPosInfo,
m_rightLabel.GetSafeHwnd(),
x + width - m_rightLabelWidth - actionButtonAndGutterWidth,
y,
m_rightLabelWidth,
height,
L"PaneHeader::DeferWindowPos::rightLabel");
}
}
if (m_nIDAction)
{
// Drop the action button next to the label we drew above
hWinPosInfo = ui::DeferWindowPos(
hWinPosInfo,
m_actionButton.GetSafeHwnd(),
x + width - actionButtonWidth,
y,
actionButtonWidth,
height,
L"PaneHeader::DeferWindowPos::actionButton");
}
output::DebugPrint(output::dbgLevel::Draw, L"PaneHeader::DeferWindowPos end\n");
return hWinPosInfo;
}
void PaneHeader::OnPaint()
{
auto ps = PAINTSTRUCT{};
::BeginPaint(m_hWnd, &ps);
if (ps.hdc)
{
auto rcWin = RECT{};
::GetClientRect(m_hWnd, &rcWin);
ui::CDoubleBuffer db;
auto hdc = ps.hdc;
db.Begin(hdc, rcWin);
FillRect(hdc, &rcWin, GetSysBrush(ui::uiColor::Background));
db.End(hdc);
}
::EndPaint(m_hWnd, &ps);
}
int PaneHeader::GetMinWidth()
{
auto cx = m_iLabelWidth;
if (m_bCollapsible) cx += m_iButtonHeight;
if (m_rightLabelWidth)
{
cx += m_iSideMargin;
cx += m_rightLabelWidth;
}
if (m_actionButtonWidth)
{
cx += m_iSideMargin;
cx += m_actionButtonWidth + 2 * m_iMargin;
}
return cx;
}
void PaneHeader::SetRightLabel(const std::wstring szLabel)
{
//if (!m_bInitialized) return;
EC_B_S(::SetWindowTextW(m_rightLabel.m_hWnd, szLabel.c_str()));
const auto hdc = ::GetDC(m_rightLabel.GetSafeHwnd());
const auto hfontOld = SelectObject(hdc, ui::GetSegoeFont());
const auto sizeText = ui::GetTextExtentPoint32(hdc, szLabel);
static_cast<void>(SelectObject(hdc, hfontOld));
::ReleaseDC(m_rightLabel.GetSafeHwnd(), hdc);
m_rightLabelWidth = sizeText.cx;
}
void PaneHeader::SetActionButton(const std::wstring szActionButton)
{
// Don't bother if we never enabled the button
if (m_nIDAction == 0) return;
EC_B_S(::SetWindowTextW(m_actionButton.GetSafeHwnd(), szActionButton.c_str()));
m_szActionButton = szActionButton;
const auto hdc = ::GetDC(m_actionButton.GetSafeHwnd());
const auto hfontOld = SelectObject(hdc, ui::GetSegoeFont());
const auto sizeText = ui::GetTextExtentPoint32(hdc, szActionButton);
static_cast<void>(SelectObject(hdc, hfontOld));
::ReleaseDC(m_actionButton.GetSafeHwnd(), hdc);
m_actionButtonWidth = sizeText.cx;
}
bool PaneHeader::HandleChange(UINT nID)
{
// Collapse buttons have a nID IDD_COLLAPSE higher than nID of the pane they toggle.
// So if we get asked about one that matches, we can assume it's time to toggle our collapse.
if (m_nIDCollapse == nID)
{
OnToggleCollapse();
return true;
}
return false;
}
void PaneHeader::OnToggleCollapse()
{
m_bCollapsed = !m_bCollapsed;
StyleButton(m_CollapseButton.m_hWnd, m_bCollapsed ? ui::uiButtonStyle::UpArrow : ui::uiButtonStyle::DownArrow);
WC_B_S(m_rightLabel.ShowWindow(m_bCollapsed ? SW_HIDE : SW_SHOW));
// Trigger a redraw
::PostMessage(m_hWndParent, WM_COMMAND, IDD_RECALCLAYOUT, NULL);
}
void PaneHeader::SetMargins(
int iMargin,
int iSideMargin,
int iLabelHeight, // Height of the label
int iButtonHeight) // Height of button
{
m_iMargin = iMargin;
m_iSideMargin = iSideMargin;
m_iLabelHeight = iLabelHeight;
m_iButtonHeight = iButtonHeight;
}
} // namespace controls<|endoftext|> |
<commit_before>#ifndef SOLAIRE_COMPRESSED_VECTOR_HPP
#define SOLAIRE_COMPRESSED_VECTOR_HPP
//Copyright 2015 Adam Smith
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
// Contact :
// Email : [email protected]
// GitHub repository : https://github.com/SolaireLibrary/SolaireCPP
/*!
\file CompressedVector.hpp
\brief Contains code for an N dimentional vector class with typedefs for commonly used vector types.
\author
Created : Adam Smith
Last modified : Adam Smith
\date
Created : 13th January 2016
Last Modified : 13th January 2016
*/
#include <cmath>
#include <cstdint>
namespace Solaire { namespace Test {
static constexpr bool binaryBlockFn(const int8_t aBytes, const int8_t aMin, const int8_t aMax) throw() {
return aBytes >= aMin && aBytes < aMax;
}
template<const uint32_t BYTES>
struct ByteArray {
private:
uint8_t mBytes[BYTES];
};
template<const uint32_t BYTES, const bool SIGN, typename ENABLE = void>
struct BinaryBlockStruct {
typedef ByteArray<BYTES> Type;
};
template<const uint32_t BYTES, const bool SIGN>
struct BinaryBlockStruct<BYTES, SIGN, typename std::enable_if<binaryBlockFn(BYTES, 33, 65) && ! SIGN>::type> {
typedef uint64_t Type;
};
template<const uint32_t BYTES, const bool SIGN>
struct BinaryBlockStruct<BYTES, SIGN, typename std::enable_if<binaryBlockFn(BYTES, 17, 33) && ! SIGN>::type> {
typedef uint32_t Type;
};
template<const uint32_t BYTES, const bool SIGN>
struct BinaryBlockStruct<BYTES, SIGN, typename std::enable_if<binaryBlockFn(BYTES, 9, 17) && ! SIGN>::type> {
typedef uint16_t Type;
};
template<const uint32_t BYTES, const bool SIGN>
struct BinaryBlockStruct<BYTES, SIGN, typename std::enable_if<binaryBlockFn(BYTES, 0, 9) && ! SIGN>::type> {
typedef uint8_t Type;
};
template<const uint32_t BYTES, const bool SIGN>
struct BinaryBlockStruct<BYTES, SIGN, typename std::enable_if<binaryBlockFn(BYTES, 33, 65) && SIGN>::type> {
typedef int64_t Type;
};
template<const uint32_t BYTES, const bool SIGN>
struct BinaryBlockStruct<BYTES, SIGN, typename std::enable_if<binaryBlockFn(BYTES, 17, 33) && SIGN>::type> {
typedef int32_t Type;
};
template<const uint32_t BYTES, const bool SIGN>
struct BinaryBlockStruct<BYTES, SIGN, typename std::enable_if<binaryBlockFn(BYTES, 9, 17) && SIGN>::type> {
typedef int16_t Type;
};
template<const uint32_t BYTES, const bool SIGN>
struct BinaryBlockStruct<BYTES, SIGN, typename std::enable_if<binaryBlockFn(BYTES, 0, 9) && SIGN>::type> {
typedef int8_t Type;
};
template<const uint32_t BYTES, const bool SIGN>
using BinaryBlock = typename BinaryBlockStruct<BYTES, SIGN>::Type;
static constexpr bool isByteAligned(const uint32_t aBits) throw() {
return (static_cast<float>(aBits) / 8.f) == static_cast<float>(aBits / 8);
}
static constexpr uint64_t MASKS[33] = {
0x00,
0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF, // 8 bit
0x01F, 0x03F, 0x07F, 0x0FF, 0x1FF, 0x3FF, 0x7F, 0xFFF, // 16 bit
0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FF, 0xFFFF, // 32 bit
0x01FFF, 0x03FFF, 0x07FFF, 0x0FFFF, 0x1FFFF, 0x3FFFF, 0x7FFF, 0xFFFFF, // 64 bit
};
////
template<const uint8_t BITS, const bool SIGN>
struct ElementInfo {
enum : uint64_t {
Bits = BITS,
Signed = SIGN
};
typedef BinaryBlock<BITS, Signed> Type;
static constexpr float scale(const Type aValue) {
return static_cast<float>(aValue) / static_cast<float>(MASKS[BITS]);
}
};
template<
const uint8_t XBITS, const uint8_t YBITS, const uint8_t ZBITS, const uint8_t WBITS,
const uint8_t XSIGN, const uint8_t YSIGN, const uint8_t ZSIGN, const uint8_t WSIGN
>
struct VectorInfo{
enum {
TotalBits = XBITS + YBITS + ZBITS + WBITS,
IsByteAligned = isByteAligned(TotalBits)
};
typedef ElementInfo<XBITS, XSIGN> XInfo;
typedef ElementInfo<YBITS, YSIGN> YInfo;
typedef ElementInfo<ZBITS, ZSIGN> ZInfo;
typedef ElementInfo<WBITS, WSIGN> WInfo;
struct Type {
typename XInfo::Type X : XBITS;
typename YInfo::Type Y : YBITS;
typename ZInfo::Type Z : ZBITS;
typename WInfo::Type W : WBITS;
};
};
}}
#endif
<commit_msg>Renamed VectorInfo to CompressedVector<commit_after>#ifndef SOLAIRE_COMPRESSED_VECTOR_HPP
#define SOLAIRE_COMPRESSED_VECTOR_HPP
//Copyright 2015 Adam Smith
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
// Contact :
// Email : [email protected]
// GitHub repository : https://github.com/SolaireLibrary/SolaireCPP
/*!
\file CompressedVector.hpp
\brief Contains code for an N dimentional vector class with typedefs for commonly used vector types.
\author
Created : Adam Smith
Last modified : Adam Smith
\date
Created : 13th January 2016
Last Modified : 13th January 2016
*/
#include <cmath>
#include <cstdint>
namespace Solaire { namespace Test {
static constexpr bool binaryBlockFn(const int8_t aBytes, const int8_t aMin, const int8_t aMax) throw() {
return aBytes >= aMin && aBytes < aMax;
}
template<const uint32_t BYTES>
struct ByteArray {
private:
uint8_t mBytes[BYTES];
};
template<const uint32_t BYTES, const bool SIGN, typename ENABLE = void>
struct BinaryBlockStruct {
typedef ByteArray<BYTES> Type;
};
template<const uint32_t BYTES, const bool SIGN>
struct BinaryBlockStruct<BYTES, SIGN, typename std::enable_if<binaryBlockFn(BYTES, 33, 65) && ! SIGN>::type> {
typedef uint64_t Type;
};
template<const uint32_t BYTES, const bool SIGN>
struct BinaryBlockStruct<BYTES, SIGN, typename std::enable_if<binaryBlockFn(BYTES, 17, 33) && ! SIGN>::type> {
typedef uint32_t Type;
};
template<const uint32_t BYTES, const bool SIGN>
struct BinaryBlockStruct<BYTES, SIGN, typename std::enable_if<binaryBlockFn(BYTES, 9, 17) && ! SIGN>::type> {
typedef uint16_t Type;
};
template<const uint32_t BYTES, const bool SIGN>
struct BinaryBlockStruct<BYTES, SIGN, typename std::enable_if<binaryBlockFn(BYTES, 0, 9) && ! SIGN>::type> {
typedef uint8_t Type;
};
template<const uint32_t BYTES, const bool SIGN>
struct BinaryBlockStruct<BYTES, SIGN, typename std::enable_if<binaryBlockFn(BYTES, 33, 65) && SIGN>::type> {
typedef int64_t Type;
};
template<const uint32_t BYTES, const bool SIGN>
struct BinaryBlockStruct<BYTES, SIGN, typename std::enable_if<binaryBlockFn(BYTES, 17, 33) && SIGN>::type> {
typedef int32_t Type;
};
template<const uint32_t BYTES, const bool SIGN>
struct BinaryBlockStruct<BYTES, SIGN, typename std::enable_if<binaryBlockFn(BYTES, 9, 17) && SIGN>::type> {
typedef int16_t Type;
};
template<const uint32_t BYTES, const bool SIGN>
struct BinaryBlockStruct<BYTES, SIGN, typename std::enable_if<binaryBlockFn(BYTES, 0, 9) && SIGN>::type> {
typedef int8_t Type;
};
template<const uint32_t BYTES, const bool SIGN>
using BinaryBlock = typename BinaryBlockStruct<BYTES, SIGN>::Type;
static constexpr bool isByteAligned(const uint32_t aBits) throw() {
return (static_cast<float>(aBits) / 8.f) == static_cast<float>(aBits / 8);
}
static constexpr uint64_t MASKS[33] = {
0x00,
0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF, // 8 bit
0x01F, 0x03F, 0x07F, 0x0FF, 0x1FF, 0x3FF, 0x7F, 0xFFF, // 16 bit
0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FF, 0xFFFF, // 32 bit
0x01FFF, 0x03FFF, 0x07FFF, 0x0FFFF, 0x1FFFF, 0x3FFFF, 0x7FFF, 0xFFFFF, // 64 bit
};
////
template<const uint8_t BITS, const bool SIGN>
struct ElementInfo {
enum : uint64_t {
Bits = BITS,
Signed = SIGN
};
typedef BinaryBlock<BITS, Signed> Type;
static constexpr float scale(const Type aValue) {
return static_cast<float>(aValue) / static_cast<float>(MASKS[BITS]);
}
};
template<
const uint8_t XBITS, const uint8_t YBITS, const uint8_t ZBITS, const uint8_t WBITS,
const bool XSIGN = false, const bool YSIGN = false, const bool ZSIGN = false, const bool WSIGN = false
>
class CompressedVector {
public:
enum {
TotalBits = XBITS + YBITS + ZBITS + WBITS,
IsByteAligned = isByteAligned(TotalBits)
};
typedef ElementInfo<XBITS, XSIGN> XInfo;
typedef ElementInfo<YBITS, YSIGN> YInfo;
typedef ElementInfo<ZBITS, ZSIGN> ZInfo;
typedef ElementInfo<WBITS, WSIGN> WInfo;
struct Type {
typename XInfo::Type X : XBITS;
typename YInfo::Type Y : YBITS;
typename ZInfo::Type Z : ZBITS;
typename WInfo::Type W : WBITS;
};
};
}}
#endif
<|endoftext|> |
<commit_before>#include "./UnicodeConverter.h"
#include "unicode/utypes.h" /* Basic ICU data types */
#include "unicode/ucnv.h" /* C Converter API */
#include "../DesktopEditor/common/File.h"
namespace NSUnicodeConverter
{
class CUnicodeConverter_Private
{
public:
CUnicodeConverter_Private()
{
#if 0
std::wstring sDumpPath = NSFile::GetProcessDirectory() + L"/codepages.txt";
NSFile::CFileBinary oFile;
oFile.CreateFileW(sDumpPath);
int32_t count = ucnv_countAvailable();
for (int i = 0; i < count; ++i)
{
std::string sCodePage = ucnv_getAvailableName(i);
UErrorCode _error = U_ZERO_ERROR;
int nCountAliases = ucnv_countAliases(sCodePage.c_str(), &_error);
char** palices = new char*[nCountAliases];
ucnv_getAliases(sCodePage.c_str(), (const char**)palices, &_error);
oFile.WriteStringUTF8(L"-----------------------------\r\n");
oFile.WriteFile((BYTE*)sCodePage.c_str(), sCodePage.length());
oFile.WriteStringUTF8(L"\r\n");
for (int j = 0; j < nCountAliases; ++j)
{
oFile.WriteFile((BYTE*)palices[j], strlen(palices[j]));
oFile.WriteStringUTF8(L"\r\n");
}
}
oFile.CloseFile();
#endif
}
~CUnicodeConverter_Private()
{
}
public:
std::string fromUnicode(const wchar_t* sInput, const unsigned int& nInputLen, const char* converterName)
{
std::string sRes = "";
UErrorCode status = U_ZERO_ERROR;
UConverter* conv = ucnv_open(converterName, &status);
if (U_SUCCESS(status))
{
int32_t nUCharCapacity = (int32_t)nInputLen;// UTF-16 uses 2 code-points per char
UChar* pUChar = (UChar*)malloc(nUCharCapacity * sizeof(UChar));
const UChar* pUCharStart = pUChar;
int32_t nUCharLength = 0;
u_strFromWCS(pUChar, nUCharCapacity, &nUCharLength, sInput, nInputLen, &status);
if (U_SUCCESS(status))
{
const UChar* pUCharLimit = pUCharStart + nUCharLength;
sRes.resize(nUCharLength * ucnv_getMaxCharSize(conv));// UTF-16 uses 2 code-points per char
char *sResStart = &sRes[0];
const char *sResLimit = sResStart + sRes.size();
ucnv_fromUnicode(conv, &sResStart, sResLimit, &pUCharStart, pUCharLimit, NULL, TRUE, &status);
}
ucnv_close(conv);
}
return sRes;
}
std::string fromUnicode(const std::wstring& sInput, const char* converterName)
{
return fromUnicode(sInput.c_str(), (unsigned int)sInput.size(), converterName);
}
std::wstring toUnicode(const char* sInput, const unsigned int& nInputLen, const char* converterName)
{
std::wstring sRes = L"";
UErrorCode status = U_ZERO_ERROR;
UConverter* conv = ucnv_open(converterName, &status);
std::string sss = ucnv_getName(conv, &status);
int iii = ucnv_getCCSID(conv, &status);
//UConverter* conv = ucnv_openCCSID(5347, UCNV_IBM, &status);
if (U_SUCCESS(status))
{
const char* source = sInput;
const char* sourceLimit = source + nInputLen;
unsigned int uBufSize = (nInputLen / ucnv_getMinCharSize(conv));
UChar* targetStart = (UChar*)malloc(uBufSize * sizeof(UChar));
UChar* target = targetStart;
UChar* targetLimit = target + uBufSize;
ucnv_toUnicode(conv, &target, targetLimit, &source, sourceLimit, NULL, TRUE, &status);
if (U_SUCCESS(status))
{
unsigned int nTargetSize = target - targetStart;
sRes.resize(nTargetSize * 2);// UTF-16 uses 2 code-points per char
int32_t nResLen = 0;
u_strToWCS(&sRes[0], sRes.size(), &nResLen, targetStart, nTargetSize, &status);
sRes.resize(nResLen);
}
ucnv_close(conv);
}
return sRes;
}
inline std::wstring toUnicode(const std::string& sInput, const char* converterName)
{
return toUnicode(sInput.c_str(), (unsigned int)sInput.size(), converterName);
}
};
}
namespace NSUnicodeConverter
{
CUnicodeConverter::CUnicodeConverter()
{
m_pInternal = new CUnicodeConverter_Private();
}
CUnicodeConverter::~CUnicodeConverter()
{
delete m_pInternal;
}
std::string CUnicodeConverter::fromUnicode(const wchar_t* sInput, const unsigned int& nInputLen, const char* converterName)
{
return m_pInternal->fromUnicode(sInput, nInputLen, converterName);
}
std::string CUnicodeConverter::fromUnicode(const std::wstring &sSrc, const char *sCodePage)
{
return m_pInternal->fromUnicode(sSrc, sCodePage);
}
std::wstring CUnicodeConverter::toUnicode(const char* sInput, const unsigned int& nInputLen, const char* converterName)
{
return m_pInternal->toUnicode(sInput, nInputLen, converterName);
}
std::wstring CUnicodeConverter::toUnicode(const std::string &sSrc, const char *sCodePage)
{
return m_pInternal->toUnicode(sSrc, sCodePage);
}
}
<commit_msg>error null на конце string после fromUnicode<commit_after>#include "./UnicodeConverter.h"
#include "unicode/utypes.h" /* Basic ICU data types */
#include "unicode/ucnv.h" /* C Converter API */
#include "../DesktopEditor/common/File.h"
namespace NSUnicodeConverter
{
class CUnicodeConverter_Private
{
public:
CUnicodeConverter_Private()
{
#if 0
std::wstring sDumpPath = NSFile::GetProcessDirectory() + L"/codepages.txt";
NSFile::CFileBinary oFile;
oFile.CreateFileW(sDumpPath);
int32_t count = ucnv_countAvailable();
for (int i = 0; i < count; ++i)
{
std::string sCodePage = ucnv_getAvailableName(i);
UErrorCode _error = U_ZERO_ERROR;
int nCountAliases = ucnv_countAliases(sCodePage.c_str(), &_error);
char** palices = new char*[nCountAliases];
ucnv_getAliases(sCodePage.c_str(), (const char**)palices, &_error);
oFile.WriteStringUTF8(L"-----------------------------\r\n");
oFile.WriteFile((BYTE*)sCodePage.c_str(), sCodePage.length());
oFile.WriteStringUTF8(L"\r\n");
for (int j = 0; j < nCountAliases; ++j)
{
oFile.WriteFile((BYTE*)palices[j], strlen(palices[j]));
oFile.WriteStringUTF8(L"\r\n");
}
}
oFile.CloseFile();
#endif
}
~CUnicodeConverter_Private()
{
}
public:
std::string fromUnicode(const wchar_t* sInput, const unsigned int& nInputLen, const char* converterName)
{
std::string sRes = "";
UErrorCode status = U_ZERO_ERROR;
UConverter* conv = ucnv_open(converterName, &status);
if (U_SUCCESS(status))
{
int32_t nUCharCapacity = (int32_t)nInputLen;// UTF-16 uses 2 code-points per char
UChar* pUChar = (UChar*)malloc(nUCharCapacity * sizeof(UChar));
const UChar* pUCharStart = pUChar;
int32_t nUCharLength = 0;
u_strFromWCS(pUChar, nUCharCapacity, &nUCharLength, sInput, nInputLen, &status);
if (U_SUCCESS(status))
{
const UChar* pUCharLimit = pUCharStart + nUCharLength;
sRes.resize(nUCharLength * ucnv_getMaxCharSize(conv));// UTF-16 uses 2 code-points per char
char *sResStart = &sRes[0];
char *sResCur = sResStart;
const char *sResLimit = sResCur + sRes.size();
ucnv_fromUnicode(conv, &sResCur, sResLimit, &pUCharStart, pUCharLimit, NULL, TRUE, &status);
sRes.resize(sResCur - sResStart);
}
ucnv_close(conv);
}
return sRes;
}
std::string fromUnicode(const std::wstring& sInput, const char* converterName)
{
return fromUnicode(sInput.c_str(), (unsigned int)sInput.size(), converterName);
}
std::wstring toUnicode(const char* sInput, const unsigned int& nInputLen, const char* converterName)
{
std::wstring sRes = L"";
UErrorCode status = U_ZERO_ERROR;
UConverter* conv = ucnv_open(converterName, &status);
std::string sss = ucnv_getName(conv, &status);
int iii = ucnv_getCCSID(conv, &status);
//UConverter* conv = ucnv_openCCSID(5347, UCNV_IBM, &status);
if (U_SUCCESS(status))
{
const char* source = sInput;
const char* sourceLimit = source + nInputLen;
unsigned int uBufSize = (nInputLen / ucnv_getMinCharSize(conv));
UChar* targetStart = (UChar*)malloc(uBufSize * sizeof(UChar));
UChar* target = targetStart;
UChar* targetLimit = target + uBufSize;
ucnv_toUnicode(conv, &target, targetLimit, &source, sourceLimit, NULL, TRUE, &status);
if (U_SUCCESS(status))
{
unsigned int nTargetSize = target - targetStart;
sRes.resize(nTargetSize * 2);// UTF-16 uses 2 code-points per char
int32_t nResLen = 0;
u_strToWCS(&sRes[0], sRes.size(), &nResLen, targetStart, nTargetSize, &status);
sRes.resize(nResLen);
}
ucnv_close(conv);
}
return sRes;
}
inline std::wstring toUnicode(const std::string& sInput, const char* converterName)
{
return toUnicode(sInput.c_str(), (unsigned int)sInput.size(), converterName);
}
};
}
namespace NSUnicodeConverter
{
CUnicodeConverter::CUnicodeConverter()
{
m_pInternal = new CUnicodeConverter_Private();
}
CUnicodeConverter::~CUnicodeConverter()
{
delete m_pInternal;
}
std::string CUnicodeConverter::fromUnicode(const wchar_t* sInput, const unsigned int& nInputLen, const char* converterName)
{
return m_pInternal->fromUnicode(sInput, nInputLen, converterName);
}
std::string CUnicodeConverter::fromUnicode(const std::wstring &sSrc, const char *sCodePage)
{
return m_pInternal->fromUnicode(sSrc, sCodePage);
}
std::wstring CUnicodeConverter::toUnicode(const char* sInput, const unsigned int& nInputLen, const char* converterName)
{
return m_pInternal->toUnicode(sInput, nInputLen, converterName);
}
std::wstring CUnicodeConverter::toUnicode(const std::string &sSrc, const char *sCodePage)
{
return m_pInternal->toUnicode(sSrc, sCodePage);
}
}
<|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <ignite/impl/interop/interop_external_memory.h>
#include <ignite/impl/binary/binary_reader_impl.h>
#include <ignite/impl/binary/binary_type_updater_impl.h>
#include <ignite/impl/module_manager.h>
#include <ignite/impl/ignite_binding_impl.h>
#include <ignite/binary/binary.h>
#include <ignite/cache/query/continuous/continuous_query.h>
#include <ignite/ignite_binding.h>
#include <ignite/ignite_binding_context.h>
#include <ignite/impl/ignite_environment.h>
using namespace ignite::common::concurrent;
using namespace ignite::jni::java;
using namespace ignite::impl::interop;
using namespace ignite::impl::binary;
using namespace ignite::binary;
using namespace ignite::impl::cache::query::continuous;
namespace ignite
{
namespace impl
{
/**
* Callback codes.
*/
enum CallbackOp
{
CACHE_INVOKE = 8,
CONTINUOUS_QUERY_LISTENER_APPLY = 18,
CONTINUOUS_QUERY_FILTER_CREATE = 19,
CONTINUOUS_QUERY_FILTER_APPLY = 20,
CONTINUOUS_QUERY_FILTER_RELEASE = 21,
REALLOC = 36,
ON_START = 49,
ON_STOP = 50
};
/**
* InLongOutLong callback.
*
* @param target Target environment.
* @param type Operation type.
* @param val Value.
*/
long long IGNITE_CALL InLongOutLong(void* target, int type, long long val)
{
int64_t res = 0;
SharedPointer<IgniteEnvironment>* env = static_cast<SharedPointer<IgniteEnvironment>*>(target);
switch (type)
{
case ON_STOP:
{
delete env;
break;
}
case CONTINUOUS_QUERY_LISTENER_APPLY:
{
SharedPointer<InteropMemory> mem = env->Get()->GetMemory(val);
env->Get()->OnContinuousQueryListenerApply(mem);
break;
}
case CONTINUOUS_QUERY_FILTER_CREATE:
{
SharedPointer<InteropMemory> mem = env->Get()->GetMemory(val);
res = env->Get()->OnContinuousQueryFilterCreate(mem);
break;
}
case CONTINUOUS_QUERY_FILTER_APPLY:
{
SharedPointer<InteropMemory> mem = env->Get()->GetMemory(val);
res = env->Get()->OnContinuousQueryFilterApply(mem);
break;
}
case CONTINUOUS_QUERY_FILTER_RELEASE:
{
// No-op.
break;
}
case CACHE_INVOKE:
{
SharedPointer<InteropMemory> mem = env->Get()->GetMemory(val);
env->Get()->CacheInvokeCallback(mem);
break;
}
default:
{
break;
}
}
return res;
}
/**
* InLongOutLong callback.
*
* @param target Target environment.
* @param type Operation type.
* @param val1 Value1.
* @param val2 Value2.
* @param val3 Value3.
* @param arg Object arg.
*/
long long IGNITE_CALL InLongLongLongObjectOutLong(void* target, int type, long long val1, long long val2,
long long val3, void* arg)
{
SharedPointer<IgniteEnvironment>* env = static_cast<SharedPointer<IgniteEnvironment>*>(target);
switch (type)
{
case ON_START:
{
env->Get()->OnStartCallback(val1, reinterpret_cast<jobject>(arg));
break;
}
case REALLOC:
{
SharedPointer<InteropMemory> mem = env->Get()->GetMemory(val1);
mem.Get()->Reallocate(static_cast<int32_t>(val2));
break;
}
default:
{
break;
}
}
return 0;
}
IgniteEnvironment::IgniteEnvironment(const IgniteConfiguration& cfg) :
cfg(new IgniteConfiguration(cfg)),
ctx(SharedPointer<JniContext>()),
latch(),
name(0),
proc(),
registry(DEFAULT_FAST_PATH_CONTAINERS_CAP, DEFAULT_SLOW_PATH_CONTAINERS_CAP),
metaMgr(new BinaryTypeManager()),
metaUpdater(0),
binding(),
moduleMgr()
{
binding = SharedPointer<IgniteBindingImpl>(new IgniteBindingImpl(*this));
IgniteBindingContext bindingContext(cfg, GetBinding());
moduleMgr = SharedPointer<ModuleManager>(new ModuleManager(bindingContext));
}
IgniteEnvironment::~IgniteEnvironment()
{
delete[] name;
delete metaUpdater;
delete metaMgr;
delete cfg;
}
const IgniteConfiguration& IgniteEnvironment::GetConfiguration() const
{
return *cfg;
}
JniHandlers IgniteEnvironment::GetJniHandlers(SharedPointer<IgniteEnvironment>* target)
{
JniHandlers hnds;
hnds.target = target;
hnds.inLongOutLong = InLongOutLong;
hnds.inLongLongLongObjectOutLong = InLongLongLongObjectOutLong;
hnds.error = 0;
return hnds;
}
void IgniteEnvironment::SetContext(SharedPointer<JniContext> ctx)
{
this->ctx = ctx;
}
void IgniteEnvironment::Initialize()
{
latch.CountDown();
jobject binaryProc = Context()->ProcessorBinaryProcessor(proc.Get());
metaUpdater = new BinaryTypeUpdaterImpl(*this, binaryProc);
metaMgr->SetUpdater(metaUpdater);
common::dynamic::Module currentModule = common::dynamic::GetCurrent();
moduleMgr.Get()->RegisterModule(currentModule);
}
const char* IgniteEnvironment::InstanceName() const
{
return name;
}
void* IgniteEnvironment::GetProcessor()
{
return (void*)proc.Get();
}
JniContext* IgniteEnvironment::Context()
{
return ctx.Get();
}
SharedPointer<InteropMemory> IgniteEnvironment::AllocateMemory()
{
SharedPointer<InteropMemory> ptr(new InteropUnpooledMemory(DEFAULT_ALLOCATION_SIZE));
return ptr;
}
SharedPointer<InteropMemory> IgniteEnvironment::AllocateMemory(int32_t cap)
{
SharedPointer<InteropMemory> ptr(new InteropUnpooledMemory(cap));
return ptr;
}
SharedPointer<InteropMemory> IgniteEnvironment::GetMemory(int64_t memPtr)
{
int8_t* memPtr0 = reinterpret_cast<int8_t*>(memPtr);
int32_t flags = InteropMemory::Flags(memPtr0);
if (InteropMemory::IsExternal(flags))
{
SharedPointer<InteropMemory> ptr(new InteropExternalMemory(memPtr0));
return ptr;
}
else
{
SharedPointer<InteropMemory> ptr(new InteropUnpooledMemory(memPtr0));
return ptr;
}
}
BinaryTypeManager* IgniteEnvironment::GetTypeManager()
{
return metaMgr;
}
BinaryTypeUpdater* IgniteEnvironment::GetTypeUpdater()
{
return metaUpdater;
}
SharedPointer<IgniteBindingImpl> IgniteEnvironment::GetBinding() const
{
return binding;
}
void IgniteEnvironment::ProcessorReleaseStart()
{
if (proc.Get())
ctx.Get()->ProcessorReleaseStart(proc.Get());
}
HandleRegistry& IgniteEnvironment::GetHandleRegistry()
{
return registry;
}
void IgniteEnvironment::OnStartCallback(long long memPtr, jobject proc)
{
this->proc = jni::JavaGlobalRef(*ctx.Get(), proc);
InteropExternalMemory mem(reinterpret_cast<int8_t*>(memPtr));
InteropInputStream stream(&mem);
BinaryReaderImpl reader(&stream);
int32_t nameLen = reader.ReadString(0, 0);
if (nameLen >= 0)
{
name = new char[nameLen + 1];
reader.ReadString(name, nameLen + 1);
}
else
name = 0;
}
void IgniteEnvironment::OnContinuousQueryListenerApply(SharedPointer<InteropMemory>& mem)
{
InteropInputStream stream(mem.Get());
BinaryReaderImpl reader(&stream);
int64_t qryHandle = reader.ReadInt64();
ContinuousQueryImplBase* contQry = reinterpret_cast<ContinuousQueryImplBase*>(registry.Get(qryHandle).Get());
if (contQry)
{
BinaryRawReader rawReader(&reader);
contQry->ReadAndProcessEvents(rawReader);
}
}
int64_t IgniteEnvironment::OnContinuousQueryFilterCreate(SharedPointer<InteropMemory>& mem)
{
if (!binding.Get())
throw IgniteError(IgniteError::IGNITE_ERR_UNKNOWN, "IgniteBinding is not initialized.");
InteropInputStream inStream(mem.Get());
BinaryReaderImpl reader(&inStream);
InteropOutputStream outStream(mem.Get());
BinaryWriterImpl writer(&outStream, GetTypeManager());
BinaryObjectImpl binFilter = BinaryObjectImpl::FromMemory(*mem.Get(), inStream.Position());
int32_t filterId = binFilter.GetTypeId();
bool invoked = false;
int64_t res = binding.Get()->InvokeCallback(invoked,
IgniteBindingImpl::CACHE_ENTRY_FILTER_CREATE, filterId, reader, writer);
if (!invoked)
{
IGNITE_ERROR_FORMATTED_1(IgniteError::IGNITE_ERR_COMPUTE_USER_UNDECLARED_EXCEPTION,
"C++ remote filter is not registered on the node (did you compile your program without -rdynamic?).",
"filterId", filterId);
}
outStream.Synchronize();
return res;
}
int64_t IgniteEnvironment::OnContinuousQueryFilterApply(SharedPointer<InteropMemory>& mem)
{
InteropInputStream inStream(mem.Get());
BinaryReaderImpl reader(&inStream);
BinaryRawReader rawReader(&reader);
int64_t handle = rawReader.ReadInt64();
SharedPointer<ContinuousQueryImplBase> qry =
StaticPointerCast<ContinuousQueryImplBase>(registry.Get(handle));
if (!qry.Get())
IGNITE_ERROR_FORMATTED_1(IgniteError::IGNITE_ERR_GENERIC, "Null query for handle.", "handle", handle);
cache::event::CacheEntryEventFilterBase* filter = qry.Get()->GetFilterHolder().GetFilter();
if (!filter)
IGNITE_ERROR_FORMATTED_1(IgniteError::IGNITE_ERR_GENERIC, "Null filter for handle.", "handle", handle);
bool res = filter->ReadAndProcessEvent(rawReader);
return res ? 1 : 0;
}
void IgniteEnvironment::CacheInvokeCallback(SharedPointer<InteropMemory>& mem)
{
if (!binding.Get())
throw IgniteError(IgniteError::IGNITE_ERR_UNKNOWN, "IgniteBinding is not initialized.");
InteropInputStream inStream(mem.Get());
BinaryReaderImpl reader(&inStream);
InteropOutputStream outStream(mem.Get());
BinaryWriterImpl writer(&outStream, GetTypeManager());
bool local = reader.ReadBool();
if (local)
throw IgniteError(IgniteError::IGNITE_ERR_UNSUPPORTED_OPERATION, "Local invokation is not supported.");
BinaryObjectImpl binProcHolder = BinaryObjectImpl::FromMemory(*mem.Get(), inStream.Position(), 0);
BinaryObjectImpl binProc = binProcHolder.GetField(0);
int32_t procId = binProc.GetTypeId();
bool invoked = false;
binding.Get()->InvokeCallback(invoked, IgniteBindingImpl::CACHE_ENTRY_PROCESSOR_APPLY, procId, reader, writer);
if (!invoked)
{
IGNITE_ERROR_FORMATTED_1(IgniteError::IGNITE_ERR_COMPUTE_USER_UNDECLARED_EXCEPTION,
"C++ entry processor is not registered on the node (did you compile your program without -rdynamic?).",
"procId", procId);
}
outStream.Synchronize();
}
}
}
<commit_msg>Fix for CPP<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <ignite/impl/interop/interop_external_memory.h>
#include <ignite/impl/binary/binary_reader_impl.h>
#include <ignite/impl/binary/binary_type_updater_impl.h>
#include <ignite/impl/module_manager.h>
#include <ignite/impl/ignite_binding_impl.h>
#include <ignite/binary/binary.h>
#include <ignite/cache/query/continuous/continuous_query.h>
#include <ignite/ignite_binding.h>
#include <ignite/ignite_binding_context.h>
#include <ignite/impl/ignite_environment.h>
using namespace ignite::common::concurrent;
using namespace ignite::jni::java;
using namespace ignite::impl::interop;
using namespace ignite::impl::binary;
using namespace ignite::binary;
using namespace ignite::impl::cache::query::continuous;
namespace ignite
{
namespace impl
{
/**
* Callback codes.
*/
enum CallbackOp
{
CACHE_INVOKE = 8,
CONTINUOUS_QUERY_LISTENER_APPLY = 18,
CONTINUOUS_QUERY_FILTER_CREATE = 19,
CONTINUOUS_QUERY_FILTER_APPLY = 20,
CONTINUOUS_QUERY_FILTER_RELEASE = 21,
REALLOC = 36,
ON_START = 49,
ON_STOP = 50
};
/**
* InLongOutLong callback.
*
* @param target Target environment.
* @param type Operation type.
* @param val Value.
*/
long long IGNITE_CALL InLongOutLong(void* target, int type, long long val)
{
int64_t res = 0;
SharedPointer<IgniteEnvironment>* env = static_cast<SharedPointer<IgniteEnvironment>*>(target);
switch (type)
{
case ON_STOP:
{
delete env;
break;
}
case CONTINUOUS_QUERY_LISTENER_APPLY:
{
SharedPointer<InteropMemory> mem = env->Get()->GetMemory(val);
env->Get()->OnContinuousQueryListenerApply(mem);
break;
}
case CONTINUOUS_QUERY_FILTER_CREATE:
{
SharedPointer<InteropMemory> mem = env->Get()->GetMemory(val);
res = env->Get()->OnContinuousQueryFilterCreate(mem);
break;
}
case CONTINUOUS_QUERY_FILTER_APPLY:
{
SharedPointer<InteropMemory> mem = env->Get()->GetMemory(val);
res = env->Get()->OnContinuousQueryFilterApply(mem);
break;
}
case CONTINUOUS_QUERY_FILTER_RELEASE:
{
// No-op.
break;
}
case CACHE_INVOKE:
{
SharedPointer<InteropMemory> mem = env->Get()->GetMemory(val);
env->Get()->CacheInvokeCallback(mem);
break;
}
default:
{
break;
}
}
return res;
}
/**
* InLongOutLong callback.
*
* @param target Target environment.
* @param type Operation type.
* @param val1 Value1.
* @param val2 Value2.
* @param val3 Value3.
* @param arg Object arg.
*/
long long IGNITE_CALL InLongLongLongObjectOutLong(void* target, int type, long long val1, long long val2,
long long val3, void* arg)
{
SharedPointer<IgniteEnvironment>* env = static_cast<SharedPointer<IgniteEnvironment>*>(target);
switch (type)
{
case ON_START:
{
env->Get()->OnStartCallback(val1, reinterpret_cast<jobject>(arg));
break;
}
case REALLOC:
{
SharedPointer<InteropMemory> mem = env->Get()->GetMemory(val1);
mem.Get()->Reallocate(static_cast<int32_t>(val2));
break;
}
default:
{
break;
}
}
return 0;
}
IgniteEnvironment::IgniteEnvironment(const IgniteConfiguration& cfg) :
cfg(new IgniteConfiguration(cfg)),
ctx(SharedPointer<JniContext>()),
latch(),
name(0),
proc(),
registry(DEFAULT_FAST_PATH_CONTAINERS_CAP, DEFAULT_SLOW_PATH_CONTAINERS_CAP),
metaMgr(new BinaryTypeManager()),
metaUpdater(0),
binding(),
moduleMgr()
{
binding = SharedPointer<IgniteBindingImpl>(new IgniteBindingImpl(*this));
IgniteBindingContext bindingContext(cfg, GetBinding());
moduleMgr = SharedPointer<ModuleManager>(new ModuleManager(bindingContext));
}
IgniteEnvironment::~IgniteEnvironment()
{
delete[] name;
delete metaUpdater;
delete metaMgr;
delete cfg;
}
const IgniteConfiguration& IgniteEnvironment::GetConfiguration() const
{
return *cfg;
}
JniHandlers IgniteEnvironment::GetJniHandlers(SharedPointer<IgniteEnvironment>* target)
{
JniHandlers hnds;
hnds.target = target;
hnds.inLongOutLong = InLongOutLong;
hnds.inLongLongLongObjectOutLong = InLongLongLongObjectOutLong;
hnds.error = 0;
return hnds;
}
void IgniteEnvironment::SetContext(SharedPointer<JniContext> ctx)
{
this->ctx = ctx;
}
void IgniteEnvironment::Initialize()
{
latch.CountDown();
jobject binaryProc = Context()->ProcessorBinaryProcessor(proc.Get());
metaUpdater = new BinaryTypeUpdaterImpl(*this, binaryProc);
metaMgr->SetUpdater(metaUpdater);
common::dynamic::Module currentModule = common::dynamic::GetCurrent();
moduleMgr.Get()->RegisterModule(currentModule);
}
const char* IgniteEnvironment::InstanceName() const
{
return name;
}
void* IgniteEnvironment::GetProcessor()
{
return (void*)proc.Get();
}
JniContext* IgniteEnvironment::Context()
{
return ctx.Get();
}
SharedPointer<InteropMemory> IgniteEnvironment::AllocateMemory()
{
SharedPointer<InteropMemory> ptr(new InteropUnpooledMemory(DEFAULT_ALLOCATION_SIZE));
return ptr;
}
SharedPointer<InteropMemory> IgniteEnvironment::AllocateMemory(int32_t cap)
{
SharedPointer<InteropMemory> ptr(new InteropUnpooledMemory(cap));
return ptr;
}
SharedPointer<InteropMemory> IgniteEnvironment::GetMemory(int64_t memPtr)
{
int8_t* memPtr0 = reinterpret_cast<int8_t*>(memPtr);
int32_t flags = InteropMemory::Flags(memPtr0);
if (InteropMemory::IsExternal(flags))
{
SharedPointer<InteropMemory> ptr(new InteropExternalMemory(memPtr0));
return ptr;
}
else
{
SharedPointer<InteropMemory> ptr(new InteropUnpooledMemory(memPtr0));
return ptr;
}
}
BinaryTypeManager* IgniteEnvironment::GetTypeManager()
{
return metaMgr;
}
BinaryTypeUpdater* IgniteEnvironment::GetTypeUpdater()
{
return metaUpdater;
}
SharedPointer<IgniteBindingImpl> IgniteEnvironment::GetBinding() const
{
return binding;
}
void IgniteEnvironment::ProcessorReleaseStart()
{
if (proc.Get())
ctx.Get()->ProcessorReleaseStart(proc.Get());
}
HandleRegistry& IgniteEnvironment::GetHandleRegistry()
{
return registry;
}
void IgniteEnvironment::OnStartCallback(long long memPtr, jobject proc)
{
this->proc = jni::JavaGlobalRef(*ctx.Get(), proc);
InteropExternalMemory mem(reinterpret_cast<int8_t*>(memPtr));
InteropInputStream stream(&mem);
BinaryReaderImpl reader(&stream);
int32_t nameLen = reader.ReadString(0, 0);
if (nameLen >= 0)
{
name = new char[nameLen + 1];
reader.ReadString(name, nameLen + 1);
}
else
name = 0;
}
void IgniteEnvironment::OnContinuousQueryListenerApply(SharedPointer<InteropMemory>& mem)
{
InteropInputStream stream(mem.Get());
BinaryReaderImpl reader(&stream);
int64_t qryHandle = reader.ReadInt64();
ContinuousQueryImplBase* contQry = reinterpret_cast<ContinuousQueryImplBase*>(registry.Get(qryHandle).Get());
if (contQry)
{
BinaryRawReader rawReader(&reader);
contQry->ReadAndProcessEvents(rawReader);
}
}
int64_t IgniteEnvironment::OnContinuousQueryFilterCreate(SharedPointer<InteropMemory>& mem)
{
if (!binding.Get())
throw IgniteError(IgniteError::IGNITE_ERR_UNKNOWN, "IgniteBinding is not initialized.");
InteropInputStream inStream(mem.Get());
BinaryReaderImpl reader(&inStream);
InteropOutputStream outStream(mem.Get());
BinaryWriterImpl writer(&outStream, GetTypeManager());
BinaryObjectImpl binFilter = BinaryObjectImpl::FromMemory(*mem.Get(), inStream.Position(), metaMgr);
int32_t filterId = binFilter.GetTypeId();
bool invoked = false;
int64_t res = binding.Get()->InvokeCallback(invoked,
IgniteBindingImpl::CACHE_ENTRY_FILTER_CREATE, filterId, reader, writer);
if (!invoked)
{
IGNITE_ERROR_FORMATTED_1(IgniteError::IGNITE_ERR_COMPUTE_USER_UNDECLARED_EXCEPTION,
"C++ remote filter is not registered on the node (did you compile your program without -rdynamic?).",
"filterId", filterId);
}
outStream.Synchronize();
return res;
}
int64_t IgniteEnvironment::OnContinuousQueryFilterApply(SharedPointer<InteropMemory>& mem)
{
InteropInputStream inStream(mem.Get());
BinaryReaderImpl reader(&inStream);
BinaryRawReader rawReader(&reader);
int64_t handle = rawReader.ReadInt64();
SharedPointer<ContinuousQueryImplBase> qry =
StaticPointerCast<ContinuousQueryImplBase>(registry.Get(handle));
if (!qry.Get())
IGNITE_ERROR_FORMATTED_1(IgniteError::IGNITE_ERR_GENERIC, "Null query for handle.", "handle", handle);
cache::event::CacheEntryEventFilterBase* filter = qry.Get()->GetFilterHolder().GetFilter();
if (!filter)
IGNITE_ERROR_FORMATTED_1(IgniteError::IGNITE_ERR_GENERIC, "Null filter for handle.", "handle", handle);
bool res = filter->ReadAndProcessEvent(rawReader);
return res ? 1 : 0;
}
void IgniteEnvironment::CacheInvokeCallback(SharedPointer<InteropMemory>& mem)
{
if (!binding.Get())
throw IgniteError(IgniteError::IGNITE_ERR_UNKNOWN, "IgniteBinding is not initialized.");
InteropInputStream inStream(mem.Get());
BinaryReaderImpl reader(&inStream);
InteropOutputStream outStream(mem.Get());
BinaryWriterImpl writer(&outStream, GetTypeManager());
bool local = reader.ReadBool();
if (local)
throw IgniteError(IgniteError::IGNITE_ERR_UNSUPPORTED_OPERATION, "Local invokation is not supported.");
BinaryObjectImpl binProcHolder = BinaryObjectImpl::FromMemory(*mem.Get(), inStream.Position(), 0);
BinaryObjectImpl binProc = binProcHolder.GetField(0);
int32_t procId = binProc.GetTypeId();
bool invoked = false;
binding.Get()->InvokeCallback(invoked, IgniteBindingImpl::CACHE_ENTRY_PROCESSOR_APPLY, procId, reader, writer);
if (!invoked)
{
IGNITE_ERROR_FORMATTED_1(IgniteError::IGNITE_ERR_COMPUTE_USER_UNDECLARED_EXCEPTION,
"C++ entry processor is not registered on the node (did you compile your program without -rdynamic?).",
"procId", procId);
}
outStream.Synchronize();
}
}
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "customwidgetwizarddialog.h"
#include "customwidgetwidgetswizardpage.h"
#include "customwidgetpluginwizardpage.h"
#include "pluginoptions.h"
#include <projectexplorer/projectexplorerconstants.h>
#include <qtsupport/qtkitinformation.h>
#include <qtsupport/qtsupportconstants.h>
namespace {
class DesktopQtKitMatcher : public ProjectExplorer::KitMatcher
{
public:
bool matches(const ProjectExplorer::Kit *k) const
{
ProjectExplorer::IDevice::ConstPtr dev = ProjectExplorer::DeviceKitInformation::device(k);
if (dev.isNull() || dev->id() != ProjectExplorer::Constants::DESKTOP_DEVICE_ID)
return false;
QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(k);
return version && version->type() == QLatin1String(QtSupport::Constants::DESKTOPQT);
}
};
} // namespace
namespace QmakeProjectManager {
namespace Internal {
enum { IntroPageId = 0};
CustomWidgetWizardDialog::CustomWidgetWizardDialog(const QString &templateName,
const QIcon &icon,
QWidget *parent,
const Core::WizardDialogParameters ¶meters) :
BaseQmakeProjectWizardDialog(false, parent, parameters),
m_widgetsPage(new CustomWidgetWidgetsWizardPage),
m_pluginPage(new CustomWidgetPluginWizardPage)
{
setWindowIcon(icon);
setWindowTitle(templateName);
setIntroDescription(tr("This wizard generates a Qt Designer Custom Widget "
"or a Qt Designer Custom Widget Collection project."));
if (!parameters.extraValues().contains(QLatin1String(ProjectExplorer::Constants::PROJECT_KIT_IDS)))
addTargetSetupPage();
addPage(m_widgetsPage);
m_pluginPageId = addPage(m_pluginPage);
addExtensionPages(parameters.extensionPages());
connect(this, SIGNAL(currentIdChanged(int)), this, SLOT(slotCurrentIdChanged(int)));
}
FileNamingParameters CustomWidgetWizardDialog::fileNamingParameters() const
{
return m_widgetsPage->fileNamingParameters();
}
void CustomWidgetWizardDialog::setFileNamingParameters(const FileNamingParameters &fnp)
{
m_widgetsPage->setFileNamingParameters(fnp);
m_pluginPage->setFileNamingParameters(fnp);
}
void CustomWidgetWizardDialog::slotCurrentIdChanged(int id)
{
if (id == m_pluginPageId)
m_pluginPage->init(m_widgetsPage);
}
QSharedPointer<PluginOptions> CustomWidgetWizardDialog::pluginOptions() const
{
QSharedPointer<PluginOptions> rc = m_pluginPage->basicPluginOptions();
rc->widgetOptions = m_widgetsPage->widgetOptions();
return rc;
}
} // namespace Internal
} // namespace QmakeProjectManager
<commit_msg>Remove some dead code left over from the KitMatcher change<commit_after>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "customwidgetwizarddialog.h"
#include "customwidgetwidgetswizardpage.h"
#include "customwidgetpluginwizardpage.h"
#include "pluginoptions.h"
#include <projectexplorer/projectexplorerconstants.h>
#include <qtsupport/qtkitinformation.h>
#include <qtsupport/qtsupportconstants.h>
namespace QmakeProjectManager {
namespace Internal {
enum { IntroPageId = 0};
CustomWidgetWizardDialog::CustomWidgetWizardDialog(const QString &templateName,
const QIcon &icon,
QWidget *parent,
const Core::WizardDialogParameters ¶meters) :
BaseQmakeProjectWizardDialog(false, parent, parameters),
m_widgetsPage(new CustomWidgetWidgetsWizardPage),
m_pluginPage(new CustomWidgetPluginWizardPage)
{
setWindowIcon(icon);
setWindowTitle(templateName);
setIntroDescription(tr("This wizard generates a Qt Designer Custom Widget "
"or a Qt Designer Custom Widget Collection project."));
if (!parameters.extraValues().contains(QLatin1String(ProjectExplorer::Constants::PROJECT_KIT_IDS)))
addTargetSetupPage();
addPage(m_widgetsPage);
m_pluginPageId = addPage(m_pluginPage);
addExtensionPages(parameters.extensionPages());
connect(this, SIGNAL(currentIdChanged(int)), this, SLOT(slotCurrentIdChanged(int)));
}
FileNamingParameters CustomWidgetWizardDialog::fileNamingParameters() const
{
return m_widgetsPage->fileNamingParameters();
}
void CustomWidgetWizardDialog::setFileNamingParameters(const FileNamingParameters &fnp)
{
m_widgetsPage->setFileNamingParameters(fnp);
m_pluginPage->setFileNamingParameters(fnp);
}
void CustomWidgetWizardDialog::slotCurrentIdChanged(int id)
{
if (id == m_pluginPageId)
m_pluginPage->init(m_widgetsPage);
}
QSharedPointer<PluginOptions> CustomWidgetWizardDialog::pluginOptions() const
{
QSharedPointer<PluginOptions> rc = m_pluginPage->basicPluginOptions();
rc->widgetOptions = m_widgetsPage->widgetOptions();
return rc;
}
} // namespace Internal
} // namespace QmakeProjectManager
<|endoftext|> |
<commit_before>/**
* This file is part of the CernVM File System
*/
#include "swissknife_tarball.h"
#include "catalog_virtual.h"
#include "sync_mediator.h"
#include "sync_union.h"
#include "sync_union_tarball.h"
int swissknife::IngestTarball::Main(const swissknife::ArgumentList &args) {
SyncParameters params;
params.dir_rdonly = MakeCanonicalPath(*args.find('c')->second);
params.dir_temp = MakeCanonicalPath(*args.find('t')->second);
params.base_hash = shash::MkFromHexPtr(shash::HexPtr(*args.find('b')->second),
shash::kSuffixCatalog);
params.stratum0 = *args.find('w')->second;
params.manifest_path = *args.find('o')->second;
params.spooler_definition = *args.find('r')->second;
params.public_keys = *args.find('K')->second;
params.repo_name = *args.find('N')->second;
params.tar_file = *args.find('T')->second;
params.base_directory = *args.find('B')->second;
if (args.find('D') != args.end()) {
params.to_delete = *args.find('D')->second;
}
shash::Algorithms hash_algorithm = shash::kSha1;
params.nested_kcatalog_limit = SyncParameters::kDefaultNestedKcatalogLimit;
params.root_kcatalog_limit = SyncParameters::kDefaultRootKcatalogLimit;
params.file_mbyte_limit = SyncParameters::kDefaultFileMbyteLimit;
params.branched_catalog = false; // could be true?
upload::SpoolerDefinition spooler_definition(
params.spooler_definition, hash_algorithm, params.compression_alg,
params.generate_legacy_bulk_chunks, params.use_file_chunking,
params.min_file_chunk_size, params.avg_file_chunk_size,
params.max_file_chunk_size, params.session_token_file, params.key_file);
if (params.max_concurrent_write_jobs > 0) {
spooler_definition.number_of_concurrent_uploads =
params.max_concurrent_write_jobs;
}
upload::SpoolerDefinition spooler_definition_catalogs(
spooler_definition.Dup2DefaultCompression());
params.spooler = upload::Spooler::Construct(spooler_definition);
if (NULL == params.spooler) return 3;
UniquePtr<upload::Spooler> spooler_catalogs(
upload::Spooler::Construct(spooler_definition_catalogs));
if (!spooler_catalogs.IsValid()) return 3;
const bool follow_redirects = (args.count('L') > 0);
if (!InitDownloadManager(follow_redirects)) {
return 3;
}
if (!InitVerifyingSignatureManager(params.public_keys,
params.trusted_certs)) {
return 3;
}
bool with_gateway =
spooler_definition.driver_type == upload::SpoolerDefinition::Gateway;
UniquePtr<manifest::Manifest> manifest;
if (params.branched_catalog) {
// Throw-away manifest
manifest = new manifest::Manifest(shash::Any(), 0, "");
} else if (params.virtual_dir_actions !=
catalog::VirtualCatalog::kActionNone) {
manifest = this->OpenLocalManifest(params.manifest_path);
params.base_hash = manifest->catalog_hash();
} else {
if (with_gateway) {
manifest =
FetchRemoteManifest(params.stratum0, params.repo_name, shash::Any());
} else {
manifest = FetchRemoteManifest(params.stratum0, params.repo_name,
params.base_hash);
}
}
if (!manifest) {
return 3;
}
const std::string old_root_hash = manifest->catalog_hash().ToString(true);
catalog::WritableCatalogManager catalog_manager(
params.base_hash, params.stratum0, params.dir_temp, spooler_catalogs,
download_manager(), params.enforce_limits, params.nested_kcatalog_limit,
params.root_kcatalog_limit, params.file_mbyte_limit, statistics(),
params.is_balanced, params.max_weight, params.min_weight);
catalog_manager.Init();
publish::SyncMediator mediator(&catalog_manager, ¶ms);
if (params.virtual_dir_actions == catalog::VirtualCatalog::kActionNone) {
publish::SyncUnion *sync;
sync = new publish::SyncUnionTarball(&mediator, params.dir_rdonly,
params.tar_file, params.base_directory,
params.to_delete);
if (!sync->Initialize()) {
LogCvmfs(kLogCvmfs, kLogStderr,
"Initialization of the synchronisation "
"engine failed");
return 4;
}
sync->Traverse();
}
if (!mediator.Commit(manifest.weak_ref())) {
PrintError("something went wrong during sync");
return 5;
}
// finalize the spooler
LogCvmfs(kLogCvmfs, kLogStdout, "Wait for all uploads to finish");
params.spooler->WaitForUpload();
spooler_catalogs->WaitForUpload();
params.spooler->FinalizeSession(false);
LogCvmfs(kLogCvmfs, kLogStdout, "Exporting repository manifest");
// We call FinalizeSession(true) this time, to also trigger the commit
// operation on the gateway machine (if the upstream is of type "gw").
// Get the path of the new root catalog
const std::string new_root_hash = manifest->catalog_hash().ToString(true);
spooler_catalogs->FinalizeSession(true, old_root_hash, new_root_hash,
params.repo_tag);
delete params.spooler;
if (!manifest->Export(params.manifest_path)) {
PrintError("Failed to create new repository");
return 6;
}
return 0;
}
<commit_msg>add check for auth<commit_after>/**
* This file is part of the CernVM File System
*/
#include "swissknife_tarball.h"
#include "catalog_virtual.h"
#include "sync_mediator.h"
#include "sync_union.h"
#include "sync_union_tarball.h"
int swissknife::IngestTarball::Main(const swissknife::ArgumentList &args) {
SyncParameters params;
params.dir_rdonly = MakeCanonicalPath(*args.find('c')->second);
params.dir_temp = MakeCanonicalPath(*args.find('t')->second);
params.base_hash = shash::MkFromHexPtr(shash::HexPtr(*args.find('b')->second),
shash::kSuffixCatalog);
params.stratum0 = *args.find('w')->second;
params.manifest_path = *args.find('o')->second;
params.spooler_definition = *args.find('r')->second;
params.public_keys = *args.find('K')->second;
params.repo_name = *args.find('N')->second;
params.tar_file = *args.find('T')->second;
params.base_directory = *args.find('B')->second;
if (args.find('D') != args.end()) {
params.to_delete = *args.find('D')->second;
}
shash::Algorithms hash_algorithm = shash::kSha1;
params.nested_kcatalog_limit = SyncParameters::kDefaultNestedKcatalogLimit;
params.root_kcatalog_limit = SyncParameters::kDefaultRootKcatalogLimit;
params.file_mbyte_limit = SyncParameters::kDefaultFileMbyteLimit;
params.branched_catalog = false; // could be true?
upload::SpoolerDefinition spooler_definition(
params.spooler_definition, hash_algorithm, params.compression_alg,
params.generate_legacy_bulk_chunks, params.use_file_chunking,
params.min_file_chunk_size, params.avg_file_chunk_size,
params.max_file_chunk_size, params.session_token_file, params.key_file);
if (params.max_concurrent_write_jobs > 0) {
spooler_definition.number_of_concurrent_uploads =
params.max_concurrent_write_jobs;
}
upload::SpoolerDefinition spooler_definition_catalogs(
spooler_definition.Dup2DefaultCompression());
params.spooler = upload::Spooler::Construct(spooler_definition);
if (NULL == params.spooler) return 3;
UniquePtr<upload::Spooler> spooler_catalogs(
upload::Spooler::Construct(spooler_definition_catalogs));
if (!spooler_catalogs.IsValid()) return 3;
const bool follow_redirects = (args.count('L') > 0);
if (!InitDownloadManager(follow_redirects)) {
return 3;
}
if (!InitVerifyingSignatureManager(params.public_keys,
params.trusted_certs)) {
return 3;
}
bool with_gateway =
spooler_definition.driver_type == upload::SpoolerDefinition::Gateway;
UniquePtr<manifest::Manifest> manifest;
if (params.branched_catalog) {
// Throw-away manifest
manifest = new manifest::Manifest(shash::Any(), 0, "");
} else if (params.virtual_dir_actions !=
catalog::VirtualCatalog::kActionNone) {
manifest = this->OpenLocalManifest(params.manifest_path);
params.base_hash = manifest->catalog_hash();
} else {
if (with_gateway) {
manifest =
FetchRemoteManifest(params.stratum0, params.repo_name, shash::Any());
} else {
manifest = FetchRemoteManifest(params.stratum0, params.repo_name,
params.base_hash);
}
}
if (!manifest) {
return 3;
}
const std::string old_root_hash = manifest->catalog_hash().ToString(true);
catalog::WritableCatalogManager catalog_manager(
params.base_hash, params.stratum0, params.dir_temp, spooler_catalogs,
download_manager(), params.enforce_limits, params.nested_kcatalog_limit,
params.root_kcatalog_limit, params.file_mbyte_limit, statistics(),
params.is_balanced, params.max_weight, params.min_weight);
catalog_manager.Init();
publish::SyncMediator mediator(&catalog_manager, ¶ms);
if (params.virtual_dir_actions == catalog::VirtualCatalog::kActionNone) {
publish::SyncUnion *sync;
sync = new publish::SyncUnionTarball(&mediator, params.dir_rdonly,
params.tar_file, params.base_directory,
params.to_delete);
if (!sync->Initialize()) {
LogCvmfs(kLogCvmfs, kLogStderr,
"Initialization of the synchronisation "
"engine failed");
return 4;
}
sync->Traverse();
}
if (!params.authz_file.empty()) {
LogCvmfs(kLogCvmfs, kLogDebug,
"Adding contents of authz file %s to"
" root catalog.",
params.authz_file.c_str());
int fd = open(params.authz_file.c_str(), O_RDONLY);
if (fd == -1) {
LogCvmfs(kLogCvmfs, kLogStderr,
"Unable to open authz file (%s)"
"from the publication process: %s",
params.authz_file.c_str(), strerror(errno));
return 7;
}
std::string new_authz;
const bool read_successful = SafeReadToString(fd, &new_authz);
close(fd);
if (!read_successful) {
LogCvmfs(kLogCvmfs, kLogStderr, "Failed to read authz file (%s): %s",
params.authz_file.c_str(), strerror(errno));
return 8;
}
catalog_manager.SetVOMSAuthz(new_authz);
}
if (!mediator.Commit(manifest.weak_ref())) {
PrintError("something went wrong during sync");
return 5;
}
// finalize the spooler
LogCvmfs(kLogCvmfs, kLogStdout, "Wait for all uploads to finish");
params.spooler->WaitForUpload();
spooler_catalogs->WaitForUpload();
params.spooler->FinalizeSession(false);
LogCvmfs(kLogCvmfs, kLogStdout, "Exporting repository manifest");
// We call FinalizeSession(true) this time, to also trigger the commit
// operation on the gateway machine (if the upstream is of type "gw").
// Get the path of the new root catalog
const std::string new_root_hash = manifest->catalog_hash().ToString(true);
spooler_catalogs->FinalizeSession(true, old_root_hash, new_root_hash,
params.repo_tag);
delete params.spooler;
if (!manifest->Export(params.manifest_path)) {
PrintError("Failed to create new repository");
return 6;
}
return 0;
}
<|endoftext|> |
<commit_before>/**
* This file is part of the CernVM File System
*/
#define __STDC_FORMAT_MACROS
#include "sync_union_tarball.h"
#include <pthread.h>
#include <stdio.h>
#include <cassert>
#include <set>
#include <string>
#include <vector>
#include "duplex_libarchive.h"
#include "fs_traversal.h"
#include "smalloc.h"
#include "sync_item.h"
#include "sync_item_dummy.h"
#include "sync_item_tar.h"
#include "sync_mediator.h"
#include "sync_union.h"
#include "util/posix.h"
#include "util_concurrency.h"
namespace publish {
SyncUnionTarball::SyncUnionTarball(AbstractSyncMediator *mediator,
const std::string &rdonly_path,
const std::string &union_path,
const std::string &scratch_path,
const std::string &tarball_path,
const std::string &base_directory,
const std::string &to_delete)
: SyncUnion(mediator, rdonly_path, union_path, scratch_path),
tarball_path_(tarball_path),
base_directory_(base_directory),
to_delete_(to_delete),
read_archive_signal_(new Signal) {
read_archive_signal_->Wakeup();
}
SyncUnionTarball::~SyncUnionTarball() {
delete read_archive_signal_;
}
bool SyncUnionTarball::Initialize() {
bool result;
src = archive_read_new();
assert(ARCHIVE_OK == archive_read_support_format_tar(src));
assert(ARCHIVE_OK == archive_read_support_format_empty(src));
if (tarball_path_ == "--") {
result = archive_read_open_filename(src, NULL, 4096);
} else {
std::string tarball_absolute_path = GetAbsolutePath(tarball_path_);
result =
archive_read_open_filename(src, tarball_absolute_path.c_str(), 4096);
}
if (result != ARCHIVE_OK) {
LogCvmfs(kLogUnionFs, kLogStderr, "Impossible to open the archive.");
return false;
}
return SyncUnion::Initialize();
}
void SyncUnionTarball::Traverse() {
assert(this->IsInitialized());
struct archive_entry *entry = archive_entry_new();
bool retry_read_header = false;
/*
* As first step we eliminate the directories we are request.
*/
if (to_delete_ != "") {
vector<std::string> to_eliminate_vec = SplitString(to_delete_, ':');
for (vector<string>::iterator s = to_eliminate_vec.begin();
s != to_eliminate_vec.end(); ++s) {
std::string parent_path;
std::string filename;
SplitPath(*s, &parent_path, &filename);
if (parent_path == ".") parent_path = "";
SharedPtr<SyncItem> sync_entry =
CreateSyncItem(parent_path, filename, kItemDir);
mediator_->Remove(sync_entry);
}
}
while (true) {
do {
retry_read_header = false;
/* Get the lock, wait if lock is not available yet */
read_archive_signal_->Wait();
int result = archive_read_next_header2(src, entry);
switch (result) {
case ARCHIVE_FATAL: {
LogCvmfs(kLogUnionFs, kLogStderr,
"Fatal error in reading the archive.");
return;
break; /* Only exit point with error */
}
case ARCHIVE_RETRY: {
LogCvmfs(kLogUnionFs, kLogStderr,
"Error in reading the header, retrying. \n %s",
archive_error_string(src));
retry_read_header = true;
break;
}
case ARCHIVE_EOF: {
for (set<string>::iterator dir = to_create_catalog_dirs_.begin();
dir != to_create_catalog_dirs_.end(); ++dir) {
assert(dirs_.find(*dir) != dirs_.end());
SharedPtr<SyncItem> to_mark = dirs_[*dir];
assert(to_mark->IsDirectory());
to_mark->SetCatalogMarker();
to_mark->AlreadyCreatedDir();
ProcessDirectory(to_mark);
}
return; /* Only successful exit point */
break;
}
case ARCHIVE_WARN: {
LogCvmfs(kLogUnionFs, kLogStderr,
"Warning in uncompression reading, going on. \n %s",
archive_error_string(src));
/* We actually want this to enter the ARCHIVE_OK case */
}
case ARCHIVE_OK: {
std::string archive_file_path(archive_entry_pathname(entry));
std::string complete_path(base_directory_ + "/" + archive_file_path);
if (*complete_path.rbegin() == '/') {
complete_path.erase(complete_path.size() - 1);
}
std::string parent_path;
std::string filename;
SplitPath(complete_path, &parent_path, &filename);
CreateDirectories(parent_path);
/*
* Libarchive is not thread aware, so we need to make sure that before
* to read/"open" the next header in the archive the content of the
* present header is been consumed completely.
* Different thread read/"open" the header from the one that consumes
* it so we opted for a conditional variable.
* The conditional variable is acquire when we read the header and as
* long as it is not released we cannot read/"open" the next header.
* At the end of the pipeline, when the IngestionSource (generated by
* the SyncItem) is been 1. Opened, 2. Read, at the closing we
* actually release the conditional variable.
* This whole process is not necessary for directories since we don't
* actually need to read data from them.
*/
SharedPtr<SyncItem> sync_entry = SharedPtr<SyncItem>(new SyncItemTar(
parent_path, filename, src, entry, read_archive_signal_, this));
if (sync_entry->IsDirectory()) {
if (know_directories_.find(complete_path) !=
know_directories_.end()) {
sync_entry->AlreadyCreatedDir();
}
ProcessDirectory(sync_entry);
dirs_[complete_path] = sync_entry;
know_directories_.insert(complete_path);
read_archive_signal_->Wakeup();
} else if (sync_entry->IsRegularFile()) {
ProcessFile(sync_entry);
if (filename == ".cvmfscatalog") {
to_create_catalog_dirs_.insert(parent_path);
}
} else {
read_archive_signal_->Wakeup();
}
}
}
} while (retry_read_header);
}
}
std::string SyncUnionTarball::UnwindWhiteoutFilename(
SharedPtr<SyncItem> entry) const {
return entry->filename();
}
bool SyncUnionTarball::IsOpaqueDirectory(SharedPtr<SyncItem> directory) const {
return false;
}
bool SyncUnionTarball::IsWhiteoutEntry(SharedPtr<SyncItem> entry) const {
return false;
}
void SyncUnionTarball::CreateDirectories(const std::string &target) {
if (know_directories_.find(target) != know_directories_.end()) return;
if (target == ".") return;
std::string dirname = "";
std::string filename = "";
SplitPath(target, &dirname, &filename);
CreateDirectories(dirname);
if (dirname == ".") dirname = "";
SharedPtr<SyncItem> dummy = SharedPtr<SyncItem>(
new SyncItemDummyDir(dirname, filename, this, kItemDir));
ProcessDirectory(dummy);
know_directories_.insert(target);
}
} // namespace publish
<commit_msg>simplify the code using continues instead of double loop<commit_after>/**
* This file is part of the CernVM File System
*/
#define __STDC_FORMAT_MACROS
#include "sync_union_tarball.h"
#include <pthread.h>
#include <stdio.h>
#include <cassert>
#include <set>
#include <string>
#include <vector>
#include "duplex_libarchive.h"
#include "fs_traversal.h"
#include "smalloc.h"
#include "sync_item.h"
#include "sync_item_dummy.h"
#include "sync_item_tar.h"
#include "sync_mediator.h"
#include "sync_union.h"
#include "util/posix.h"
#include "util_concurrency.h"
namespace publish {
SyncUnionTarball::SyncUnionTarball(AbstractSyncMediator *mediator,
const std::string &rdonly_path,
const std::string &union_path,
const std::string &scratch_path,
const std::string &tarball_path,
const std::string &base_directory,
const std::string &to_delete)
: SyncUnion(mediator, rdonly_path, union_path, scratch_path),
tarball_path_(tarball_path),
base_directory_(base_directory),
to_delete_(to_delete),
read_archive_signal_(new Signal) {
read_archive_signal_->Wakeup();
}
SyncUnionTarball::~SyncUnionTarball() { delete read_archive_signal_; }
bool SyncUnionTarball::Initialize() {
bool result;
src = archive_read_new();
assert(ARCHIVE_OK == archive_read_support_format_tar(src));
assert(ARCHIVE_OK == archive_read_support_format_empty(src));
if (tarball_path_ == "--") {
result = archive_read_open_filename(src, NULL, 4096);
} else {
std::string tarball_absolute_path = GetAbsolutePath(tarball_path_);
result =
archive_read_open_filename(src, tarball_absolute_path.c_str(), 4096);
}
if (result != ARCHIVE_OK) {
LogCvmfs(kLogUnionFs, kLogStderr, "Impossible to open the archive.");
return false;
}
return SyncUnion::Initialize();
}
void SyncUnionTarball::Traverse() {
assert(this->IsInitialized());
struct archive_entry *entry = archive_entry_new();
/*
* As first step we eliminate the directories we are request.
*/
if (to_delete_ != "") {
vector<std::string> to_eliminate_vec = SplitString(to_delete_, ':');
for (vector<string>::iterator s = to_eliminate_vec.begin();
s != to_eliminate_vec.end(); ++s) {
std::string parent_path;
std::string filename;
SplitPath(*s, &parent_path, &filename);
if (parent_path == ".") parent_path = "";
SharedPtr<SyncItem> sync_entry =
CreateSyncItem(parent_path, filename, kItemDir);
mediator_->Remove(sync_entry);
}
}
while (true) {
/* Get the lock, wait if lock is not available yet */
read_archive_signal_->Wait();
int result = archive_read_next_header2(src, entry);
switch (result) {
case ARCHIVE_FATAL: {
LogCvmfs(kLogUnionFs, kLogStderr,
"Fatal error in reading the archive.");
return;
break; /* Only exit point with error */
}
case ARCHIVE_RETRY: {
LogCvmfs(kLogUnionFs, kLogStderr,
"Error in reading the header, retrying. \n %s",
archive_error_string(src));
continue;
break;
}
case ARCHIVE_EOF: {
for (set<string>::iterator dir = to_create_catalog_dirs_.begin();
dir != to_create_catalog_dirs_.end(); ++dir) {
assert(dirs_.find(*dir) != dirs_.end());
SharedPtr<SyncItem> to_mark = dirs_[*dir];
assert(to_mark->IsDirectory());
to_mark->SetCatalogMarker();
to_mark->AlreadyCreatedDir();
ProcessDirectory(to_mark);
}
return; /* Only successful exit point */
break;
}
case ARCHIVE_WARN: {
LogCvmfs(kLogUnionFs, kLogStderr,
"Warning in uncompression reading, going on. \n %s",
archive_error_string(src));
/* We actually want this to enter the ARCHIVE_OK case */
}
case ARCHIVE_OK: {
std::string archive_file_path(archive_entry_pathname(entry));
std::string complete_path(base_directory_ + "/" + archive_file_path);
if (*complete_path.rbegin() == '/') {
complete_path.erase(complete_path.size() - 1);
}
std::string parent_path;
std::string filename;
SplitPath(complete_path, &parent_path, &filename);
CreateDirectories(parent_path);
/*
* Libarchive is not thread aware, so we need to make sure that before
* to read/"open" the next header in the archive the content of the
* present header is been consumed completely.
* Different thread read/"open" the header from the one that consumes
* it so we opted for a conditional variable.
* The conditional variable is acquire when we read the header and as
* long as it is not released we cannot read/"open" the next header.
* At the end of the pipeline, when the IngestionSource (generated by
* the SyncItem) is been 1. Opened, 2. Read, at the closing we
* actually release the conditional variable.
* This whole process is not necessary for directories since we don't
* actually need to read data from them.
*/
SharedPtr<SyncItem> sync_entry = SharedPtr<SyncItem>(new SyncItemTar(
parent_path, filename, src, entry, read_archive_signal_, this));
if (sync_entry->IsDirectory()) {
if (know_directories_.find(complete_path) !=
know_directories_.end()) {
sync_entry->AlreadyCreatedDir();
}
ProcessDirectory(sync_entry);
dirs_[complete_path] = sync_entry;
know_directories_.insert(complete_path);
read_archive_signal_->Wakeup();
} else if (sync_entry->IsRegularFile()) {
ProcessFile(sync_entry);
if (filename == ".cvmfscatalog") {
to_create_catalog_dirs_.insert(parent_path);
}
} else {
read_archive_signal_->Wakeup();
}
}
}
}
}
std::string SyncUnionTarball::UnwindWhiteoutFilename(
SharedPtr<SyncItem> entry) const {
return entry->filename();
}
bool SyncUnionTarball::IsOpaqueDirectory(SharedPtr<SyncItem> directory) const {
return false;
}
bool SyncUnionTarball::IsWhiteoutEntry(SharedPtr<SyncItem> entry) const {
return false;
}
void SyncUnionTarball::CreateDirectories(const std::string &target) {
if (know_directories_.find(target) != know_directories_.end()) return;
if (target == ".") return;
std::string dirname = "";
std::string filename = "";
SplitPath(target, &dirname, &filename);
CreateDirectories(dirname);
if (dirname == ".") dirname = "";
SharedPtr<SyncItem> dummy = SharedPtr<SyncItem>(
new SyncItemDummyDir(dirname, filename, this, kItemDir));
ProcessDirectory(dummy);
know_directories_.insert(target);
}
} // namespace publish
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2011-2017, The DART development contributors
* All rights reserved.
*
* The list of contributors can be found at:
* https://github.com/dartsim/dart/blob/master/LICENSE
*
* This file is provided under the following "BSD-style" License:
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "dart/dynamics/MeshShape.hpp"
#include <limits>
#include <string>
#include <assimp/Importer.hpp>
#include <assimp/postprocess.h>
#include <assimp/cimport.h>
#include "dart/config.hpp"
#include "dart/common/Console.hpp"
#include "dart/common/LocalResourceRetriever.hpp"
#include "dart/common/Uri.hpp"
#include "dart/dynamics/AssimpInputResourceAdaptor.hpp"
#include "dart/dynamics/BoxShape.hpp"
#if !(ASSIMP_AISCENE_CTOR_DTOR_DEFINED)
// We define our own constructor and destructor for aiScene, because it seems to
// be missing from the standard assimp library (see #451)
aiScene::aiScene()
: mFlags(0),
mRootNode(nullptr),
mNumMeshes(0),
mMeshes(nullptr),
mNumMaterials(0),
mMaterials(nullptr),
mAnimations(nullptr),
mNumTextures(0),
mTextures(nullptr),
mNumLights(0),
mLights(nullptr),
mNumCameras(0),
mCameras(nullptr)
{
}
aiScene::~aiScene()
{
delete mRootNode;
if(mNumMeshes && mMeshes)
for(std::size_t a=0; a<mNumMeshes; ++a)
delete mMeshes[a];
delete[] mMeshes;
if(mNumMaterials && mMaterials)
for(std::size_t a=0; a<mNumMaterials; ++a)
delete mMaterials[a];
delete[] mMaterials;
if(mNumAnimations && mAnimations)
for(std::size_t a=0; a<mNumAnimations; ++a)
delete mAnimations[a];
delete[] mAnimations;
if(mNumTextures && mTextures)
for(std::size_t a=0; a<mNumTextures; ++a)
delete mTextures[a];
delete[] mTextures;
if(mNumLights && mLights)
for(std::size_t a=0; a<mNumLights; ++a)
delete mLights[a];
delete[] mLights;
if(mNumCameras && mCameras)
for(std::size_t a=0; a<mNumCameras; ++a)
delete mCameras[a];
delete[] mCameras;
}
#endif // #if !(ASSIMP_AISCENE_CTOR_DTOR_DEFINED)
// We define our own constructor and destructor for aiMaterial, because it seems
// to be missing from the standard assimp library (see #451)
#if !(ASSIMP_AIMATERIAL_CTOR_DTOR_DEFINED)
aiMaterial::aiMaterial()
{
mNumProperties = 0;
mNumAllocated = 5;
mProperties = new aiMaterialProperty*[5];
for(std::size_t i=0; i<5; ++i)
mProperties[i] = nullptr;
}
aiMaterial::~aiMaterial()
{
for(std::size_t i=0; i<mNumProperties; ++i)
delete mProperties[i];
delete[] mProperties;
}
#endif // #if !(ASSIMP_AIMATERIAL_CTOR_DTOR_DEFINED)
namespace dart {
namespace dynamics {
MeshShape::MeshShape(const Eigen::Vector3d& _scale, const aiScene* _mesh,
const std::string& _path,
const common::ResourceRetrieverPtr& _resourceRetriever)
: Shape(MESH),
mResourceRetriever(_resourceRetriever),
mDisplayList(0),
mColorMode(MATERIAL_COLOR),
mColorIndex(0)
{
assert(_scale[0] > 0.0);
assert(_scale[1] > 0.0);
assert(_scale[2] > 0.0);
setMesh(_mesh, _path, _resourceRetriever);
setScale(_scale);
}
MeshShape::~MeshShape() {
delete mMesh;
}
//==============================================================================
const std::string& MeshShape::getType() const
{
return getStaticType();
}
//==============================================================================
const std::string& MeshShape::getStaticType()
{
static const std::string type("MeshShape");
return type;
}
const aiScene* MeshShape::getMesh() const {
return mMesh;
}
const std::string& MeshShape::getMeshUri() const
{
return mMeshUri;
}
void MeshShape::update()
{
// Do nothing
}
//==============================================================================
void MeshShape::notifyAlphaUpdated(double alpha)
{
for(std::size_t i=0; i<mMesh->mNumMeshes; ++i)
{
aiMesh* mesh = mMesh->mMeshes[i];
for(std::size_t j=0; j<mesh->mNumVertices; ++j)
mesh->mColors[0][j][3] = alpha;
}
}
const std::string& MeshShape::getMeshPath() const
{
return mMeshPath;
}
void MeshShape::setMesh(
const aiScene* _mesh, const std::string& _path,
const common::ResourceRetrieverPtr& _resourceRetriever)
{
mMesh = _mesh;
if(nullptr == _mesh) {
mMeshPath = "";
mMeshUri = "";
mResourceRetriever = nullptr;
return;
}
common::Uri uri;
if(uri.fromString(_path))
{
mMeshUri = _path;
if(uri.mScheme.get_value_or("file") == "file")
mMeshPath = uri.mPath.get_value_or("");
}
else
{
dtwarn << "[MeshShape::setMesh] Failed parsing URI '" << _path << "'.\n";
mMeshUri = "";
mMeshPath = "";
}
mResourceRetriever = _resourceRetriever;
_updateBoundingBoxDim();
updateVolume();
}
void MeshShape::setScale(const Eigen::Vector3d& _scale) {
assert(_scale[0] > 0.0);
assert(_scale[1] > 0.0);
assert(_scale[2] > 0.0);
mScale = _scale;
updateVolume();
_updateBoundingBoxDim();
}
const Eigen::Vector3d& MeshShape::getScale() const {
return mScale;
}
void MeshShape::setColorMode(ColorMode _mode)
{
mColorMode = _mode;
}
MeshShape::ColorMode MeshShape::getColorMode() const
{
return mColorMode;
}
void MeshShape::setColorIndex(int _index)
{
mColorIndex = _index;
}
int MeshShape::getColorIndex() const
{
return mColorIndex;
}
int MeshShape::getDisplayList() const {
return mDisplayList;
}
void MeshShape::setDisplayList(int _index) {
mDisplayList = _index;
}
//==============================================================================
Eigen::Matrix3d MeshShape::computeInertia(double _mass) const
{
// Use bounding box to represent the mesh
return BoxShape::computeInertia(mBoundingBox.computeFullExtents(), _mass);
}
void MeshShape::updateVolume() {
Eigen::Vector3d bounds = mBoundingBox.computeFullExtents();
mVolume = bounds.x() * bounds.y() * bounds.z();
}
void MeshShape::_updateBoundingBoxDim() {
if(!mMesh)
{
mBoundingBox.setMin(Eigen::Vector3d::Zero());
mBoundingBox.setMax(Eigen::Vector3d::Zero());
return;
}
double max_X = -std::numeric_limits<double>::infinity();
double max_Y = -std::numeric_limits<double>::infinity();
double max_Z = -std::numeric_limits<double>::infinity();
double min_X = std::numeric_limits<double>::infinity();
double min_Y = std::numeric_limits<double>::infinity();
double min_Z = std::numeric_limits<double>::infinity();
for (unsigned int i = 0; i < mMesh->mNumMeshes; i++) {
for (unsigned int j = 0; j < mMesh->mMeshes[i]->mNumVertices; j++) {
if (mMesh->mMeshes[i]->mVertices[j].x > max_X)
max_X = mMesh->mMeshes[i]->mVertices[j].x;
if (mMesh->mMeshes[i]->mVertices[j].x < min_X)
min_X = mMesh->mMeshes[i]->mVertices[j].x;
if (mMesh->mMeshes[i]->mVertices[j].y > max_Y)
max_Y = mMesh->mMeshes[i]->mVertices[j].y;
if (mMesh->mMeshes[i]->mVertices[j].y < min_Y)
min_Y = mMesh->mMeshes[i]->mVertices[j].y;
if (mMesh->mMeshes[i]->mVertices[j].z > max_Z)
max_Z = mMesh->mMeshes[i]->mVertices[j].z;
if (mMesh->mMeshes[i]->mVertices[j].z < min_Z)
min_Z = mMesh->mMeshes[i]->mVertices[j].z;
}
}
mBoundingBox.setMin(Eigen::Vector3d(min_X * mScale[0], min_Y * mScale[1], min_Z * mScale[2]));
mBoundingBox.setMax(Eigen::Vector3d(max_X * mScale[0], max_Y * mScale[1], max_Z * mScale[2]));
}
const aiScene* MeshShape::loadMesh(
const std::string& _uri, const common::ResourceRetrieverPtr& _retriever)
{
// Remove points and lines from the import.
aiPropertyStore* propertyStore = aiCreatePropertyStore();
aiSetImportPropertyInteger(propertyStore,
AI_CONFIG_PP_SBP_REMOVE,
aiPrimitiveType_POINT
| aiPrimitiveType_LINE
);
// Wrap ResourceRetriever in an IOSystem from Assimp's C++ API. Then wrap
// the IOSystem in an aiFileIO from Assimp's C API. Yes, this API is
// completely ridiculous...
AssimpInputResourceRetrieverAdaptor systemIO(_retriever);
aiFileIO fileIO = createFileIO(&systemIO);
// Import the file.
const aiScene* scene = aiImportFileExWithProperties(
_uri.c_str(),
aiProcess_GenNormals
| aiProcess_Triangulate
| aiProcess_JoinIdenticalVertices
| aiProcess_SortByPType
| aiProcess_OptimizeMeshes,
&fileIO,
propertyStore
);
// If succeeded, store the importer in the scene to keep it alive. This is
// necessary because the importer owns the memory that it allocates.
if(!scene)
{
dtwarn << "[MeshShape::loadMesh] Failed loading mesh '" << _uri << "'.\n";
return nullptr;
}
// Assimp rotates collada files such that the up-axis (specified in the
// collada file) aligns with assimp's y-axis. Here we are reverting this
// rotation. We are only catching files with the .dae file ending here. We
// might miss files with an .xml file ending, which would need to be looked
// into to figure out whether they are collada files.
std::string extension;
const std::size_t extensionIndex = _uri.find_last_of('.');
if(extensionIndex != std::string::npos)
extension = _uri.substr(extensionIndex);
std::transform(std::begin(extension), std::end(extension),
std::begin(extension), ::tolower);
if(extension == ".dae" || extension == ".zae")
scene->mRootNode->mTransformation = aiMatrix4x4();
// Finally, pre-transform the vertices. We can't do this as part of the
// import process, because we may have changed mTransformation above.
scene = aiApplyPostProcessing(scene, aiProcess_PreTransformVertices);
if(!scene)
dtwarn << "[MeshShape::loadMesh] Failed pre-transforming vertices.\n";
return scene;
}
const aiScene* MeshShape::loadMesh(const std::string& _fileName)
{
const auto retriever = std::make_shared<common::LocalResourceRetriever>();
return loadMesh("file://" + _fileName, retriever);
}
} // namespace dynamics
} // namespace dart
<commit_msg>Fix for #734 (#958)<commit_after>/*
* Copyright (c) 2011-2017, The DART development contributors
* All rights reserved.
*
* The list of contributors can be found at:
* https://github.com/dartsim/dart/blob/master/LICENSE
*
* This file is provided under the following "BSD-style" License:
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "dart/dynamics/MeshShape.hpp"
#include <limits>
#include <string>
#include <assimp/Importer.hpp>
#include <assimp/postprocess.h>
#include <assimp/cimport.h>
#include "dart/config.hpp"
#include "dart/common/Console.hpp"
#include "dart/common/LocalResourceRetriever.hpp"
#include "dart/common/Uri.hpp"
#include "dart/dynamics/AssimpInputResourceAdaptor.hpp"
#include "dart/dynamics/BoxShape.hpp"
#if !(ASSIMP_AISCENE_CTOR_DTOR_DEFINED)
// We define our own constructor and destructor for aiScene, because it seems to
// be missing from the standard assimp library (see #451)
aiScene::aiScene()
: mFlags(0),
mRootNode(nullptr),
mNumMeshes(0),
mMeshes(nullptr),
mNumMaterials(0),
mMaterials(nullptr),
mAnimations(nullptr),
mNumTextures(0),
mTextures(nullptr),
mNumLights(0),
mLights(nullptr),
mNumCameras(0),
mCameras(nullptr)
{
}
aiScene::~aiScene()
{
delete mRootNode;
if(mNumMeshes && mMeshes)
for(std::size_t a=0; a<mNumMeshes; ++a)
delete mMeshes[a];
delete[] mMeshes;
if(mNumMaterials && mMaterials)
for(std::size_t a=0; a<mNumMaterials; ++a)
delete mMaterials[a];
delete[] mMaterials;
if(mNumAnimations && mAnimations)
for(std::size_t a=0; a<mNumAnimations; ++a)
delete mAnimations[a];
delete[] mAnimations;
if(mNumTextures && mTextures)
for(std::size_t a=0; a<mNumTextures; ++a)
delete mTextures[a];
delete[] mTextures;
if(mNumLights && mLights)
for(std::size_t a=0; a<mNumLights; ++a)
delete mLights[a];
delete[] mLights;
if(mNumCameras && mCameras)
for(std::size_t a=0; a<mNumCameras; ++a)
delete mCameras[a];
delete[] mCameras;
}
#endif // #if !(ASSIMP_AISCENE_CTOR_DTOR_DEFINED)
// We define our own constructor and destructor for aiMaterial, because it seems
// to be missing from the standard assimp library (see #451)
#if !(ASSIMP_AIMATERIAL_CTOR_DTOR_DEFINED)
aiMaterial::aiMaterial()
{
mNumProperties = 0;
mNumAllocated = 5;
mProperties = new aiMaterialProperty*[5];
for(std::size_t i=0; i<5; ++i)
mProperties[i] = nullptr;
}
aiMaterial::~aiMaterial()
{
for(std::size_t i=0; i<mNumProperties; ++i)
delete mProperties[i];
delete[] mProperties;
}
#endif // #if !(ASSIMP_AIMATERIAL_CTOR_DTOR_DEFINED)
namespace dart {
namespace dynamics {
MeshShape::MeshShape(const Eigen::Vector3d& _scale, const aiScene* _mesh,
const std::string& _path,
const common::ResourceRetrieverPtr& _resourceRetriever)
: Shape(MESH),
mResourceRetriever(_resourceRetriever),
mDisplayList(0),
mColorMode(MATERIAL_COLOR),
mColorIndex(0)
{
assert(_scale[0] > 0.0);
assert(_scale[1] > 0.0);
assert(_scale[2] > 0.0);
setMesh(_mesh, _path, _resourceRetriever);
setScale(_scale);
}
MeshShape::~MeshShape() {
delete mMesh;
}
//==============================================================================
const std::string& MeshShape::getType() const
{
return getStaticType();
}
//==============================================================================
const std::string& MeshShape::getStaticType()
{
static const std::string type("MeshShape");
return type;
}
const aiScene* MeshShape::getMesh() const {
return mMesh;
}
const std::string& MeshShape::getMeshUri() const
{
return mMeshUri;
}
void MeshShape::update()
{
// Do nothing
}
//==============================================================================
void MeshShape::notifyAlphaUpdated(double alpha)
{
for(std::size_t i=0; i<mMesh->mNumMeshes; ++i)
{
aiMesh* mesh = mMesh->mMeshes[i];
for(std::size_t j=0; j<mesh->mNumVertices; ++j)
mesh->mColors[0][j][3] = alpha;
}
}
const std::string& MeshShape::getMeshPath() const
{
return mMeshPath;
}
void MeshShape::setMesh(
const aiScene* _mesh, const std::string& _path,
const common::ResourceRetrieverPtr& _resourceRetriever)
{
mMesh = _mesh;
if(nullptr == _mesh) {
mMeshPath = "";
mMeshUri = "";
mResourceRetriever = nullptr;
return;
}
common::Uri uri;
if(uri.fromString(_path))
{
mMeshUri = _path;
if(uri.mScheme.get_value_or("file") == "file")
mMeshPath = uri.mPath.get_value_or("");
}
else
{
dtwarn << "[MeshShape::setMesh] Failed parsing URI '" << _path << "'.\n";
mMeshUri = "";
mMeshPath = "";
}
mResourceRetriever = _resourceRetriever;
_updateBoundingBoxDim();
updateVolume();
}
void MeshShape::setScale(const Eigen::Vector3d& _scale) {
assert(_scale[0] > 0.0);
assert(_scale[1] > 0.0);
assert(_scale[2] > 0.0);
mScale = _scale;
_updateBoundingBoxDim();
updateVolume();
}
const Eigen::Vector3d& MeshShape::getScale() const {
return mScale;
}
void MeshShape::setColorMode(ColorMode _mode)
{
mColorMode = _mode;
}
MeshShape::ColorMode MeshShape::getColorMode() const
{
return mColorMode;
}
void MeshShape::setColorIndex(int _index)
{
mColorIndex = _index;
}
int MeshShape::getColorIndex() const
{
return mColorIndex;
}
int MeshShape::getDisplayList() const {
return mDisplayList;
}
void MeshShape::setDisplayList(int _index) {
mDisplayList = _index;
}
//==============================================================================
Eigen::Matrix3d MeshShape::computeInertia(double _mass) const
{
// Use bounding box to represent the mesh
return BoxShape::computeInertia(mBoundingBox.computeFullExtents(), _mass);
}
void MeshShape::updateVolume() {
Eigen::Vector3d bounds = mBoundingBox.computeFullExtents();
mVolume = bounds.x() * bounds.y() * bounds.z();
}
void MeshShape::_updateBoundingBoxDim() {
if(!mMesh)
{
mBoundingBox.setMin(Eigen::Vector3d::Zero());
mBoundingBox.setMax(Eigen::Vector3d::Zero());
return;
}
double max_X = -std::numeric_limits<double>::infinity();
double max_Y = -std::numeric_limits<double>::infinity();
double max_Z = -std::numeric_limits<double>::infinity();
double min_X = std::numeric_limits<double>::infinity();
double min_Y = std::numeric_limits<double>::infinity();
double min_Z = std::numeric_limits<double>::infinity();
for (unsigned int i = 0; i < mMesh->mNumMeshes; i++) {
for (unsigned int j = 0; j < mMesh->mMeshes[i]->mNumVertices; j++) {
if (mMesh->mMeshes[i]->mVertices[j].x > max_X)
max_X = mMesh->mMeshes[i]->mVertices[j].x;
if (mMesh->mMeshes[i]->mVertices[j].x < min_X)
min_X = mMesh->mMeshes[i]->mVertices[j].x;
if (mMesh->mMeshes[i]->mVertices[j].y > max_Y)
max_Y = mMesh->mMeshes[i]->mVertices[j].y;
if (mMesh->mMeshes[i]->mVertices[j].y < min_Y)
min_Y = mMesh->mMeshes[i]->mVertices[j].y;
if (mMesh->mMeshes[i]->mVertices[j].z > max_Z)
max_Z = mMesh->mMeshes[i]->mVertices[j].z;
if (mMesh->mMeshes[i]->mVertices[j].z < min_Z)
min_Z = mMesh->mMeshes[i]->mVertices[j].z;
}
}
mBoundingBox.setMin(Eigen::Vector3d(min_X * mScale[0], min_Y * mScale[1], min_Z * mScale[2]));
mBoundingBox.setMax(Eigen::Vector3d(max_X * mScale[0], max_Y * mScale[1], max_Z * mScale[2]));
}
const aiScene* MeshShape::loadMesh(
const std::string& _uri, const common::ResourceRetrieverPtr& _retriever)
{
// Remove points and lines from the import.
aiPropertyStore* propertyStore = aiCreatePropertyStore();
aiSetImportPropertyInteger(propertyStore,
AI_CONFIG_PP_SBP_REMOVE,
aiPrimitiveType_POINT
| aiPrimitiveType_LINE
);
// Wrap ResourceRetriever in an IOSystem from Assimp's C++ API. Then wrap
// the IOSystem in an aiFileIO from Assimp's C API. Yes, this API is
// completely ridiculous...
AssimpInputResourceRetrieverAdaptor systemIO(_retriever);
aiFileIO fileIO = createFileIO(&systemIO);
// Import the file.
const aiScene* scene = aiImportFileExWithProperties(
_uri.c_str(),
aiProcess_GenNormals
| aiProcess_Triangulate
| aiProcess_JoinIdenticalVertices
| aiProcess_SortByPType
| aiProcess_OptimizeMeshes,
&fileIO,
propertyStore
);
// If succeeded, store the importer in the scene to keep it alive. This is
// necessary because the importer owns the memory that it allocates.
if(!scene)
{
dtwarn << "[MeshShape::loadMesh] Failed loading mesh '" << _uri << "'.\n";
return nullptr;
}
// Assimp rotates collada files such that the up-axis (specified in the
// collada file) aligns with assimp's y-axis. Here we are reverting this
// rotation. We are only catching files with the .dae file ending here. We
// might miss files with an .xml file ending, which would need to be looked
// into to figure out whether they are collada files.
std::string extension;
const std::size_t extensionIndex = _uri.find_last_of('.');
if(extensionIndex != std::string::npos)
extension = _uri.substr(extensionIndex);
std::transform(std::begin(extension), std::end(extension),
std::begin(extension), ::tolower);
if(extension == ".dae" || extension == ".zae")
scene->mRootNode->mTransformation = aiMatrix4x4();
// Finally, pre-transform the vertices. We can't do this as part of the
// import process, because we may have changed mTransformation above.
scene = aiApplyPostProcessing(scene, aiProcess_PreTransformVertices);
if(!scene)
dtwarn << "[MeshShape::loadMesh] Failed pre-transforming vertices.\n";
return scene;
}
const aiScene* MeshShape::loadMesh(const std::string& _fileName)
{
const auto retriever = std::make_shared<common::LocalResourceRetriever>();
return loadMesh("file://" + _fileName, retriever);
}
} // namespace dynamics
} // namespace dart
<|endoftext|> |
<commit_before>#ifndef VIENNAGRID_IO_POLY_READER_GUARD
#define VIENNAGRID_IO_POLY_READER_GUARD
/* =======================================================================
Copyright (c) 2011-2013, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
-----------------
ViennaGrid - The Vienna Grid Library
-----------------
License: MIT (X11), see file LICENSE in the base directory
======================================================================= */
#include <fstream>
#include <iostream>
#include <assert.h>
#include "viennagrid/forwards.hpp"
#include "viennagrid/io/helper.hpp"
#include "viennagrid/mesh/mesh.hpp"
/** @file viennagrid/io/tetgen_poly_reader.hpp
@brief Provides a reader for Tetgen .poly files. See http://wias-berlin.de/software/tetgen/fformats.poly.html
*/
namespace viennagrid
{
namespace io
{
template<typename stream_type>
bool get_valid_line( stream_type & stream, std::string & line, char comment_line = '#' )
{
std::string tmp;
while (true)
{
if (!std::getline(stream, tmp))
return false;
std::size_t pos = tmp.find(comment_line);
if (pos != std::string::npos)
tmp = tmp.substr(0, pos);
for (std::size_t i = 0; i != tmp.size(); ++i)
{
if ( tmp[i] != ' ' )
{
line = tmp.substr(i, std::string::npos);
return true;
}
}
}
}
/** @brief Reader for Tetgen .poly files.
*
* See http://wias-berlin.de/software/tetgen/fformats.poly.html for a description of the file format
*/
struct tetgen_poly_reader
{
/** @brief The functor interface triggering the read operation. Segmentations are not supported in this version.
*
* @param mesh_obj The mesh where the file content is written to
* @param filename Name of the file
*/
template <typename MeshT>
int operator()(MeshT & mesh_obj, std::string const & filename) const
{
typedef typename viennagrid::result_of::point<MeshT>::type PointType;
static const int point_dim = viennagrid::result_of::static_size<PointType>::value;
typedef typename result_of::element<MeshT, vertex_tag>::type VertexType;
typedef typename result_of::handle<MeshT, vertex_tag>::type VertexHandleType;
typedef typename VertexType::id_type VertexIDType;
typedef typename result_of::handle<MeshT, line_tag>::type LineHandleType;
std::ifstream reader(filename.c_str());
#if defined VIENNAGRID_DEBUG_STATUS || defined VIENNAGRID_DEBUG_IO
std::cout << "* poly_reader::operator(): Reading file " << filename << std::endl;
#endif
if (!reader)
{
throw cannot_open_file_exception(filename);
return EXIT_FAILURE;
}
std::string tmp;
std::istringstream current_line;
long node_num = 0;
long dim = 0;
long attribute_num = 0;
long boundary_marker_num = 0;
if (!reader.good())
throw bad_file_format_exception(filename, "File is empty.");
//
// Read vertices:
//
if (!get_valid_line(reader, tmp))
throw bad_file_format_exception(filename, "EOF encountered when reading information");
current_line.str(tmp); current_line.clear();
current_line >> node_num >> dim >> attribute_num >> boundary_marker_num;
if (node_num < 0)
throw bad_file_format_exception(filename, "POLY file has less than 0 nodes");
if (dim != point_dim)
throw bad_file_format_exception(filename, "POLY point dimension missmatch");
if (attribute_num < 0)
throw bad_file_format_exception(filename, "POLY file has less than 0 attributes");
if ((boundary_marker_num < 0) || (boundary_marker_num > 1))
throw bad_file_format_exception(filename, "POLY file has not 0 or 1 boundary marker");
#if defined VIENNAGRID_DEBUG_STATUS || defined VIENNAGRID_DEBUG_IO
std::cout << "* poly_reader::operator(): Reading " << node_num << " vertices... " << std::endl;
#endif
for (int i=0; i<node_num; i++)
{
if (!get_valid_line(reader, tmp))
throw bad_file_format_exception(filename, "EOF encountered when reading information");
typename VertexIDType::base_id_type id;
current_line.str(tmp); current_line.clear();
current_line >> id;
PointType p;
for (int j=0; j<point_dim; j++)
current_line >> p[j];
/*VertexHandleType vertex =*/ viennagrid::make_vertex_with_id( mesh_obj, VertexIDType(id), p );
// if (attribute_num > 0)
// {
// std::vector<CoordType> attributes(attribute_num);
// for (int j=0; j<attribute_num; j++)
// current_line >> attributes[j];
//
// // TODO fix using accesor or appendix!
// // viennadata::access<poly_attribute_tag, std::vector<CoordType> >()(viennagrid::dereference_handle(mesh_obj, vertex)) = attributes;
// }
}
//std::cout << "DONE" << std::endl;
if (!reader.good())
throw bad_file_format_exception(filename, "EOF encountered when reading number of cells.");
//
// Read facets:
//
long facet_num = 0;
if (!get_valid_line(reader, tmp))
throw bad_file_format_exception(filename, "EOF encountered when reading information");
current_line.str(tmp); current_line.clear();
current_line >> facet_num >> boundary_marker_num;
if (facet_num < 0)
throw bad_file_format_exception(filename, "POLY file has less than 0 facets");
if ((boundary_marker_num < 0) || (boundary_marker_num > 1))
throw bad_file_format_exception(filename, "POLY file has not 0 or 1 boundary marker");
#if defined VIENNAGRID_DEBUG_STATUS || defined VIENNAGRID_DEBUG_IO
std::cout << "* netgen_reader::operator(): Reading " << cell_num << " cells... " << std::endl;
#endif
for (int i=0; i<facet_num; ++i)
{
long polygon_num;
long hole_num;
if (!get_valid_line(reader, tmp))
throw bad_file_format_exception(filename, "EOF encountered when reading information");
current_line.str(tmp); current_line.clear();
current_line >> polygon_num >> hole_num;
if (polygon_num < 0)
throw bad_file_format_exception(filename, "POLY facet has less than 0 polygons");
if (hole_num < 0)
throw bad_file_format_exception(filename, "POLY facet has less than 0 holes");
std::list<LineHandleType> lines;
std::list<VertexHandleType> vertices;
for (int j = 0; j<polygon_num; ++j)
{
long vertex_num;
if (!get_valid_line(reader, tmp))
throw bad_file_format_exception(filename, "EOF encountered when reading information");
current_line.str(tmp); current_line.clear();
current_line >> vertex_num;
if (vertex_num < 0)
throw bad_file_format_exception(filename, "POLY polygon has less than 0 vertices");
std::vector<VertexHandleType> vertex_handles(vertex_num);
for (int k = 0; k<vertex_num; ++k)
{
long id;
current_line >> id;
vertex_handles[k] = viennagrid::find( mesh_obj, VertexIDType(id) ).handle();
}
if (vertex_num == 1)
{
vertices.push_back( vertex_handles.front() );
}
else if (vertex_num == 2)
{
lines.push_back( viennagrid::make_line(mesh_obj, vertex_handles[0], vertex_handles[1]) );
}
else
{
typename std::vector<VertexHandleType>::iterator it1 = vertex_handles.begin();
typename std::vector<VertexHandleType>::iterator it2 = it1; ++it2;
for (; it2 != vertex_handles.end(); ++it1, ++it2)
lines.push_back( viennagrid::make_line(mesh_obj, *it1, *it2) );
lines.push_back( viennagrid::make_line(mesh_obj, vertex_handles.back(), vertex_handles.front()) );
}
}
std::list<PointType> hole_points;
for (int j = 0; j<hole_num; ++j)
{
if (!get_valid_line(reader, tmp))
throw bad_file_format_exception(filename, "EOF encountered when reading information");
long hole_id;
current_line.str(tmp); current_line.clear();
current_line >> hole_id;
PointType p;
for (int j=0; j<point_dim; j++)
current_line >> p[j];
hole_points.push_back(p);
}
viennagrid::make_plc(
mesh_obj,
lines.begin(), lines.end(),
vertices.begin(), vertices.end(),
hole_points.begin(), hole_points.end()
);
}
return EXIT_SUCCESS;
} //operator()
}; //class tetgen_poly_reader
} //namespace io
} //namespace viennagrid
#endif
<commit_msg>Added support for volumetric hole and seed points<commit_after>#ifndef VIENNAGRID_IO_POLY_READER_GUARD
#define VIENNAGRID_IO_POLY_READER_GUARD
/* =======================================================================
Copyright (c) 2011-2013, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
-----------------
ViennaGrid - The Vienna Grid Library
-----------------
License: MIT (X11), see file LICENSE in the base directory
======================================================================= */
#include <fstream>
#include <iostream>
#include <assert.h>
#include "viennagrid/forwards.hpp"
#include "viennagrid/io/helper.hpp"
#include "viennagrid/mesh/mesh.hpp"
/** @file viennagrid/io/tetgen_poly_reader.hpp
@brief Provides a reader for Tetgen .poly files. See http://wias-berlin.de/software/tetgen/fformats.poly.html
*/
namespace viennagrid
{
namespace io
{
template<typename stream_type>
bool get_valid_line( stream_type & stream, std::string & line, char comment_line = '#' )
{
std::string tmp;
while (true)
{
if (!std::getline(stream, tmp))
return false;
std::size_t pos = tmp.find(comment_line);
if (pos != std::string::npos)
tmp = tmp.substr(0, pos);
for (std::size_t i = 0; i != tmp.size(); ++i)
{
if ( tmp[i] != ' ' )
{
line = tmp.substr(i, std::string::npos);
return true;
}
}
}
}
/** @brief Reader for Tetgen .poly files.
*
* See http://wias-berlin.de/software/tetgen/fformats.poly.html for a description of the file format
*/
struct tetgen_poly_reader
{
/** @brief The functor interface triggering the read operation. Segmentations are not supported in this version.
*
* @param mesh_obj The mesh where the file content is written to
* @param filename Name of the file
*/
template <typename MeshT>
int operator()(MeshT & mesh_obj, std::string const & filename) const
{
std::vector< typename viennagrid::result_of::point<MeshT>::type > hole_points;
std::vector< std::pair<typename viennagrid::result_of::point<MeshT>::type, int> > seed_points;
return (*this)(mesh_obj, filename, hole_points, seed_points);
}
template <typename MeshT>
int operator()(MeshT & mesh_obj, std::string const & filename,
std::vector< typename viennagrid::result_of::point<MeshT>::type > & hole_points) const
{
std::vector< std::pair<typename viennagrid::result_of::point<MeshT>::type, int> > seed_points;
return (*this)(mesh_obj, filename, hole_points, seed_points);
}
template <typename MeshT>
int operator()(MeshT & mesh_obj, std::string const & filename,
std::vector< std::pair<typename viennagrid::result_of::point<MeshT>::type, int> > & seed_points) const
{
std::vector< typename viennagrid::result_of::point<MeshT>::type > hole_points;
return (*this)(mesh_obj, filename, hole_points, seed_points);
}
template <typename MeshT>
int operator()(MeshT & mesh_obj, std::string const & filename,
std::vector< typename viennagrid::result_of::point<MeshT>::type > & hole_points,
std::vector< std::pair<typename viennagrid::result_of::point<MeshT>::type, int> > & seed_points) const
{
typedef typename viennagrid::result_of::point<MeshT>::type PointType;
static const int point_dim = viennagrid::result_of::static_size<PointType>::value;
typedef typename result_of::element<MeshT, vertex_tag>::type VertexType;
typedef typename result_of::handle<MeshT, vertex_tag>::type VertexHandleType;
typedef typename VertexType::id_type VertexIDType;
typedef typename result_of::handle<MeshT, line_tag>::type LineHandleType;
std::ifstream reader(filename.c_str());
#if defined VIENNAGRID_DEBUG_STATUS || defined VIENNAGRID_DEBUG_IO
std::cout << "* poly_reader::operator(): Reading file " << filename << std::endl;
#endif
if (!reader)
{
throw cannot_open_file_exception(filename);
return EXIT_FAILURE;
}
hole_points.clear();
seed_points.clear();
std::string tmp;
std::istringstream current_line;
long node_num = 0;
long dim = 0;
long attribute_num = 0;
long boundary_marker_num = 0;
if (!reader.good())
throw bad_file_format_exception(filename, "File is empty.");
//
// Read vertices:
//
if (!get_valid_line(reader, tmp))
throw bad_file_format_exception(filename, "EOF encountered when reading information");
current_line.str(tmp); current_line.clear();
current_line >> node_num >> dim >> attribute_num >> boundary_marker_num;
if (node_num < 0)
throw bad_file_format_exception(filename, "POLY file has less than 0 nodes");
if (dim != point_dim)
throw bad_file_format_exception(filename, "POLY point dimension missmatch");
if (attribute_num < 0)
throw bad_file_format_exception(filename, "POLY file has less than 0 attributes");
if ((boundary_marker_num < 0) || (boundary_marker_num > 1))
throw bad_file_format_exception(filename, "POLY file has not 0 or 1 boundary marker");
#if defined VIENNAGRID_DEBUG_STATUS || defined VIENNAGRID_DEBUG_IO
std::cout << "* poly_reader::operator(): Reading " << node_num << " vertices... " << std::endl;
#endif
for (int i=0; i<node_num; i++)
{
if (!get_valid_line(reader, tmp))
throw bad_file_format_exception(filename, "EOF encountered when reading information");
typename VertexIDType::base_id_type id;
current_line.str(tmp); current_line.clear();
current_line >> id;
PointType p;
for (int j=0; j<point_dim; j++)
current_line >> p[j];
viennagrid::make_vertex_with_id( mesh_obj, VertexIDType(id), p );
}
if (!reader.good())
throw bad_file_format_exception(filename, "EOF encountered when reading number of cells.");
//
// Read facets:
//
long facet_num = 0;
if (!get_valid_line(reader, tmp))
throw bad_file_format_exception(filename, "EOF encountered when reading information");
current_line.str(tmp); current_line.clear();
current_line >> facet_num >> boundary_marker_num;
if (facet_num < 0)
throw bad_file_format_exception(filename, "POLY file has less than 0 facets");
if ((boundary_marker_num < 0) || (boundary_marker_num > 1))
throw bad_file_format_exception(filename, "POLY file has not 0 or 1 boundary marker");
#if defined VIENNAGRID_DEBUG_STATUS || defined VIENNAGRID_DEBUG_IO
std::cout << "* netgen_reader::operator(): Reading " << cell_num << " cells... " << std::endl;
#endif
for (int i=0; i<facet_num; ++i)
{
long polygon_num;
long hole_num;
if (!get_valid_line(reader, tmp))
throw bad_file_format_exception(filename, "EOF encountered when reading information");
current_line.str(tmp); current_line.clear();
current_line >> polygon_num >> hole_num;
if (polygon_num < 0)
throw bad_file_format_exception(filename, "POLY facet has less than 0 polygons");
if (hole_num < 0)
throw bad_file_format_exception(filename, "POLY facet has less than 0 holes");
std::list<LineHandleType> lines;
std::list<VertexHandleType> vertices;
for (int j = 0; j<polygon_num; ++j)
{
long vertex_num;
if (!get_valid_line(reader, tmp))
throw bad_file_format_exception(filename, "EOF encountered when reading information");
current_line.str(tmp); current_line.clear();
current_line >> vertex_num;
if (vertex_num < 0)
throw bad_file_format_exception(filename, "POLY polygon has less than 0 vertices");
std::vector<VertexHandleType> vertex_handles(vertex_num);
for (int k = 0; k<vertex_num; ++k)
{
long id;
current_line >> id;
vertex_handles[k] = viennagrid::find( mesh_obj, VertexIDType(id) ).handle();
}
if (vertex_num == 1)
{
vertices.push_back( vertex_handles.front() );
}
else if (vertex_num == 2)
{
lines.push_back( viennagrid::make_line(mesh_obj, vertex_handles[0], vertex_handles[1]) );
}
else
{
typename std::vector<VertexHandleType>::iterator it1 = vertex_handles.begin();
typename std::vector<VertexHandleType>::iterator it2 = it1; ++it2;
for (; it2 != vertex_handles.end(); ++it1, ++it2)
lines.push_back( viennagrid::make_line(mesh_obj, *it1, *it2) );
lines.push_back( viennagrid::make_line(mesh_obj, vertex_handles.back(), vertex_handles.front()) );
}
}
std::list<PointType> hole_points;
for (int j = 0; j<hole_num; ++j)
{
if (!get_valid_line(reader, tmp))
throw bad_file_format_exception(filename, "EOF encountered when reading information");
long hole_id;
current_line.str(tmp); current_line.clear();
current_line >> hole_id;
PointType p;
for (int j=0; j<point_dim; j++)
current_line >> p[j];
hole_points.push_back(p);
}
viennagrid::make_plc(
mesh_obj,
lines.begin(), lines.end(),
vertices.begin(), vertices.end(),
hole_points.begin(), hole_points.end()
);
}
long hole_num;
if (!get_valid_line(reader, tmp))
{
// no holes -> Okay, SUCCESS xD
return EXIT_SUCCESS;
}
current_line.str(tmp); current_line.clear();
current_line >> hole_num;
if (hole_num < 0)
throw bad_file_format_exception(filename, "POLY file has less than 0 holes");
for (int i=0; i<hole_num; ++i)
{
if (!get_valid_line(reader, tmp))
throw bad_file_format_exception(filename, "EOF encountered when reading information");
long hole_number;
PointType hole_point;
current_line.str(tmp); current_line.clear();
current_line >> hole_number;
for (int j=0; j < point_dim; j++)
current_line >> hole_point[j];
hole_points.push_back( hole_point );
}
long segment_num;
if (!get_valid_line(reader, tmp))
{
// no region -> SUCCESS xD
return EXIT_SUCCESS;
}
current_line.str(tmp); current_line.clear();
current_line >> segment_num;
if (segment_num < 0)
throw bad_file_format_exception(filename, "POLY file has less than 0 segments");
for (int i=0; i<segment_num; ++i)
{
if (!get_valid_line(reader, tmp))
throw bad_file_format_exception(filename, "EOF encountered when reading information");
long segment_number;
PointType seed_point;
int segment_id;
current_line.str(tmp); current_line.clear();
current_line >> segment_number;
for (int j=0; j < point_dim; j++)
current_line >> seed_point[j];
current_line >> segment_id;
seed_points.push_back( std::make_pair(seed_point, segment_id) );
}
return EXIT_SUCCESS;
} //operator()
}; //class tetgen_poly_reader
} //namespace io
} //namespace viennagrid
#endif
<|endoftext|> |
<commit_before>/// HEADER
#include "blob_detector.h"
/// COMPONENT
#include <vision_plugins/cvblob.h>
/// PROJECT
#include <csapex_core_plugins/vector_message.h>
#include <csapex_vision/cv_mat_message.h>
#include <csapex_vision/roi_message.h>
#include <csapex_vision_features/keypoint_message.h>
/// PROJECT
#include <csapex/msg/output.h>
#include <csapex/msg/input.h>
#include <utils_param/parameter_factory.h>
#include <csapex/utility/register_apex_plugin.h>
#include <csapex/model/node_modifier.h>
/// SYSTEM
#include <sstream>
CSAPEX_REGISTER_CLASS(csapex::BlobDetector, csapex::Node)
using namespace csapex;
using namespace connection_types;
using namespace cvb;
BlobDetector::BlobDetector()
{
addParameter(param::ParameterFactory::declareBool("RoiInformation",
param::ParameterDescription("Show the information of each RoI"),
false));
addParameter(param::ParameterFactory::declareRange("min_size/w", 1, 1024, 1, 1));
addParameter(param::ParameterFactory::declareRange("min_size/h", 1, 1024, 1, 1));
}
BlobDetector::~BlobDetector()
{
}
#define _HSV2RGB_(H, S, V, R, G, B) \
{ \
double _h = H/60.; \
int _hf = (int)floor(_h); \
int _hi = ((int)_h)%6; \
double _f = _h - _hf; \
\
double _p = V * (1. - S); \
double _q = V * (1. - _f * S); \
double _t = V * (1. - (1. - _f) * S); \
\
switch (_hi) \
{ \
case 0: \
R = 255.*V; G = 255.*_t; B = 255.*_p; \
break; \
case 1: \
R = 255.*_q; G = 255.*V; B = 255.*_p; \
break; \
case 2: \
R = 255.*_p; G = 255.*V; B = 255.*_t; \
break; \
case 3: \
R = 255.*_p; G = 255.*_q; B = 255.*V; \
break; \
case 4: \
R = 255.*_t; G = 255.*_p; B = 255.*V; \
break; \
case 5: \
R = 255.*V; G = 255.*_p; B = 255.*_q; \
break; \
} \
}
void BlobDetector::process()
{
bool roi_info = readParameter<bool>("RoiInformation");
CvMatMessage::Ptr img = input_->getMessage<CvMatMessage>();
if(!img->hasChannels(1, CV_8U)) {
throw std::runtime_error("image must be one channel grayscale.");
}
cv::Mat& gray = img->value;
CvMatMessage::Ptr debug(new CvMatMessage(enc::bgr, img->stamp));
cv::cvtColor(gray, debug->value, CV_GRAY2BGR);
CvBlobs blobs;
IplImage* grayPtr = new IplImage(gray);
IplImage* labelImgPtr = cvCreateImage(cvGetSize(grayPtr), IPL_DEPTH_LABEL, 1);
cvLabel(grayPtr, labelImgPtr, blobs);
VectorMessage::Ptr out(VectorMessage::make<RoiMessage>());
int minw = readParameter<int>("min_size/w");
int minh = readParameter<int>("min_size/h");
for (CvBlobs::const_iterator it=blobs.begin(); it!=blobs.end(); ++it) {
const CvBlob& blob = *it->second;
int w = (blob.maxx - blob.minx + 1);
int h = (blob.maxy - blob.miny + 1);
if(w < minw || h < minh) {
continue;
}
RoiMessage::Ptr roi(new RoiMessage);
double r, g, b;
_HSV2RGB_((double)((blob.label *77)%360), .5, 1., r, g, b);
cv::Scalar color(b,g,r);
roi->value = Roi(blob.minx, blob.miny, w, h, color);
out->value.push_back(roi);
}
output_->publish(out);
if(output_debug_->isConnected()) {
IplImage* debugPtr = new IplImage(debug->value);
cvRenderBlobs(labelImgPtr, blobs, debugPtr, debugPtr);
for (CvBlobs::const_iterator it=blobs.begin(); it!=blobs.end(); ++it) {
const CvBlob& blob = *it->second;
const CvChainCodes& c = blob.contour.chainCode;
cv::Point p = blob.contour.startingPoint;
for(CvChainCodes::const_iterator i = c.begin(); i != c.end(); ++i) {
const CvChainCode& chain = *i;
cv::Point next = p + cv::Point(cvChainCodeMoves[chain][0], cvChainCodeMoves[chain][1]);
double r, g, b;
_HSV2RGB_((double)((blob.label *77)%360), .5, 1., r, g, b);
cv::Scalar color(b,g,r);
cv::line(debug->value, p, next, color, 5, CV_AA);
p = next;
}
}
if (roi_info){
for (CvBlobs::const_iterator it=blobs.begin(); it!=blobs.end(); ++it) {
const CvBlob& blob = *it->second;
std::stringstream ss;
ss << "Blob #" << blob.label << ": A=" << blob.area << ", C=(" << blob.centroid.x << ", " << blob.centroid.y << ")";
double r, g, b;
_HSV2RGB_((double)((blob.label *77)%360), .5, 1., r, g, b);
cv::Scalar color(b,g,r);
cv::putText(debug->value, ss.str(), cv::Point(blob.centroid.x, blob.centroid.y), cv::FONT_HERSHEY_PLAIN, 1.0, color, 3);
cv::putText(debug->value, ss.str(), cv::Point(blob.centroid.x, blob.centroid.y), cv::FONT_HERSHEY_PLAIN, 1.0, cv::Scalar::all(255), 1);
}
}
output_debug_->publish(debug);
}
cvReleaseImage(&labelImgPtr);
}
void BlobDetector::setup()
{
input_ = modifier_->addInput<CvMatMessage>("Image");
output_debug_ = modifier_->addOutput<CvMatMessage>("OutputImage");
output_ = modifier_->addOutput<VectorMessage, RoiMessage>("ROIs");
}
<commit_msg>stuffed a memory leak<commit_after>/// HEADER
#include "blob_detector.h"
/// COMPONENT
#include <vision_plugins/cvblob.h>
/// PROJECT
#include <csapex_core_plugins/vector_message.h>
#include <csapex_vision/cv_mat_message.h>
#include <csapex_vision/roi_message.h>
#include <csapex_vision_features/keypoint_message.h>
/// PROJECT
#include <csapex/msg/output.h>
#include <csapex/msg/input.h>
#include <utils_param/parameter_factory.h>
#include <csapex/utility/register_apex_plugin.h>
#include <csapex/model/node_modifier.h>
/// SYSTEM
#include <sstream>
CSAPEX_REGISTER_CLASS(csapex::BlobDetector, csapex::Node)
using namespace csapex;
using namespace connection_types;
using namespace cvb;
BlobDetector::BlobDetector()
{
addParameter(param::ParameterFactory::declareBool("RoiInformation",
param::ParameterDescription("Show the information of each RoI"),
false));
addParameter(param::ParameterFactory::declareRange("min_size/w", 1, 1024, 1, 1));
addParameter(param::ParameterFactory::declareRange("min_size/h", 1, 1024, 1, 1));
}
BlobDetector::~BlobDetector()
{
}
#define _HSV2RGB_(H, S, V, R, G, B) \
{ \
double _h = H/60.; \
int _hf = (int)floor(_h); \
int _hi = ((int)_h)%6; \
double _f = _h - _hf; \
\
double _p = V * (1. - S); \
double _q = V * (1. - _f * S); \
double _t = V * (1. - (1. - _f) * S); \
\
switch (_hi) \
{ \
case 0: \
R = 255.*V; G = 255.*_t; B = 255.*_p; \
break; \
case 1: \
R = 255.*_q; G = 255.*V; B = 255.*_p; \
break; \
case 2: \
R = 255.*_p; G = 255.*V; B = 255.*_t; \
break; \
case 3: \
R = 255.*_p; G = 255.*_q; B = 255.*V; \
break; \
case 4: \
R = 255.*_t; G = 255.*_p; B = 255.*V; \
break; \
case 5: \
R = 255.*V; G = 255.*_p; B = 255.*_q; \
break; \
} \
}
void BlobDetector::process()
{
bool roi_info = readParameter<bool>("RoiInformation");
CvMatMessage::Ptr img = input_->getMessage<CvMatMessage>();
if(!img->hasChannels(1, CV_8U)) {
throw std::runtime_error("image must be one channel grayscale.");
}
cv::Mat& gray = img->value;
CvMatMessage::Ptr debug(new CvMatMessage(enc::bgr, img->stamp));
cv::cvtColor(gray, debug->value, CV_GRAY2BGR);
CvBlobs blobs;
IplImage* grayPtr = new IplImage(gray);
IplImage* labelImgPtr = cvCreateImage(cvGetSize(grayPtr), IPL_DEPTH_LABEL, 1);
cvLabel(grayPtr, labelImgPtr, blobs);
VectorMessage::Ptr out(VectorMessage::make<RoiMessage>());
int minw = readParameter<int>("min_size/w");
int minh = readParameter<int>("min_size/h");
for (CvBlobs::const_iterator it=blobs.begin(); it!=blobs.end(); ++it) {
const CvBlob& blob = *it->second;
int w = (blob.maxx - blob.minx + 1);
int h = (blob.maxy - blob.miny + 1);
if(w < minw || h < minh) {
continue;
}
RoiMessage::Ptr roi(new RoiMessage);
double r, g, b;
_HSV2RGB_((double)((blob.label *77)%360), .5, 1., r, g, b);
cv::Scalar color(b,g,r);
roi->value = Roi(blob.minx, blob.miny, w, h, color);
out->value.push_back(roi);
}
output_->publish(out);
if(output_debug_->isConnected()) {
IplImage* debugPtr = new IplImage(debug->value);
cvRenderBlobs(labelImgPtr, blobs, debugPtr, debugPtr);
for (CvBlobs::const_iterator it=blobs.begin(); it!=blobs.end(); ++it) {
const CvBlob& blob = *it->second;
const CvChainCodes& c = blob.contour.chainCode;
cv::Point p = blob.contour.startingPoint;
for(CvChainCodes::const_iterator i = c.begin(); i != c.end(); ++i) {
const CvChainCode& chain = *i;
cv::Point next = p + cv::Point(cvChainCodeMoves[chain][0], cvChainCodeMoves[chain][1]);
double r, g, b;
_HSV2RGB_((double)((blob.label *77)%360), .5, 1., r, g, b);
cv::Scalar color(b,g,r);
cv::line(debug->value, p, next, color, 5, CV_AA);
p = next;
}
}
if (roi_info){
for (CvBlobs::const_iterator it=blobs.begin(); it!=blobs.end(); ++it) {
const CvBlob& blob = *it->second;
std::stringstream ss;
ss << "Blob #" << blob.label << ": A=" << blob.area << ", C=(" << blob.centroid.x << ", " << blob.centroid.y << ")";
double r, g, b;
_HSV2RGB_((double)((blob.label *77)%360), .5, 1., r, g, b);
cv::Scalar color(b,g,r);
cv::putText(debug->value, ss.str(), cv::Point(blob.centroid.x, blob.centroid.y), cv::FONT_HERSHEY_PLAIN, 1.0, color, 3);
cv::putText(debug->value, ss.str(), cv::Point(blob.centroid.x, blob.centroid.y), cv::FONT_HERSHEY_PLAIN, 1.0, cv::Scalar::all(255), 1);
}
}
output_debug_->publish(debug);
}
cvReleaseBlobs(blobs);
cvReleaseImage(&labelImgPtr);
}
void BlobDetector::setup()
{
input_ = modifier_->addInput<CvMatMessage>("Image");
output_debug_ = modifier_->addOutput<CvMatMessage>("OutputImage");
output_ = modifier_->addOutput<VectorMessage, RoiMessage>("ROIs");
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: unoautopilot.inl,v $
*
* $Revision: 1.1 $
*
* last change: $Author: fs $ $Date: 2001-02-21 09:24:52 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc..
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
// no include protecttion
// this file is included from unoautopilot.hxx directly
//using namespace ::com::sun::star::uno;
//using namespace ::com::sun::star::lang;
//using namespace ::com::sun::star::beans;
//
//=====================================================================
//= OUnoAutoPilot
//=====================================================================
//---------------------------------------------------------------------
template <class TYPE, class SERVICEINFO>
OUnoAutoPilot<TYPE, SERVICEINFO>::OUnoAutoPilot(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB)
:OUnoAutoPilot_Base(_rxORB)
{
}
//---------------------------------------------------------------------
template <class TYPE, class SERVICEINFO>
::com::sun::star::uno::Sequence<sal_Int8> SAL_CALL OUnoAutoPilot<TYPE, SERVICEINFO>::getImplementationId( ) throw(::com::sun::star::uno::RuntimeException)
{
static ::cppu::OImplementationId aId;
return aId.getImplementationId();
}
//---------------------------------------------------------------------
template <class TYPE, class SERVICEINFO>
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL OUnoAutoPilot<TYPE, SERVICEINFO>::Create(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory)
{
return *(new OUnoAutoPilot<TYPE, SERVICEINFO>(_rxFactory));
}
//---------------------------------------------------------------------
template <class TYPE, class SERVICEINFO>
::rtl::OUString SAL_CALL OUnoAutoPilot<TYPE, SERVICEINFO>::getImplementationName() throw(::com::sun::star::uno::RuntimeException)
{
return getImplementationName_Static();
}
//---------------------------------------------------------------------
template <class TYPE, class SERVICEINFO>
::rtl::OUString OUnoAutoPilot<TYPE, SERVICEINFO>::getImplementationName_Static() throw(::com::sun::star::uno::RuntimeException)
{
return SERVICEINFO().getImplementationName();
}
//---------------------------------------------------------------------
template <class TYPE, class SERVICEINFO>
::comphelper::StringSequence SAL_CALL OUnoAutoPilot<TYPE, SERVICEINFO>::getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException)
{
return getSupportedServiceNames_Static();
}
//---------------------------------------------------------------------
template <class TYPE, class SERVICEINFO>
::comphelper::StringSequence OUnoAutoPilot<TYPE, SERVICEINFO>::getSupportedServiceNames_Static() throw(::com::sun::star::uno::RuntimeException)
{
return SERVICEINFO().getServiceNames();
}
//---------------------------------------------------------------------
template <class TYPE, class SERVICEINFO>
::com::sun::star::uno::Reference<::com::sun::star::beans::XPropertySetInfo> SAL_CALL OUnoAutoPilot<TYPE, SERVICEINFO>::getPropertySetInfo() throw(::com::sun::star::uno::RuntimeException)
{
::com::sun::star::uno::Reference<::com::sun::star::beans::XPropertySetInfo> xInfo( createPropertySetInfo( getInfoHelper() ) );
return xInfo;
}
//---------------------------------------------------------------------
template <class TYPE, class SERVICEINFO>
::cppu::IPropertyArrayHelper& OUnoAutoPilot<TYPE, SERVICEINFO>::getInfoHelper()
{
return *const_cast<OUnoAutoPilot*>(this)->getArrayHelper();
}
//--------------------------------------------------------------------------
template <class TYPE, class SERVICEINFO>
::cppu::IPropertyArrayHelper* OUnoAutoPilot<TYPE, SERVICEINFO>::createArrayHelper( ) const
{
::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property > aProps;
describeProperties(aProps);
return new ::cppu::OPropertyArrayHelper(aProps);
}
//--------------------------------------------------------------------------
template <class TYPE, class SERVICEINFO>
Dialog* OUnoAutoPilot<TYPE, SERVICEINFO>::createDialog(Window* _pParent)
{
return new TYPE(_pParent, m_xObjectModel, m_xORB);
}
//--------------------------------------------------------------------------
template <class TYPE, class SERVICEINFO>
void OUnoAutoPilot<TYPE, SERVICEINFO>::implInitialize(const com::sun::star::uno::Any& _rValue)
{
::com::sun::star::beans::PropertyValue aArgument;
if (_rValue >>= aArgument)
if (0 == aArgument.Name.compareToAscii("ObjectModel"))
{
aArgument.Value >>= m_xObjectModel;
return;
}
OUnoAutoPilot_Base::implInitialize(_rValue);
}
/*************************************************************************
* history:
* $Log: not supported by cvs2svn $
*
* Revision 1.0 14.02.01 10:18:07 fs
************************************************************************/
<commit_msg>#65293# parse error linux<commit_after>/*************************************************************************
*
* $RCSfile: unoautopilot.inl,v $
*
* $Revision: 1.2 $
*
* last change: $Author: obo $ $Date: 2001-03-06 10:06:40 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc..
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
// no include protecttion
// this file is included from unoautopilot.hxx directly
//using namespace ::com::sun::star::uno;
//using namespace ::com::sun::star::lang;
//using namespace ::com::sun::star::beans;
//
//=====================================================================
//= OUnoAutoPilot
//=====================================================================
//---------------------------------------------------------------------
template <class TYPE, class SERVICEINFO>
OUnoAutoPilot<TYPE, SERVICEINFO>::OUnoAutoPilot(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB)
:OUnoAutoPilot_Base(_rxORB)
{
}
//---------------------------------------------------------------------
template <class TYPE, class SERVICEINFO>
::com::sun::star::uno::Sequence<sal_Int8> SAL_CALL OUnoAutoPilot<TYPE, SERVICEINFO>::getImplementationId( ) throw(::com::sun::star::uno::RuntimeException)
{
static ::cppu::OImplementationId aId;
return aId.getImplementationId();
}
//---------------------------------------------------------------------
template <class TYPE, class SERVICEINFO>
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL OUnoAutoPilot<TYPE, SERVICEINFO>::Create(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory)
{
return *(new OUnoAutoPilot<TYPE, SERVICEINFO>(_rxFactory));
}
//---------------------------------------------------------------------
template <class TYPE, class SERVICEINFO>
::rtl::OUString SAL_CALL OUnoAutoPilot<TYPE, SERVICEINFO>::getImplementationName() throw(::com::sun::star::uno::RuntimeException)
{
return getImplementationName_Static();
}
//---------------------------------------------------------------------
template <class TYPE, class SERVICEINFO>
::rtl::OUString OUnoAutoPilot<TYPE, SERVICEINFO>::getImplementationName_Static() throw(::com::sun::star::uno::RuntimeException)
{
return SERVICEINFO().getImplementationName();
}
//---------------------------------------------------------------------
template <class TYPE, class SERVICEINFO>
::comphelper::StringSequence SAL_CALL OUnoAutoPilot<TYPE, SERVICEINFO>::getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException)
{
return getSupportedServiceNames_Static();
}
//---------------------------------------------------------------------
template <class TYPE, class SERVICEINFO>
::comphelper::StringSequence OUnoAutoPilot<TYPE, SERVICEINFO>::getSupportedServiceNames_Static() throw(::com::sun::star::uno::RuntimeException)
{
return SERVICEINFO().getServiceNames();
}
//---------------------------------------------------------------------
template <class TYPE, class SERVICEINFO>
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL OUnoAutoPilot<TYPE, SERVICEINFO>::getPropertySetInfo() throw(::com::sun::star::uno::RuntimeException)
{
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > xInfo( createPropertySetInfo( getInfoHelper() ) );
return xInfo;
}
//---------------------------------------------------------------------
template <class TYPE, class SERVICEINFO>
::cppu::IPropertyArrayHelper& OUnoAutoPilot<TYPE, SERVICEINFO>::getInfoHelper()
{
return *const_cast<OUnoAutoPilot*>(this)->getArrayHelper();
}
//--------------------------------------------------------------------------
template <class TYPE, class SERVICEINFO>
::cppu::IPropertyArrayHelper* OUnoAutoPilot<TYPE, SERVICEINFO>::createArrayHelper( ) const
{
::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property > aProps;
describeProperties(aProps);
return new ::cppu::OPropertyArrayHelper(aProps);
}
//--------------------------------------------------------------------------
template <class TYPE, class SERVICEINFO>
Dialog* OUnoAutoPilot<TYPE, SERVICEINFO>::createDialog(Window* _pParent)
{
return new TYPE(_pParent, m_xObjectModel, m_xORB);
}
//--------------------------------------------------------------------------
template <class TYPE, class SERVICEINFO>
void OUnoAutoPilot<TYPE, SERVICEINFO>::implInitialize(const com::sun::star::uno::Any& _rValue)
{
::com::sun::star::beans::PropertyValue aArgument;
if (_rValue >>= aArgument)
if (0 == aArgument.Name.compareToAscii("ObjectModel"))
{
aArgument.Value >>= m_xObjectModel;
return;
}
OUnoAutoPilot_Base::implInitialize(_rValue);
}
/*************************************************************************
* history:
* $Log: not supported by cvs2svn $
* Revision 1.1 2001/02/21 09:24:52 fs
* initial checkin - form control auto pilots
*
*
* Revision 1.0 14.02.01 10:18:07 fs
************************************************************************/
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: browserpage.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2004-10-13 09:04:20 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc..
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _EXTENSIONS_PROPCTRLR_BROWSERPAGE_HXX_
#include "browserpage.hxx"
#endif
//............................................................................
namespace pcr
{
//............................................................................
//==================================================================
// class OBrowserPage
//==================================================================
//------------------------------------------------------------------
OBrowserPage::OBrowserPage(Window* pParent,WinBits nWinStyle)
:TabPage(pParent,nWinStyle)
,m_aListBox(this)
{
m_aListBox.SetBackground(GetBackground());
m_aListBox.SetPaintTransparent( TRUE );
Point aPos(3,3);
m_aListBox.SetPosPixel(aPos);
m_aListBox.Show();
}
//------------------------------------------------------------------
OBrowserPage::~OBrowserPage()
{
}
//------------------------------------------------------------------
void OBrowserPage::Resize()
{
Size aSize( GetOutputSizePixel() );
aSize.Width() -= 6;
aSize.Height() -= 6;
m_aListBox.SetPosSizePixel( Point( 3, 3 ), aSize );
}
//------------------------------------------------------------------
OBrowserListBox* OBrowserPage::getListBox()
{
return &m_aListBox;
}
//------------------------------------------------------------------
void OBrowserPage::StateChanged(StateChangedType nType)
{
Window::StateChanged( nType);
if (STATE_CHANGE_VISIBLE == nType)
m_aListBox.Activate(IsVisible());
}
// #95343# ---------------------------------------------------------
sal_Int32 OBrowserPage::getMinimumWidth()
{
return m_aListBox.GetMinimumWidth()+6;
}
//............................................................................
} // namespace pcr
//............................................................................
<commit_msg>INTEGRATION: CWS eforms2 (1.3.156); FILE MERGED 2004/11/07 06:09:58 dvo 1.3.156.4: RESYNC: (1.5-1.6); FILE MERGED 2004/10/08 21:13:59 dvo 1.3.156.3: RESYNC: (1.4-1.5); FILE MERGED 2004/07/27 14:04:21 fs 1.3.156.2: RESYNC: (1.3-1.4); FILE MERGED 2004/04/26 11:26:19 fs 1.3.156.1: some cleanup/consolidation / (optionally) allow for a second button per line<commit_after>/*************************************************************************
*
* $RCSfile: browserpage.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: obo $ $Date: 2004-11-16 12:01:14 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc..
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _EXTENSIONS_PROPCTRLR_BROWSERPAGE_HXX_
#include "browserpage.hxx"
#endif
//............................................................................
namespace pcr
{
//............................................................................
//==================================================================
// class OBrowserPage
//==================================================================
//------------------------------------------------------------------
OBrowserPage::OBrowserPage(Window* pParent,WinBits nWinStyle)
:TabPage(pParent,nWinStyle)
,m_aListBox(this)
{
m_aListBox.SetBackground(GetBackground());
m_aListBox.SetPaintTransparent( TRUE );
Point aPos(3,3);
m_aListBox.SetPosPixel(aPos);
m_aListBox.Show();
}
//------------------------------------------------------------------
OBrowserPage::~OBrowserPage()
{
}
//------------------------------------------------------------------
void OBrowserPage::Resize()
{
Size aSize( GetOutputSizePixel() );
aSize.Width() -= 6;
aSize.Height() -= 6;
m_aListBox.SetPosSizePixel( Point( 3, 3 ), aSize );
}
//------------------------------------------------------------------
OBrowserListBox* OBrowserPage::getListBox()
{
return &m_aListBox;
}
//------------------------------------------------------------------
const OBrowserListBox* OBrowserPage::getListBox() const
{
return &m_aListBox;
}
//------------------------------------------------------------------
void OBrowserPage::StateChanged(StateChangedType nType)
{
Window::StateChanged( nType);
if (STATE_CHANGE_VISIBLE == nType)
m_aListBox.Activate(IsVisible());
}
// #95343# ---------------------------------------------------------
sal_Int32 OBrowserPage::getMinimumWidth()
{
return m_aListBox.GetMinimumWidth()+6;
}
//............................................................................
} // namespace pcr
//............................................................................
<|endoftext|> |
<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// File NektarUnivConsts.hpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Scientific Computing and Imaging Institute,
// University of Utah (USA) and Department of Aeronautics, Imperial
// College London (UK).
//
// License for the specific language governing rights and limitations under
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Description: Universal constants in the Nektar Library
//
///////////////////////////////////////////////////////////////////////////////
#ifndef NEKTARUNIVCONSTS_HPP
#define NEKTARUNIVCONSTS_HPP
#include <LibUtilities/BasicConst/NektarUnivTypeDefs.hpp>
namespace Nektar
{
// Null defintion of Array<OneD, NekDouble>
// static Array<OneD, NekDouble> NullNekDouble1DSharedArray;
// static NekDouble2DSharedArray NullNekDouble2DSharedArray;
// static NekDouble3DSharedArray NullNekDouble3DSharedArray;
} //end of namespace
#endif
/***
$Log: NektarUnivConsts.hpp,v $
Revision 1.4 2007/04/26 21:51:54 jfrazier
Converted to new multi_array implementation.
Revision 1.3 2007/03/31 00:39:51 bnelson
*** empty log message ***
Revision 1.2 2007/03/21 20:56:42 sherwin
Update to change BasisSharedVector to boost::shared_array<BasisSharedPtr> and removed tthe Vector definitions in GetCoords and PhysDeriv
Revision 1.1 2007/03/20 11:56:25 sherwin
.
**/
<commit_msg>Removed unneeded code.<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// File NektarUnivConsts.hpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Scientific Computing and Imaging Institute,
// University of Utah (USA) and Department of Aeronautics, Imperial
// College London (UK).
//
// License for the specific language governing rights and limitations under
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Description: Universal constants in the Nektar Library
//
///////////////////////////////////////////////////////////////////////////////
#ifndef NEKTARUNIVCONSTS_HPP
#define NEKTARUNIVCONSTS_HPP
#include <LibUtilities/BasicConst/NektarUnivTypeDefs.hpp>
namespace Nektar
{
} //end of namespace
#endif
/***
$Log: NektarUnivConsts.hpp,v $
Revision 1.5 2007/05/14 23:24:40 bnelson
Removed unneeded code.
Revision 1.4 2007/04/26 21:51:54 jfrazier
Converted to new multi_array implementation.
Revision 1.3 2007/03/31 00:39:51 bnelson
*** empty log message ***
Revision 1.2 2007/03/21 20:56:42 sherwin
Update to change BasisSharedVector to boost::shared_array<BasisSharedPtr> and removed tthe Vector definitions in GetCoords and PhysDeriv
Revision 1.1 2007/03/20 11:56:25 sherwin
.
**/
<|endoftext|> |
<commit_before>// -------------------------------------------------------------------------
// @FileName : NFCUrlClientModule.cpp
// @Author : LvSheng.Huang
// @Date : 2013-07-08
// @Module : NFCUrlClientModule
// @Desc :
// -------------------------------------------------------------------------
#include "NFCUrlClientModule.h"
#include "curl/curl.h"
#include "NFCWebCharacter.hpp"
#include "NFComm/NFPluginModule/NFIPluginManager.h"
#include <msgpack.hpp>
#include <string>
#include <iostream>
#include <sstream>
const std::string NFCURLComponent::GetComponentName() const
{
return "NFCURLComponent";
}
int NFCURLComponent::OnASyncEvent( const NFGUID& self, const int event, std::string& arg )
{
SURLParam xparam;
if (!NFCUrlClientModule::UnPackParam(arg, xparam))
{
return -1;
}
xparam.nRet = NFCUrlClientModule::HttpReq(xparam.strUrl, xparam.strGetParams, xparam.strBodyData, xparam.xCookies, xparam.fTimeOutSec, xparam.strRsp);
if (!NFCUrlClientModule::PackParam(xparam, arg))
{
return -2;
}
return 0;
}
NF_SHARE_PTR<NFIComponent> NFCURLComponent::CreateNewInstance()
{
return NF_SHARE_PTR<NFIComponent> (NF_NEW NFCURLComponent(NFGUID(1, 2)));
}
bool NFCUrlClientModule::Init()
{
return true;
}
bool NFCUrlClientModule::Shut()
{
return true;
}
bool NFCUrlClientModule::Execute( const float fLasFrametime, const float fStartedTime )
{
return true;
}
bool NFCUrlClientModule::AfterInit()
{
return true;
}
bool NFCUrlClientModule::BeforeShut()
{
return true;
}
int NFCUrlClientModule::HttpPostRequest(const std::string& strUrl, const std::map<std::string, std::string>& mxGetParams, const std::map<std::string, std::string>& mxPostParams,const std::map<std::string, std::string>& mxCookies, const float fTimeOutSec, std::string& strRsp)
{
std::string strGetParam = CompositeParam(mxGetParams);
std::string strCookies = CompositeCookies(mxCookies);
std::string strPostParam = CompositeParam(mxPostParams);
return HttpReq(strUrl, strGetParam, strPostParam, strCookies, fTimeOutSec, strRsp);
}
int NFCUrlClientModule::HttpRequest(const std::string& strUrl, const std::map<std::string, std::string>& mxGetParams, const std::string& strBodyData,const std::map<std::string, std::string>& mxCookies, const float fTimeOutSec, std::string& strRsp)
{
std::string strGetParam = CompositeParam(mxGetParams);
std::string strCookies = CompositeCookies(mxCookies);
return HttpReq(strUrl, strGetParam, strBodyData, strCookies, fTimeOutSec, strRsp);
}
size_t NFCUrlClientModule::RecvHttpData(void* buffer, size_t size, size_t nmemb, std::string* pStrRecveData)
{
unsigned long sizes = size * nmemb;
if (NULL != pStrRecveData)
{
try
{
pStrRecveData->append((char *)buffer, sizes);
}
catch (...)
{
return 0;
}
}
return sizes;
}
std::string NFCUrlClientModule::CompositeParam( const std::map<std::string,std::string>& params )
{
std::stringstream ss;
std::multimap<std::string,std::string>::const_iterator iter = params.begin();
while( iter != params.end() )
{
ss<< iter->first
<<"="
<< NFCWebCharacter::encodeURIValue(iter->second.c_str())
<<"&";
++iter;
}
std::string line = ss.str();
if (line.size() > 1)
{//ȥĩβ&
line.erase( line.size() -1 );
}
return line;
}
std::string NFCUrlClientModule::CompositeCookies( const std::map<std::string,std::string>& params )
{
std::stringstream ss;
std::multimap<std::string,std::string>::const_iterator iter = params.begin();
while( iter != params.end() )
{
ss<< iter->first
<<"="
<< NFCWebCharacter::encodeURIValue(iter->second.c_str())
<<";";
++iter;
}
std::string line = ss.str();
if (line.size() > 1)
{//ȥĩβ;
line.erase( line.size() -1 );
}
return line;
}
int NFCUrlClientModule::HttpReq( const std::string& strUrl, const std::string& strGetParam, const std::string& strBodyData,const std::string& strCookies, const float fTimeOutSec, std::string& strRsp )
{
try
{
if(strUrl.empty())
{
return -2;
}
std::string strFullStr;
strFullStr += strUrl;
strFullStr += "?";
strFullStr += strGetParam;
CURL *curl = 0;
CURLcode ret;
curl = curl_easy_init();
if (0 == curl)
{
return -3;
}
StConnFree conn_free(curl);
struct curl_slist *headerlist=NULL;
char buf[256] = {0};
NFSPRINTF(buf, sizeof(buf), "%s", "Expect:");
headerlist = curl_slist_append(headerlist, buf);
StSlistFree slist_free(headerlist);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist);
char strerrorBuffer[CURL_ERROR_SIZE] = {0};
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, strerrorBuffer);
curl_easy_setopt(curl, CURLOPT_URL, strFullStr.c_str()); // ok
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &strRsp); // ok
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, RecvHttpData); // ok
if (!strCookies.empty())
{
curl_easy_setopt(curl, CURLOPT_COOKIE, strCookies.c_str()); // ok
}
curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS, (int)(fTimeOutSec*1000));
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS, (int)(fTimeOutSec*1000));
curl_easy_setopt(curl,CURLOPT_SSL_VERIFYPEER,false);
curl_easy_setopt(curl,CURLOPT_SSL_VERIFYHOST,false);
curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
curl_easy_setopt(curl, CURLOPT_POST, 1);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, strBodyData.c_str());
ret = curl_easy_perform(curl);
if (ret != CURLE_OK) // CURLE_OK : 0
{
return ret;
}
else
{//http״̬벻200ֱӷhttp״̬
long http_code = 0;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
if(200 != http_code)
{
return http_code;
}
return 0;//״̬Ϊ200ʱ0
}
}
catch(...)
{
return -1;
}
}
bool NFCUrlClientModule::StartActorPool( const int nCount )
{
NFIActorManager* pActorManager = pPluginManager->GetActorManager();
if (NULL == pActorManager)
{
return false;
}
for (int i = 0; i < nCount; i++)
{
int nActorID = pActorManager->RequireActor<NFCURLComponent>(this, &NFCUrlClientModule::HttpRequestAsyEnd);
if (nActorID > 0)
{
mActorList.AddElement(i, NF_SHARE_PTR<int> (NF_NEW int(nActorID)));
}
}
return false;
}
bool NFCUrlClientModule::CloseActorPool()
{
int nActor =0;
NFIActorManager* pActorManager = pPluginManager->GetActorManager();
if (NULL == pActorManager)
{
return false;
}
for (NF_SHARE_PTR<int> pData = mActorList.First(nActor); pData != NULL; pData = mActorList.Next(nActor))
{
pActorManager->ReleaseActor(nActor);
}
mActorList.ClearAll();
return false;
}
int NFCUrlClientModule::HttpRequestAsyEnd(const NFGUID& self, const int nFormActor, const int nSubMsgID, const std::string& strData)
{
SURLParam xResultparam;
if (!NFCUrlClientModule::UnPackParam(strData, xResultparam))
{
return -1;
}
NF_SHARE_PTR<SURLParam> pReqData = mReqList.GetElement(xResultparam.nReqID);
if (NULL == pReqData)
{
return -2;
}
if (pReqData->mFunRsp._Empty())
{
return -3;
}
pReqData->mFunRsp(self, xResultparam.nRet, xResultparam.strRsp);
return 0;
}
int NFCUrlClientModule::HttpRequestAs(const NFGUID& self, const std::string& strUrl, const std::map<std::string, std::string>& mxGetParams, const std::string& strBodyData,const std::map<std::string, std::string>& mxCookies, const float fTimeOutSec, const HTTP_RSP_FUNCTOR& RspFucn)
{
std::string strGetParam = CompositeParam(mxGetParams);
std::string strCookies = CompositeCookies(mxCookies);
NF_SHARE_PTR<SURLParam> pUrlParam(NF_NEW SURLParam());
if (NULL == pUrlParam)
{
return false;
}
pUrlParam->strUrl = strUrl;
pUrlParam->strGetParams = strGetParam;
pUrlParam->strBodyData = strBodyData;
pUrlParam->xCookies = strCookies;
pUrlParam->fTimeOutSec = fTimeOutSec;
pUrlParam->nReqID = nCurReqID++;
pUrlParam->mFunRsp = RspFucn;
NFIActorManager* pActorManager = pPluginManager->GetActorManager();
if (NULL == pActorManager)
{
return -1;
}
int nAcotrID = GetActor();
if (nAcotrID <=0 )
{
return -2;
}
std::string arg;
const int nEvetID =1;
if (!PackParam(*pUrlParam, arg))
{
return -3;
}
if (!mReqList.AddElement(pUrlParam->nReqID, pUrlParam))
{
return -4;
}
if (!pActorManager->SendMsgToActor(nAcotrID, self, nEvetID, arg))
{
mReqList.RemoveElement(pUrlParam->nReqID);
return -5;
}
return 0;
}
int NFCUrlClientModule::HttpRequestPostAs( const NFGUID& self, const std::string& strUrl, const std::map<std::string, std::string>& mxGetParams, const std::map<std::string, std::string>& mxPostParams,const std::map<std::string, std::string>& mxCookies, const float fTimeOutSec, const HTTP_RSP_FUNCTOR& RspFucn )
{
std::string strPostParam = CompositeParam(mxPostParams);
return HttpRequestAs(self, strUrl, mxGetParams, strPostParam, mxCookies, fTimeOutSec, RspFucn);
}
bool NFCUrlClientModule::PackParam( const SURLParam& xParam, std::string& strData )
{
try
{
msgpack::type::tuple<std::string, std::string, std::string, std::string, std::string, float, int, int> xPackMode(xParam.strUrl, xParam.strGetParams, xParam.strBodyData, xParam.xCookies, xParam.strRsp, xParam.fTimeOutSec, xParam.nRet, xParam.nReqID);
std::stringstream buffer;
msgpack::pack(buffer, xPackMode);
buffer.seekg(0);
strData.assign(buffer.str());
}
catch (...)
{
return false;
}
return true;
}
bool NFCUrlClientModule::UnPackParam( const std::string& strData, SURLParam& xParam )
{
try
{
msgpack::unpacked result;
msgpack::unpack(result, strData.data(), strData.size());
msgpack::object deserialized = result.get();
msgpack::type::tuple<std::string, std::string, std::string, std::string, std::string, float, int, int> dst;
deserialized.convert(&dst);
xParam.strUrl = dst.a0;
xParam.strGetParams = dst.a1;
xParam.strBodyData = dst.a2;
xParam.xCookies = dst.a3;
xParam.strRsp = dst.a4;
xParam.fTimeOutSec = dst.a5;
xParam.nRet = dst.a6;
xParam.nReqID = dst.a7;
}
catch(...)
{
return false;
}
return true;
}
int NFCUrlClientModule::GetActor()
{
int nActor = 0;
NF_SHARE_PTR<int> pdata = mActorList.Next(nActor);
if (NULL != pdata)
{
return nActor;
}
pdata = mActorList.First(nActor);
if (NULL != pdata)
{
return nActor;
}
return -1;
}
<commit_msg>fixed url plugin for build<commit_after>// -------------------------------------------------------------------------
// @FileName : NFCUrlClientModule.cpp
// @Author : LvSheng.Huang
// @Date : 2013-07-08
// @Module : NFCUrlClientModule
// @Desc :
// -------------------------------------------------------------------------
#include "NFCUrlClientModule.h"
#include "NFCWebCharacter.hpp"
#include "Dependencies/curl-7.37.1/include/curl/curl.h"
#include "NFComm/NFPluginModule/NFIPluginManager.h"
#include <string>
#include <iostream>
#include <sstream>
const std::string NFCURLComponent::GetComponentName() const
{
return "NFCURLComponent";
}
int NFCURLComponent::OnASyncEvent( const NFGUID& self, const int event, std::string& arg )
{
SURLParam xparam;
if (!NFCUrlClientModule::UnPackParam(arg, xparam))
{
return -1;
}
xparam.nRet = NFCUrlClientModule::HttpReq(xparam.strUrl, xparam.strGetParams, xparam.strBodyData, xparam.xCookies, xparam.fTimeOutSec, xparam.strRsp);
if (!NFCUrlClientModule::PackParam(xparam, arg))
{
return -2;
}
return 0;
}
NF_SHARE_PTR<NFIComponent> NFCURLComponent::CreateNewInstance()
{
return NF_SHARE_PTR<NFIComponent> (NF_NEW NFCURLComponent(NFGUID(1, 2)));
}
bool NFCUrlClientModule::Init()
{
return true;
}
bool NFCUrlClientModule::Shut()
{
return true;
}
bool NFCUrlClientModule::Execute( const float fLasFrametime, const float fStartedTime )
{
return true;
}
bool NFCUrlClientModule::AfterInit()
{
return true;
}
bool NFCUrlClientModule::BeforeShut()
{
return true;
}
int NFCUrlClientModule::HttpPostRequest(const std::string& strUrl, const std::map<std::string, std::string>& mxGetParams, const std::map<std::string, std::string>& mxPostParams,const std::map<std::string, std::string>& mxCookies, const float fTimeOutSec, std::string& strRsp)
{
std::string strGetParam = CompositeParam(mxGetParams);
std::string strCookies = CompositeCookies(mxCookies);
std::string strPostParam = CompositeParam(mxPostParams);
return HttpReq(strUrl, strGetParam, strPostParam, strCookies, fTimeOutSec, strRsp);
}
int NFCUrlClientModule::HttpRequest(const std::string& strUrl, const std::map<std::string, std::string>& mxGetParams, const std::string& strBodyData,const std::map<std::string, std::string>& mxCookies, const float fTimeOutSec, std::string& strRsp)
{
std::string strGetParam = CompositeParam(mxGetParams);
std::string strCookies = CompositeCookies(mxCookies);
return HttpReq(strUrl, strGetParam, strBodyData, strCookies, fTimeOutSec, strRsp);
}
size_t NFCUrlClientModule::RecvHttpData(void* buffer, size_t size, size_t nmemb, std::string* pStrRecveData)
{
unsigned long sizes = size * nmemb;
if (NULL != pStrRecveData)
{
try
{
pStrRecveData->append((char *)buffer, sizes);
}
catch (...)
{
return 0;
}
}
return sizes;
}
std::string NFCUrlClientModule::CompositeParam( const std::map<std::string,std::string>& params )
{
std::stringstream ss;
std::multimap<std::string,std::string>::const_iterator iter = params.begin();
while( iter != params.end() )
{
ss<< iter->first
<<"="
<< NFCWebCharacter::encodeURIValue(iter->second.c_str())
<<"&";
++iter;
}
std::string line = ss.str();
if (line.size() > 1)
{//ȥĩβ&
line.erase( line.size() -1 );
}
return line;
}
std::string NFCUrlClientModule::CompositeCookies( const std::map<std::string,std::string>& params )
{
std::stringstream ss;
std::multimap<std::string,std::string>::const_iterator iter = params.begin();
while( iter != params.end() )
{
ss<< iter->first
<<"="
<< NFCWebCharacter::encodeURIValue(iter->second.c_str())
<<";";
++iter;
}
std::string line = ss.str();
if (line.size() > 1)
{//ȥĩβ;
line.erase( line.size() -1 );
}
return line;
}
int NFCUrlClientModule::HttpReq( const std::string& strUrl, const std::string& strGetParam, const std::string& strBodyData,const std::string& strCookies, const float fTimeOutSec, std::string& strRsp )
{
try
{
if(strUrl.empty())
{
return -2;
}
std::string strFullStr;
strFullStr += strUrl;
strFullStr += "?";
strFullStr += strGetParam;
CURL *curl = 0;
CURLcode ret;
curl = curl_easy_init();
if (0 == curl)
{
return -3;
}
StConnFree conn_free(curl);
struct curl_slist *headerlist=NULL;
char buf[256] = {0};
NFSPRINTF(buf, sizeof(buf), "%s", "Expect:");
headerlist = curl_slist_append(headerlist, buf);
StSlistFree slist_free(headerlist);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist);
char strerrorBuffer[CURL_ERROR_SIZE] = {0};
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, strerrorBuffer);
curl_easy_setopt(curl, CURLOPT_URL, strFullStr.c_str()); // ok
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &strRsp); // ok
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, RecvHttpData); // ok
if (!strCookies.empty())
{
curl_easy_setopt(curl, CURLOPT_COOKIE, strCookies.c_str()); // ok
}
curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS, (int)(fTimeOutSec*1000));
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS, (int)(fTimeOutSec*1000));
curl_easy_setopt(curl,CURLOPT_SSL_VERIFYPEER,false);
curl_easy_setopt(curl,CURLOPT_SSL_VERIFYHOST,false);
curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
curl_easy_setopt(curl, CURLOPT_POST, 1);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, strBodyData.c_str());
ret = curl_easy_perform(curl);
if (ret != CURLE_OK) // CURLE_OK : 0
{
return ret;
}
else
{//http״̬벻200ֱӷhttp״̬
long http_code = 0;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
if(200 != http_code)
{
return http_code;
}
return 0;//״̬Ϊ200ʱ0
}
}
catch(...)
{
return -1;
}
}
bool NFCUrlClientModule::StartActorPool( const int nCount )
{
NFIActorManager* pActorManager = pPluginManager->GetActorManager();
if (NULL == pActorManager)
{
return false;
}
for (int i = 0; i < nCount; i++)
{
int nActorID = pActorManager->RequireActor<NFCURLComponent>(this, &NFCUrlClientModule::HttpRequestAsyEnd);
if (nActorID > 0)
{
mActorList.AddElement(i, NF_SHARE_PTR<int> (NF_NEW int(nActorID)));
}
}
return false;
}
bool NFCUrlClientModule::CloseActorPool()
{
int nActor =0;
NFIActorManager* pActorManager = pPluginManager->GetActorManager();
if (NULL == pActorManager)
{
return false;
}
for (NF_SHARE_PTR<int> pData = mActorList.First(nActor); pData != NULL; pData = mActorList.Next(nActor))
{
pActorManager->ReleaseActor(nActor);
}
mActorList.ClearAll();
return false;
}
int NFCUrlClientModule::HttpRequestAsyEnd(const NFGUID& self, const int nFormActor, const int nSubMsgID, const std::string& strData)
{
SURLParam xResultparam;
if (!NFCUrlClientModule::UnPackParam(strData, xResultparam))
{
return -1;
}
NF_SHARE_PTR<SURLParam> pReqData = mReqList.GetElement(xResultparam.nReqID);
if (NULL == pReqData)
{
return -2;
}
if (pReqData->mFunRsp._Empty())
{
return -3;
}
pReqData->mFunRsp(self, xResultparam.nRet, xResultparam.strRsp);
return 0;
}
int NFCUrlClientModule::HttpRequestAs(const NFGUID& self, const std::string& strUrl, const std::map<std::string, std::string>& mxGetParams, const std::string& strBodyData,const std::map<std::string, std::string>& mxCookies, const float fTimeOutSec, const HTTP_RSP_FUNCTOR& RspFucn)
{
std::string strGetParam = CompositeParam(mxGetParams);
std::string strCookies = CompositeCookies(mxCookies);
NF_SHARE_PTR<SURLParam> pUrlParam(NF_NEW SURLParam());
if (NULL == pUrlParam)
{
return false;
}
pUrlParam->strUrl = strUrl;
pUrlParam->strGetParams = strGetParam;
pUrlParam->strBodyData = strBodyData;
pUrlParam->xCookies = strCookies;
pUrlParam->fTimeOutSec = fTimeOutSec;
pUrlParam->nReqID = nCurReqID++;
pUrlParam->mFunRsp = RspFucn;
NFIActorManager* pActorManager = pPluginManager->GetActorManager();
if (NULL == pActorManager)
{
return -1;
}
int nAcotrID = GetActor();
if (nAcotrID <=0 )
{
return -2;
}
std::string arg;
const int nEvetID =1;
if (!PackParam(*pUrlParam, arg))
{
return -3;
}
if (!mReqList.AddElement(pUrlParam->nReqID, pUrlParam))
{
return -4;
}
if (!pActorManager->SendMsgToActor(nAcotrID, self, nEvetID, arg))
{
mReqList.RemoveElement(pUrlParam->nReqID);
return -5;
}
return 0;
}
int NFCUrlClientModule::HttpRequestPostAs( const NFGUID& self, const std::string& strUrl, const std::map<std::string, std::string>& mxGetParams, const std::map<std::string, std::string>& mxPostParams,const std::map<std::string, std::string>& mxCookies, const float fTimeOutSec, const HTTP_RSP_FUNCTOR& RspFucn )
{
std::string strPostParam = CompositeParam(mxPostParams);
return HttpRequestAs(self, strUrl, mxGetParams, strPostParam, mxCookies, fTimeOutSec, RspFucn);
}
bool NFCUrlClientModule::PackParam( const SURLParam& xParam, std::string& strData )
{
try
{
// msgpack::type::tuple<std::string, std::string, std::string, std::string, std::string, float, int, int> xPackMode(xParam.strUrl, xParam.strGetParams, xParam.strBodyData, xParam.xCookies, xParam.strRsp, xParam.fTimeOutSec, xParam.nRet, xParam.nReqID);
//
// std::stringstream buffer;
// msgpack::pack(buffer, xPackMode);
// buffer.seekg(0);
// strData.assign(buffer.str());
}
catch (...)
{
return false;
}
return true;
}
bool NFCUrlClientModule::UnPackParam( const std::string& strData, SURLParam& xParam )
{
try
{
// msgpack::unpacked result;
//
// msgpack::unpack(result, strData.data(), strData.size());
// msgpack::object deserialized = result.get();
//
// msgpack::type::tuple<std::string, std::string, std::string, std::string, std::string, float, int, int> dst;
// deserialized.convert(&dst);
//
// xParam.strUrl = dst.a0;
// xParam.strGetParams = dst.a1;
// xParam.strBodyData = dst.a2;
// xParam.xCookies = dst.a3;
// xParam.strRsp = dst.a4;
// xParam.fTimeOutSec = dst.a5;
// xParam.nRet = dst.a6;
// xParam.nReqID = dst.a7;
}
catch(...)
{
return false;
}
return true;
}
int NFCUrlClientModule::GetActor()
{
int nActor = 0;
NF_SHARE_PTR<int> pdata = mActorList.Next(nActor);
if (NULL != pdata)
{
return nActor;
}
pdata = mActorList.First(nActor);
if (NULL != pdata)
{
return nActor;
}
return -1;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Library: TubeTK
Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
// Qt includes
#include <QtPlugin>
// SlicerQt includes
#include <qSlicerCoreApplication.h>
#include <qSlicerIOManager.h>
#include <qSlicerModuleManager.h>
#include <qSlicerNodeWriter.h>
// Tortuosity Logic includes
#include "vtkSlicerTortuosityLogic.h"
// Tortuosity QTModule includes
#include "qSlicerTortuosityModule.h"
#include "qSlicerTortuosityModuleWidget.h"
//------------------------------------------------------------------------------
Q_EXPORT_PLUGIN2( qSlicerTortuosityModule, qSlicerTortuosityModule );
//------------------------------------------------------------------------------
/// \ingroup Slicer_QtModules_Tortuosity
class qSlicerTortuosityModulePrivate
{};
//------------------------------------------------------------------------------
qSlicerTortuosityModule::qSlicerTortuosityModule( QObject* _parent )
: Superclass( _parent )
, d_ptr( new qSlicerTortuosityModulePrivate )
{}
//------------------------------------------------------------------------------
qSlicerTortuosityModule::~qSlicerTortuosityModule()
{}
//------------------------------------------------------------------------------
QString qSlicerTortuosityModule::helpText() const
{
QString help = QString( "Run tortuosity metrics on spatial objects.\n Documentation"
" about these metrics can be found in the TubeTK source code,"
" in Base/Filtering/itkTubeTortuositySpatialObjectFilter.h" );
return help;
}
//------------------------------------------------------------------------------
QString qSlicerTortuosityModule::acknowledgementText() const
{
QString acknowledgement = QString( "" );
return acknowledgement;
}
//------------------------------------------------------------------------------
QStringList qSlicerTortuosityModule::contributors() const
{
QStringList moduleContributors;
moduleContributors << QString( "Johan Andruejol (Kitware)" );
return moduleContributors;
}
//------------------------------------------------------------------------------
QIcon qSlicerTortuosityModule::icon()const
{
return QIcon( ":/Icons/Tortuosity.png" );
}
//------------------------------------------------------------------------------
QStringList qSlicerTortuosityModule::categories() const
{
return QStringList() << "TubeTK";
}
//------------------------------------------------------------------------------
QStringList qSlicerTortuosityModule::dependencies() const
{
QStringList moduleDependencies;
moduleDependencies << "SpatialObjects";
return moduleDependencies;
}
//------------------------------------------------------------------------------
void qSlicerTortuosityModule::setup()
{
this->Superclass::setup();
vtkSlicerTortuosityLogic* tortuosityLogic =
vtkSlicerTortuosityLogic::SafeDownCast( this->logic() );
}
//------------------------------------------------------------------------------
qSlicerAbstractModuleRepresentation*
qSlicerTortuosityModule::createWidgetRepresentation()
{
return new qSlicerTortuosityModuleWidget;
}
//------------------------------------------------------------------------------
vtkMRMLAbstractLogic* qSlicerTortuosityModule::createLogic()
{
return vtkSlicerTortuosityLogic::New();
}
<commit_msg>ENH: Fixed warning in qSlicerTortuosityModule<commit_after>/*=========================================================================
Library: TubeTK
Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
// Qt includes
#include <QtPlugin>
// SlicerQt includes
#include <qSlicerCoreApplication.h>
#include <qSlicerIOManager.h>
#include <qSlicerModuleManager.h>
#include <qSlicerNodeWriter.h>
// Tortuosity Logic includes
#include "vtkSlicerTortuosityLogic.h"
// Tortuosity QTModule includes
#include "qSlicerTortuosityModule.h"
#include "qSlicerTortuosityModuleWidget.h"
//------------------------------------------------------------------------------
Q_EXPORT_PLUGIN2( qSlicerTortuosityModule, qSlicerTortuosityModule );
//------------------------------------------------------------------------------
/// \ingroup Slicer_QtModules_Tortuosity
class qSlicerTortuosityModulePrivate
{};
//------------------------------------------------------------------------------
qSlicerTortuosityModule::qSlicerTortuosityModule( QObject* _parent )
: Superclass( _parent )
, d_ptr( new qSlicerTortuosityModulePrivate )
{}
//------------------------------------------------------------------------------
qSlicerTortuosityModule::~qSlicerTortuosityModule()
{}
//------------------------------------------------------------------------------
QString qSlicerTortuosityModule::helpText() const
{
QString help = QString( "Run tortuosity metrics on spatial objects.\n Documentation"
" about these metrics can be found in the TubeTK source code,"
" in Base/Filtering/itkTubeTortuositySpatialObjectFilter.h" );
return help;
}
//------------------------------------------------------------------------------
QString qSlicerTortuosityModule::acknowledgementText() const
{
QString acknowledgement = QString( "" );
return acknowledgement;
}
//------------------------------------------------------------------------------
QStringList qSlicerTortuosityModule::contributors() const
{
QStringList moduleContributors;
moduleContributors << QString( "Johan Andruejol (Kitware)" );
return moduleContributors;
}
//------------------------------------------------------------------------------
QIcon qSlicerTortuosityModule::icon()const
{
return QIcon( ":/Icons/Tortuosity.png" );
}
//------------------------------------------------------------------------------
QStringList qSlicerTortuosityModule::categories() const
{
return QStringList() << "TubeTK";
}
//------------------------------------------------------------------------------
QStringList qSlicerTortuosityModule::dependencies() const
{
QStringList moduleDependencies;
moduleDependencies << "SpatialObjects";
return moduleDependencies;
}
//------------------------------------------------------------------------------
void qSlicerTortuosityModule::setup()
{
this->Superclass::setup();
}
//------------------------------------------------------------------------------
qSlicerAbstractModuleRepresentation*
qSlicerTortuosityModule::createWidgetRepresentation()
{
return new qSlicerTortuosityModuleWidget;
}
//------------------------------------------------------------------------------
vtkMRMLAbstractLogic* qSlicerTortuosityModule::createLogic()
{
return vtkSlicerTortuosityLogic::New();
}
<|endoftext|> |
<commit_before>/**
* For conditions of distribution and use, see copyright notice in license.txt
*
* @file OgreMaterialUtils.cpp
* @brief Contains some often needed utlitity functions when dealing with OGRE material scripts.
*/
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "MemoryLeakCheck.h"
#include "OgreMaterialUtils.h"
#include "OgreRenderingModule.h"
#include "OgreConversionUtils.h"
#include <Ogre.h>
namespace OgreRenderer
{
std::string BaseMaterials[] = {
"LitTextured", // normal
"UnlitTextured", // normal fullbright
"LitTexturedAdd", // additive
"UnlitTexturedAdd", // additive fullbright
"LitTexturedSoftAlpha", // forced soft alpha
"UnlitTexturedSoftAlpha", // forced soft alpha fullbright
"LitTexturedVCol", // vertexcolor
"UnlitTexturedVCol", // vertexcolor fullbright
"LitTexturedSoftAlphaVCol", // vertexcolor forced soft alpha
"UnlitTexturedSoftAlphaVCol" // vertexcolor forced soft alpha fullbright
};
std::string AlphaBaseMaterials[] = {
"LitTexturedSoftAlpha", // soft alpha
"UnlitTexturedSoftAlpha", // soft alpha fullbright
"LitTexturedAdd", // additive
"UnlitTexturedAdd", // additive fullbright
"LitTexturedSoftAlpha", // forced soft alpha
"UnlitTexturedSoftAlpha", // forced soft alpha fullbright
"LitTexturedSoftAlphaVCol", // vertexcolor soft alpha
"UnlitTexturedSoftAlphaVCol", // vertexcolor soft alpha fullbright
"LitTexturedSoftAlphaVCol", // vertexcolor forced soft alpha
"UnlitTexturedSoftAlphaVCol" // vertexcolor forced soft alpha fullbright
};
std::string MaterialSuffix[] = {
"", // normal
"fb", // normal fullbright
"add", // additive
"fbadd", // additive fullbright
"alpha", // forced alpha
"fbalpha", // forced alpha fullbright
"vcol", // vertex color
"fbvcol", // vertex color fullbright
"vcolalpha", // vertex color alpha
"fbvcolalpha" // vertex color alpha fullbright
};
bool IsMaterialSuffixValid(const std::string& suffix)
{
for (uint i = 0; i < MAX_MATERIAL_VARIATIONS; ++i)
{
if (suffix == MaterialSuffix[i])
return true;
}
return false;
}
std::string GetMaterialSuffix(uint variation)
{
if (variation >= MAX_MATERIAL_VARIATIONS)
{
OgreRenderingModule::LogWarning("Requested suffix for non-existing material variation " + ToString<uint>(variation));
variation = 0;
}
return MaterialSuffix[variation];
}
uint GetMaterialVariation(const std::string& suffix)
{
for (uint i = 0; i < MAX_MATERIAL_VARIATIONS; ++i)
if (suffix == MaterialSuffix[i])
return i;
return 0;
}
Ogre::MaterialPtr CloneMaterial(const std::string& sourceMaterialName, const std::string &newName)
{
Ogre::MaterialManager &mm = Ogre::MaterialManager::getSingleton();
Ogre::MaterialPtr material = mm.getByName(SanitateAssetIdForOgre(sourceMaterialName));
material = material->clone(SanitateAssetIdForOgre(newName));
assert(material.get());
return material;
}
Ogre::MaterialPtr GetOrCreateLitTexturedMaterial(const std::string& materialName)
{
const char baseMaterialName[] = "LitTextured";
Ogre::MaterialManager &mm = Ogre::MaterialManager::getSingleton();
Ogre::MaterialPtr material = mm.getByName(SanitateAssetIdForOgre(materialName));
if (!material.get())
{
Ogre::MaterialPtr baseMaterial = mm.getByName(SanitateAssetIdForOgre(baseMaterialName));
if (baseMaterial.isNull())
return Ogre::MaterialPtr();
material = baseMaterial->clone(SanitateAssetIdForOgre(materialName));
}
assert(material.get());
return material;
}
Ogre::MaterialPtr GetOrCreateUnlitTexturedMaterial(const std::string& materialName)
{
const char baseMaterialName[] = "UnlitTextured";
Ogre::MaterialManager &mm = Ogre::MaterialManager::getSingleton();
Ogre::MaterialPtr material = mm.getByName(SanitateAssetIdForOgre(materialName));
if (!material.get())
{
Ogre::MaterialPtr baseMaterial = mm.getByName(SanitateAssetIdForOgre(baseMaterialName));
if (baseMaterial.isNull())
return Ogre::MaterialPtr();
material = baseMaterial->clone(SanitateAssetIdForOgre(materialName));
}
assert(material.get());
return material;
}
Ogre::MaterialPtr GetOrCreateLegacyMaterial(const std::string& texture_name, const std::string& suffix)
{
uint variation = GetMaterialVariation(suffix);
return GetOrCreateLegacyMaterial(texture_name, variation);
}
Ogre::MaterialPtr GetOrCreateLegacyMaterial(const std::string& texture_name, uint variation)
{
if (variation >= MAX_MATERIAL_VARIATIONS)
{
OgreRenderingModule::LogWarning("Requested suffix for non-existing material variation " + ToString<uint>(variation));
variation = 0;
}
const std::string& suffix = MaterialSuffix[variation];
std::string sanitatedtexname = SanitateAssetIdForOgre(texture_name);
Ogre::TextureManager &tm = Ogre::TextureManager::getSingleton();
Ogre::MaterialManager &mm = Ogre::MaterialManager::getSingleton();
std::string material_name = sanitatedtexname + suffix;
Ogre::MaterialPtr material = mm.getByName(material_name);
if (!material.get())
{
material = mm.create(material_name, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
assert(material.get());
}
else
return material;
Ogre::TexturePtr tex = tm.getByName(sanitatedtexname);
bool has_alpha = false;
if (!tex.isNull())
{
// As far as the legacy materials are concerned, DXT1 is not alpha
if (tex->getFormat() == Ogre::PF_DXT1)
has_alpha = false;
else if (Ogre::PixelUtil::hasAlpha(tex->getFormat()))
has_alpha = true;
}
Ogre::MaterialPtr base_material;
if (!has_alpha)
base_material = mm.getByName(BaseMaterials[variation]);
else
base_material = mm.getByName(AlphaBaseMaterials[variation]);
if (!base_material.get())
{
OgreRenderingModule::LogError("Could not find " + MaterialSuffix[variation] + " base material for " + texture_name);
return Ogre::MaterialPtr();
}
base_material->copyDetailsTo(material);
SetTextureUnitOnMaterial(material, texture_name, 0);
return material;
}
void UpdateLegacyMaterials(const std::string& texture_name)
{
Ogre::TextureManager &tm = Ogre::TextureManager::getSingleton();
Ogre::MaterialManager &mm = Ogre::MaterialManager::getSingleton();
std::string sanitatedtexname = SanitateAssetIdForOgre(texture_name);
Ogre::TexturePtr tex = tm.getByName(sanitatedtexname);
bool has_alpha = false;
if (!tex.isNull())
if (Ogre::PixelUtil::hasAlpha(tex->getFormat()))
has_alpha = true;
for (uint i = 0; i < MAX_MATERIAL_VARIATIONS; ++i)
{
std::string material_name = sanitatedtexname + MaterialSuffix[i];
Ogre::MaterialPtr material = mm.getByName(material_name);
if (!material.get())
continue;
Ogre::MaterialPtr base_material;
if (!has_alpha)
base_material = mm.getByName(BaseMaterials[i]);
else
base_material = mm.getByName(AlphaBaseMaterials[i]);
if (!base_material.get())
{
OgreRenderingModule::LogError("Could not find " + MaterialSuffix[i] + " base material for " + texture_name);
continue;
}
base_material->copyDetailsTo(material);
SetTextureUnitOnMaterial(material, texture_name, 0);
}
}
void SetTextureUnitOnMaterial(Ogre::MaterialPtr material, const std::string& texture_name, uint index)
{
if (material.isNull())
return;
std::string sanitatedtexname = SanitateAssetIdForOgre(texture_name);
Ogre::TextureManager &tm = Ogre::TextureManager::getSingleton();
Ogre::TexturePtr tex = tm.getByName(sanitatedtexname);
Ogre::Material::TechniqueIterator iter = material->getTechniqueIterator();
while(iter.hasMoreElements())
{
Ogre::Technique *tech = iter.getNext();
assert(tech);
Ogre::Technique::PassIterator passIter = tech->getPassIterator();
while(passIter.hasMoreElements())
{
Ogre::Pass *pass = passIter.getNext();
Ogre::Pass::TextureUnitStateIterator texIter = pass->getTextureUnitStateIterator();
uint cmp_index = 0;
while(texIter.hasMoreElements())
{
Ogre::TextureUnitState *texUnit = texIter.getNext();
if (index == cmp_index)
{
if (tex.get())
texUnit->setTextureName(sanitatedtexname);
else
texUnit->setTextureName("TextureMissing.png");
return; // We found and replaced the index we wanted to - can early-out return without looping the rest of the indices for nothing.
}
cmp_index++;
}
}
}
}
void ReplaceTextureOnMaterial(Ogre::MaterialPtr material, const std::string& original_name, const std::string& texture_name)
{
if (material.isNull())
return;
std::string sanitatedorgname = SanitateAssetIdForOgre(original_name);
std::string sanitatedtexname = SanitateAssetIdForOgre(texture_name);
Ogre::TextureManager &tm = Ogre::TextureManager::getSingleton();
Ogre::TexturePtr tex = tm.getByName(sanitatedtexname);
Ogre::Material::TechniqueIterator iter = material->getTechniqueIterator();
while(iter.hasMoreElements())
{
Ogre::Technique *tech = iter.getNext();
assert(tech);
Ogre::Technique::PassIterator passIter = tech->getPassIterator();
while(passIter.hasMoreElements())
{
Ogre::Pass *pass = passIter.getNext();
Ogre::Pass::TextureUnitStateIterator texIter = pass->getTextureUnitStateIterator();
while(texIter.hasMoreElements())
{
Ogre::TextureUnitState *texUnit = texIter.getNext();
if (texUnit->getTextureName() == sanitatedorgname)
{
if (tex.get())
texUnit->setTextureName(sanitatedtexname);
else
texUnit->setTextureName("TextureMissing.png");
}
}
}
}
}
void GetTextureNamesFromMaterial(Ogre::MaterialPtr material, StringVector& textures)
{
textures.clear();
if (material.isNull())
return;
// Use a set internally to avoid duplicates
std::set<std::string> textures_set;
Ogre::Material::TechniqueIterator iter = material->getTechniqueIterator();
while(iter.hasMoreElements())
{
Ogre::Technique *tech = iter.getNext();
assert(tech);
Ogre::Technique::PassIterator passIter = tech->getPassIterator();
while(passIter.hasMoreElements())
{
Ogre::Pass *pass = passIter.getNext();
Ogre::Pass::TextureUnitStateIterator texIter = pass->getTextureUnitStateIterator();
while(texIter.hasMoreElements())
{
Ogre::TextureUnitState *texUnit = texIter.getNext();
const std::string& texname = texUnit->getTextureName();
if (!texname.empty())
textures_set.insert(texname);
}
}
}
std::set<std::string>::iterator i = textures_set.begin();
while (i != textures_set.end())
{
textures.push_back(*i);
++i;
}
}
void RemoveMaterial(Ogre::MaterialPtr& material)
{
if (!material.isNull())
{
std::string material_name = material->getName();
material.setNull();
try
{
Ogre::MaterialManager::getSingleton().remove(material_name);
}
catch (Ogre::Exception& e)
{
OgreRenderingModule::LogDebug("Failed to remove Ogre material:" + std::string(e.what()));
}
}
}
bool ProcessBraces(const std::string& line, int& braceLevel)
{
if (line == "{")
{
++braceLevel;
return true;
}
else if (line == "}")
{
--braceLevel;
return true;
}
else return false;
}
}
<commit_msg>Have OgreMaterialUtils::CloneMaterial not assert-fail if cloning doesn't succeed, but instead returns a null material.<commit_after>/**
* For conditions of distribution and use, see copyright notice in license.txt
*
* @file OgreMaterialUtils.cpp
* @brief Contains some often needed utlitity functions when dealing with OGRE material scripts.
*/
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "MemoryLeakCheck.h"
#include "OgreMaterialUtils.h"
#include "OgreRenderingModule.h"
#include "OgreConversionUtils.h"
#include <Ogre.h>
namespace OgreRenderer
{
std::string BaseMaterials[] = {
"LitTextured", // normal
"UnlitTextured", // normal fullbright
"LitTexturedAdd", // additive
"UnlitTexturedAdd", // additive fullbright
"LitTexturedSoftAlpha", // forced soft alpha
"UnlitTexturedSoftAlpha", // forced soft alpha fullbright
"LitTexturedVCol", // vertexcolor
"UnlitTexturedVCol", // vertexcolor fullbright
"LitTexturedSoftAlphaVCol", // vertexcolor forced soft alpha
"UnlitTexturedSoftAlphaVCol" // vertexcolor forced soft alpha fullbright
};
std::string AlphaBaseMaterials[] = {
"LitTexturedSoftAlpha", // soft alpha
"UnlitTexturedSoftAlpha", // soft alpha fullbright
"LitTexturedAdd", // additive
"UnlitTexturedAdd", // additive fullbright
"LitTexturedSoftAlpha", // forced soft alpha
"UnlitTexturedSoftAlpha", // forced soft alpha fullbright
"LitTexturedSoftAlphaVCol", // vertexcolor soft alpha
"UnlitTexturedSoftAlphaVCol", // vertexcolor soft alpha fullbright
"LitTexturedSoftAlphaVCol", // vertexcolor forced soft alpha
"UnlitTexturedSoftAlphaVCol" // vertexcolor forced soft alpha fullbright
};
std::string MaterialSuffix[] = {
"", // normal
"fb", // normal fullbright
"add", // additive
"fbadd", // additive fullbright
"alpha", // forced alpha
"fbalpha", // forced alpha fullbright
"vcol", // vertex color
"fbvcol", // vertex color fullbright
"vcolalpha", // vertex color alpha
"fbvcolalpha" // vertex color alpha fullbright
};
bool IsMaterialSuffixValid(const std::string& suffix)
{
for (uint i = 0; i < MAX_MATERIAL_VARIATIONS; ++i)
{
if (suffix == MaterialSuffix[i])
return true;
}
return false;
}
std::string GetMaterialSuffix(uint variation)
{
if (variation >= MAX_MATERIAL_VARIATIONS)
{
OgreRenderingModule::LogWarning("Requested suffix for non-existing material variation " + ToString<uint>(variation));
variation = 0;
}
return MaterialSuffix[variation];
}
uint GetMaterialVariation(const std::string& suffix)
{
for (uint i = 0; i < MAX_MATERIAL_VARIATIONS; ++i)
if (suffix == MaterialSuffix[i])
return i;
return 0;
}
Ogre::MaterialPtr CloneMaterial(const std::string& sourceMaterialName, const std::string &newName)
{
Ogre::MaterialManager &mm = Ogre::MaterialManager::getSingleton();
Ogre::MaterialPtr material = mm.getByName(SanitateAssetIdForOgre(sourceMaterialName));
if (!material.get())
{
OgreRenderingModule::LogWarning("Failed to clone material \"" + sourceMaterialName + "\". It was not found.");
return Ogre::MaterialPtr();
}
material = material->clone(SanitateAssetIdForOgre(newName));
if (!material.get())
{
OgreRenderingModule::LogWarning("Failed to clone material \"" + sourceMaterialName + "\" to name \"" + SanitateAssetIdForOgre(newName) + "\"");
return Ogre::MaterialPtr();
}
return material;
}
Ogre::MaterialPtr GetOrCreateLitTexturedMaterial(const std::string& materialName)
{
const char baseMaterialName[] = "LitTextured";
Ogre::MaterialManager &mm = Ogre::MaterialManager::getSingleton();
Ogre::MaterialPtr material = mm.getByName(SanitateAssetIdForOgre(materialName));
if (!material.get())
{
Ogre::MaterialPtr baseMaterial = mm.getByName(SanitateAssetIdForOgre(baseMaterialName));
if (baseMaterial.isNull())
return Ogre::MaterialPtr();
material = baseMaterial->clone(SanitateAssetIdForOgre(materialName));
}
assert(material.get());
return material;
}
Ogre::MaterialPtr GetOrCreateUnlitTexturedMaterial(const std::string& materialName)
{
const char baseMaterialName[] = "UnlitTextured";
Ogre::MaterialManager &mm = Ogre::MaterialManager::getSingleton();
Ogre::MaterialPtr material = mm.getByName(SanitateAssetIdForOgre(materialName));
if (!material.get())
{
Ogre::MaterialPtr baseMaterial = mm.getByName(SanitateAssetIdForOgre(baseMaterialName));
if (baseMaterial.isNull())
return Ogre::MaterialPtr();
material = baseMaterial->clone(SanitateAssetIdForOgre(materialName));
}
assert(material.get());
return material;
}
Ogre::MaterialPtr GetOrCreateLegacyMaterial(const std::string& texture_name, const std::string& suffix)
{
uint variation = GetMaterialVariation(suffix);
return GetOrCreateLegacyMaterial(texture_name, variation);
}
Ogre::MaterialPtr GetOrCreateLegacyMaterial(const std::string& texture_name, uint variation)
{
if (variation >= MAX_MATERIAL_VARIATIONS)
{
OgreRenderingModule::LogWarning("Requested suffix for non-existing material variation " + ToString<uint>(variation));
variation = 0;
}
const std::string& suffix = MaterialSuffix[variation];
std::string sanitatedtexname = SanitateAssetIdForOgre(texture_name);
Ogre::TextureManager &tm = Ogre::TextureManager::getSingleton();
Ogre::MaterialManager &mm = Ogre::MaterialManager::getSingleton();
std::string material_name = sanitatedtexname + suffix;
Ogre::MaterialPtr material = mm.getByName(material_name);
if (!material.get())
{
material = mm.create(material_name, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
assert(material.get());
}
else
return material;
Ogre::TexturePtr tex = tm.getByName(sanitatedtexname);
bool has_alpha = false;
if (!tex.isNull())
{
// As far as the legacy materials are concerned, DXT1 is not alpha
if (tex->getFormat() == Ogre::PF_DXT1)
has_alpha = false;
else if (Ogre::PixelUtil::hasAlpha(tex->getFormat()))
has_alpha = true;
}
Ogre::MaterialPtr base_material;
if (!has_alpha)
base_material = mm.getByName(BaseMaterials[variation]);
else
base_material = mm.getByName(AlphaBaseMaterials[variation]);
if (!base_material.get())
{
OgreRenderingModule::LogError("Could not find " + MaterialSuffix[variation] + " base material for " + texture_name);
return Ogre::MaterialPtr();
}
base_material->copyDetailsTo(material);
SetTextureUnitOnMaterial(material, texture_name, 0);
return material;
}
void UpdateLegacyMaterials(const std::string& texture_name)
{
Ogre::TextureManager &tm = Ogre::TextureManager::getSingleton();
Ogre::MaterialManager &mm = Ogre::MaterialManager::getSingleton();
std::string sanitatedtexname = SanitateAssetIdForOgre(texture_name);
Ogre::TexturePtr tex = tm.getByName(sanitatedtexname);
bool has_alpha = false;
if (!tex.isNull())
if (Ogre::PixelUtil::hasAlpha(tex->getFormat()))
has_alpha = true;
for (uint i = 0; i < MAX_MATERIAL_VARIATIONS; ++i)
{
std::string material_name = sanitatedtexname + MaterialSuffix[i];
Ogre::MaterialPtr material = mm.getByName(material_name);
if (!material.get())
continue;
Ogre::MaterialPtr base_material;
if (!has_alpha)
base_material = mm.getByName(BaseMaterials[i]);
else
base_material = mm.getByName(AlphaBaseMaterials[i]);
if (!base_material.get())
{
OgreRenderingModule::LogError("Could not find " + MaterialSuffix[i] + " base material for " + texture_name);
continue;
}
base_material->copyDetailsTo(material);
SetTextureUnitOnMaterial(material, texture_name, 0);
}
}
void SetTextureUnitOnMaterial(Ogre::MaterialPtr material, const std::string& texture_name, uint index)
{
if (material.isNull())
return;
std::string sanitatedtexname = SanitateAssetIdForOgre(texture_name);
Ogre::TextureManager &tm = Ogre::TextureManager::getSingleton();
Ogre::TexturePtr tex = tm.getByName(sanitatedtexname);
Ogre::Material::TechniqueIterator iter = material->getTechniqueIterator();
while(iter.hasMoreElements())
{
Ogre::Technique *tech = iter.getNext();
assert(tech);
Ogre::Technique::PassIterator passIter = tech->getPassIterator();
while(passIter.hasMoreElements())
{
Ogre::Pass *pass = passIter.getNext();
Ogre::Pass::TextureUnitStateIterator texIter = pass->getTextureUnitStateIterator();
uint cmp_index = 0;
while(texIter.hasMoreElements())
{
Ogre::TextureUnitState *texUnit = texIter.getNext();
if (index == cmp_index)
{
if (tex.get())
texUnit->setTextureName(sanitatedtexname);
else
texUnit->setTextureName("TextureMissing.png");
return; // We found and replaced the index we wanted to - can early-out return without looping the rest of the indices for nothing.
}
cmp_index++;
}
}
}
}
void ReplaceTextureOnMaterial(Ogre::MaterialPtr material, const std::string& original_name, const std::string& texture_name)
{
if (material.isNull())
return;
std::string sanitatedorgname = SanitateAssetIdForOgre(original_name);
std::string sanitatedtexname = SanitateAssetIdForOgre(texture_name);
Ogre::TextureManager &tm = Ogre::TextureManager::getSingleton();
Ogre::TexturePtr tex = tm.getByName(sanitatedtexname);
Ogre::Material::TechniqueIterator iter = material->getTechniqueIterator();
while(iter.hasMoreElements())
{
Ogre::Technique *tech = iter.getNext();
assert(tech);
Ogre::Technique::PassIterator passIter = tech->getPassIterator();
while(passIter.hasMoreElements())
{
Ogre::Pass *pass = passIter.getNext();
Ogre::Pass::TextureUnitStateIterator texIter = pass->getTextureUnitStateIterator();
while(texIter.hasMoreElements())
{
Ogre::TextureUnitState *texUnit = texIter.getNext();
if (texUnit->getTextureName() == sanitatedorgname)
{
if (tex.get())
texUnit->setTextureName(sanitatedtexname);
else
texUnit->setTextureName("TextureMissing.png");
}
}
}
}
}
void GetTextureNamesFromMaterial(Ogre::MaterialPtr material, StringVector& textures)
{
textures.clear();
if (material.isNull())
return;
// Use a set internally to avoid duplicates
std::set<std::string> textures_set;
Ogre::Material::TechniqueIterator iter = material->getTechniqueIterator();
while(iter.hasMoreElements())
{
Ogre::Technique *tech = iter.getNext();
assert(tech);
Ogre::Technique::PassIterator passIter = tech->getPassIterator();
while(passIter.hasMoreElements())
{
Ogre::Pass *pass = passIter.getNext();
Ogre::Pass::TextureUnitStateIterator texIter = pass->getTextureUnitStateIterator();
while(texIter.hasMoreElements())
{
Ogre::TextureUnitState *texUnit = texIter.getNext();
const std::string& texname = texUnit->getTextureName();
if (!texname.empty())
textures_set.insert(texname);
}
}
}
std::set<std::string>::iterator i = textures_set.begin();
while (i != textures_set.end())
{
textures.push_back(*i);
++i;
}
}
void RemoveMaterial(Ogre::MaterialPtr& material)
{
if (!material.isNull())
{
std::string material_name = material->getName();
material.setNull();
try
{
Ogre::MaterialManager::getSingleton().remove(material_name);
}
catch (Ogre::Exception& e)
{
OgreRenderingModule::LogDebug("Failed to remove Ogre material:" + std::string(e.what()));
}
}
}
bool ProcessBraces(const std::string& line, int& braceLevel)
{
if (line == "{")
{
++braceLevel;
return true;
}
else if (line == "}")
{
--braceLevel;
return true;
}
else return false;
}
}
<|endoftext|> |
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2009 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "ParticleTest.h"
String VisualTest::TRANSIENT_RESOURCE_GROUP = "VisualTestTransient";
ParticleTest::ParticleTest()
{
mInfo["Title"] = "VTests_Particles";
mInfo["Description"] = "Tests basic particle system functionality.";
// take screenshot early, when emitters are just beginning
addScreenshotFrame(200);
// and another after particles have died, extra emitters emitted, etc
addScreenshotFrame(2000);
}
//---------------------------------------------------------------------------
void ParticleTest::setupContent()
{
}
//-----------------------------------------------------------------------
<commit_msg>Added particle test.<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2009 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "ParticleTest.h"
String VisualTest::TRANSIENT_RESOURCE_GROUP = "VisualTestTransient";
ParticleTest::ParticleTest()
{
mInfo["Title"] = "VTests_Particles";
mInfo["Description"] = "Tests basic particle system functionality.";
// take screenshot early, when emitters are just beginning
addScreenshotFrame(35);
// and another after particles have died, extra emitters emitted, etc
addScreenshotFrame(2000);
}
//---------------------------------------------------------------------------
void ParticleTest::setupContent()
{
// create a bunch of random particle systems
Ogre::ParticleSystem* ps = mSceneMgr->createParticleSystem("Fireworks", "Examples/Fireworks");
mSceneMgr->getRootSceneNode()->attachObject(ps);
ps = mSceneMgr->createParticleSystem("Fountain", "Examples/PurpleFountain");
mSceneMgr->getRootSceneNode()->attachObject(ps);
ps = mSceneMgr->createParticleSystem("Nimbus", "Examples/GreenyNimbus");
mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(150, 0, 0))->attachObject(ps);
ps = mSceneMgr->createParticleSystem("Nimbus2", "Examples/GreenyNimbus");
mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-150, 0, 0))->attachObject(ps);
mCamera->setPosition(0,150,500);
}
//-----------------------------------------------------------------------
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include "leveldb/db.h"
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "leveldb/cache.h"
#include "leveldb/env.h"
#include "leveldb/table.h"
#include "leveldb/write_batch.h"
#include "db/db_impl.h"
#include "db/filename.h"
#include "db/log_format.h"
#include "db/version_set.h"
#include "util/logging.h"
#include "util/testharness.h"
#include "util/testutil.h"
namespace leveldb {
static const int kValueSize = 1000;
class CorruptionTest {
public:
test::ErrorEnv env_;
std::string dbname_;
Cache* tiny_cache_;
Options options_;
DB* db_;
CorruptionTest() {
tiny_cache_ = NewLRUCache(100);
options_.env = &env_;
options_.block_cache = tiny_cache_;
dbname_ = test::TmpDir() + "/db_test";
DestroyDB(dbname_, options_);
db_ = NULL;
options_.create_if_missing = true;
Reopen();
options_.create_if_missing = false;
}
~CorruptionTest() {
delete db_;
DestroyDB(dbname_, Options());
delete tiny_cache_;
}
Status TryReopen() {
delete db_;
db_ = NULL;
return DB::Open(options_, dbname_, &db_);
}
void Reopen() {
ASSERT_OK(TryReopen());
}
void RepairDB() {
delete db_;
db_ = NULL;
ASSERT_OK(::leveldb::RepairDB(dbname_, options_));
}
void Build(int n) {
std::string key_space, value_space;
WriteBatch batch;
for (int i = 0; i < n; i++) {
//if ((i % 100) == 0) fprintf(stderr, "@ %d of %d\n", i, n);
Slice key = Key(i, &key_space);
batch.Clear();
batch.Put(key, Value(i, &value_space));
WriteOptions options;
// Corrupt() doesn't work without this sync on windows; stat reports 0 for
// the file size.
if (i == n - 1) {
options.sync = true;
}
ASSERT_OK(db_->Write(options, &batch));
}
}
void Check(int min_expected, int max_expected) {
int next_expected = 0;
int missed = 0;
int bad_keys = 0;
int bad_values = 0;
int correct = 0;
std::string value_space;
Iterator* iter = db_->NewIterator(ReadOptions());
for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
uint64_t key;
Slice in(iter->key());
if (in == "" || in == "~") {
// Ignore boundary keys.
continue;
}
if (!ConsumeDecimalNumber(&in, &key) ||
!in.empty() ||
key < next_expected) {
bad_keys++;
continue;
}
missed += (key - next_expected);
next_expected = key + 1;
if (iter->value() != Value(key, &value_space)) {
bad_values++;
} else {
correct++;
}
}
delete iter;
fprintf(stderr,
"expected=%d..%d; got=%d; bad_keys=%d; bad_values=%d; missed=%d\n",
min_expected, max_expected, correct, bad_keys, bad_values, missed);
ASSERT_LE(min_expected, correct);
ASSERT_GE(max_expected, correct);
}
void Corrupt(FileType filetype, int offset, int bytes_to_corrupt) {
// Pick file to corrupt
std::vector<std::string> filenames;
ASSERT_OK(env_.GetChildren(dbname_, &filenames));
uint64_t number;
FileType type;
std::string fname;
int picked_number = -1;
for (size_t i = 0; i < filenames.size(); i++) {
if (ParseFileName(filenames[i], &number, &type) &&
type == filetype &&
int(number) > picked_number) { // Pick latest file
fname = dbname_ + "/" + filenames[i];
picked_number = number;
}
}
ASSERT_TRUE(!fname.empty()) << filetype;
struct stat sbuf;
if (stat(fname.c_str(), &sbuf) != 0) {
const char* msg = strerror(errno);
ASSERT_TRUE(false) << fname << ": " << msg;
}
if (offset < 0) {
// Relative to end of file; make it absolute
if (-offset > sbuf.st_size) {
offset = 0;
} else {
offset = sbuf.st_size + offset;
}
}
if (offset > sbuf.st_size) {
offset = sbuf.st_size;
}
if (offset + bytes_to_corrupt > sbuf.st_size) {
bytes_to_corrupt = sbuf.st_size - offset;
}
// Do it
std::string contents;
Status s = ReadFileToString(Env::Default(), fname, &contents);
ASSERT_TRUE(s.ok()) << s.ToString();
for (int i = 0; i < bytes_to_corrupt; i++) {
contents[i + offset] ^= 0x80;
}
s = WriteStringToFile(Env::Default(), contents, fname);
ASSERT_TRUE(s.ok()) << s.ToString();
}
int Property(const std::string& name) {
std::string property;
int result;
if (db_->GetProperty(name, &property) &&
sscanf(property.c_str(), "%d", &result) == 1) {
return result;
} else {
return -1;
}
}
// Return the ith key
Slice Key(int i, std::string* storage) {
char buf[100];
snprintf(buf, sizeof(buf), "%016d", i);
storage->assign(buf, strlen(buf));
return Slice(*storage);
}
// Return the value to associate with the specified key
Slice Value(int k, std::string* storage) {
Random r(k);
return test::RandomString(&r, kValueSize, storage);
}
};
TEST(CorruptionTest, Recovery) {
Build(100);
Check(100, 100);
Corrupt(kLogFile, 19, 1); // WriteBatch tag for first record
Corrupt(kLogFile, log::kBlockSize + 1000, 1); // Somewhere in second block
Reopen();
// The 64 records in the first two log blocks are completely lost.
Check(36, 36);
}
TEST(CorruptionTest, RecoverWriteError) {
env_.writable_file_error_ = true;
Status s = TryReopen();
ASSERT_TRUE(!s.ok());
}
TEST(CorruptionTest, NewFileErrorDuringWrite) {
// Do enough writing to force minor compaction
env_.writable_file_error_ = true;
const int num = 3 + (Options().write_buffer_size / kValueSize);
std::string value_storage;
Status s;
for (int i = 0; s.ok() && i < num; i++) {
WriteBatch batch;
batch.Put("a", Value(100, &value_storage));
s = db_->Write(WriteOptions(), &batch);
}
ASSERT_TRUE(!s.ok());
ASSERT_GE(env_.num_writable_file_errors_, 1);
env_.writable_file_error_ = false;
Reopen();
}
TEST(CorruptionTest, TableFile) {
Build(100);
DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
dbi->TEST_CompactMemTable();
dbi->TEST_CompactRange(0, NULL, NULL);
dbi->TEST_CompactRange(1, NULL, NULL);
Corrupt(kTableFile, 100, 1);
Check(90, 99);
}
TEST(CorruptionTest, TableFileRepair) {
options_.block_size = 2 * kValueSize; // Limit scope of corruption
options_.paranoid_checks = true;
Reopen();
Build(100);
DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
dbi->TEST_CompactMemTable();
dbi->TEST_CompactRange(0, NULL, NULL);
dbi->TEST_CompactRange(1, NULL, NULL);
Corrupt(kTableFile, 100, 1);
RepairDB();
Reopen();
Check(95, 99);
}
TEST(CorruptionTest, TableFileIndexData) {
Build(10000); // Enough to build multiple Tables
DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
dbi->TEST_CompactMemTable();
Corrupt(kTableFile, -2000, 500);
Reopen();
Check(5000, 9999);
}
TEST(CorruptionTest, MissingDescriptor) {
Build(1000);
RepairDB();
Reopen();
Check(1000, 1000);
}
TEST(CorruptionTest, SequenceNumberRecovery) {
ASSERT_OK(db_->Put(WriteOptions(), "foo", "v1"));
ASSERT_OK(db_->Put(WriteOptions(), "foo", "v2"));
ASSERT_OK(db_->Put(WriteOptions(), "foo", "v3"));
ASSERT_OK(db_->Put(WriteOptions(), "foo", "v4"));
ASSERT_OK(db_->Put(WriteOptions(), "foo", "v5"));
RepairDB();
Reopen();
std::string v;
ASSERT_OK(db_->Get(ReadOptions(), "foo", &v));
ASSERT_EQ("v5", v);
// Write something. If sequence number was not recovered properly,
// it will be hidden by an earlier write.
ASSERT_OK(db_->Put(WriteOptions(), "foo", "v6"));
ASSERT_OK(db_->Get(ReadOptions(), "foo", &v));
ASSERT_EQ("v6", v);
Reopen();
ASSERT_OK(db_->Get(ReadOptions(), "foo", &v));
ASSERT_EQ("v6", v);
}
TEST(CorruptionTest, CorruptedDescriptor) {
ASSERT_OK(db_->Put(WriteOptions(), "foo", "hello"));
DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
dbi->TEST_CompactMemTable();
dbi->TEST_CompactRange(0, NULL, NULL);
Corrupt(kDescriptorFile, 0, 1000);
Status s = TryReopen();
ASSERT_TRUE(!s.ok());
RepairDB();
Reopen();
std::string v;
ASSERT_OK(db_->Get(ReadOptions(), "foo", &v));
ASSERT_EQ("hello", v);
}
TEST(CorruptionTest, CompactionInputError) {
Build(10);
DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
dbi->TEST_CompactMemTable();
const int last = config::kMaxMemCompactLevel;
ASSERT_EQ(1, Property("leveldb.num-files-at-level" + NumberToString(last)));
Corrupt(kTableFile, 100, 1);
Check(5, 9);
// Force compactions by writing lots of values
Build(10000);
Check(10000, 10000);
}
TEST(CorruptionTest, CompactionInputErrorParanoid) {
options_.paranoid_checks = true;
options_.write_buffer_size = 512 << 10;
Reopen();
DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
// Make multiple inputs so we need to compact.
for (int i = 0; i < 2; i++) {
Build(10);
dbi->TEST_CompactMemTable();
Corrupt(kTableFile, 100, 1);
env_.SleepForMicroseconds(100000);
}
dbi->CompactRange(NULL, NULL);
// Write must fail because of corrupted table
std::string tmp1, tmp2;
Status s = db_->Put(WriteOptions(), Key(5, &tmp1), Value(5, &tmp2));
ASSERT_TRUE(!s.ok()) << "write did not fail in corrupted paranoid db";
}
TEST(CorruptionTest, UnrelatedKeys) {
Build(10);
DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
dbi->TEST_CompactMemTable();
Corrupt(kTableFile, 100, 1);
std::string tmp1, tmp2;
ASSERT_OK(db_->Put(WriteOptions(), Key(1000, &tmp1), Value(1000, &tmp2)));
std::string v;
ASSERT_OK(db_->Get(ReadOptions(), Key(1000, &tmp1), &v));
ASSERT_EQ(Value(1000, &tmp2).ToString(), v);
dbi->TEST_CompactMemTable();
ASSERT_OK(db_->Get(ReadOptions(), Key(1000, &tmp1), &v));
ASSERT_EQ(Value(1000, &tmp2).ToString(), v);
}
} // namespace leveldb
int main(int argc, char** argv) {
return leveldb::test::RunAllTests();
}
<commit_msg>Delete corruption_test.cc<commit_after><|endoftext|> |
<commit_before>/* -------------------------------------------------------------------------- *
* OpenSim: PathActuator.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2012 Stanford University and the Authors *
* Author(s): Ajay Seth *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may *
* not use this file except in compliance with the License. You may obtain a *
* copy of the License at http://www.apache.org/licenses/LICENSE-2.0. *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* -------------------------------------------------------------------------- */
//=============================================================================
// INCLUDES
//=============================================================================
#include "PathActuator.h"
#include "Model.h"
#include "PointForceDirection.h"
using namespace OpenSim;
using namespace std;
//=============================================================================
// CONSTRUCTOR(S) AND DESTRUCTOR
//=============================================================================
// default destructor, copy constructor, copy assignment
//_____________________________________________________________________________
/**
* Default constructor.
*/
PathActuator::PathActuator()
{
setNull();
constructProperties();
}
//=============================================================================
// CONSTRUCTION
//=============================================================================
//_____________________________________________________________________________
/**
* Set the data members of this actuator to their null values.
*/
void PathActuator::setNull()
{
setAuthors("Ajay Seth");
}
//_____________________________________________________________________________
/**
* Connect properties to local pointers.
*/
void PathActuator::constructProperties()
{
constructProperty_GeometryPath(GeometryPath());
constructProperty_optimal_force(1.0);
}
//=============================================================================
// GET AND SET
//=============================================================================
//-----------------------------------------------------------------------------
// OPTIMAL FORCE
//-----------------------------------------------------------------------------
//_____________________________________________________________________________
/**
* Set the optimal force of the force.
*
* @param aOptimalForce Optimal force.
*/
void PathActuator::setOptimalForce(double aOptimalForce)
{
set_optimal_force(aOptimalForce);
}
//_____________________________________________________________________________
/**
* Get the optimal force of the force.
*
* @return Optimal force.
*/
double PathActuator::getOptimalForce() const
{
return get_optimal_force();
}
//-----------------------------------------------------------------------------
// LENGTH
//-----------------------------------------------------------------------------
//_____________________________________________________________________________
/**
* Get the length of the path actuator. This is a convenience function that
* calls the underlying path object for its length.
*
* @return Current length of the actuator's path.
*/
double PathActuator::getLength(const SimTK::State& s) const
{
return getGeometryPath().getLength(s);
}
//_____________________________________________________________________________
/**
* Get the speed of actuator along its path.
*
* @return path lengthening speed.
*/
double PathActuator::getLengtheningSpeed(const SimTK::State& s) const
{
return getGeometryPath().getLengtheningSpeed(s);
}
//_____________________________________________________________________________
/**
* Get the stress of the force.
*
* @return Stress.
*/
double PathActuator::getStress( const SimTK::State& s) const
{
return fabs(getForce(s)/get_optimal_force());
}
//_____________________________________________________________________________
/**
* Add a Path point to the _path of the actuator. The new point is appended
* to the end of the current path
*
*/
void PathActuator::addNewPathPoint(
const std::string& proposedName,
OpenSim::Body& aBody,
const SimTK::Vec3& aPositionOnBody) {
// Create new PathPoint
PathPoint* newPathPoint = updGeometryPath()
.appendNewPathPoint(proposedName, aBody, aPositionOnBody);
// Set offset/position on owner body
newPathPoint->setName(proposedName);
for (int i=0; i<3; i++) // Use interface that does not depend on state
newPathPoint->setLocationCoord(i, aPositionOnBody[i]);
}
//=============================================================================
// COMPUTATIONS
//=============================================================================
//_____________________________________________________________________________
/**
* Compute all quantities necessary for applying the actuator force to the
* model.
*/
double PathActuator::computeActuation( const SimTK::State& s ) const
{
if(_model==NULL)
return 0.0;
// FORCE
return( getControl(s) * get_optimal_force() );
}
//=============================================================================
// APPLICATION
//=============================================================================
//_____________________________________________________________________________
/**
* Apply the actuator force along path wrapping over and connecting rigid bodies
*/
void PathActuator::computeForce( const SimTK::State& s,
SimTK::Vector_<SimTK::SpatialVec>& bodyForces,
SimTK::Vector& mobilityForces) const
{
if(_model==NULL) return;
const GeometryPath &path = getGeometryPath();
// compute path's lengthening speed if necessary
double speed = path.getLengtheningSpeed(s);
// the lengthening speed of this actutor is the "speed" of the actuator
// used to compute power
setSpeed(s, speed);
double force =0;
if( isForceOverriden(s) ) {
force = computeOverrideForce(s);
} else {
force = computeActuation(s);
}
// the force of this actuator used to compute power
setForce(s, force );
path.addInEquivalentForcesOnBodies(s, force, bodyForces);
}
/**
* Compute the moment-arm of this muscle about a coordinate.
*/
double PathActuator::computeMomentArm(const SimTK::State& s, Coordinate& aCoord) const
{
return getGeometryPath().computeMomentArm(s, aCoord);
}
//------------------------------------------------------------------------------
// CONNECT TO MODEL
//------------------------------------------------------------------------------
/**
* Perform some setup functions that happen after the
* object has been deserialized or copied.
*
* @param aModel OpenSim model containing this PathActuator.
*/
void PathActuator::connectToModel(Model& aModel)
{
GeometryPath &path = updGeometryPath();
// Specify underlying ModelComponents prior to calling
// Super::connectToModel() to automatically propagate connectToModel()
// calls to subcomponents. Subsequent addToSystem() will also be
// automatically propagated.
// TODO: this is awkward; subcomponent API needs to be revisited (sherm).
includeAsSubComponent(&path);
//TODO: can't call this at start of override; this is an API bug.
Super::connectToModel(aModel);
// _model will be NULL when objects are being registered.
if (_model == NULL)
return;
path.setOwner(this);
}
//------------------------------------------------------------------------------
// REALIZE DYNAMICS
//------------------------------------------------------------------------------
// See if anyone has an opinion about the path color and change it if so.
void PathActuator::realizeDynamics(const SimTK::State& state) const {
Super::realizeDynamics(state); // Mandatory first line
// if this force is disabled OR it is being overidden (not computing dynamics)
// then don't compute the color of the path.
if(!isDisabled(state) && !isForceOverriden(state)){
const SimTK::Vec3 color = computePathColor(state);
if (!color.isNaN())
getGeometryPath().setColor(state, color);
}
}
//------------------------------------------------------------------------------
// COMPUTE PATH COLOR
//------------------------------------------------------------------------------
// This is the PathActuator base class implementation for choosing the path
// color. Derived classes like Muscle will override this with something
// meaningful.
// TODO: should the default attempt to use the actuation level to control
// colors? Not sure how to scale. Muscles could still override that with
// activation level.
SimTK::Vec3 PathActuator::computePathColor(const SimTK::State& state) const {
return SimTK::Vec3(SimTK::NaN);
}
//=============================================================================
// XML
//=============================================================================
//-----------------------------------------------------------------------------
// UPDATE FROM XML NODE
//-----------------------------------------------------------------------------
//_____________________________________________________________________________
/**
* Update this object based on its XML node.
*
* This method simply calls Object::updateFromXMLNode(SimTK::Xml::Element& aNode, int versionNumber) and then calls
* a few methods in this class to ensure that variable members have been
* set in a consistent manner.
*/
void PathActuator::updateFromXMLNode(SimTK::Xml::Element& aNode, int versionNumber)
{
updGeometryPath().setOwner(this);
Super::updateFromXMLNode(aNode, versionNumber);
}
//_____________________________________________________________________________
/**
* Get the visible object used to represent the muscle.
*/
const VisibleObject* PathActuator::getDisplayer() const
{
return getGeometryPath().getDisplayer();
}
//_____________________________________________________________________________
/**
* Update the visible object used to represent the muscle.
*/
void PathActuator::updateDisplayer(const SimTK::State& s) const
{
getGeometryPath().updateDisplayer(s);
}
//=============================================================================
// SCALING
//=============================================================================
//_____________________________________________________________________________
/**
* Perform computations that need to happen before the muscle is scaled.
* For this object, that entails calculating and storing the muscle-tendon
* length in the current body position.
*
* @param aScaleSet XYZ scale factors for the bodies.
*/
void PathActuator::preScale(const SimTK::State& s, const ScaleSet& aScaleSet)
{
updGeometryPath().preScale(s, aScaleSet);
}
//_____________________________________________________________________________
/**
* Scale the muscle based on XYZ scale factors for each body.
*
* @param aScaleSet XYZ scale factors for the bodies.
* @return Whether muscle was successfully scaled or not.
*/
void PathActuator::scale(const SimTK::State& s, const ScaleSet& aScaleSet)
{
updGeometryPath().scale(s, aScaleSet);
}
//_____________________________________________________________________________
/**
* Perform computations that need to happen after the muscle is scaled.
* For this object, that entails updating the muscle path. Derived classes
* should probably also scale or update some of the force-generating
* properties.
*
* @param aScaleSet XYZ scale factors for the bodies.
*/
void PathActuator::postScale(const SimTK::State& s, const ScaleSet& aScaleSet)
{
updGeometryPath().postScale(s, aScaleSet);
}
<commit_msg>Fix crash calling initSystem with a ConditionalPathPoint that refers to invalid coordinate name to throw exception (instead of crashing dereferencing NULL pointer)<commit_after>/* -------------------------------------------------------------------------- *
* OpenSim: PathActuator.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2012 Stanford University and the Authors *
* Author(s): Ajay Seth *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may *
* not use this file except in compliance with the License. You may obtain a *
* copy of the License at http://www.apache.org/licenses/LICENSE-2.0. *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* -------------------------------------------------------------------------- */
//=============================================================================
// INCLUDES
//=============================================================================
#include "PathActuator.h"
#include "Model.h"
#include "PointForceDirection.h"
using namespace OpenSim;
using namespace std;
//=============================================================================
// CONSTRUCTOR(S) AND DESTRUCTOR
//=============================================================================
// default destructor, copy constructor, copy assignment
//_____________________________________________________________________________
/**
* Default constructor.
*/
PathActuator::PathActuator()
{
setNull();
constructProperties();
}
//=============================================================================
// CONSTRUCTION
//=============================================================================
//_____________________________________________________________________________
/**
* Set the data members of this actuator to their null values.
*/
void PathActuator::setNull()
{
setAuthors("Ajay Seth");
}
//_____________________________________________________________________________
/**
* Connect properties to local pointers.
*/
void PathActuator::constructProperties()
{
constructProperty_GeometryPath(GeometryPath());
constructProperty_optimal_force(1.0);
}
//=============================================================================
// GET AND SET
//=============================================================================
//-----------------------------------------------------------------------------
// OPTIMAL FORCE
//-----------------------------------------------------------------------------
//_____________________________________________________________________________
/**
* Set the optimal force of the force.
*
* @param aOptimalForce Optimal force.
*/
void PathActuator::setOptimalForce(double aOptimalForce)
{
set_optimal_force(aOptimalForce);
}
//_____________________________________________________________________________
/**
* Get the optimal force of the force.
*
* @return Optimal force.
*/
double PathActuator::getOptimalForce() const
{
return get_optimal_force();
}
//-----------------------------------------------------------------------------
// LENGTH
//-----------------------------------------------------------------------------
//_____________________________________________________________________________
/**
* Get the length of the path actuator. This is a convenience function that
* calls the underlying path object for its length.
*
* @return Current length of the actuator's path.
*/
double PathActuator::getLength(const SimTK::State& s) const
{
return getGeometryPath().getLength(s);
}
//_____________________________________________________________________________
/**
* Get the speed of actuator along its path.
*
* @return path lengthening speed.
*/
double PathActuator::getLengtheningSpeed(const SimTK::State& s) const
{
return getGeometryPath().getLengtheningSpeed(s);
}
//_____________________________________________________________________________
/**
* Get the stress of the force.
*
* @return Stress.
*/
double PathActuator::getStress( const SimTK::State& s) const
{
return fabs(getForce(s)/get_optimal_force());
}
//_____________________________________________________________________________
/**
* Add a Path point to the _path of the actuator. The new point is appended
* to the end of the current path
*
*/
void PathActuator::addNewPathPoint(
const std::string& proposedName,
OpenSim::Body& aBody,
const SimTK::Vec3& aPositionOnBody) {
// Create new PathPoint
PathPoint* newPathPoint = updGeometryPath()
.appendNewPathPoint(proposedName, aBody, aPositionOnBody);
// Set offset/position on owner body
newPathPoint->setName(proposedName);
for (int i=0; i<3; i++) // Use interface that does not depend on state
newPathPoint->setLocationCoord(i, aPositionOnBody[i]);
}
//=============================================================================
// COMPUTATIONS
//=============================================================================
//_____________________________________________________________________________
/**
* Compute all quantities necessary for applying the actuator force to the
* model.
*/
double PathActuator::computeActuation( const SimTK::State& s ) const
{
if(_model==NULL)
return 0.0;
// FORCE
return( getControl(s) * get_optimal_force() );
}
//=============================================================================
// APPLICATION
//=============================================================================
//_____________________________________________________________________________
/**
* Apply the actuator force along path wrapping over and connecting rigid bodies
*/
void PathActuator::computeForce( const SimTK::State& s,
SimTK::Vector_<SimTK::SpatialVec>& bodyForces,
SimTK::Vector& mobilityForces) const
{
if(_model==NULL) return;
const GeometryPath &path = getGeometryPath();
// compute path's lengthening speed if necessary
double speed = path.getLengtheningSpeed(s);
// the lengthening speed of this actutor is the "speed" of the actuator
// used to compute power
setSpeed(s, speed);
double force =0;
if( isForceOverriden(s) ) {
force = computeOverrideForce(s);
} else {
force = computeActuation(s);
}
// the force of this actuator used to compute power
setForce(s, force );
path.addInEquivalentForcesOnBodies(s, force, bodyForces);
}
/**
* Compute the moment-arm of this muscle about a coordinate.
*/
double PathActuator::computeMomentArm(const SimTK::State& s, Coordinate& aCoord) const
{
return getGeometryPath().computeMomentArm(s, aCoord);
}
//------------------------------------------------------------------------------
// CONNECT TO MODEL
//------------------------------------------------------------------------------
/**
* Perform some setup functions that happen after the
* object has been deserialized or copied.
*
* @param aModel OpenSim model containing this PathActuator.
*/
void PathActuator::connectToModel(Model& aModel)
{
GeometryPath &path = updGeometryPath();
// Specify underlying ModelComponents prior to calling
// Super::connectToModel() to automatically propagate connectToModel()
// calls to subcomponents. Subsequent addToSystem() will also be
// automatically propagated.
// TODO: this is awkward; subcomponent API needs to be revisited (sherm).
includeAsSubComponent(&path);
// Set owner here in case errors happen later so we can put useful message about responsible party.
path.setOwner(this);
//TODO: can't call this at start of override; this is an API bug.
Super::connectToModel(aModel);
}
//------------------------------------------------------------------------------
// REALIZE DYNAMICS
//------------------------------------------------------------------------------
// See if anyone has an opinion about the path color and change it if so.
void PathActuator::realizeDynamics(const SimTK::State& state) const {
Super::realizeDynamics(state); // Mandatory first line
// if this force is disabled OR it is being overidden (not computing dynamics)
// then don't compute the color of the path.
if(!isDisabled(state) && !isForceOverriden(state)){
const SimTK::Vec3 color = computePathColor(state);
if (!color.isNaN())
getGeometryPath().setColor(state, color);
}
}
//------------------------------------------------------------------------------
// COMPUTE PATH COLOR
//------------------------------------------------------------------------------
// This is the PathActuator base class implementation for choosing the path
// color. Derived classes like Muscle will override this with something
// meaningful.
// TODO: should the default attempt to use the actuation level to control
// colors? Not sure how to scale. Muscles could still override that with
// activation level.
SimTK::Vec3 PathActuator::computePathColor(const SimTK::State& state) const {
return SimTK::Vec3(SimTK::NaN);
}
//=============================================================================
// XML
//=============================================================================
//-----------------------------------------------------------------------------
// UPDATE FROM XML NODE
//-----------------------------------------------------------------------------
//_____________________________________________________________________________
/**
* Update this object based on its XML node.
*
* This method simply calls Object::updateFromXMLNode(SimTK::Xml::Element& aNode, int versionNumber) and then calls
* a few methods in this class to ensure that variable members have been
* set in a consistent manner.
*/
void PathActuator::updateFromXMLNode(SimTK::Xml::Element& aNode, int versionNumber)
{
updGeometryPath().setOwner(this);
Super::updateFromXMLNode(aNode, versionNumber);
}
//_____________________________________________________________________________
/**
* Get the visible object used to represent the muscle.
*/
const VisibleObject* PathActuator::getDisplayer() const
{
return getGeometryPath().getDisplayer();
}
//_____________________________________________________________________________
/**
* Update the visible object used to represent the muscle.
*/
void PathActuator::updateDisplayer(const SimTK::State& s) const
{
getGeometryPath().updateDisplayer(s);
}
//=============================================================================
// SCALING
//=============================================================================
//_____________________________________________________________________________
/**
* Perform computations that need to happen before the muscle is scaled.
* For this object, that entails calculating and storing the muscle-tendon
* length in the current body position.
*
* @param aScaleSet XYZ scale factors for the bodies.
*/
void PathActuator::preScale(const SimTK::State& s, const ScaleSet& aScaleSet)
{
updGeometryPath().preScale(s, aScaleSet);
}
//_____________________________________________________________________________
/**
* Scale the muscle based on XYZ scale factors for each body.
*
* @param aScaleSet XYZ scale factors for the bodies.
* @return Whether muscle was successfully scaled or not.
*/
void PathActuator::scale(const SimTK::State& s, const ScaleSet& aScaleSet)
{
updGeometryPath().scale(s, aScaleSet);
}
//_____________________________________________________________________________
/**
* Perform computations that need to happen after the muscle is scaled.
* For this object, that entails updating the muscle path. Derived classes
* should probably also scale or update some of the force-generating
* properties.
*
* @param aScaleSet XYZ scale factors for the bodies.
*/
void PathActuator::postScale(const SimTK::State& s, const ScaleSet& aScaleSet)
{
updGeometryPath().postScale(s, aScaleSet);
}
<|endoftext|> |
<commit_before>/*************************************************************************
* Copyright(c) 1998-2008, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
// -----------------------------------------------
// particle level cuts for azimuthal isotropic
// expansion in highly central collisions analysis
// author: Cristian Andrei
// [email protected]
// ------------------------------------------------
#include <TF1.h>
#include <TFile.h>
#include "AliAnalysisCentralCutESD.h"
#include "AliESDtrack.h"
class TObject;
class TParticle;
//____________________________________________________________________
ClassImp(AliAnalysisCentralCutESD)
//____________________________________________________________________
AliAnalysisCentralCutESD::AliAnalysisCentralCutESD(const Char_t* name, const Char_t* title)
:AliAnalysisCuts(name,title)
,fReqPID(kFALSE)
,fReqCharge(kFALSE)
,fPartType(kPiPlus)
,fPIDtype("Custom")
,fPriorsFunc(kFALSE)
,fPartPriors()
,fElectronFunction(0)
,fMuonFunction(0)
,fPionFunction(0)
,fKaonFunction(0)
,fProtonFunction(0)
{
// Constructor
// Initialize the priors
fPartPriors[0] = 0.01;
fPartPriors[1] = 0.01;
fPartPriors[2] = 0.85;
fPartPriors[3] = 0.1;
fPartPriors[4] = 0.05;
if(fPriorsFunc){
TFile *f = TFile::Open("$ALICE_ROOT/PWG2/data/PriorProbabilities.root ");
if(!f){
printf("Can't open PWG2 prior probabilities file!\n Exiting ...\n");
return;
}
fElectronFunction = (TF1 *)f->Get("fitElectrons");
fMuonFunction = (TF1 *)f->Get("fitMuons");
fPionFunction = (TF1 *)f->Get("fitPions");
fKaonFunction = (TF1 *)f->Get("fitKaons");
fProtonFunction = (TF1 *)f->Get("fitProtons");
}
}
AliAnalysisCentralCutESD::~AliAnalysisCentralCutESD() {
// Destructor
// Delete the created priors
if(fElectronFunction) delete fElectronFunction;
if(fMuonFunction) delete fMuonFunction;
if(fPionFunction) delete fPionFunction;
if(fKaonFunction) delete fKaonFunction;
if(fProtonFunction) delete fProtonFunction;
}
Bool_t AliAnalysisCentralCutESD::IsSelected(TObject *obj){
// Checks if a particle passes the cuts
AliESDtrack *track = dynamic_cast<AliESDtrack *>(obj);
if(!track){
printf("AliAnalysisCentralCutESD:IsSelected ->Can't get track!\n");
return kFALSE;
}
if(fReqCharge){
if(!IsCharged(track)) return kFALSE;
}
if(fReqPID){
if(!IsA(track, fPartType)) return kFALSE;
}
return kTRUE;
}
Double_t AliAnalysisCentralCutESD::GetPriors(Int_t i, Double_t p) {
//Return the a priori probs
Double_t priors=0;
if(fPriorsFunc) {
if(i == 0) priors = fElectronFunction->Eval(p);
if(i == 1) priors = fMuonFunction->Eval(p);
if(i == 2) priors = fPionFunction->Eval(p);
if(i == 3) priors = fKaonFunction->Eval(p);
if(i == 4) priors = fProtonFunction->Eval(p);
}
else {
priors = fPartPriors[i];
}
return priors;
}
Bool_t AliAnalysisCentralCutESD::IsA(AliESDtrack *track, PDG_t reqPartType){
// Determines the type of the particle
Int_t charge;
if(reqPartType < 0){
charge = -1;
}
else{
charge = 1;
}
Double_t probability[5] = {0.0,0.0,0.0,0.0,0.0};
Double_t w[5] = {0.0,0.0,0.0,0.0,0.0};
Long64_t partType = 0;
Double_t p = track->P();
track->GetESDpid(probability);
Double_t s = 0.0;
for(Int_t i = 0; i < AliPID::kSPECIES; i++){
s += probability[i]*GetPriors(i,p);
}
if(!s < 0.000001) {
for(Int_t i = 0; i < AliPID::kSPECIES; i++){
w[i] = probability[i]*GetPriors(i,p)/s;
}
}
if(fPIDtype.Contains("Bayesian")) {
partType = TMath::LocMax(AliPID::kSPECIES,w);
if(partType<0.) return kFALSE;
}
else if(fPIDtype.Contains("Custom")){
for(Int_t i=0;i<AliPID::kSPECIES;i++) {
if(w[i]>0.9){
partType = i;
}
}
}
else{
printf("Unknown PID method!\n");
return kFALSE;
}
if(partType<0.) return kFALSE;
if((AliPID::ParticleCode(partType)) != reqPartType){
return kFALSE;
}
if(track->Charge() != charge) return kFALSE;
return kTRUE;
}
Bool_t AliAnalysisCentralCutESD::IsCharged(AliESDtrack* const track) const{
if(track->Charge() == 0) return kFALSE;
return kTRUE;
}
<commit_msg>Fixing Coverity 11174 (B.Hippolyte)<commit_after>/*************************************************************************
* Copyright(c) 1998-2008, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
// -----------------------------------------------
// particle level cuts for azimuthal isotropic
// expansion in highly central collisions analysis
// author: Cristian Andrei
// [email protected]
// ------------------------------------------------
#include <TF1.h>
#include <TFile.h>
#include "AliAnalysisCentralCutESD.h"
#include "AliESDtrack.h"
class TObject;
class TParticle;
//____________________________________________________________________
ClassImp(AliAnalysisCentralCutESD)
//____________________________________________________________________
AliAnalysisCentralCutESD::AliAnalysisCentralCutESD(const Char_t* name, const Char_t* title)
:AliAnalysisCuts(name,title)
,fReqPID(kFALSE)
,fReqCharge(kFALSE)
,fPartType(kPiPlus)
,fPIDtype("Custom")
,fPriorsFunc(kFALSE)
,fPartPriors()
,fElectronFunction(0)
,fMuonFunction(0)
,fPionFunction(0)
,fKaonFunction(0)
,fProtonFunction(0)
{
// Constructor
// Initialize the priors
fPartPriors[0] = 0.01;
fPartPriors[1] = 0.01;
fPartPriors[2] = 0.85;
fPartPriors[3] = 0.1;
fPartPriors[4] = 0.05;
if(fPriorsFunc){
TFile *f = TFile::Open("$ALICE_ROOT/PWG2/data/PriorProbabilities.root ");
if(!f){
printf("Can't open PWG2 prior probabilities file!\n Exiting ...\n");
return;
}
fElectronFunction = (TF1 *)f->Get("fitElectrons");
fMuonFunction = (TF1 *)f->Get("fitMuons");
fPionFunction = (TF1 *)f->Get("fitPions");
fKaonFunction = (TF1 *)f->Get("fitKaons");
fProtonFunction = (TF1 *)f->Get("fitProtons");
}
}
AliAnalysisCentralCutESD::~AliAnalysisCentralCutESD() {
// Destructor
// Delete the created priors
if(fElectronFunction) delete fElectronFunction;
if(fMuonFunction) delete fMuonFunction;
if(fPionFunction) delete fPionFunction;
if(fKaonFunction) delete fKaonFunction;
if(fProtonFunction) delete fProtonFunction;
}
Bool_t AliAnalysisCentralCutESD::IsSelected(TObject *obj){
// Checks if a particle passes the cuts
AliESDtrack *track = dynamic_cast<AliESDtrack *>(obj);
if(!track){
printf("AliAnalysisCentralCutESD:IsSelected ->Can't get track!\n");
return kFALSE;
}
if(fReqCharge){
if(!IsCharged(track)) return kFALSE;
}
if(fReqPID){
if(!IsA(track, fPartType)) return kFALSE;
}
return kTRUE;
}
Double_t AliAnalysisCentralCutESD::GetPriors(Int_t i, Double_t p) {
//Return the a priori probs
Double_t priors=0;
if(fPriorsFunc) {
if(i == 0) priors = fElectronFunction->Eval(p);
if(i == 1) priors = fMuonFunction->Eval(p);
if(i == 2) priors = fPionFunction->Eval(p);
if(i == 3) priors = fKaonFunction->Eval(p);
if(i == 4) priors = fProtonFunction->Eval(p);
}
else {
priors = fPartPriors[i];
}
return priors;
}
Bool_t AliAnalysisCentralCutESD::IsA(AliESDtrack *track, PDG_t reqPartType){
// Determines the type of the particle
Int_t charge;
if(reqPartType < 0){
charge = -1;
}
else{
charge = 1;
}
Double_t probability[5] = {0.0,0.0,0.0,0.0,0.0};
Double_t w[5] = {0.0,0.0,0.0,0.0,0.0};
Long64_t partType = 0;
Double_t p = track->P();
track->GetESDpid(probability);
Double_t s = 0.0;
for(Int_t i = 0; i < AliPID::kSPECIES; i++){
s += probability[i]*GetPriors(i,p);
}
if(!s < 0.000001) {
for(Int_t i = 0; i < AliPID::kSPECIES; i++){
w[i] = probability[i]*GetPriors(i,p)/s;
}
}
if(fPIDtype.Contains("Bayesian")) {
partType = TMath::LocMax(AliPID::kSPECIES,w);
if(partType<0.) return kFALSE;
}
else if(fPIDtype.Contains("Custom")){
for(Int_t i=0;i<AliPID::kSPECIES;i++) {
if(w[i]>0.9){
partType = i;
}
}
}
else{
printf("Unknown PID method!\n");
return kFALSE;
}
if(partType<0.) return kFALSE;
else if((AliPID::ParticleCode(partType)) != reqPartType) return kFALSE;
if(track->Charge() != charge) return kFALSE;
return kTRUE;
}
Bool_t AliAnalysisCentralCutESD::IsCharged(AliESDtrack* const track) const{
if(track->Charge() == 0) return kFALSE;
return kTRUE;
}
<|endoftext|> |
<commit_before>#include "cinder/app/AppCocoaTouch.h"
#include "cinder/app/Renderer.h"
#include "cinder/Surface.h"
#include "cinder/gl/Texture.h"
#include "cinder/Camera.h"
using namespace ci;
using namespace ci::app;
class iPhoneAccelerometerApp : public AppCocoaTouch {
public:
virtual void setup();
virtual void accelerated( AccelEvent event );
virtual void update();
virtual void draw();
Matrix44f mModelView;
};
void iPhoneAccelerometerApp::setup()
{
enableAccelerometer( 30.0f, 0.5f );
}
void iPhoneAccelerometerApp::accelerated( AccelEvent event )
{
mModelView = event.getMatrix();
}
void iPhoneAccelerometerApp::update()
{
}
void iPhoneAccelerometerApp::draw()
{
gl::clear( Color( 0.2f, 0.2f, 0.3f ) );
gl::enableDepthRead();
CameraPersp cam = CameraPersp( getWindowWidth(), getWindowHeight(), 45.0f );
cam.setPerspective( 60, getWindowAspectRatio(), 1, 1000 );
cam.lookAt( Vec3f( 0, 0, 3 ), Vec3f::zero() );
gl::setMatrices( cam );
gl::multModelView( mModelView );
gl::drawColorCube( Vec3f::zero(), Vec3f( 1, 1, 1 ) );
}
CINDER_APP_COCOA_TOUCH( iPhoneAccelerometerApp, RendererGl )
<commit_msg>Cleaning up some code on accelerometer sample<commit_after>#include "cinder/app/AppCocoaTouch.h"
#include "cinder/Camera.h"
using namespace ci;
using namespace ci::app;
class iPhoneAccelerometerApp : public AppCocoaTouch {
public:
virtual void setup();
virtual void accelerated( AccelEvent event );
virtual void draw();
Matrix44f mModelView;
CameraPersp mCam;
};
void iPhoneAccelerometerApp::setup()
{
enableAccelerometer();
mCam.setPerspective( 60, getWindowAspectRatio(), 1, 1000 );
mCam.lookAt( Vec3f( 0, 0, 3 ), Vec3f::zero() );
}
void iPhoneAccelerometerApp::accelerated( AccelEvent event )
{
mModelView = event.getMatrix();
}
void iPhoneAccelerometerApp::draw()
{
gl::clear( Color( 0.2f, 0.2f, 0.3f ) );
gl::enableDepthRead();
gl::setMatrices( mCam );
gl::multModelView( mModelView );
gl::drawColorCube( Vec3f::zero(), Vec3f( 1, 1, 1 ) );
}
CINDER_APP_COCOA_TOUCH( iPhoneAccelerometerApp, RendererGl )
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: MPreparedStatement.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: oj $ $Date: 2001-11-26 13:51:14 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the License); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an AS IS basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef CONNECTIVITY_SPREPAREDSTATEMENT_HXX
#define CONNECTIVITY_SPREPAREDSTATEMENT_HXX
#ifndef CONNECTIVITY_SRESULTSET_HXX
#include "MResultSet.hxx"
#endif
#ifndef CONNECTIVITY_SSTATEMENT_HXX
#include "MStatement.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XPREPAREDSTATEMENT_HPP_
#include <com/sun/star/sdbc/XPreparedStatement.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XPARAMETERS_HPP_
#include <com/sun/star/sdbc/XParameters.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSETMETADATASUPPLIER_HPP_
#include <com/sun/star/sdbc/XResultSetMetaDataSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XMULTIPLERESULTS_HPP_
#include <com/sun/star/sdbc/XMultipleResults.hpp>
#endif
#ifndef _CPPUHELPER_COMPBASE5_HXX_
#include <cppuhelper/compbase5.hxx>
#endif
namespace connectivity
{
namespace mozab
{
class OBoundParam;
typedef ::cppu::ImplHelper5< ::com::sun::star::sdbc::XPreparedStatement,
::com::sun::star::sdbc::XParameters,
::com::sun::star::sdbc::XResultSetMetaDataSupplier,
::com::sun::star::sdbc::XMultipleResults,
::com::sun::star::lang::XServiceInfo> OPreparedStatement_BASE;
class OPreparedStatement : public OStatement_BASE2,
public OPreparedStatement_BASE
{
protected:
struct Parameter
{
::com::sun::star::uno::Any aValue;
sal_Int32 nDataType;
Parameter(const ::com::sun::star::uno::Any& rValue,
sal_Int32 rDataType) : aValue(rValue),nDataType(rDataType)
{
}
};
::std::vector< Parameter> m_aParameters;
//====================================================================
// Data attributes
//====================================================================
sal_Int32 m_nNumParams; // Number of parameter markers
// for the prepared statement
::rtl::OUString m_sSqlStatement;
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > m_xMetaData;
sal_Bool m_bPrepared;
OResultSet* m_pResultSet;
::vos::ORef<connectivity::OSQLColumns> m_xParamColumns; // the parameter columns
OValueRow m_aParameterRow;
void checkParameterIndex(sal_Int32 _parameterIndex);
protected:
virtual void SAL_CALL setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,
const ::com::sun::star::uno::Any& rValue)
throw (::com::sun::star::uno::Exception);
virtual ~OPreparedStatement();
virtual void SAL_CALL disposing();
virtual void parseSql( const ::rtl::OUString& sql ) throw (
::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException );
virtual OResultSet* createResultSet();
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet> initResultSet();
void checkAndResizeParameters(sal_Int32 parameterIndex);
void setParameter(sal_Int32 parameterIndex, const ORowSetValue& x);
sal_uInt32 AddParameter(connectivity::OSQLParseNode * pParameter,
const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xCol);
void scanParameter(OSQLParseNode* pParseNode,::std::vector< OSQLParseNode*>& _rParaNodes);
void describeColumn(OSQLParseNode* _pParameter,OSQLParseNode* _pNode,const OSQLTable& _xTable);
void describeParameter();
virtual void initializeResultSet( OResultSet* _pResult );
public:
DECLARE_SERVICE_INFO();
// ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird:
OPreparedStatement( OConnection* _pConnection,const ::rtl::OUString& sql);
//XInterface
virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL acquire() throw();
virtual void SAL_CALL release() throw();
//XTypeProvider
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw(::com::sun::star::uno::RuntimeException);
// XPreparedStatement
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL executeQuery( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL executeUpdate( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL execute( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > SAL_CALL getConnection( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
// XParameters
virtual void SAL_CALL setNull( sal_Int32 parameterIndex, sal_Int32 sqlType ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setObjectNull( sal_Int32 parameterIndex, sal_Int32 sqlType, const ::rtl::OUString& typeName ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setBoolean( sal_Int32 parameterIndex, sal_Bool x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setByte( sal_Int32 parameterIndex, sal_Int8 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setShort( sal_Int32 parameterIndex, sal_Int16 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setInt( sal_Int32 parameterIndex, sal_Int32 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setLong( sal_Int32 parameterIndex, sal_Int64 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setFloat( sal_Int32 parameterIndex, float x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setDouble( sal_Int32 parameterIndex, double x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setString( sal_Int32 parameterIndex, const ::rtl::OUString& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setBytes( sal_Int32 parameterIndex, const ::com::sun::star::uno::Sequence< sal_Int8 >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setDate( sal_Int32 parameterIndex, const ::com::sun::star::util::Date& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setTime( sal_Int32 parameterIndex, const ::com::sun::star::util::Time& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setTimestamp( sal_Int32 parameterIndex, const ::com::sun::star::util::DateTime& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setBinaryStream( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& x, sal_Int32 length ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setCharacterStream( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& x, sal_Int32 length ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setObject( sal_Int32 parameterIndex, const ::com::sun::star::uno::Any& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setObjectWithInfo( sal_Int32 parameterIndex, const ::com::sun::star::uno::Any& x, sal_Int32 targetSqlType, sal_Int32 scale ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setRef( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRef >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setBlob( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XBlob >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setClob( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XClob >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setArray( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XArray >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL clearParameters( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
// XCloseable
virtual void SAL_CALL close( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
// XResultSetMetaDataSupplier
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > SAL_CALL getMetaData( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
// XMultipleResults
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL getResultSet( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getUpdateCount( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL getMoreResults( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
};
}
}
#endif // CONNECTIVITY_SPREPAREDSTATEMENT_HXX
<commit_msg>INTEGRATION: CWS mozab04 (1.4.182); FILE MERGED 2004/04/12 10:15:53 windly 1.4.182.1: #i6883# make mozab driver threadsafe<commit_after>/*************************************************************************
*
* $RCSfile: MPreparedStatement.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hjs $ $Date: 2004-06-25 18:28:38 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the License); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an AS IS basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef CONNECTIVITY_SPREPAREDSTATEMENT_HXX
#define CONNECTIVITY_SPREPAREDSTATEMENT_HXX
#ifndef CONNECTIVITY_SRESULTSET_HXX
#include "MResultSet.hxx"
#endif
#ifndef CONNECTIVITY_SSTATEMENT_HXX
#include "MStatement.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XPREPAREDSTATEMENT_HPP_
#include <com/sun/star/sdbc/XPreparedStatement.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XPARAMETERS_HPP_
#include <com/sun/star/sdbc/XParameters.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSETMETADATASUPPLIER_HPP_
#include <com/sun/star/sdbc/XResultSetMetaDataSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XMULTIPLERESULTS_HPP_
#include <com/sun/star/sdbc/XMultipleResults.hpp>
#endif
#ifndef _CPPUHELPER_COMPBASE5_HXX_
#include <cppuhelper/compbase5.hxx>
#endif
namespace connectivity
{
namespace mozab
{
class OBoundParam;
typedef ::cppu::ImplHelper5< ::com::sun::star::sdbc::XPreparedStatement,
::com::sun::star::sdbc::XParameters,
::com::sun::star::sdbc::XResultSetMetaDataSupplier,
::com::sun::star::sdbc::XMultipleResults,
::com::sun::star::lang::XServiceInfo> OPreparedStatement_BASE;
class OPreparedStatement : public OStatement_BASE2,
public OPreparedStatement_BASE
{
protected:
struct Parameter
{
::com::sun::star::uno::Any aValue;
sal_Int32 nDataType;
Parameter(const ::com::sun::star::uno::Any& rValue,
sal_Int32 rDataType) : aValue(rValue),nDataType(rDataType)
{
}
};
::std::vector< Parameter> m_aParameters;
//====================================================================
// Data attributes
//====================================================================
sal_Int32 m_nNumParams; // Number of parameter markers
// for the prepared statement
::rtl::OUString m_sSqlStatement;
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > m_xMetaData;
sal_Bool m_bPrepared;
OResultSet* m_pResultSet;
::vos::ORef<connectivity::OSQLColumns> m_xParamColumns; // the parameter columns
OValueRow m_aParameterRow;
void checkParameterIndex(sal_Int32 _parameterIndex);
protected:
virtual void SAL_CALL setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,
const ::com::sun::star::uno::Any& rValue)
throw (::com::sun::star::uno::Exception);
virtual ~OPreparedStatement();
virtual void SAL_CALL disposing();
virtual sal_Bool parseSql( const ::rtl::OUString& sql , sal_Bool bAdjusted = sal_False) throw (
::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException );
virtual OResultSet* createResultSet();
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet> initResultSet();
void checkAndResizeParameters(sal_Int32 parameterIndex);
void setParameter(sal_Int32 parameterIndex, const ORowSetValue& x);
sal_uInt32 AddParameter(connectivity::OSQLParseNode * pParameter,
const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xCol);
void scanParameter(OSQLParseNode* pParseNode,::std::vector< OSQLParseNode*>& _rParaNodes);
void describeColumn(OSQLParseNode* _pParameter,OSQLParseNode* _pNode,const OSQLTable& _xTable);
void describeParameter();
virtual void initializeResultSet( OResultSet* _pResult );
public:
DECLARE_SERVICE_INFO();
// ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird:
OPreparedStatement( OConnection* _pConnection,const ::rtl::OUString& sql);
//XInterface
virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL acquire() throw();
virtual void SAL_CALL release() throw();
//XTypeProvider
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw(::com::sun::star::uno::RuntimeException);
// XPreparedStatement
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL executeQuery( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL executeUpdate( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL execute( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > SAL_CALL getConnection( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
// XParameters
virtual void SAL_CALL setNull( sal_Int32 parameterIndex, sal_Int32 sqlType ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setObjectNull( sal_Int32 parameterIndex, sal_Int32 sqlType, const ::rtl::OUString& typeName ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setBoolean( sal_Int32 parameterIndex, sal_Bool x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setByte( sal_Int32 parameterIndex, sal_Int8 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setShort( sal_Int32 parameterIndex, sal_Int16 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setInt( sal_Int32 parameterIndex, sal_Int32 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setLong( sal_Int32 parameterIndex, sal_Int64 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setFloat( sal_Int32 parameterIndex, float x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setDouble( sal_Int32 parameterIndex, double x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setString( sal_Int32 parameterIndex, const ::rtl::OUString& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setBytes( sal_Int32 parameterIndex, const ::com::sun::star::uno::Sequence< sal_Int8 >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setDate( sal_Int32 parameterIndex, const ::com::sun::star::util::Date& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setTime( sal_Int32 parameterIndex, const ::com::sun::star::util::Time& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setTimestamp( sal_Int32 parameterIndex, const ::com::sun::star::util::DateTime& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setBinaryStream( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& x, sal_Int32 length ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setCharacterStream( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& x, sal_Int32 length ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setObject( sal_Int32 parameterIndex, const ::com::sun::star::uno::Any& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setObjectWithInfo( sal_Int32 parameterIndex, const ::com::sun::star::uno::Any& x, sal_Int32 targetSqlType, sal_Int32 scale ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setRef( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRef >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setBlob( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XBlob >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setClob( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XClob >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setArray( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XArray >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL clearParameters( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
// XCloseable
virtual void SAL_CALL close( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
// XResultSetMetaDataSupplier
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > SAL_CALL getMetaData( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
// XMultipleResults
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL getResultSet( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getUpdateCount( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL getMoreResults( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
};
}
}
#endif // CONNECTIVITY_SPREPAREDSTATEMENT_HXX
<|endoftext|> |
<commit_before>#include "NativeJIT/CodeGen/ExecutionBuffer.h"
#include "NativeJIT/CodeGen/FunctionBuffer.h"
#include "NativeJIT/Function.h"
#include "Temporary/Allocator.h"
#include <cassert>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using NativeJIT::Allocator;
using NativeJIT::ExecutionBuffer;
using NativeJIT::Function;
using NativeJIT::FunctionBuffer;
// TODO: refactor so that we push JIT nodes the same way we do for the
// non-JIT'ed version.
int64_t calc() {
ExecutionBuffer codeAllocator(8192);
Allocator allocator(8192);
FunctionBuffer code(codeAllocator, 8192);
Function<int64_t, int64_t, int64_t> expr(allocator, code);
int numArgs = 2;
int curArg = 0;
std::string tok;
std::vector<int64_t> stack;
NativeJIT::Node<int64_t> *temp = NULL;
std::vector<int64_t> args;
while (std::cin >> tok) {
int64_t digits;
if (std::istringstream(tok) >> digits) {
if (curArg < numArgs) {
stack.push_back(digits);
args.push_back(digits);
++curArg;
std::cout << "Add token to stack" << std::endl;
} else {
std::cout << "Out of arguments. Please enter an operator.\n";
}
} else {
if (stack.size() < 2) {
std::cout << "Not enough operands. Please enter an operand.\n";
continue;
}
if (tok == "+") {
int64_t op2 = stack.back(); stack.pop_back();
int64_t op1 = stack.back(); stack.pop_back();
stack.push_back(op1 + op2);
--curArg;
std::cout << "Add node" << std::endl;
temp = &expr.Add(expr.GetP1(), expr.GetP2());
} else if (tok == "*") {
int64_t op2 = stack.back(); stack.pop_back();
int64_t op1 = stack.back(); stack.pop_back();
stack.push_back(op1 * op2);
--curArg;
std::cout << "Mul node" << std::endl;
temp = &expr.Mul(expr.GetP1(), expr.GetP2());
} else {
std::cout << "Invalid input: " << tok << std::endl;
}
}
}
std::cout << "Compiling" << std::endl;
auto fn = expr.Compile(*temp);
int64_t res = fn(args[0], args[1]);
std::cout << "JIT result:normal result -- " << res << ":" << stack.back() << std::endl;
assert(res == stack.back());
return stack.back();
}
int main() {
std::cout << calc() << std::endl;
}
<commit_msg>Make calc example more uniform.<commit_after>#include "NativeJIT/CodeGen/ExecutionBuffer.h"
#include "NativeJIT/CodeGen/FunctionBuffer.h"
#include "NativeJIT/Function.h"
#include "Temporary/Allocator.h"
#include <cassert>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using NativeJIT::Allocator;
using NativeJIT::ExecutionBuffer;
using NativeJIT::Function;
using NativeJIT::FunctionBuffer;
// TODO: refactor so that we push JIT nodes the same way we do for the
// non-JIT'ed version.
int64_t calc() {
ExecutionBuffer codeAllocator(8192);
Allocator allocator(8192);
FunctionBuffer code(codeAllocator, 8192);
Function<int64_t> expr(allocator, code);
std::string tok;
std::vector<int64_t> stack;
std::vector<NativeJIT::Node<int64_t>*> jitStack;
while (std::cin >> tok) {
int64_t digits;
if (std::istringstream(tok) >> digits) {
stack.push_back(digits);
jitStack.push_back(&expr.Immediate(digits));
} else {
if (stack.size() < 2) {
std::cout << "Not enough operands. Please enter an operand.\n";
continue;
}
if (tok == "+") {
int64_t op2 = stack.back(); stack.pop_back();
int64_t op1 = stack.back(); stack.pop_back();
stack.push_back(op1 + op2);
auto right = jitStack.back(); jitStack.pop_back();
auto left = jitStack.back(); jitStack.pop_back();
jitStack.push_back(&(expr.Add(*left, *right)));
} else if (tok == "*") {
int64_t op2 = stack.back(); stack.pop_back();
int64_t op1 = stack.back(); stack.pop_back();
stack.push_back(op1 * op2);
auto right = jitStack.back(); jitStack.pop_back();
auto left = jitStack.back(); jitStack.pop_back();
jitStack.push_back(&(expr.Mul(*left, *right)));
} else if (tok == "-") {
int64_t op2 = stack.back(); stack.pop_back();
int64_t op1 = stack.back(); stack.pop_back();
stack.push_back(op1 - op2);
auto right = jitStack.back(); jitStack.pop_back();
auto left = jitStack.back(); jitStack.pop_back();
jitStack.push_back(&(expr.Sub(*left, *right)));
} else if (tok == "|") {
int64_t op2 = stack.back(); stack.pop_back();
int64_t op1 = stack.back(); stack.pop_back();
stack.push_back(op1 | op2);
auto right = jitStack.back(); jitStack.pop_back();
auto left = jitStack.back(); jitStack.pop_back();
jitStack.push_back(&(expr.Or(*left, *right)));
} else if (tok == "&") {
int64_t op2 = stack.back(); stack.pop_back();
int64_t op1 = stack.back(); stack.pop_back();
stack.push_back(op1 & op2);
auto right = jitStack.back(); jitStack.pop_back();
auto left = jitStack.back(); jitStack.pop_back();
jitStack.push_back(&(expr.And(*left, *right)));
} else {
std::cout << "Invalid input: " << tok << std::endl;
}
}
}
std::cout << "Compiling" << std::endl;
auto fn = expr.Compile(*jitStack.back());
auto res = fn();
std::cout << "JIT result:normal result -- " << res << ":" << stack.back() << std::endl;
assert(res == stack.back());
return stack.back();
}
int main() {
std::cout << calc() << std::endl;
}
<|endoftext|> |
<commit_before><commit_msg>INTEGRATION: CWS gh14 (1.10.66); FILE MERGED 2007/05/25 11:33:39 gh 1.10.66.1: #i76946# parent not set anymore -> crash<commit_after><|endoftext|> |
<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2016 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Hammad Mazhar, Radu Serban
// =============================================================================
#include "chrono_parallel/collision/ChContactContainerParallel.h"
#include "chrono_parallel/physics/ChSystemParallel.h"
//
#include "chrono/physics/ChSystem.h"
#include "chrono/physics/ChBody.h"
#include "chrono/physics/ChParticlesClones.h"
namespace chrono {
using namespace collision;
using namespace geometry;
ChContactContainerParallel::ChContactContainerParallel(ChParallelDataManager* dc) : data_manager(dc) {
contactlist_6_6.clear();
n_added_6_6 = 0;
}
ChContactContainerParallel::ChContactContainerParallel(const ChContactContainerParallel& other)
: ChContactContainer(other) {
//// TODO
}
ChContactContainerParallel::~ChContactContainerParallel() {
RemoveAllContacts();
}
void ChContactContainerParallel::RemoveAllContacts() {
std::list<ChContact_6_6*>::iterator itercontact = contactlist_6_6.begin();
while (itercontact != contactlist_6_6.end()) {
delete (*itercontact);
(*itercontact) = 0;
++itercontact;
}
contactlist_6_6.clear();
lastcontact_6_6 = contactlist_6_6.begin();
n_added_6_6 = 0;
}
void ChContactContainerParallel::BeginAddContact() {
lastcontact_6_6 = contactlist_6_6.begin();
n_added_6_6 = 0;
}
void ChContactContainerParallel::EndAddContact() {
// remove contacts that are beyond last contact
while (lastcontact_6_6 != contactlist_6_6.end()) {
delete (*lastcontact_6_6);
lastcontact_6_6 = contactlist_6_6.erase(lastcontact_6_6);
}
}
static inline chrono::ChVector<> ToChVector(const real3& a) {
return chrono::ChVector<>(a.x, a.y, a.z);
}
void ChContactContainerParallel::ReportAllContacts(std::shared_ptr<ReportContactCallback> callback) {
// Readibility
auto& ptA = data_manager->host_data.cpta_rigid_rigid;
auto& ptB = data_manager->host_data.cptb_rigid_rigid;
auto& nrm = data_manager->host_data.norm_rigid_rigid;
auto& depth = data_manager->host_data.dpth_rigid_rigid;
auto& erad = data_manager->host_data.erad_rigid_rigid;
auto& bids = data_manager->host_data.bids_rigid_rigid;
// Grab the list of bodies.
// NOTE: we assume that bodies were added in the order of their IDs!
auto bodylist = GetSystem()->Get_bodylist();
// No reaction forces or torques reported!
ChVector<> zero(0, 0, 0);
// Contact plane
ChVector<> plane_x, plane_y, plane_z;
ChMatrix33<> contact_plane;
for (uint i = 0; i < data_manager->num_rigid_contacts; i++) {
// Contact plane coordinate system (normal in x direction)
XdirToDxDyDz(ToChVector(nrm[i]), VECT_Y, plane_x, plane_y, plane_z);
contact_plane.Set_A_axis(plane_x, plane_y, plane_z);
// Invoke callback function
bool proceed =
callback->OnReportContact(ToChVector(ptA[i]), ToChVector(ptB[i]), contact_plane, depth[i], erad[i], zero,
zero, bodylist[bids[i].x].get(), bodylist[bids[i].y].get());
if (!proceed)
break;
}
}
void ChContactContainerParallel::ComputeContactForces() {
// Defer to associated system
static_cast<ChSystemParallel*>(GetSystem())->CalculateContactForces();
}
ChVector<> ChContactContainerParallel::GetContactableForce(ChContactable* contactable) {
// If contactable is a body, defer to associated system
if (auto body = dynamic_cast<ChBody*>(contactable)) {
real3 frc = static_cast<ChSystemParallel*>(GetSystem())->GetBodyContactForce(body->GetId());
return ToChVector(frc);
}
return ChVector<>(0, 0, 0);
}
ChVector<> ChContactContainerParallel::GetContactableTorque(ChContactable* contactable) {
// If contactable is a body, defer to associated system
if (auto body = dynamic_cast<ChBody*>(contactable)) {
real3 trq = static_cast<ChSystemParallel*>(GetSystem())->GetBodyContactTorque(body->GetId());
return ToChVector(trq);
}
return ChVector<>(0, 0, 0);
}
} // end namespace chrono
<commit_msg>Calculate and pass contact forces and torques to user callback function (SMC, Chrono::Parallel)<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2016 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Hammad Mazhar, Radu Serban
// =============================================================================
#include "chrono_parallel/collision/ChContactContainerParallel.h"
#include "chrono_parallel/physics/ChSystemParallel.h"
//
#include "chrono/physics/ChSystem.h"
#include "chrono/physics/ChBody.h"
#include "chrono/physics/ChParticlesClones.h"
namespace chrono {
using namespace collision;
using namespace geometry;
ChContactContainerParallel::ChContactContainerParallel(ChParallelDataManager* dc) : data_manager(dc) {
contactlist_6_6.clear();
n_added_6_6 = 0;
}
ChContactContainerParallel::ChContactContainerParallel(const ChContactContainerParallel& other)
: ChContactContainer(other) {
//// TODO
}
ChContactContainerParallel::~ChContactContainerParallel() {
RemoveAllContacts();
}
void ChContactContainerParallel::RemoveAllContacts() {
std::list<ChContact_6_6*>::iterator itercontact = contactlist_6_6.begin();
while (itercontact != contactlist_6_6.end()) {
delete (*itercontact);
(*itercontact) = 0;
++itercontact;
}
contactlist_6_6.clear();
lastcontact_6_6 = contactlist_6_6.begin();
n_added_6_6 = 0;
}
void ChContactContainerParallel::BeginAddContact() {
lastcontact_6_6 = contactlist_6_6.begin();
n_added_6_6 = 0;
}
void ChContactContainerParallel::EndAddContact() {
// remove contacts that are beyond last contact
while (lastcontact_6_6 != contactlist_6_6.end()) {
delete (*lastcontact_6_6);
lastcontact_6_6 = contactlist_6_6.erase(lastcontact_6_6);
}
}
static inline chrono::ChVector<> ToChVector(const real3& a) {
return chrono::ChVector<>(a.x, a.y, a.z);
}
void ChContactContainerParallel::ReportAllContacts(std::shared_ptr<ReportContactCallback> callback) {
// Readibility
auto& ptA = data_manager->host_data.cpta_rigid_rigid;
auto& ptB = data_manager->host_data.cptb_rigid_rigid;
auto& nrm = data_manager->host_data.norm_rigid_rigid;
auto& depth = data_manager->host_data.dpth_rigid_rigid;
auto& erad = data_manager->host_data.erad_rigid_rigid;
auto& bids = data_manager->host_data.bids_rigid_rigid;
auto& ct_force = data_manager->host_data.ct_force;
auto& ct_torque = data_manager->host_data.ct_torque;
// Grab the list of bodies.
// NOTE: we assume that bodies were added in the order of their IDs!
auto bodylist = GetSystem()->Get_bodylist();
// Contact forces
ChVector<> force;
ChVector<> torque;
// Contact plane
ChVector<> plane_x, plane_y, plane_z;
ChMatrix33<> contact_plane;
for (uint i = 0; i < data_manager->num_rigid_contacts; i++) {
auto bodyA = bodylist[bids[i].x].get();
auto bodyB = bodylist[bids[i].y].get();
auto pA = ToChVector(ptA[i]); // in absolute frame
auto pB = ToChVector(ptB[i]); // in absolute frame
// Contact plane coordinate system (normal in x direction from pB to pA)
XdirToDxDyDz(ToChVector(nrm[i]), VECT_Y, plane_x, plane_y, plane_z);
contact_plane.Set_A_axis(plane_x, plane_y, plane_z);
// Contact force and torque expressed in the contact plane
switch (GetSystem()->GetContactMethod()) {
case ChContactMethod::NSC: {
//// TODO
force = ChVector<>(0, 0, 0);
torque = ChVector<>(0, 0, 0);
break;
}
case ChContactMethod::SMC: {
// Convert force and torque to the contact frame.
// Consistent with the normal direction, use force and torque on body B.
auto force_abs = ToChVector(ct_force[2 * i + 1]); // in abs frame
auto torque_loc = ToChVector(ct_torque[2 * i + 1]); // in body frame, at body origin
auto force_loc = bodyB->TransformDirectionParentToLocal(force_abs); // in body frame
auto ptB_loc = bodyB->TransformPointParentToLocal(pB); // in body frame
force = contact_plane.transpose() * force_abs; // in contact frame
auto torque_loc1 = torque_loc - ptB_loc.Cross(force_loc); // in body frame, at contact
auto torque_abs = bodyB->TransformDirectionLocalToParent(torque_loc1); // in abs frame, at contact
torque = contact_plane.transpose() * force_abs; // in contact frame, at contact
break;
}
}
// Invoke callback function
bool proceed = callback->OnReportContact(pA, pB, contact_plane, depth[i], erad[i], force, torque, bodyA, bodyB);
if (!proceed)
break;
}
}
void ChContactContainerParallel::ComputeContactForces() {
// Defer to associated system
static_cast<ChSystemParallel*>(GetSystem())->CalculateContactForces();
}
ChVector<> ChContactContainerParallel::GetContactableForce(ChContactable* contactable) {
// If contactable is a body, defer to associated system
if (auto body = dynamic_cast<ChBody*>(contactable)) {
real3 frc = static_cast<ChSystemParallel*>(GetSystem())->GetBodyContactForce(body->GetId());
return ToChVector(frc);
}
return ChVector<>(0, 0, 0);
}
ChVector<> ChContactContainerParallel::GetContactableTorque(ChContactable* contactable) {
// If contactable is a body, defer to associated system
if (auto body = dynamic_cast<ChBody*>(contactable)) {
real3 trq = static_cast<ChSystemParallel*>(GetSystem())->GetBodyContactTorque(body->GetId());
return ToChVector(trq);
}
return ChVector<>(0, 0, 0);
}
} // end namespace chrono
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_mem_startclocks.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
//------------------------------------------------------------------------------
/// @file p9_mem_startclocks.C
///
/// @brief Start clocks on MBA/MCAs
//------------------------------------------------------------------------------
// *HWP HW Owner : Abhishek Agarwal <[email protected]>
// *HWP HW Backup Owner : Srinivas V Naga <[email protected]>
// *HWP FW Owner : Sunil kumar <[email protected]>
// *HWP Team : Perv
// *HWP Level : 2
// *HWP Consumed by : HB
//------------------------------------------------------------------------------
//## auto_generated
#include "p9_mem_startclocks.H"
#include "p9_const_common.H"
#include "p9_misc_scom_addresses_fld.H"
#include "p9_perv_scom_addresses.H"
#include "p9_perv_scom_addresses_fld.H"
#include "p9_quad_scom_addresses_fld.H"
#include "p9_sbe_common.H"
enum P9_MEM_STARTCLOCKS_Private_Constants
{
CLOCK_CMD = 0x1,
STARTSLAVE = 0x1,
STARTMASTER = 0x1,
REGIONS_ALL_EXCEPT_VITAL_NESTPLL = 0x7FE,
CLOCK_TYPES = 0x7,
DONT_STARTMASTER = 0x0,
DONT_STARTSLAVE = 0x0
};
static fapi2::ReturnCode p9_mem_startclocks_fence_setup_function(
const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet,
const fapi2::buffer<uint64_t> i_pg_vector);
static fapi2::ReturnCode p9_mem_startclocks_cplt_ctrl_action_function(
const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet);
static fapi2::ReturnCode p9_mem_startclocks_flushmode(
const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet);
fapi2::ReturnCode p9_mem_startclocks(const
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip)
{
uint8_t l_sync_mode = 0;
fapi2::buffer<uint64_t> l_pg_vector;
FAPI_DBG("Entering ...");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_MC_SYNC_MODE, i_target_chip, l_sync_mode),
"Error from FAPI_ATTR_GET (ATTR_MC_SYNC_MODE)");
FAPI_TRY(p9_sbe_common_get_pg_vector(i_target_chip, l_pg_vector));
FAPI_DBG("pg targets vector: %#018lX", l_pg_vector);
if (!l_sync_mode)
{
for (auto l_trgt_chplt : i_target_chip.getChildren<fapi2::TARGET_TYPE_PERV>
(fapi2::TARGET_FILTER_ALL_MC, fapi2::TARGET_STATE_FUNCTIONAL))
{
FAPI_INF("Call p9_mem_startclocks_cplt_ctrl_action_function for Mc chiplets");
FAPI_TRY(p9_mem_startclocks_cplt_ctrl_action_function(l_trgt_chplt));
FAPI_INF("Call module align chiplets for Mc chiplets");
FAPI_TRY(p9_sbe_common_align_chiplets(l_trgt_chplt));
FAPI_INF("Call module clock start stop for MC01, MC23.");
FAPI_TRY(p9_sbe_common_clock_start_stop(l_trgt_chplt, CLOCK_CMD,
DONT_STARTSLAVE, DONT_STARTMASTER, REGIONS_ALL_EXCEPT_VITAL_NESTPLL,
CLOCK_TYPES));
FAPI_INF("Call p9_mem_startclocks_fence_setup_function for Mc chiplets ");
FAPI_TRY(p9_mem_startclocks_fence_setup_function(l_trgt_chplt, l_pg_vector));
FAPI_INF("Call p9_mem_startclocks_flushmode for Mc chiplets");
FAPI_TRY(p9_mem_startclocks_flushmode(l_trgt_chplt));
FAPI_INF("Call p9_sbe_common_configure_chiplet_FIR for MC chiplets");
FAPI_TRY(p9_sbe_common_configure_chiplet_FIR(l_trgt_chplt));
}
}
FAPI_DBG("Exiting ...");
fapi_try_exit:
return fapi2::current_err;
}
/// @brief --drop chiplet fence
/// @param[in] i_target_chiplet Reference to TARGET_TYPE_PERV target
/// @return FAPI2_RC_SUCCESS if success, else error code.
static fapi2::ReturnCode p9_mem_startclocks_fence_setup_function(
const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet,
const fapi2::buffer<uint64_t> i_pg_vector)
{
uint8_t l_read_attrunitpos = 0;
fapi2::buffer<uint64_t> l_data64;
FAPI_DBG("Entering ...");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, i_target_chiplet,
l_read_attrunitpos));
if ( l_read_attrunitpos == 0x07 )
{
if ( i_pg_vector.getBit<5>() == 1 )
{
FAPI_DBG("Drop chiplet fence");
//Setting NET_CTRL0 register value
l_data64.flush<1>();
l_data64.clearBit<PERV_1_NET_CTRL0_FENCE_EN>(); //NET_CTRL0.FENCE_EN = 0
FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_NET_CTRL0_WAND, l_data64));
}
}
if ( l_read_attrunitpos == 0x08 )
{
if ( i_pg_vector.getBit<3>() == 1 )
{
FAPI_DBG("Drop chiplet fence");
//Setting NET_CTRL0 register value
l_data64.flush<1>();
l_data64.clearBit<PERV_1_NET_CTRL0_FENCE_EN>(); //NET_CTRL0.FENCE_EN = 0
FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_NET_CTRL0_WAND, l_data64));
}
}
FAPI_DBG("Exiting ...");
fapi_try_exit:
return fapi2::current_err;
}
/// @brief --drop vital fence
/// --reset abstclk muxsel and syncclk muxsel
///
/// @param[in] i_target_chiplet Reference to TARGET_TYPE_PERV target
/// @return FAPI2_RC_SUCCESS if success, else error code.
static fapi2::ReturnCode p9_mem_startclocks_cplt_ctrl_action_function(
const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet)
{
fapi2::buffer<uint64_t> l_data64;
FAPI_DBG("Entering ...");
// Local variable and constant definition
fapi2::buffer <uint16_t> l_attr_pg;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PG, i_target_chiplet, l_attr_pg));
l_attr_pg.invert();
FAPI_INF("Drop partial good fences");
//Setting CPLT_CTRL1 register value
l_data64.flush<0>();
//CPLT_CTRL1.TC_VITL_REGION_FENCE = l_attr_pg.getBit<19>()
l_data64.writeBit<PEC_CPLT_CTRL1_TC_VITL_REGION_FENCE>(l_attr_pg.getBit<3>());
//CPLT_CTRL1.TC_PERV_REGION_FENCE = l_attr_pg.getBit<20>()
l_data64.writeBit<PEC_CPLT_CTRL1_TC_PERV_REGION_FENCE>(l_attr_pg.getBit<4>());
//CPLT_CTRL1.TC_REGION1_FENCE = l_attr_pg.getBit<21>()
l_data64.writeBit<PEC_CPLT_CTRL1_TC_REGION1_FENCE>(l_attr_pg.getBit<5>());
//CPLT_CTRL1.TC_REGION2_FENCE = l_attr_pg.getBit<22>()
l_data64.writeBit<PEC_CPLT_CTRL1_TC_REGION2_FENCE>(l_attr_pg.getBit<6>());
//CPLT_CTRL1.TC_REGION3_FENCE = l_attr_pg.getBit<23>()
l_data64.writeBit<PERV_1_CPLT_CTRL1_TC_REGION3_FENCE>(l_attr_pg.getBit<7>());
//CPLT_CTRL1.TC_REGION4_FENCE = l_attr_pg.getBit<24>()
l_data64.writeBit<EQ_CPLT_CTRL1_TC_REGION4_FENCE>(l_attr_pg.getBit<8>());
//CPLT_CTRL1.TC_REGION5_FENCE = l_attr_pg.getBit<25>()
l_data64.writeBit<EQ_CPLT_CTRL1_TC_REGION5_FENCE>(l_attr_pg.getBit<9>());
//CPLT_CTRL1.TC_REGION6_FENCE = l_attr_pg.getBit<26>()
l_data64.writeBit<EQ_CPLT_CTRL1_TC_REGION6_FENCE>(l_attr_pg.getBit<10>());
//CPLT_CTRL1.TC_REGION7_FENCE = l_attr_pg.getBit<27>()
l_data64.writeBit<EQ_CPLT_CTRL1_TC_REGION7_FENCE>(l_attr_pg.getBit<11>());
//CPLT_CTRL1.UNUSED_12B = l_attr_pg.getBit<28>()
l_data64.writeBit<PEC_CPLT_CTRL1_UNUSED_12B>(l_attr_pg.getBit<12>());
//CPLT_CTRL1.UNUSED_13B = l_attr_pg.getBit<29>()
l_data64.writeBit<PEC_CPLT_CTRL1_UNUSED_13B>(l_attr_pg.getBit<13>());
//CPLT_CTRL1.UNUSED_14B = l_attr_pg.getBit<30>()
l_data64.writeBit<PEC_CPLT_CTRL1_UNUSED_14B>(l_attr_pg.getBit<14>());
FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_CPLT_CTRL1_CLEAR, l_data64));
FAPI_INF("reset abistclk_muxsel and syncclk_muxsel");
//Setting CPLT_CTRL0 register value
l_data64.flush<0>();
//CPLT_CTRL0.CTRL_CC_ABSTCLK_MUXSEL_DC = 1
l_data64.writeBit<PEC_CPLT_CTRL0_CTRL_CC_ABSTCLK_MUXSEL_DC>(1);
//CPLT_CTRL0.TC_UNIT_SYNCCLK_MUXSEL_DC = 1
l_data64.writeBit<PEC_CPLT_CTRL0_TC_UNIT_SYNCCLK_MUXSEL_DC>(1);
FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_CPLT_CTRL0_CLEAR, l_data64));
FAPI_DBG("Exiting ...");
fapi_try_exit:
return fapi2::current_err;
}
/// @brief will force all chiplets out of flush
///
/// @param[in] i_target_chiplet Reference to TARGET_TYPE_PERV target
/// @return FAPI2_RC_SUCCESS if success, else error code.
static fapi2::ReturnCode p9_mem_startclocks_flushmode(
const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet)
{
fapi2::buffer<uint64_t> l_data64;
FAPI_DBG("Entering ...");
FAPI_INF("Clear flush_inhibit to go in to flush mode");
//Setting CPLT_CTRL0 register value
l_data64.flush<0>();
//CPLT_CTRL0.CTRL_CC_FLUSHMODE_INH_DC = 0
l_data64.setBit<PEC_CPLT_CTRL0_CTRL_CC_FLUSHMODE_INH_DC>();
FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_CPLT_CTRL0_CLEAR, l_data64));
FAPI_DBG("Exiting ...");
fapi_try_exit:
return fapi2::current_err;
}
<commit_msg>p9_mem_startclocks.C update<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_mem_startclocks.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
//------------------------------------------------------------------------------
/// @file p9_mem_startclocks.C
///
/// @brief Start clocks on MBA/MCAs
//------------------------------------------------------------------------------
// *HWP HW Owner : Abhishek Agarwal <[email protected]>
// *HWP HW Backup Owner : Srinivas V Naga <[email protected]>
// *HWP FW Owner : Sunil kumar <[email protected]>
// *HWP Team : Perv
// *HWP Level : 2
// *HWP Consumed by : HB
//------------------------------------------------------------------------------
//## auto_generated
#include "p9_mem_startclocks.H"
#include "p9_const_common.H"
#include "p9_misc_scom_addresses_fld.H"
#include "p9_perv_scom_addresses.H"
#include "p9_perv_scom_addresses_fld.H"
#include "p9_quad_scom_addresses_fld.H"
#include "p9_sbe_common.H"
enum P9_MEM_STARTCLOCKS_Private_Constants
{
CLOCK_CMD = 0x1,
STARTSLAVE = 0x1,
STARTMASTER = 0x1,
REGIONS_ALL_EXCEPT_VITAL_NESTPLL = 0x7FE,
CLOCK_TYPES = 0x7,
DONT_STARTMASTER = 0x0,
DONT_STARTSLAVE = 0x0
};
static fapi2::ReturnCode p9_mem_startclocks_fence_setup_function(
const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet,
const fapi2::buffer<uint64_t> i_pg_vector);
static fapi2::ReturnCode p9_mem_startclocks_cplt_ctrl_action_function(
const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet);
static fapi2::ReturnCode p9_mem_startclocks_flushmode(
const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet);
static fapi2::ReturnCode p9_mem_startclocks_regions_setup(
const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet,
const fapi2::buffer<uint16_t> i_regions_except_vital_pll,
fapi2::buffer<uint64_t>& o_regions_enabled_after_pg);
fapi2::ReturnCode p9_mem_startclocks(const
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip)
{
uint8_t l_sync_mode = 0;
fapi2::buffer<uint64_t> l_pg_vector;
fapi2::buffer<uint64_t> l_clock_regions;
FAPI_DBG("Entering ...");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_MC_SYNC_MODE, i_target_chip, l_sync_mode),
"Error from FAPI_ATTR_GET (ATTR_MC_SYNC_MODE)");
FAPI_TRY(p9_sbe_common_get_pg_vector(i_target_chip, l_pg_vector));
FAPI_DBG("pg targets vector: %#018lX", l_pg_vector);
if (!l_sync_mode)
{
for (auto l_trgt_chplt : i_target_chip.getChildren<fapi2::TARGET_TYPE_PERV>
(fapi2::TARGET_FILTER_ALL_MC, fapi2::TARGET_STATE_FUNCTIONAL))
{
FAPI_INF("Call p9_mem_startclocks_cplt_ctrl_action_function for Mc chiplets");
FAPI_TRY(p9_mem_startclocks_cplt_ctrl_action_function(l_trgt_chplt));
FAPI_INF("Call module align chiplets for Mc chiplets");
FAPI_TRY(p9_sbe_common_align_chiplets(l_trgt_chplt));
FAPI_TRY(p9_mem_startclocks_regions_setup(l_trgt_chplt,
REGIONS_ALL_EXCEPT_VITAL_NESTPLL, l_clock_regions));
FAPI_INF("Call module clock start stop for MC01, MC23.");
FAPI_TRY(p9_sbe_common_clock_start_stop(l_trgt_chplt, CLOCK_CMD,
DONT_STARTSLAVE, DONT_STARTMASTER, l_clock_regions,
CLOCK_TYPES));
FAPI_INF("Call p9_mem_startclocks_fence_setup_function for Mc chiplets ");
FAPI_TRY(p9_mem_startclocks_fence_setup_function(l_trgt_chplt, l_pg_vector));
FAPI_INF("Call p9_mem_startclocks_flushmode for Mc chiplets");
FAPI_TRY(p9_mem_startclocks_flushmode(l_trgt_chplt));
FAPI_INF("Call p9_sbe_common_configure_chiplet_FIR for MC chiplets");
FAPI_TRY(p9_sbe_common_configure_chiplet_FIR(l_trgt_chplt));
}
}
FAPI_DBG("Exiting ...");
fapi_try_exit:
return fapi2::current_err;
}
/// @brief --drop chiplet fence
/// @param[in] i_target_chiplet Reference to TARGET_TYPE_PERV target
/// @return FAPI2_RC_SUCCESS if success, else error code.
static fapi2::ReturnCode p9_mem_startclocks_fence_setup_function(
const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet,
const fapi2::buffer<uint64_t> i_pg_vector)
{
uint8_t l_read_attrunitpos = 0;
fapi2::buffer<uint64_t> l_data64;
FAPI_DBG("Entering ...");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, i_target_chiplet,
l_read_attrunitpos));
if ( l_read_attrunitpos == 0x07 )
{
if ( i_pg_vector.getBit<5>() == 1 )
{
FAPI_DBG("Drop chiplet fence");
//Setting NET_CTRL0 register value
l_data64.flush<1>();
l_data64.clearBit<PERV_1_NET_CTRL0_FENCE_EN>(); //NET_CTRL0.FENCE_EN = 0
FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_NET_CTRL0_WAND, l_data64));
}
}
if ( l_read_attrunitpos == 0x08 )
{
if ( i_pg_vector.getBit<3>() == 1 )
{
FAPI_DBG("Drop chiplet fence");
//Setting NET_CTRL0 register value
l_data64.flush<1>();
l_data64.clearBit<PERV_1_NET_CTRL0_FENCE_EN>(); //NET_CTRL0.FENCE_EN = 0
FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_NET_CTRL0_WAND, l_data64));
}
}
FAPI_DBG("Exiting ...");
fapi_try_exit:
return fapi2::current_err;
}
/// @brief --drop vital fence
/// --reset abstclk muxsel and syncclk muxsel
///
/// @param[in] i_target_chiplet Reference to TARGET_TYPE_PERV target
/// @return FAPI2_RC_SUCCESS if success, else error code.
static fapi2::ReturnCode p9_mem_startclocks_cplt_ctrl_action_function(
const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet)
{
fapi2::buffer<uint64_t> l_data64;
FAPI_DBG("Entering ...");
// Local variable and constant definition
fapi2::buffer <uint16_t> l_attr_pg;
fapi2::buffer <uint16_t> l_cplt_ctrl_init;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PG, i_target_chiplet, l_attr_pg));
l_attr_pg.invert();
l_attr_pg.extractToRight<4, 11>(l_cplt_ctrl_init);
FAPI_DBG("Drop partial good fences");
//Setting CPLT_CTRL1 register value
l_data64.flush<0>();
l_data64.writeBit<PEC_CPLT_CTRL1_TC_VITL_REGION_FENCE>(l_attr_pg.getBit<3>());
//CPLT_CTRL1.TC_ALL_REGIONS_FENCE = l_cplt_ctrl_init
l_data64.insertFromRight<4, 11>(l_cplt_ctrl_init);
FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_CPLT_CTRL1_CLEAR, l_data64));
FAPI_DBG("reset abistclk_muxsel and syncclk_muxsel");
//Setting CPLT_CTRL0 register value
l_data64.flush<0>();
//CPLT_CTRL0.CTRL_CC_ABSTCLK_MUXSEL_DC = 1
l_data64.writeBit<PEC_CPLT_CTRL0_CTRL_CC_ABSTCLK_MUXSEL_DC>(1);
//CPLT_CTRL0.TC_UNIT_SYNCCLK_MUXSEL_DC = 1
l_data64.writeBit<PEC_CPLT_CTRL0_TC_UNIT_SYNCCLK_MUXSEL_DC>(1);
FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_CPLT_CTRL0_CLEAR, l_data64));
FAPI_DBG("Exiting ...");
fapi_try_exit:
return fapi2::current_err;
}
/// @brief will force all chiplets out of flush
///
/// @param[in] i_target_chiplet Reference to TARGET_TYPE_PERV target
/// @return FAPI2_RC_SUCCESS if success, else error code.
static fapi2::ReturnCode p9_mem_startclocks_flushmode(
const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet)
{
fapi2::buffer<uint64_t> l_data64;
FAPI_DBG("Entering ...");
FAPI_DBG("Clear flush_inhibit to go in to flush mode");
//Setting CPLT_CTRL0 register value
l_data64.flush<0>();
//CPLT_CTRL0.CTRL_CC_FLUSHMODE_INH_DC = 0
l_data64.setBit<PEC_CPLT_CTRL0_CTRL_CC_FLUSHMODE_INH_DC>();
FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_CPLT_CTRL0_CLEAR, l_data64));
FAPI_DBG("Exiting ...");
fapi_try_exit:
return fapi2::current_err;
}
/// @brief Region value settings : The anding of REGIONS_ALL_EXCEPT_VITAL_NESTPLL, ATTR_PG
// disables PLL region and retains enabled regions info from chiplet pg attribute.
///
/// @param[in] i_target_chiplet Reference to TARGET_TYPE_PERV target
/// @param[in] i_regions_except_vital_pll regions except vital and pll
/// @param[out] o_regions_enabled_after_pg enabled regions value after anding with ATTR_PG
/// @return FAPI2_RC_SUCCESS if success, else error code.
static fapi2::ReturnCode p9_mem_startclocks_regions_setup(const
fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet,
const fapi2::buffer<uint16_t> i_regions_except_vital_pll,
fapi2::buffer<uint64_t>& o_regions_enabled_after_pg)
{
fapi2::buffer<uint16_t> l_read_attr = 0;
fapi2::buffer<uint16_t> l_read_attr_invert = 0;
fapi2::buffer<uint16_t> l_read_attr_shift1_right = 0;
FAPI_DBG("p9_mem_startclocks_regions_setup: Entering ...");
FAPI_DBG("Reading ATTR_PG");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PG, i_target_chiplet, l_read_attr));
if ( l_read_attr == 0x0 )
{
o_regions_enabled_after_pg = static_cast<uint64_t>(i_regions_except_vital_pll) ;
}
else
{
l_read_attr_invert = l_read_attr.invert();
l_read_attr_shift1_right = (l_read_attr_invert >> 1);
o_regions_enabled_after_pg = (i_regions_except_vital_pll & l_read_attr_shift1_right);
}
FAPI_DBG("p9_mem_startclocks_regions_setup : Exiting ...");
fapi_try_exit:
return fapi2::current_err;
}
<|endoftext|> |
<commit_before>/**
* @file Cosa/OneWire.cpp
* @version 1.0
*
* @section License
* Copyright (C) 2012, Mikael Patel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General
* Public License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA
*
* @section Description
* 1-Wire device driver support class.
*
* This file is part of the Arduino Che Cosa project.
*/
#include "Cosa/OneWire.h"
#include <util/delay_basic.h>
#define DELAY(us) _delay_loop_2((us) << 2)
bool
OneWire::reset()
{
uint8_t retry = 64;
uint8_t res = 0;
// Check that the bus is not active
set_mode(INPUT_MODE);
while (is_clear() && retry--) DELAY(10);
if (retry == 0) return (0);
// Generate the reset signal
set_mode(OUTPUT_MODE);
clear();
DELAY(480);
// Check that there is a slave device
set_mode(INPUT_MODE);
DELAY(70);
res = is_clear();
DELAY(410);
return (res);
}
uint8_t
OneWire::read(uint8_t bits)
{
uint8_t res = 0;
uint8_t mix = 0;
while (bits--) {
synchronized {
// Generate the read slot
set_mode(OUTPUT_MODE);
clear();
DELAY(3);
set_mode(INPUT_MODE);
DELAY(9);
res >>= 1;
// Sample the data from the slave and generate crc
if (is_set()) {
res |= 0x80;
mix = (_crc ^ 1) & 0x01;
}
else {
mix = (_crc ^ 0) & 0x01;
}
_crc >>= 1;
if (mix) _crc ^= 0x8C;
DELAY(52);
}
}
return (res);
}
void
OneWire::write(uint8_t value)
{
set_mode(OUTPUT_MODE);
for (uint8_t bits = 0; bits < CHARBITS; bits++) {
synchronized {
// Generate the write slot; LSB first
clear();
if (value & 1) {
DELAY(10);
set();
DELAY(55);
}
else {
DELAY(65);
set();
DELAY(5);
}
value = value >> 1;
}
}
set_mode(INPUT_MODE);
}
bool
OneWire::Device::read_rom()
{
if (!_pin->reset()) return (0);
_pin->write(OneWire::READ_ROM);
_pin->begin();
for (uint8_t i = 0; i < ROM_MAX; i++) {
_rom[i] = _pin->read();
}
return (_pin->end() == 0);
}
void
OneWire::Device::print_rom(IOStream& stream)
{
for (uint8_t i = 0; i < ROM_MAX; i++)
stream.printf_P(PSTR("rom[%d] = %hd\n"), i, _rom[i]);
}
<commit_msg>Update OneWire timing according to AVR318: Dallas 1-Wire master.<commit_after>/**
* @file Cosa/OneWire.cpp
* @version 1.0
*
* @section License
* Copyright (C) 2012, Mikael Patel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General
* Public License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA
*
* @section Description
* 1-Wire device driver support class.
*
* This file is part of the Arduino Che Cosa project.
*/
#include "Cosa/OneWire.h"
#include <util/delay_basic.h>
#define DELAY(us) _delay_loop_2((us) << 2)
bool
OneWire::reset()
{
uint8_t retry = 64;
uint8_t res = 0;
// Check that the bus is not active
set_mode(INPUT_MODE);
while (is_clear() && retry--) DELAY(10);
if (retry == 0) return (0);
// Generate the reset signal
set_mode(OUTPUT_MODE);
clear();
DELAY(480);
// Check that there is a slave device
set_mode(INPUT_MODE);
DELAY(70);
res = is_clear();
DELAY(410);
return (res);
}
uint8_t
OneWire::read(uint8_t bits)
{
uint8_t res = 0;
uint8_t mix = 0;
while (bits--) {
synchronized {
// Generate the read slot
set_mode(OUTPUT_MODE);
clear();
DELAY(6);
set_mode(INPUT_MODE);
DELAY(9);
res >>= 1;
// Sample the data from the slave and generate crc
if (is_set()) {
res |= 0x80;
mix = (_crc ^ 1);
}
else {
mix = (_crc ^ 0);
}
_crc >>= 1;
if (mix & 1) _crc ^= 0x8C;
DELAY(55);
}
}
return (res);
}
void
OneWire::write(uint8_t value)
{
set_mode(OUTPUT_MODE);
for (uint8_t bits = 0; bits < CHARBITS; bits++) {
synchronized {
// Generate the write slot; LSB first
clear();
if (value & 1) {
DELAY(6);
set();
DELAY(64);
}
else {
DELAY(60);
set();
DELAY(10);
}
value = value >> 1;
}
}
set_mode(INPUT_MODE);
}
bool
OneWire::Device::read_rom()
{
if (!_pin->reset()) return (0);
_pin->write(OneWire::READ_ROM);
_pin->begin();
for (uint8_t i = 0; i < ROM_MAX; i++) {
_rom[i] = _pin->read();
}
return (_pin->end() == 0);
}
void
OneWire::Device::print_rom(IOStream& stream)
{
for (uint8_t i = 0; i < ROM_MAX; i++)
stream.printf_P(PSTR("rom[%d] = %hd\n"), i, _rom[i]);
}
<|endoftext|> |
<commit_before>/**
* @version GrPPI v0.2
* @copyright Copyright (C) 2017 Universidad Carlos III de Madrid. All rights reserved.
* @license GNU/GPL, see LICENSE.txt
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You have received a copy of the GNU General Public License in LICENSE.txt
* also available in <http://www.gnu.org/licenses/gpl.html>.
*
* See COPYRIGHT.txt for copyright notices and details.
*/
#include <atomic>
#include <utility>
#include <gtest/gtest.h>
#include <iostream>
#include <thread>
#include "common/mpmc_queue.h"
using namespace std;
using namespace grppi;
TEST(mpmc_queue, constructor){
mpmc_queue<int> queue(10, queue_mode::lockfree);
EXPECT_EQ(true,queue.is_empty());
}
TEST(mpmc_queue, lockfree_push_pop){
mpmc_queue<int> queue(10, queue_mode::lockfree);
auto inserted = queue.push(1);
EXPECT_EQ(true, inserted);
EXPECT_EQ(false, queue.is_empty());
auto value = queue.pop();
EXPECT_EQ(true, queue.is_empty());
EXPECT_EQ(1,value);
}
TEST(mpmc_queue, concurrent_push_pop){
mpmc_queue<int> queue(3, queue_mode::lockfree);
std::vector<std::thread> thrs;
for(auto i = 0; i<6; i++){
thrs.push_back(std::thread([&,i](){queue.push(i);} ));
}
auto val = 0;
for(auto i = 0;i<6; i++){
val += queue.pop();
}
for(auto & t : thrs) t.join();
EXPECT_EQ(15, val);
EXPECT_EQ(true, queue.is_empty());
}
<commit_msg>Extended test to fully cover the mpmc-queue<commit_after>/**
* @version GrPPI v0.2
* @copyright Copyright (C) 2017 Universidad Carlos III de Madrid. All rights reserved.
* @license GNU/GPL, see LICENSE.txt
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You have received a copy of the GNU General Public License in LICENSE.txt
* also available in <http://www.gnu.org/licenses/gpl.html>.
*
* See COPYRIGHT.txt for copyright notices and details.
*/
#include <atomic>
#include <utility>
#include <gtest/gtest.h>
#include <iostream>
#include <thread>
#include "common/mpmc_queue.h"
using namespace std;
using namespace grppi;
TEST(mpmc_queue_blocking, constructor){
mpmc_queue<int> queue(10, queue_mode::blocking);
EXPECT_EQ(true,queue.is_empty());
}
TEST(mpmc_queue_lockfree, constructor){
mpmc_queue<int> queue(10, queue_mode::lockfree);
EXPECT_EQ(true,queue.is_empty());
}
TEST(mpmc_queue_blocking, push_pop){
mpmc_queue<int> queue(10, queue_mode::blocking);
auto inserted = queue.push(1);
EXPECT_EQ(true, inserted);
EXPECT_EQ(false, queue.is_empty());
auto value = queue.pop();
EXPECT_EQ(true, queue.is_empty());
EXPECT_EQ(1,value);
}
TEST(mpmc_queue_lockfree, push_pop){
mpmc_queue<int> queue(10, queue_mode::lockfree);
auto inserted = queue.push(1);
EXPECT_EQ(true, inserted);
EXPECT_EQ(false, queue.is_empty());
auto value = queue.pop();
EXPECT_EQ(true, queue.is_empty());
EXPECT_EQ(1,value);
}
TEST(mpmc_queue_blocking, concurrent_push_pop){
mpmc_queue<int> queue(3, queue_mode::blocking);
std::vector<std::thread> thrs;
for(auto i = 0; i<6; i++){
thrs.push_back(std::thread([&,i](){queue.push(i);} ));
}
auto val = 0;
for(auto i = 0;i<6; i++){
val += queue.pop();
}
for(auto & t : thrs) t.join();
EXPECT_EQ(15, val);
EXPECT_EQ(true, queue.is_empty());
}
TEST(mpmc_queue_lockfree, concurrent_push_pop){
mpmc_queue<int> queue(3, queue_mode::lockfree);
std::vector<std::thread> thrs;
for(auto i = 0; i<6; i++){
thrs.push_back(std::thread([&,i](){queue.push(i);} ));
}
auto val = 0;
for(auto i = 0;i<6; i++){
val += queue.pop();
}
for(auto & t : thrs) t.join();
EXPECT_EQ(15, val);
EXPECT_EQ(true, queue.is_empty());
}
TEST(mpmc_queue_blocking, concurrent_pop_push){
mpmc_queue<int> queue(3, queue_mode::blocking);
std::vector<std::thread> thrs;
std::vector<int> values(6);
for(auto i = 0; i<6; i++){
thrs.push_back(std::thread([&,i](){values[i] = queue.pop();} ));
}
for(auto i = 0;i<6; i++){
queue.push(i);
}
for(auto & t : thrs) t.join();
auto val = 0;
for( auto &v : values) val+=v;
EXPECT_EQ(15, val);
EXPECT_EQ(true, queue.is_empty());
}
TEST(mpmc_queue_lockfree, concurrent_pop_push){
mpmc_queue<int> queue(3, queue_mode::lockfree);
std::vector<std::thread> thrs;
std::vector<int> values(6);
for(auto i = 0; i<6; i++){
thrs.push_back(std::thread([&,i](){values[i] = queue.pop();} ));
}
for(auto i = 0;i<6; i++){
queue.push(i);
}
for(auto & t : thrs) t.join();
auto val = 0;
for( auto &v : values) val+=v;
EXPECT_EQ(15, val);
EXPECT_EQ(true, queue.is_empty());
}
<|endoftext|> |
<commit_before>//===- llvm/unittest/Support/AnyTest.cpp - Any tests ---===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/Any.h"
#include "gtest/gtest.h"
#include <cstdlib>
using namespace llvm;
namespace {
// Make sure we can construct, copy-construct, move-construct, and assign Any's.
TEST(AnyTest, ConstructionAndAssignment) {
llvm::Any A;
llvm::Any B{7};
llvm::Any C{8};
llvm::Any D{"hello"};
llvm::Any E{3.7};
// An empty Any is not anything.
EXPECT_FALSE(A.hasValue());
EXPECT_FALSE(any_isa<int>(A));
// An int is an int but not something else.
EXPECT_TRUE(B.hasValue());
EXPECT_TRUE(any_isa<int>(B));
EXPECT_FALSE(any_isa<float>(B));
EXPECT_TRUE(C.hasValue());
EXPECT_TRUE(any_isa<int>(C));
// A const char * is a const char * but not an int.
EXPECT_TRUE(D.hasValue());
EXPECT_TRUE(any_isa<const char *>(D));
EXPECT_FALSE(any_isa<int>(D));
// A double is a double but not a float.
EXPECT_TRUE(E.hasValue());
EXPECT_TRUE(any_isa<double>(E));
EXPECT_FALSE(any_isa<float>(E));
// After copy constructing from an int, the new item and old item are both
// ints.
llvm::Any F(B);
EXPECT_TRUE(B.hasValue());
EXPECT_TRUE(F.hasValue());
EXPECT_TRUE(any_isa<int>(F));
EXPECT_TRUE(any_isa<int>(B));
// After move constructing from an int, the new item is an int and the old one
// isn't.
llvm::Any G(std::move(C));
EXPECT_FALSE(C.hasValue());
EXPECT_TRUE(G.hasValue());
EXPECT_TRUE(any_isa<int>(G));
EXPECT_FALSE(any_isa<int>(C));
// After copy-assigning from an int, the new item and old item are both ints.
A = F;
EXPECT_TRUE(A.hasValue());
EXPECT_TRUE(F.hasValue());
EXPECT_TRUE(any_isa<int>(A));
EXPECT_TRUE(any_isa<int>(F));
// After move-assigning from an int, the new item and old item are both ints.
B = std::move(G);
EXPECT_TRUE(B.hasValue());
EXPECT_FALSE(G.hasValue());
EXPECT_TRUE(any_isa<int>(B));
EXPECT_FALSE(any_isa<int>(G));
}
TEST(AnyTest, GoodAnyCast) {
llvm::Any A;
llvm::Any B{7};
llvm::Any C{8};
llvm::Any D{"hello"};
llvm::Any E{'x'};
// Check each value twice to make sure it isn't damaged by the cast.
EXPECT_EQ(7, llvm::any_cast<int>(B));
EXPECT_EQ(7, llvm::any_cast<int>(B));
EXPECT_STREQ("hello", llvm::any_cast<const char *>(D));
EXPECT_STREQ("hello", llvm::any_cast<const char *>(D));
EXPECT_EQ('x', llvm::any_cast<char>(E));
EXPECT_EQ('x', llvm::any_cast<char>(E));
llvm::Any F(B);
EXPECT_EQ(7, llvm::any_cast<int>(F));
EXPECT_EQ(7, llvm::any_cast<int>(F));
llvm::Any G(std::move(C));
EXPECT_EQ(8, llvm::any_cast<int>(G));
EXPECT_EQ(8, llvm::any_cast<int>(G));
A = F;
EXPECT_EQ(7, llvm::any_cast<int>(A));
EXPECT_EQ(7, llvm::any_cast<int>(A));
E = std::move(G);
EXPECT_EQ(8, llvm::any_cast<int>(E));
EXPECT_EQ(8, llvm::any_cast<int>(E));
// Make sure we can any_cast from an rvalue and that it's properly destroyed
// in the process.
EXPECT_EQ(8, llvm::any_cast<int>(std::move(E)));
EXPECT_TRUE(E.hasValue());
// Make sure moving from pointers gives back pointers, and that we can modify
// the underlying value through those pointers.
EXPECT_EQ(7, *llvm::any_cast<int>(&A));
int *N = llvm::any_cast<int>(&A);
*N = 42;
EXPECT_EQ(42, llvm::any_cast<int>(A));
// Make sure that we can any_cast to a reference and this is considered a good
// cast, resulting in an lvalue which can be modified.
llvm::any_cast<int &>(A) = 43;
EXPECT_EQ(43, llvm::any_cast<int>(A));
}
TEST(AnyTest, CopiesAndMoves) {
struct TestType {
TestType() = default;
TestType(const TestType &Other)
: Copies(Other.Copies + 1), Moves(Other.Moves) {}
TestType(TestType &&Other) : Copies(Other.Copies), Moves(Other.Moves + 1) {}
int Copies = 0;
int Moves = 0;
};
// One move to get TestType into the Any, and one move on the cast.
TestType T1 = llvm::any_cast<TestType>(Any{TestType()});
EXPECT_EQ(0, T1.Copies);
EXPECT_EQ(2, T1.Moves);
// One move to get TestType into the Any, and one copy on the cast.
Any A{TestType()};
TestType T2 = llvm::any_cast<TestType>(A);
EXPECT_EQ(1, T2.Copies);
EXPECT_EQ(1, T2.Moves);
// One move to get TestType into the Any, and one move on the cast.
TestType T3 = llvm::any_cast<TestType>(std::move(A));
EXPECT_EQ(0, T3.Copies);
EXPECT_EQ(2, T3.Moves);
}
TEST(AnyTest, BadAnyCast) {
llvm::Any A;
llvm::Any B{7};
llvm::Any C{"hello"};
llvm::Any D{'x'};
EXPECT_DEBUG_DEATH(llvm::any_cast<int>(A), "");
EXPECT_DEBUG_DEATH(llvm::any_cast<float>(B), "");
EXPECT_DEBUG_DEATH(llvm::any_cast<int *>(B), "");
EXPECT_DEBUG_DEATH(llvm::any_cast<std::string>(C), "");
EXPECT_DEBUG_DEATH(llvm::any_cast<unsigned char>(D), "");
}
} // anonymous namespace
<commit_msg>[ADT] Only run death tests in !NDEBUG<commit_after>//===- llvm/unittest/Support/AnyTest.cpp - Any tests ---===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/Any.h"
#include "gtest/gtest.h"
#include <cstdlib>
using namespace llvm;
namespace {
// Make sure we can construct, copy-construct, move-construct, and assign Any's.
TEST(AnyTest, ConstructionAndAssignment) {
llvm::Any A;
llvm::Any B{7};
llvm::Any C{8};
llvm::Any D{"hello"};
llvm::Any E{3.7};
// An empty Any is not anything.
EXPECT_FALSE(A.hasValue());
EXPECT_FALSE(any_isa<int>(A));
// An int is an int but not something else.
EXPECT_TRUE(B.hasValue());
EXPECT_TRUE(any_isa<int>(B));
EXPECT_FALSE(any_isa<float>(B));
EXPECT_TRUE(C.hasValue());
EXPECT_TRUE(any_isa<int>(C));
// A const char * is a const char * but not an int.
EXPECT_TRUE(D.hasValue());
EXPECT_TRUE(any_isa<const char *>(D));
EXPECT_FALSE(any_isa<int>(D));
// A double is a double but not a float.
EXPECT_TRUE(E.hasValue());
EXPECT_TRUE(any_isa<double>(E));
EXPECT_FALSE(any_isa<float>(E));
// After copy constructing from an int, the new item and old item are both
// ints.
llvm::Any F(B);
EXPECT_TRUE(B.hasValue());
EXPECT_TRUE(F.hasValue());
EXPECT_TRUE(any_isa<int>(F));
EXPECT_TRUE(any_isa<int>(B));
// After move constructing from an int, the new item is an int and the old one
// isn't.
llvm::Any G(std::move(C));
EXPECT_FALSE(C.hasValue());
EXPECT_TRUE(G.hasValue());
EXPECT_TRUE(any_isa<int>(G));
EXPECT_FALSE(any_isa<int>(C));
// After copy-assigning from an int, the new item and old item are both ints.
A = F;
EXPECT_TRUE(A.hasValue());
EXPECT_TRUE(F.hasValue());
EXPECT_TRUE(any_isa<int>(A));
EXPECT_TRUE(any_isa<int>(F));
// After move-assigning from an int, the new item and old item are both ints.
B = std::move(G);
EXPECT_TRUE(B.hasValue());
EXPECT_FALSE(G.hasValue());
EXPECT_TRUE(any_isa<int>(B));
EXPECT_FALSE(any_isa<int>(G));
}
TEST(AnyTest, GoodAnyCast) {
llvm::Any A;
llvm::Any B{7};
llvm::Any C{8};
llvm::Any D{"hello"};
llvm::Any E{'x'};
// Check each value twice to make sure it isn't damaged by the cast.
EXPECT_EQ(7, llvm::any_cast<int>(B));
EXPECT_EQ(7, llvm::any_cast<int>(B));
EXPECT_STREQ("hello", llvm::any_cast<const char *>(D));
EXPECT_STREQ("hello", llvm::any_cast<const char *>(D));
EXPECT_EQ('x', llvm::any_cast<char>(E));
EXPECT_EQ('x', llvm::any_cast<char>(E));
llvm::Any F(B);
EXPECT_EQ(7, llvm::any_cast<int>(F));
EXPECT_EQ(7, llvm::any_cast<int>(F));
llvm::Any G(std::move(C));
EXPECT_EQ(8, llvm::any_cast<int>(G));
EXPECT_EQ(8, llvm::any_cast<int>(G));
A = F;
EXPECT_EQ(7, llvm::any_cast<int>(A));
EXPECT_EQ(7, llvm::any_cast<int>(A));
E = std::move(G);
EXPECT_EQ(8, llvm::any_cast<int>(E));
EXPECT_EQ(8, llvm::any_cast<int>(E));
// Make sure we can any_cast from an rvalue and that it's properly destroyed
// in the process.
EXPECT_EQ(8, llvm::any_cast<int>(std::move(E)));
EXPECT_TRUE(E.hasValue());
// Make sure moving from pointers gives back pointers, and that we can modify
// the underlying value through those pointers.
EXPECT_EQ(7, *llvm::any_cast<int>(&A));
int *N = llvm::any_cast<int>(&A);
*N = 42;
EXPECT_EQ(42, llvm::any_cast<int>(A));
// Make sure that we can any_cast to a reference and this is considered a good
// cast, resulting in an lvalue which can be modified.
llvm::any_cast<int &>(A) = 43;
EXPECT_EQ(43, llvm::any_cast<int>(A));
}
TEST(AnyTest, CopiesAndMoves) {
struct TestType {
TestType() = default;
TestType(const TestType &Other)
: Copies(Other.Copies + 1), Moves(Other.Moves) {}
TestType(TestType &&Other) : Copies(Other.Copies), Moves(Other.Moves + 1) {}
int Copies = 0;
int Moves = 0;
};
// One move to get TestType into the Any, and one move on the cast.
TestType T1 = llvm::any_cast<TestType>(Any{TestType()});
EXPECT_EQ(0, T1.Copies);
EXPECT_EQ(2, T1.Moves);
// One move to get TestType into the Any, and one copy on the cast.
Any A{TestType()};
TestType T2 = llvm::any_cast<TestType>(A);
EXPECT_EQ(1, T2.Copies);
EXPECT_EQ(1, T2.Moves);
// One move to get TestType into the Any, and one move on the cast.
TestType T3 = llvm::any_cast<TestType>(std::move(A));
EXPECT_EQ(0, T3.Copies);
EXPECT_EQ(2, T3.Moves);
}
TEST(AnyTest, BadAnyCast) {
llvm::Any A;
llvm::Any B{7};
llvm::Any C{"hello"};
llvm::Any D{'x'};
#if !defined(NDEBUG) && GTEST_HAS_DEATH_TEST
EXPECT_DEATH(llvm::any_cast<int>(A), "");
EXPECT_DEATH(llvm::any_cast<float>(B), "");
EXPECT_DEATH(llvm::any_cast<int *>(B), "");
EXPECT_DEATH(llvm::any_cast<std::string>(C), "");
EXPECT_DEATH(llvm::any_cast<unsigned char>(D), "");
#endif
}
} // anonymous namespace
<|endoftext|> |
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkUSImageSource.h"
#include "mitkProperties.h"
const char* mitk::USImageSource::IMAGE_PROPERTY_IDENTIFIER = "id_nummer";
mitk::USImageSource::USImageSource()
: m_OpenCVToMitkFilter(mitk::OpenCVToMitkImageFilter::New()),
m_MitkToOpenCVFilter(0),
m_ImageFilter(mitk::BasicCombinationOpenCVImageFilter::New()),
m_CurrentImageId(0)
{
m_OpenCVToMitkFilter->SetCopyBuffer(false);
}
mitk::USImageSource::~USImageSource()
{
}
void mitk::USImageSource::PushFilter(AbstractOpenCVImageFilter::Pointer filter)
{
m_ImageFilter->PushFilter(filter);
}
bool mitk::USImageSource::RemoveFilter(AbstractOpenCVImageFilter::Pointer filter)
{
return m_ImageFilter->RemoveFilter(filter);
}
bool mitk::USImageSource::GetIsFilterInThePipeline(AbstractOpenCVImageFilter::Pointer filter)
{
return m_ImageFilter->GetIsFilterOnTheList(filter);
}
mitk::Image::Pointer mitk::USImageSource::GetNextImage()
{
mitk::Image::Pointer result;
if ( m_ImageFilter.IsNotNull() && ! m_ImageFilter->GetIsEmpty() )
{
cv::Mat image;
this->GetNextRawImage(image);
if ( ! image.empty() )
{
// execute filter if a filter is specified
if ( m_ImageFilter.IsNotNull() ) { m_ImageFilter->FilterImage(image, m_CurrentImageId); }
// convert to MITK image
IplImage ipl_img = image;
this->m_OpenCVToMitkFilter->SetOpenCVImage(&ipl_img);
this->m_OpenCVToMitkFilter->Update();
// OpenCVToMitkImageFilter returns a standard mitk::image.
result = this->m_OpenCVToMitkFilter->GetOutput();
}
// clean up
image.release();
}
else
{
// mitk image can be received direclty if no filtering is necessary
this->GetNextRawImage(result);
}
if ( result.IsNotNull() )
{
result->SetProperty(IMAGE_PROPERTY_IDENTIFIER, mitk::IntProperty::New(m_CurrentImageId));
m_CurrentImageId++;
// Everything as expected, return result
return result;
}
else
{
//MITK_WARN("mitkUSImageSource") << "Result image is not set.";
return mitk::Image::New();
}
}
void mitk::USImageSource::GetNextRawImage( cv::Mat& image )
{
// create filter object if it does not exist yet
if ( ! m_MitkToOpenCVFilter )
{
m_MitkToOpenCVFilter = mitk::ImageToOpenCVImageFilter::New();
}
// get mitk image through virtual method of the subclass
mitk::Image::Pointer mitkImg;
this->GetNextRawImage(mitkImg);
if ( mitkImg.IsNull() || ! mitkImg->IsInitialized() )
{
image = cv::Mat();
return;
}
// convert mitk::Image to an OpenCV image
m_MitkToOpenCVFilter->SetImage(mitkImg);
image = m_MitkToOpenCVFilter->GetOpenCVMat();
}
<commit_msg>Got rid of IplImage.<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkUSImageSource.h"
#include "mitkProperties.h"
const char* mitk::USImageSource::IMAGE_PROPERTY_IDENTIFIER = "id_nummer";
mitk::USImageSource::USImageSource()
: m_OpenCVToMitkFilter(mitk::OpenCVToMitkImageFilter::New()),
m_MitkToOpenCVFilter(0),
m_ImageFilter(mitk::BasicCombinationOpenCVImageFilter::New()),
m_CurrentImageId(0)
{
m_OpenCVToMitkFilter->SetCopyBuffer(false);
}
mitk::USImageSource::~USImageSource()
{
}
void mitk::USImageSource::PushFilter(AbstractOpenCVImageFilter::Pointer filter)
{
m_ImageFilter->PushFilter(filter);
}
bool mitk::USImageSource::RemoveFilter(AbstractOpenCVImageFilter::Pointer filter)
{
return m_ImageFilter->RemoveFilter(filter);
}
bool mitk::USImageSource::GetIsFilterInThePipeline(AbstractOpenCVImageFilter::Pointer filter)
{
return m_ImageFilter->GetIsFilterOnTheList(filter);
}
mitk::Image::Pointer mitk::USImageSource::GetNextImage()
{
mitk::Image::Pointer result;
if ( m_ImageFilter.IsNotNull() && ! m_ImageFilter->GetIsEmpty() )
{
cv::Mat image;
this->GetNextRawImage(image);
if ( ! image.empty() )
{
// execute filter if a filter is specified
if ( m_ImageFilter.IsNotNull() ) { m_ImageFilter->FilterImage(image, m_CurrentImageId); }
// convert to MITK image
this->m_OpenCVToMitkFilter->SetOpenCVMat(image);
this->m_OpenCVToMitkFilter->Update();
// OpenCVToMitkImageFilter returns a standard mitk::image.
result = this->m_OpenCVToMitkFilter->GetOutput();
}
}
else
{
// mitk image can be received direclty if no filtering is necessary
this->GetNextRawImage(result);
}
if ( result.IsNotNull() )
{
result->SetProperty(IMAGE_PROPERTY_IDENTIFIER, mitk::IntProperty::New(m_CurrentImageId));
m_CurrentImageId++;
// Everything as expected, return result
return result;
}
else
{
//MITK_WARN("mitkUSImageSource") << "Result image is not set.";
return mitk::Image::New();
}
}
void mitk::USImageSource::GetNextRawImage( cv::Mat& image )
{
// create filter object if it does not exist yet
if ( ! m_MitkToOpenCVFilter )
{
m_MitkToOpenCVFilter = mitk::ImageToOpenCVImageFilter::New();
}
// get mitk image through virtual method of the subclass
mitk::Image::Pointer mitkImg;
this->GetNextRawImage(mitkImg);
if ( mitkImg.IsNull() || ! mitkImg->IsInitialized() )
{
image = cv::Mat();
return;
}
// convert mitk::Image to an OpenCV image
m_MitkToOpenCVFilter->SetImage(mitkImg);
image = m_MitkToOpenCVFilter->GetOpenCVMat();
}
<|endoftext|> |
<commit_before>#include <stdarg.h>
#include <ctype.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdbool.h>
#include <string.h>
#define INTERLEAVE_TEST
#define __code
#define __data
#define __pdata
#define __xdata
#define PARAM_ECC 1
int interleave=1;
int param_get(int param)
{
// ECC_PARAM returns "Golay + interlacing"
if (interleave)
return 2;
else return 1;
}
#include "interleave.c"
#include "golay.c"
int show(char *msg,int n,unsigned char *b)
{
int i;
printf("%s:\n",msg);
for(i=0;i<n;i++) {
if (!(i&0xf)) printf("\n%02x:",i);
printf(" %02x",b[i]);
}
printf("\n");
return 0;
}
int prefill(unsigned char *b)
{
int i;
for(i=0;i<256;i++) b[i]=i;
return 0;
}
int countones(int n,unsigned char *b)
{
int j,i=0;
int count=0;
for(i=0;i<n;i++) {
for(j=0;j<8;j++)
if (b[i]&(1<<j)) count++;
}
return count;
}
int showbitpattern(int n,int byte_low,int byte_high,int burst_low,int burst_high)
{
printf("Interleaved bit pattern: (n=%d, range=[%d,%d)\n",n,byte_low,byte_high);
int i,j;
int count=0;
for(i=byte_low*8;i<byte_high*8;i+=8)
{
int affected=0;
for(j=i+7;j>=i;j--)
{
int b=bitnumber(n,j);
if (b>=burst_low&&b<=burst_high)
affected=1;
}
if (affected) {
printf("byte 0x%02x : ",i/8);
for(j=i+7;j>=i;j--)
{
int b=bitnumber(n,j);
printf("b7=0x%02x.%d ",b/8,b&7);
}
printf("\n");
count++;
}
}
if (!count) printf(" no blocks were affected by the burst error.\n");
return 0;
}
int main()
{
int n;
unsigned char in[256];
unsigned char out[512];
unsigned char verify[256];
printf("Testing interleaver at low level\n");
for(n=6;n<=510;n+=6) {
// Perform some diagnostics on the interleaver
bzero(out,512);
interleave_data_size=n;
// printf("step=%d bits.\n",steps[n/3]);
int i;
for(i=0;i<n;i++) {
interleave_setbyte(out,i,0xff);
int ones=countones(n,out);
if (ones!=((i+1)*8)) {
printf("Test failed for golay encoded packet size=%d\n",n);
printf("n=%d, i=%d\n",n,i);
show("bits clash with another byte",n,out);
int k,l;
for(k=0;k<(8*i);k++)
for(l=0;l<8;l++)
if (bitnumber(n,k)==bitnumber(n,i*8+l)) {
printf(" byte %d.%d (bit=%d) clashes with bit %d of this byte"
" @ bit %d\n",
k/8,k&7,k,l,bitnumber(n,i*8+l));
printf("them: bit*steps[n/3]%%(n*8) = %d*steps[%d]%%%d = %d\n",
k,n/3,n*8,k*steps[n/3]%(n*8));
printf("us: bit*steps[n/3]%%(n*8) = %d*steps[%d]%%%d = %d\n",
i*8+l,n/3,n*8,(i*8+l)*steps[n/3]%(n*8));
}
exit(-1);
}
int j;
for(j=0;j<=255;j++) {
interleave_setbyte(out,i,j);
if (interleave_getbyte(out,i)!=j) {
printf("Test failed for interleave_{set,get}byte(n=%d,%d) value 0x%02x\n",
n,i,j);
printf(" Expected 0x%02x, but got 0x%02x\n",j,interleave_getbyte(out,i));
printf(" Bits:\n");
int k;
for(k=0;k<8;k++) {
printf(" bit %d(%d) : %d (bit number = %d)\n",
k,i*8+k,
interleave_getbit(interleave_data_size,out,(i*8)+k),
bitnumber(interleave_data_size,(i*8)+k));
}
show("interleaved encoded data",n,out);
exit(-1);
}
}
}
printf("."); fflush(stdout);
}
printf(" -- test passed\n");
// Try interleaving and golay protecting a block of data
// 256 bytes of golay protected data = 128 bytes of raw data.
printf("Testing interleaving at golay_{en,de}code() level.\n");
for(n=0;n<128;n+=3) {
prefill(in);
interleave=0;
golay_encode(n,in,out);
int icount=countones(n*2,out);
interleave=1;
golay_encode(n,in,out);
int ncount=countones(n*2,out);
if (icount!=ncount) {
printf("Test failed: different number of set bits with/without"
" interleaving: %d vs %d\n",icount,ncount);
exit(-1);
}
bzero(verify,256);
int errcount=golay_decode(n*2,out,verify);
if (bcmp(in,verify,n)||errcount) {
printf("Decode error for packet of %d bytes (errcount=%d)\n",n,errcount);
show("input",n,in);
show("verify error (should be 0x00 -- 0xnn)",n,verify);
show("interleaved encoded version",n*2,out);
unsigned char out2[512];
interleave=0;
golay_encode(n,in,out2);
show("uninterleaved encoded version",n*2,out2);
int k;
interleave_data_size=n*2;
for(k=0;k<n*2;k++)
out2[k]=interleave_getbyte(out,k);
show("de-interleaved version of interleaved encoded version",n*2,out2);
exit(-1);
}
}
printf(" -- test passed.\n");
// Try interleaving and golay protecting a block of data
// But this time, introduce errors
printf("Testing interleaving at golay_{en,de}code() level with burst errors.\n");
int e,o,j;
for(n=126;n>0;n-=3) {
// Wiping out upto 1/4 of the bytes should not prevent reception
for(e=0;e<(n*2/4)-1;e++)
{
for(o=(2*n)-e-1;o>=0;o--)
{
prefill(in);
interleave=0;
golay_encode(n,in,out);
int icount=countones(n*2,out);
interleave=1;
golay_encode(n,in,out);
int ncount=countones(n*2,out);
if (icount!=ncount) {
printf("Test failed: different number of set bits with/without"
" interleaving: %d vs %d\n",icount,ncount);
exit(-1);
}
// introduce the burst error
for(j=o;j<o+e;j++) out[j]=0;
// Verify that it still decodes properly
bzero(verify,256);
int errcount=golay_decode(n*2,out,verify);
if (bcmp(in,verify,n)) {
if (e>0)
printf("Decode error for packet of %d bytes, with burst error from 0x%02x..0x%02x bytes inclusive\n",n,o,o+e-1);
else
printf("Decode error for packet of %d bytes, with zero length burst error.\n",n);
printf(" golay_decode() noticed %d errors.\n",errcount);
show("input",n,in);
show("verify error (should be 0x00 -- 0xnn)",n,verify);
unsigned char out2[512];
int k,count=0;
for(k=0;k<n;k++) out2[k]=in[k]^verify[k];
show("Differences",n,out2);
showbitpattern(n*2,0,n*2,o*8,(o+e-1)*8+7);
/* Show how the code words have been affected */
golay_encode(n,in,out2);
for(k=0;k<n*2;k+=6) {
int m;
int show=0;
for(m=0;m<6;m++) if (interleave_getbyte(out2,k+m)!=interleave_getbyte(out,k+m)) show=1;
for(m=0;m<6;m++) g6[m]=interleave_getbyte(out,k+m);
if (golay_decode24()) show=1;
for(m=0;m<6;m++) g6[m]=interleave_getbyte(out2,k+m);
if (golay_decode24()) show=1;
if (show) {
count++;
printf("Golay block #%2d (without burst error) : ",k/6);
for(m=0;m<6;m++) printf("%02x",interleave_getbyte(out2,k+m));
printf("\n (with burst error) : ",k/6);
for(m=0;m<6;m++) printf("%02x",interleave_getbyte(out,k+m));
printf("\n");
for(m=0;m<6;m++) g6[m]=interleave_getbyte(out,k+m);
printf(" golay error count (with burst error) = %d\n",golay_decode24());
for(m=0;m<6;m++) g6[m]=interleave_getbyte(out2,k+m);
printf(" golay error count (without burst error) = %d\n",golay_decode24());
}
}
if (!count) printf(" no golay blocks were affected by the burst error.\n");
exit(-1);
} else printf(".");
}
}
}
printf(" -- test passed.\n");
return 0;
}
<commit_msg>show % of packet length zeroed out when reporting a verify error. Evidence is pointing to golay coder only being able to recover from 2 wrong bits, not 3 in every 12.<commit_after>#include <stdarg.h>
#include <ctype.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdbool.h>
#include <string.h>
#define INTERLEAVE_TEST
#define __code
#define __data
#define __pdata
#define __xdata
#define PARAM_ECC 1
int interleave=1;
int param_get(int param)
{
// ECC_PARAM returns "Golay + interlacing"
if (interleave)
return 2;
else return 1;
}
#include "interleave.c"
#include "golay.c"
int show(char *msg,int n,unsigned char *b)
{
int i;
printf("%s:\n",msg);
for(i=0;i<n;i++) {
if (!(i&0xf)) printf("\n%02x:",i);
printf(" %02x",b[i]);
}
printf("\n");
return 0;
}
int prefill(unsigned char *b)
{
int i;
for(i=0;i<256;i++) b[i]=i;
return 0;
}
int countones(int n,unsigned char *b)
{
int j,i=0;
int count=0;
for(i=0;i<n;i++) {
for(j=0;j<8;j++)
if (b[i]&(1<<j)) count++;
}
return count;
}
int showbitpattern(int n,int byte_low,int byte_high,int burst_low,int burst_high)
{
printf("Interleaved bit pattern: (n=%d, range=[%d,%d)\n",n,byte_low,byte_high);
int i,j;
int count=0;
for(i=byte_low*8;i<byte_high*8;i+=8)
{
int affected=0;
for(j=i+7;j>=i;j--)
{
int b=bitnumber(n,j);
if (b>=burst_low&&b<=burst_high)
affected=1;
}
if (affected) {
printf("byte 0x%02x : ",i/8);
for(j=i+7;j>=i;j--)
{
int b=bitnumber(n,j);
printf("b7=0x%02x.%d ",b/8,b&7);
}
printf("\n");
count++;
}
}
if (!count) printf(" no blocks were affected by the burst error.\n");
return 0;
}
int main()
{
int n;
unsigned char in[256];
unsigned char out[512];
unsigned char verify[256];
printf("Testing interleaver at low level\n");
for(n=6;n<=510;n+=6) {
// Perform some diagnostics on the interleaver
bzero(out,512);
interleave_data_size=n;
// printf("step=%d bits.\n",steps[n/3]);
int i;
for(i=0;i<n;i++) {
interleave_setbyte(out,i,0xff);
int ones=countones(n,out);
if (ones!=((i+1)*8)) {
printf("Test failed for golay encoded packet size=%d\n",n);
printf("n=%d, i=%d\n",n,i);
show("bits clash with another byte",n,out);
int k,l;
for(k=0;k<(8*i);k++)
for(l=0;l<8;l++)
if (bitnumber(n,k)==bitnumber(n,i*8+l)) {
printf(" byte %d.%d (bit=%d) clashes with bit %d of this byte"
" @ bit %d\n",
k/8,k&7,k,l,bitnumber(n,i*8+l));
printf("them: bit*steps[n/3]%%(n*8) = %d*steps[%d]%%%d = %d\n",
k,n/3,n*8,k*steps[n/3]%(n*8));
printf("us: bit*steps[n/3]%%(n*8) = %d*steps[%d]%%%d = %d\n",
i*8+l,n/3,n*8,(i*8+l)*steps[n/3]%(n*8));
}
exit(-1);
}
int j;
for(j=0;j<=255;j++) {
interleave_setbyte(out,i,j);
if (interleave_getbyte(out,i)!=j) {
printf("Test failed for interleave_{set,get}byte(n=%d,%d) value 0x%02x\n",
n,i,j);
printf(" Expected 0x%02x, but got 0x%02x\n",j,interleave_getbyte(out,i));
printf(" Bits:\n");
int k;
for(k=0;k<8;k++) {
printf(" bit %d(%d) : %d (bit number = %d)\n",
k,i*8+k,
interleave_getbit(interleave_data_size,out,(i*8)+k),
bitnumber(interleave_data_size,(i*8)+k));
}
show("interleaved encoded data",n,out);
exit(-1);
}
}
}
printf("."); fflush(stdout);
}
printf(" -- test passed\n");
// Try interleaving and golay protecting a block of data
// 256 bytes of golay protected data = 128 bytes of raw data.
printf("Testing interleaving at golay_{en,de}code() level.\n");
for(n=0;n<128;n+=3) {
prefill(in);
interleave=0;
golay_encode(n,in,out);
int icount=countones(n*2,out);
interleave=1;
golay_encode(n,in,out);
int ncount=countones(n*2,out);
if (icount!=ncount) {
printf("Test failed: different number of set bits with/without"
" interleaving: %d vs %d\n",icount,ncount);
exit(-1);
}
bzero(verify,256);
int errcount=golay_decode(n*2,out,verify);
if (bcmp(in,verify,n)||errcount) {
printf("Decode error for packet of %d bytes (errcount=%d)\n",n,errcount);
show("input",n,in);
show("verify error (should be 0x00 -- 0xnn)",n,verify);
show("interleaved encoded version",n*2,out);
unsigned char out2[512];
interleave=0;
golay_encode(n,in,out2);
show("uninterleaved encoded version",n*2,out2);
int k;
interleave_data_size=n*2;
for(k=0;k<n*2;k++)
out2[k]=interleave_getbyte(out,k);
show("de-interleaved version of interleaved encoded version",n*2,out2);
exit(-1);
}
}
printf(" -- test passed.\n");
// Try interleaving and golay protecting a block of data
// But this time, introduce errors
printf("Testing interleaving at golay_{en,de}code() level with burst errors.\n");
int e,o,j;
for(n=126;n>0;n-=3) {
// Wiping out upto 1/4 of the bytes should not prevent reception
for(e=0;e<(n*2/4)-1;e++)
{
for(o=(2*n)-e-1;o>=0;o--)
{
prefill(in);
interleave=0;
golay_encode(n,in,out);
int icount=countones(n*2,out);
interleave=1;
golay_encode(n,in,out);
int ncount=countones(n*2,out);
if (icount!=ncount) {
printf("Test failed: different number of set bits with/without"
" interleaving: %d vs %d\n",icount,ncount);
exit(-1);
}
// introduce the burst error
for(j=o;j<o+e;j++) out[j]=0;
// Verify that it still decodes properly
bzero(verify,256);
int errcount=golay_decode(n*2,out,verify);
if (bcmp(in,verify,n)) {
if (e>0)
printf("Decode error for packet of %d bytes, with burst error from 0x%02x..0x%02x bytes inclusive (%2f%% of length)\n",n,o,o+e-1,
e*50.0/n);
else
printf("Decode error for packet of %d bytes, with zero length burst error.\n",n);
printf(" golay_decode() noticed %d errors.\n",errcount);
show("input",n,in);
show("verify error (should be 0x00 -- 0xnn)",n,verify);
unsigned char out2[512];
int k,count=0;
for(k=0;k<n;k++) out2[k]=in[k]^verify[k];
show("Differences",n,out2);
showbitpattern(n*2,0,n*2,o*8,(o+e-1)*8+7);
/* Show how the code words have been affected */
golay_encode(n,in,out2);
for(k=0;k<n*2;k+=6) {
int m;
int show=0;
for(m=0;m<6;m++) if (interleave_getbyte(out2,k+m)!=interleave_getbyte(out,k+m)) show=1;
for(m=0;m<6;m++) g6[m]=interleave_getbyte(out,k+m);
if (golay_decode24()) show=1;
for(m=0;m<6;m++) g6[m]=interleave_getbyte(out2,k+m);
if (golay_decode24()) show=1;
if (show) {
count++;
printf("Golay block #%2d (without burst error) : ",k/6);
for(m=0;m<6;m++) printf("%02x",interleave_getbyte(out2,k+m));
printf("\n (with burst error) : ",k/6);
for(m=0;m<6;m++) printf("%02x",interleave_getbyte(out,k+m));
printf("\n");
for(m=0;m<6;m++) g6[m]=interleave_getbyte(out,k+m);
printf(" golay error count (with burst error) = %d\n",golay_decode24());
for(m=0;m<6;m++) g6[m]=interleave_getbyte(out2,k+m);
printf(" golay error count (without burst error) = %d\n",golay_decode24());
}
}
if (!count) printf(" no golay blocks were affected by the burst error.\n");
exit(-1);
} else printf(".");
}
}
}
printf(" -- test passed.\n");
return 0;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Programme : OTB (ORFEO ToolBox)
Auteurs : CS - C.Ruffel
Language : C++
Date : 14 mars 2006
Version :
Role : Test du filtre de detection de lignes (instanciation)
$Id$
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#define MAIN
#include "itkExceptionObject.h"
#include "itkImage.h"
#include <iostream>
#include "otbLineRatioDetector.h"
int otbLineRatioDetectorNew( int argc, char* argv[] )
{
try
{
typedef unsigned char InputPixelType;
typedef double OutputPixelType;
const unsigned int Dimension = 2;
typedef itk::Image< InputPixelType, Dimension > InputImageType;
typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
typedef otb::LineRatioEdgeDetector< InputImageType, OutputImageType> FilterType;
FilterType::Pointer FilterLineRatio = FilterType::New();
}
catch( itk::ExceptionObject & err )
{
std::cout << "Exception itk::ExceptionObject levee !" << std::endl;
std::cout << err << std::endl;
return EXIT_FAILURE;
}
catch( ... )
{
std::cout << "Exception levee inconnue !" << std::endl;
return EXIT_FAILURE;
}
// Software Guide : EndCodeSnippet
//#endif
return EXIT_SUCCESS;
}
<commit_msg>nomsg<commit_after>/*=========================================================================
Programme : OTB (ORFEO ToolBox)
Auteurs : CS - C.Ruffel
Language : C++
Date : 14 mars 2006
Version :
Role : Test du filtre de detection de lignes (instanciation)
$Id$
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#define MAIN
#include "itkExceptionObject.h"
#include "itkImage.h"
#include <iostream>
#include "otbLineRatioDetector.h"
int otbLineRatioDetectorNew( int argc, char* argv[] )
{
try
{
typedef unsigned char InputPixelType;
typedef double OutputPixelType;
const unsigned int Dimension = 2;
typedef itk::Image< InputPixelType, Dimension > InputImageType;
typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
typedef otb::LineRatioDetector< InputImageType, OutputImageType> FilterType;
FilterType::Pointer FilterLineRatio = FilterType::New();
}
catch( itk::ExceptionObject & err )
{
std::cout << "Exception itk::ExceptionObject levee !" << std::endl;
std::cout << err << std::endl;
return EXIT_FAILURE;
}
catch( ... )
{
std::cout << "Exception levee inconnue !" << std::endl;
return EXIT_FAILURE;
}
// Software Guide : EndCodeSnippet
//#endif
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <mapnik/version.hpp>
#include <mapnik/debug.hpp>
#include <mapnik/marker.hpp>
#include <mapnik/marker_cache.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/svg/svg_path_adapter.hpp>
#include <mapnik/svg/svg_renderer_agg.hpp>
#include <mapnik/svg/svg_path_attributes.hpp>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wunused-local-typedef"
#include <boost/algorithm/string.hpp>
#include <boost/program_options.hpp>
#pragma GCC diagnostic pop
#include "agg_rasterizer_scanline_aa.h"
#include "agg_basics.h"
#include "agg_rendering_buffer.h"
#include "agg_renderer_base.h"
#include "agg_pixfmt_rgba.h"
#include "agg_scanline_u.h"
struct main_marker_visitor
{
main_marker_visitor(std::string const& svg_name,
bool verbose,
bool auto_open)
: svg_name_(svg_name),
verbose_(verbose),
auto_open_(auto_open) {}
int operator() (mapnik::marker_svg const& marker)
{
using pixfmt = agg::pixfmt_rgba32_pre;
using renderer_base = agg::renderer_base<pixfmt>;
using renderer_solid = agg::renderer_scanline_aa_solid<renderer_base>;
agg::rasterizer_scanline_aa<> ras_ptr;
agg::scanline_u8 sl;
double opacity = 1;
int w = marker.width();
int h = marker.height();
if (verbose_)
{
std::clog << "found width of '" << w << "' and height of '" << h << "'\n";
}
// 10 pixel buffer to avoid edge clipping of 100% svg's
mapnik::image_rgba8 im(w+0,h+0);
agg::rendering_buffer buf(im.bytes(), im.width(), im.height(), im.row_size());
pixfmt pixf(buf);
renderer_base renb(pixf);
mapnik::box2d<double> const& bbox = marker.get_data()->bounding_box();
mapnik::coord<double,2> c = bbox.center();
// center the svg marker on '0,0'
agg::trans_affine mtx = agg::trans_affine_translation(-c.x,-c.y);
// render the marker at the center of the marker box
mtx.translate(0.5 * im.width(), 0.5 * im.height());
mapnik::svg::vertex_stl_adapter<mapnik::svg::svg_path_storage> stl_storage(marker.get_data()->source());
mapnik::svg::svg_path_adapter svg_path(stl_storage);
mapnik::svg::svg_renderer_agg<mapnik::svg::svg_path_adapter,
agg::pod_bvector<mapnik::svg::path_attributes>,
renderer_solid,
agg::pixfmt_rgba32_pre > svg_renderer_this(svg_path,
marker.get_data()->attributes());
svg_renderer_this.render(ras_ptr, sl, renb, mtx, opacity, bbox);
std::string png_name(svg_name_);
boost::algorithm::ireplace_last(png_name,".svg",".png");
demultiply_alpha(im);
mapnik::save_to_file<mapnik::image_rgba8>(im,png_name,"png");
int status = 0;
if (auto_open_)
{
std::ostringstream s;
#ifdef DARWIN
s << "open " << png_name;
#else
s << "xdg-open " << png_name;
#endif
int ret = system(s.str().c_str());
if (ret != 0)
status = ret;
}
std::clog << "rendered to: " << png_name << "\n";
return status;
}
// default
template <typename T>
int operator() (T const&)
{
std::clog << "svg2png error: '" << svg_name_ << "' is not a valid vector!\n";
return -1;
}
private:
std::string const& svg_name_;
bool verbose_;
bool auto_open_;
};
int main (int argc,char** argv)
{
namespace po = boost::program_options;
bool verbose = false;
bool auto_open = false;
int status = 0;
std::vector<std::string> svg_files;
mapnik::logger::instance().set_severity(mapnik::logger::error);
try
{
po::options_description desc("svg2png utility");
desc.add_options()
("help,h", "produce usage message")
("version,V","print version string")
("verbose,v","verbose output")
("open","automatically open the file after rendering (os x only)")
("svg",po::value<std::vector<std::string> >(),"svg file to read")
;
po::positional_options_description p;
p.add("svg",-1);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
po::notify(vm);
if (vm.count("version"))
{
std::clog <<"version " << MAPNIK_VERSION_STRING << std::endl;
return 1;
}
if (vm.count("help"))
{
std::clog << desc << std::endl;
return 1;
}
if (vm.count("verbose"))
{
verbose = true;
}
if (vm.count("open"))
{
auto_open = true;
}
if (vm.count("svg"))
{
svg_files=vm["svg"].as< std::vector<std::string> >();
}
else
{
std::clog << "please provide an svg file!" << std::endl;
return -1;
}
std::vector<std::string>::const_iterator itr = svg_files.begin();
if (itr == svg_files.end())
{
std::clog << "no svg files to render" << std::endl;
return 0;
}
while (itr != svg_files.end())
{
std::string svg_name (*itr++);
if (verbose)
{
std::clog << "found: " << svg_name << "\n";
}
std::shared_ptr<mapnik::marker const> marker = mapnik::marker_cache::instance().find(svg_name, false);
main_marker_visitor visitor(svg_name, verbose, auto_open);
status = mapnik::util::apply_visitor(visitor, *marker);
}
}
catch (std::exception const& ex)
{
std::clog << "Exception caught:" << ex.what() << std::endl;
return -1;
}
catch (...)
{
std::clog << "Exception of unknown type!" << std::endl;
return -1;
}
return status;
}
<commit_msg>use std::system<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <mapnik/version.hpp>
#include <mapnik/debug.hpp>
#include <mapnik/marker.hpp>
#include <mapnik/marker_cache.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/svg/svg_path_adapter.hpp>
#include <mapnik/svg/svg_renderer_agg.hpp>
#include <mapnik/svg/svg_path_attributes.hpp>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wunused-local-typedef"
#include <boost/algorithm/string.hpp>
#include <boost/program_options.hpp>
#pragma GCC diagnostic pop
#include "agg_rasterizer_scanline_aa.h"
#include "agg_basics.h"
#include "agg_rendering_buffer.h"
#include "agg_renderer_base.h"
#include "agg_pixfmt_rgba.h"
#include "agg_scanline_u.h"
struct main_marker_visitor
{
main_marker_visitor(std::string const& svg_name,
bool verbose,
bool auto_open)
: svg_name_(svg_name),
verbose_(verbose),
auto_open_(auto_open) {}
int operator() (mapnik::marker_svg const& marker)
{
using pixfmt = agg::pixfmt_rgba32_pre;
using renderer_base = agg::renderer_base<pixfmt>;
using renderer_solid = agg::renderer_scanline_aa_solid<renderer_base>;
agg::rasterizer_scanline_aa<> ras_ptr;
agg::scanline_u8 sl;
double opacity = 1;
int w = marker.width();
int h = marker.height();
if (verbose_)
{
std::clog << "found width of '" << w << "' and height of '" << h << "'\n";
}
// 10 pixel buffer to avoid edge clipping of 100% svg's
mapnik::image_rgba8 im(w+0,h+0);
agg::rendering_buffer buf(im.bytes(), im.width(), im.height(), im.row_size());
pixfmt pixf(buf);
renderer_base renb(pixf);
mapnik::box2d<double> const& bbox = marker.get_data()->bounding_box();
mapnik::coord<double,2> c = bbox.center();
// center the svg marker on '0,0'
agg::trans_affine mtx = agg::trans_affine_translation(-c.x,-c.y);
// render the marker at the center of the marker box
mtx.translate(0.5 * im.width(), 0.5 * im.height());
mapnik::svg::vertex_stl_adapter<mapnik::svg::svg_path_storage> stl_storage(marker.get_data()->source());
mapnik::svg::svg_path_adapter svg_path(stl_storage);
mapnik::svg::svg_renderer_agg<mapnik::svg::svg_path_adapter,
agg::pod_bvector<mapnik::svg::path_attributes>,
renderer_solid,
agg::pixfmt_rgba32_pre > svg_renderer_this(svg_path,
marker.get_data()->attributes());
svg_renderer_this.render(ras_ptr, sl, renb, mtx, opacity, bbox);
std::string png_name(svg_name_);
boost::algorithm::ireplace_last(png_name,".svg",".png");
demultiply_alpha(im);
mapnik::save_to_file<mapnik::image_rgba8>(im,png_name,"png");
int status = 0;
if (auto_open_)
{
std::ostringstream s;
#ifdef DARWIN
s << "open " << png_name;
#else
s << "xdg-open " << png_name;
#endif
int ret = std::system(s.str().c_str());
if (ret != 0)
status = ret;
}
std::clog << "rendered to: " << png_name << "\n";
return status;
}
// default
template <typename T>
int operator() (T const&)
{
std::clog << "svg2png error: '" << svg_name_ << "' is not a valid vector!\n";
return -1;
}
private:
std::string const& svg_name_;
bool verbose_;
bool auto_open_;
};
int main (int argc,char** argv)
{
namespace po = boost::program_options;
bool verbose = false;
bool auto_open = false;
int status = 0;
std::vector<std::string> svg_files;
mapnik::logger::instance().set_severity(mapnik::logger::error);
try
{
po::options_description desc("svg2png utility");
desc.add_options()
("help,h", "produce usage message")
("version,V","print version string")
("verbose,v","verbose output")
("open","automatically open the file after rendering (os x only)")
("svg",po::value<std::vector<std::string> >(),"svg file to read")
;
po::positional_options_description p;
p.add("svg",-1);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
po::notify(vm);
if (vm.count("version"))
{
std::clog <<"version " << MAPNIK_VERSION_STRING << std::endl;
return 1;
}
if (vm.count("help"))
{
std::clog << desc << std::endl;
return 1;
}
if (vm.count("verbose"))
{
verbose = true;
}
if (vm.count("open"))
{
auto_open = true;
}
if (vm.count("svg"))
{
svg_files=vm["svg"].as< std::vector<std::string> >();
}
else
{
std::clog << "please provide an svg file!" << std::endl;
return -1;
}
std::vector<std::string>::const_iterator itr = svg_files.begin();
if (itr == svg_files.end())
{
std::clog << "no svg files to render" << std::endl;
return 0;
}
while (itr != svg_files.end())
{
std::string svg_name (*itr++);
if (verbose)
{
std::clog << "found: " << svg_name << "\n";
}
std::shared_ptr<mapnik::marker const> marker = mapnik::marker_cache::instance().find(svg_name, false);
main_marker_visitor visitor(svg_name, verbose, auto_open);
status = mapnik::util::apply_visitor(visitor, *marker);
}
}
catch (std::exception const& ex)
{
std::clog << "Exception caught:" << ex.what() << std::endl;
return -1;
}
catch (...)
{
std::clog << "Exception of unknown type!" << std::endl;
return -1;
}
return status;
}
<|endoftext|> |
<commit_before>///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Industrial Light & Magic nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////
//
// Authors:
// Simon Green <[email protected]>
// Drew Hess <[email protected]>
//
//----------------------------------------------------------------------------
//
// class ImageViewFragShader
//
//----------------------------------------------------------------------------
#include <ImageViewFragShader.h>
#if defined PLATFORM_DARWIN_PPC
#include <OpenGL/glu.h>
#else
#include <GL/glu.h>
#endif
#define GLH_EXT_SINGLE_FILE
#include <glh/glh_extensions.h>
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <ImathFun.h>
#include <Iex.h>
ImageViewFragShader::ImageViewFragShader (int x, int y,
int width, int height,
const char label[],
const Imf::Rgba pixels[],
int dw, int dh,
int dx, int dy,
float exposure,
float defog,
float kneeLow,
float kneeHigh,
const std::string & filename)
:
ImageView (x, y,
width, height,
label,
pixels,
dw, dh,
dx, dy,
exposure,
defog,
kneeLow,
kneeHigh),
_useSoftware (false),
_fsFilename (filename)
{
}
bool
ImageViewFragShader::initGL ()
{
bool status = true;
try
{
if (!glh_init_extensions("GL_ARB_multitexture "
"GL_NV_vertex_program "
"GL_NV_fragment_program "))
{
THROW (Iex::BaseExc, "GL extensions required for fragment " <<
"shader support are not available: " << std::endl <<
" " << glh_get_unsupported_extensions ());
}
if (_fsFilename.empty ())
loadBuiltinFragShader ();
else
loadFragShaderFromFile ();
loadTexture ();
}
catch (const Iex::BaseExc & e)
{
std::cerr << e.what () << std::endl;
std::cerr << "Falling back to software rendering." << std::endl;
status = false;
}
return status;
}
void
ImageViewFragShader::loadTexture ()
{
//
// load OpenEXR image as OpenGL texture
//
GLenum target = GL_TEXTURE_RECTANGLE_NV;
glGenTextures (1, &_texture);
glBindTexture (target, _texture);
glTexParameteri (target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri (target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri (target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri (target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
glTexImage2D (target, 0, GL_FLOAT_RGBA16_NV, _dw, _dh, 0,
GL_RGBA, GL_HALF_FLOAT_NV, _rawPixels);
//
// Check for errors
//
GLenum error = glGetError ();
if (error != GL_NO_ERROR)
{
do
{
std::cerr << "Error loading texture: " <<
(char *) gluErrorString (error) << std::endl;
} while ((error = glGetError ()) != GL_NO_ERROR);
THROW (Iex::BaseExc, "Unable to load OpenEXR image as a texture.");
}
}
void
ImageViewFragShader::draw()
{
if (!valid())
{
if (!initGL ())
_useSoftware = true;
//
// Set up camera.
//
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
glViewport (0, 0, w (), h ());
glOrtho (0, w (), h (), 0, -1, 1);
glMatrixMode (GL_MODELVIEW);
glLoadIdentity ();
}
if (_useSoftware)
{
ImageView::updateScreenPixels ();
ImageView::draw ();
return;
}
glClearColor (0.3, 0.3, 0.3, 1.0);
glClear (GL_COLOR_BUFFER_BIT);
//
// Set fragment program parameters. See ImageView.cpp for details
// on what the parameters mean.
//
setCgNamedParameter ("exposure",
Imath::Math<float>::pow (2, _exposure + 2.47393));
setCgNamedParameter ("defog", _defog * _fogR, _defog * _fogG,
_defog * _fogB);
setCgNamedParameter ("gamma", 0.4545f);
setCgNamedParameter ("grayTarget", 84.66/255.0);
float kl = Imath::Math<float>::pow (2, _kneeLow);
setCgNamedParameter ("kneeLow", kl);
setCgNamedParameter ("kneeF", findKneeF (Imath::Math<float>::pow (2, _kneeHigh) - kl,
Imath::Math<float>::pow (2, 3.5) - kl));
//
// draw a textured quad
//
glEnable (GL_FRAGMENT_PROGRAM_NV);
glEnable (GL_TEXTURE_RECTANGLE_NV);
glBegin (GL_QUADS);
glTexCoord2f (0.0, 0.0); glVertex2f(0.0, 0.0);
glTexCoord2f (_dw, 0.0); glVertex2f(_dw, 0.0);
glTexCoord2f (_dw, _dh); glVertex2f(_dw, _dh);
glTexCoord2f (0.0, _dh); glVertex2f(0.0, _dh);
glEnd ();
glDisable (GL_TEXTURE_RECTANGLE_NV);
glDisable (GL_FRAGMENT_PROGRAM_NV);
}
void
ImageViewFragShader::loadFragShaderFromFile ()
{
FILE * f = 0;
char * code = 0;
try
{
f = fopen (_fsFilename.c_str (), "rb");
if (!f)
{
THROW_ERRNO ("Can't load fragment shader file " << _fsFilename <<
" (%T)");
}
fseek (f, 0, SEEK_END);
int len = ftell (f);
fseek (f, 0, SEEK_SET);
code = new char[len + 1];
int read = fread (code, 1, len, f);
if (read != len)
{
THROW (Iex::BaseExc, "Expected " << len << " bytes in fragment " <<
"shader file " << _fsFilename << ", only got " << read);
}
code[read] = '\0'; // null-terminate
if (!loadFragShader (code))
{
THROW (Iex::BaseExc, "Can't download fragment shader " <<
_fsFilename);
}
delete [] code;
fclose (f);
}
catch (Iex::BaseExc & e)
{
delete [] code;
if (f)
fclose (f);
throw e;
}
}
namespace
{
//
// This is the built-in fragment shader. It was generated by
// running:
//
// cgc -profile fp30 -o exrdisplay.fp30 exrdisplay.cg
//
// and then trimming the comments out and formatting it as a C string.
//
const char *
theFragShader =
"!!FP1.0\n" \
"DECLARE defog;\n" \
"DECLARE exposure;\n" \
"DECLARE gamma;\n" \
"DECLARE zerovec;\n" \
"DECLARE grayTarget;\n" \
"DECLARE kneeLow;\n" \
"DECLARE kneeF;\n" \
"TEX H0.xyz, f[TEX0].xyxx, TEX0, RECT;\n" \
"ADDR R0.xyz, H0.xyzx, -defog.xyzx;\n" \
"MAXH H0.xyz, zerovec.xyzx, R0.xyzx;\n" \
"MULR R0.xyz, H0.xyzx, exposure.x;\n" \
"ADDH H0.xyz, R0.xyzx, -kneeLow.x;\n" \
"MOVH H0.w, {1, 1, 1}.x;\n" \
"MADH H0.xyz, H0.xyzx, kneeF.x, H0.w;\n" \
"LG2H H0.w, H0.x;\n" \
"MOVH H1.x, H0.w;\n" \
"LG2H H0.w, H0.y;\n" \
"MOVH H1.y, H0.w;\n" \
"LG2H H0.x, H0.z;\n" \
"MOVH H1.z, H0.x;\n" \
"MULH H1.xyz, H1.xyzx, {0.69335938, 0.69335938, 0.69335938}.x;\n" \
"RCPH H0.x, kneeF.x;\n" \
"MADH H0.xyz, H1.xyzx, H0.x, kneeLow.x;\n" \
"MOVR H1.xyz, R0.xyzx;\n" \
"SGTH H2.xyz, R0.xyzx, kneeLow.x;\n" \
"MOVXC HC.xyz, H2.xyzx;\n" \
"MOVH H1.xyz(GT.xyzx), H0.xyzx;\n" \
"POWH H0.x, H1.x, gamma.x;\n" \
"POWH H0.w, H1.y, gamma.x;\n" \
"MOVH H0.y, H0.w;\n" \
"POWH H0.w, H1.z, gamma.x;\n" \
"MOVH H0.z, H0.w;\n" \
"MULH H0.xyz, H0.xyzx, grayTarget.x;\n" \
"MOVH o[COLH].xyz, H0.xyzx;\n" \
"END\n" \
"\0";
}
void
ImageViewFragShader::loadBuiltinFragShader ()
{
//
// Use the built-in fragment shader
//
if (!loadFragShader (theFragShader))
THROW (Iex::BaseExc, "There was a roblem downloading built-in " <<
"fragment shader.");
}
bool
ImageViewFragShader::loadFragShader (const char * code)
{
int len = strlen (code);
//
// load the fragment shader into the card
//
glGenProgramsNV (1, &_fprog);
glBindProgramNV (GL_FRAGMENT_PROGRAM_NV, _fprog);
glLoadProgramNV (GL_FRAGMENT_PROGRAM_NV, _fprog, len,
(const GLubyte *) code);
//
// check for errors
//
GLint errpos;
glGetIntegerv (GL_PROGRAM_ERROR_POSITION_NV, &errpos);
if (errpos != -1)
{
std::cerr << "Fragment shader error:" << std::endl << std::endl;
int begin = (errpos - 20) < 0 ? 0 : errpos - 20;
char errtxt[81];
strncpy (errtxt, code + begin, 80);
errtxt[80] = '\0';
std::cerr << errtxt << std::endl << std::endl;
}
return errpos == -1;
}
void
ImageViewFragShader::setCgNamedParameter (const char * name,
float x,
float y,
float z,
float w)
{
glProgramNamedParameter4fNV (_fprog, strlen (name), (GLubyte *) name,
x, y, z, w);
}
<commit_msg><commit_after>///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Industrial Light & Magic nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////
//
// Authors:
// Simon Green <[email protected]>
// Drew Hess <[email protected]>
//
//----------------------------------------------------------------------------
//
// class ImageViewFragShader
//
//----------------------------------------------------------------------------
#include <ImageViewFragShader.h>
#if defined PLATFORM_DARWIN_PPC
#include <OpenGL/glu.h>
#else
#include <GL/glu.h>
#endif
#define GLH_EXT_SINGLE_FILE
#include <glh/glh_extensions.h>
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <ImathFun.h>
#include <ImathMath.h>
#include <Iex.h>
ImageViewFragShader::ImageViewFragShader (int x, int y,
int width, int height,
const char label[],
const Imf::Rgba pixels[],
int dw, int dh,
int dx, int dy,
float exposure,
float defog,
float kneeLow,
float kneeHigh,
const std::string & filename)
:
ImageView (x, y,
width, height,
label,
pixels,
dw, dh,
dx, dy,
exposure,
defog,
kneeLow,
kneeHigh),
_useSoftware (false),
_fsFilename (filename)
{
}
bool
ImageViewFragShader::initGL ()
{
bool status = true;
try
{
if (!glh_init_extensions("GL_ARB_multitexture "
"GL_NV_vertex_program "
"GL_NV_fragment_program "))
{
THROW (Iex::BaseExc, "GL extensions required for fragment " <<
"shader support are not available: " << std::endl <<
" " << glh_get_unsupported_extensions ());
}
if (_fsFilename.empty ())
loadBuiltinFragShader ();
else
loadFragShaderFromFile ();
loadTexture ();
}
catch (const Iex::BaseExc & e)
{
std::cerr << e.what () << std::endl;
std::cerr << "Falling back to software rendering." << std::endl;
status = false;
}
return status;
}
void
ImageViewFragShader::loadTexture ()
{
//
// load OpenEXR image as OpenGL texture
//
GLenum target = GL_TEXTURE_RECTANGLE_NV;
glGenTextures (1, &_texture);
glBindTexture (target, _texture);
glTexParameteri (target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri (target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri (target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri (target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
glTexImage2D (target, 0, GL_FLOAT_RGBA16_NV, _dw, _dh, 0,
GL_RGBA, GL_HALF_FLOAT_NV, _rawPixels);
//
// Check for errors
//
GLenum error = glGetError ();
if (error != GL_NO_ERROR)
{
do
{
std::cerr << "Error loading texture: " <<
(char *) gluErrorString (error) << std::endl;
} while ((error = glGetError ()) != GL_NO_ERROR);
THROW (Iex::BaseExc, "Unable to load OpenEXR image as a texture.");
}
}
void
ImageViewFragShader::draw()
{
if (!valid())
{
if (!initGL ())
_useSoftware = true;
//
// Set up camera.
//
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
glViewport (0, 0, w (), h ());
glOrtho (0, w (), h (), 0, -1, 1);
glMatrixMode (GL_MODELVIEW);
glLoadIdentity ();
}
if (_useSoftware)
{
ImageView::updateScreenPixels ();
ImageView::draw ();
return;
}
glClearColor (0.3, 0.3, 0.3, 1.0);
glClear (GL_COLOR_BUFFER_BIT);
//
// Set fragment program parameters. See ImageView.cpp for details
// on what the parameters mean.
//
setCgNamedParameter ("exposure",
Imath::Math<float>::pow (2, _exposure + 2.47393));
setCgNamedParameter ("defog", _defog * _fogR, _defog * _fogG,
_defog * _fogB);
setCgNamedParameter ("gamma", 0.4545f);
setCgNamedParameter ("grayTarget", 84.66/255.0);
float kl = Imath::Math<float>::pow (2, _kneeLow);
setCgNamedParameter ("kneeLow", kl);
setCgNamedParameter ("kneeF", findKneeF (Imath::Math<float>::pow (2, _kneeHigh) - kl,
Imath::Math<float>::pow (2, 3.5) - kl));
//
// draw a textured quad
//
glEnable (GL_FRAGMENT_PROGRAM_NV);
glEnable (GL_TEXTURE_RECTANGLE_NV);
glBegin (GL_QUADS);
glTexCoord2f (0.0, 0.0); glVertex2f(0.0, 0.0);
glTexCoord2f (_dw, 0.0); glVertex2f(_dw, 0.0);
glTexCoord2f (_dw, _dh); glVertex2f(_dw, _dh);
glTexCoord2f (0.0, _dh); glVertex2f(0.0, _dh);
glEnd ();
glDisable (GL_TEXTURE_RECTANGLE_NV);
glDisable (GL_FRAGMENT_PROGRAM_NV);
}
void
ImageViewFragShader::loadFragShaderFromFile ()
{
FILE * f = 0;
char * code = 0;
try
{
f = fopen (_fsFilename.c_str (), "rb");
if (!f)
{
THROW_ERRNO ("Can't load fragment shader file " << _fsFilename <<
" (%T)");
}
fseek (f, 0, SEEK_END);
int len = ftell (f);
fseek (f, 0, SEEK_SET);
code = new char[len + 1];
int read = fread (code, 1, len, f);
if (read != len)
{
THROW (Iex::BaseExc, "Expected " << len << " bytes in fragment " <<
"shader file " << _fsFilename << ", only got " << read);
}
code[read] = '\0'; // null-terminate
if (!loadFragShader (code))
{
THROW (Iex::BaseExc, "Can't download fragment shader " <<
_fsFilename);
}
delete [] code;
fclose (f);
}
catch (Iex::BaseExc & e)
{
delete [] code;
if (f)
fclose (f);
throw e;
}
}
namespace
{
//
// This is the built-in fragment shader. It was generated by
// running:
//
// cgc -profile fp30 -o exrdisplay.fp30 exrdisplay.cg
//
// and then trimming the comments out and formatting it as a C string.
//
const char *
theFragShader =
"!!FP1.0\n" \
"DECLARE defog;\n" \
"DECLARE exposure;\n" \
"DECLARE gamma;\n" \
"DECLARE zerovec;\n" \
"DECLARE grayTarget;\n" \
"DECLARE kneeLow;\n" \
"DECLARE kneeF;\n" \
"TEX H0.xyz, f[TEX0].xyxx, TEX0, RECT;\n" \
"ADDR R0.xyz, H0.xyzx, -defog.xyzx;\n" \
"MAXH H0.xyz, zerovec.xyzx, R0.xyzx;\n" \
"MULR R0.xyz, H0.xyzx, exposure.x;\n" \
"ADDH H0.xyz, R0.xyzx, -kneeLow.x;\n" \
"MOVH H0.w, {1, 1, 1}.x;\n" \
"MADH H0.xyz, H0.xyzx, kneeF.x, H0.w;\n" \
"LG2H H0.w, H0.x;\n" \
"MOVH H1.x, H0.w;\n" \
"LG2H H0.w, H0.y;\n" \
"MOVH H1.y, H0.w;\n" \
"LG2H H0.x, H0.z;\n" \
"MOVH H1.z, H0.x;\n" \
"MULH H1.xyz, H1.xyzx, {0.69335938, 0.69335938, 0.69335938}.x;\n" \
"RCPH H0.x, kneeF.x;\n" \
"MADH H0.xyz, H1.xyzx, H0.x, kneeLow.x;\n" \
"MOVR H1.xyz, R0.xyzx;\n" \
"SGTH H2.xyz, R0.xyzx, kneeLow.x;\n" \
"MOVXC HC.xyz, H2.xyzx;\n" \
"MOVH H1.xyz(GT.xyzx), H0.xyzx;\n" \
"POWH H0.x, H1.x, gamma.x;\n" \
"POWH H0.w, H1.y, gamma.x;\n" \
"MOVH H0.y, H0.w;\n" \
"POWH H0.w, H1.z, gamma.x;\n" \
"MOVH H0.z, H0.w;\n" \
"MULH H0.xyz, H0.xyzx, grayTarget.x;\n" \
"MOVH o[COLH].xyz, H0.xyzx;\n" \
"END\n" \
"\0";
}
void
ImageViewFragShader::loadBuiltinFragShader ()
{
//
// Use the built-in fragment shader
//
if (!loadFragShader (theFragShader))
THROW (Iex::BaseExc, "There was a roblem downloading built-in " <<
"fragment shader.");
}
bool
ImageViewFragShader::loadFragShader (const char * code)
{
int len = strlen (code);
//
// load the fragment shader into the card
//
glGenProgramsNV (1, &_fprog);
glBindProgramNV (GL_FRAGMENT_PROGRAM_NV, _fprog);
glLoadProgramNV (GL_FRAGMENT_PROGRAM_NV, _fprog, len,
(const GLubyte *) code);
//
// check for errors
//
GLint errpos;
glGetIntegerv (GL_PROGRAM_ERROR_POSITION_NV, &errpos);
if (errpos != -1)
{
std::cerr << "Fragment shader error:" << std::endl << std::endl;
int begin = (errpos - 20) < 0 ? 0 : errpos - 20;
char errtxt[81];
strncpy (errtxt, code + begin, 80);
errtxt[80] = '\0';
std::cerr << errtxt << std::endl << std::endl;
}
return errpos == -1;
}
void
ImageViewFragShader::setCgNamedParameter (const char * name,
float x,
float y,
float z,
float w)
{
glProgramNamedParameter4fNV (_fprog, strlen (name), (GLubyte *) name,
x, y, z, w);
}
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-2014, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/**************************************************************************
* AliXtAnalysis:
* This class constructs inclusive and isolated (based on charged tracks)
* invariant spectra. Isolated case uses a different efficiency where the
* contamination from cases where non-isolated particle appears as an
* isolated one due to finite detector efficiency is taken into account.
*
* contact: Sami Räsänen
* University of Jyväskylä, Finland
* [email protected]
**************************************************************************/
// general + root classes
#include <TList.h>
#include <TChain.h>
#include <TObjArray.h>
// AliRoot classes
#include <AliAnalysisManager.h>
#include <AliInputEventHandler.h>
#include <AliAnalysisUtils.h>
#include <AliAODTrack.h>
#include <AliAODEvent.h>
// Jyväskylä classes
#include "AliJCard.h"
#include "AliJXtHistos.h"
//#include "AliIsolatedEfficiency.h"
// This analysis
#include "AliXtAnalysis.h"
ClassImp(AliXtAnalysis)
//________________________________________________________________________
AliXtAnalysis::AliXtAnalysis()
: AliAnalysisTaskSE(), fOutputList(0x0)
{
// Constructor
fhEvents = NULL;
fAnaUtils = NULL;
fHistDir = NULL;
fHistos = NULL;
fhEvents = NULL;
//fEfficiency = NULL;
fCard = NULL;
fChargedList = NULL;
fIsolatedChargedList = NULL;
fCentBin = -1;
fZBin = -1;
fZVert = 999999.;
fevt = 0;
fDebugMode = 0;
}
//________________________________________________________________________
AliXtAnalysis::AliXtAnalysis(const char *name, const char * cardname)
: AliAnalysisTaskSE(name),
fOutputList(0x0),
fAnaUtils(0x0),
fHistDir(0x0),
fHistos(0x0),
fhEvents(0x0),
//fEfficiency(0x0),
fChargedList(0x0),
fIsolatedChargedList(0x0),
fCentBin(-1),
fZBin(-1),
fZVert(999999.),
fevt(0),
fDebugMode(0)
{
// All parameters of the analysis
fCard = new AliJCard(cardname);
fCard->PrintOut();
fAnaUtils = new AliAnalysisUtils();
fAnaUtils->SetUseOutOfBunchPileUp( kTRUE );
fAnaUtils->SetUseSPDCutInMultBins( kTRUE);
// Define input and output slots here
// Input slot #0 works with a TChain
DefineInput(0, TChain::Class());
// Output slot #0 writes into a TH1 container
DefineOutput(1, TList::Class());
// JHistos into TDirectory
DefineOutput(2, TDirectory::Class());
}
//________________________________________________________________________
AliXtAnalysis::AliXtAnalysis(const AliXtAnalysis& a):
AliAnalysisTaskSE(a.GetName()),
fOutputList(a.fOutputList),
fAnaUtils(a.fAnaUtils),
fCard(a.fCard),
fHistDir(a.fHistDir),
fHistos(a.fHistos),
fhEvents(a.fhEvents),
//fEfficiency(a.fEfficiency),
fChargedList(a.fChargedList),
fIsolatedChargedList(a.fIsolatedChargedList),
fCentBin(-1),
fZBin(-1),
fZVert(999999.),
fevt(0),
fDebugMode(0)
{
//copy constructor
fhEvents = (TH1D*) a.fhEvents->Clone(a.fhEvents->GetName());
}
//________________________________________________________________________
AliXtAnalysis& AliXtAnalysis::operator = (const AliXtAnalysis& ap){
// assignment operator
this->~AliXtAnalysis();
new(this) AliXtAnalysis(ap);
return *this;
}
//________________________________________________________________________
AliXtAnalysis::~AliXtAnalysis() {
// destructor
delete fOutputList;
delete [] fAnaUtils;
delete [] fhEvents;
delete fHistos;
//delete fEfficiency;
delete fCard;
delete fChargedList;
delete fIsolatedChargedList;
}
//________________________________________________________________________
void AliXtAnalysis::UserCreateOutputObjects(){
// Create histograms
// Called once
cout<<"\n=============== CARD =============="<<endl;
fCard->PrintOut();
cout<<"===================================\n"<<endl;
fhEvents = new TH1D("hEvents","events passing cuts", 11, -0.5, 10.5 );
fhEvents->SetXTitle( "0 - all, 1 - pileup, 2 - kMB selected, 3 - has vertex, 4 - good vertex, 5 - MB + good vertex, 6 - MB + good vertex + centrality" );
fhEvents->Sumw2();
fOutputList = new TList();
fOutputList->SetOwner(kTRUE);
//for any MC track filled with MC pt
fOutputList->Add(fhEvents);
fChargedList = new TObjArray;
fChargedList->SetOwner(kTRUE);
fIsolatedChargedList = new TObjArray;
PostData(1, fOutputList);
bool orignalTH1AdddirectoryStatus=TH1::AddDirectoryStatus();
TH1::AddDirectory(kTRUE);
if( !orignalTH1AdddirectoryStatus ) cout<<"DEBUG : TH1::AddDirectory is turned on"<<endl;
TFile * file2 = OpenFile(2);
file2-> SetCompressionLevel(9);
file2->cd();
fHistDir=gDirectory;
fHistos = new AliJXtHistos(fCard);
fHistos->CreateXtHistos();
PostData(2, fHistDir);
TH1::AddDirectory( orignalTH1AdddirectoryStatus );
cout<<"DEBUG : TH1::AddDirectory get orignal Value = "<<( orignalTH1AdddirectoryStatus?"True":"False" )<<endl;
//fEfficiency = new AliJEfficiency();
fevt = 0;
}
//________________________________________________________________________
void AliXtAnalysis::UserExec(Option_t *) {
// Main loop - called for each event
fevt++;
if(fevt % 10000 == 0) cout << "Number of event scanned = "<< fevt << endl;
Int_t filterBit = AliAODTrack::kTrkGlobal; //fCard->Get("TrackFilterBit");
AliVEvent *event = InputEvent();
if(!event) return;
// check if the event was triggered or not and vertex
if( !IsGoodEvent( event ) ) return; // fZBin is set there
fhEvents->Fill( 5 );
if(fDebugMode > 0) cout << "zvtx = " << fZVert << endl;
AliAODEvent* aodEvent = dynamic_cast<AliAODEvent*>(event);
if(!aodEvent) return;
// centrality - in case of pPb and PbPb, dictated by DataType in the card
double fcent;
if( fCard->Get("DataType") > 0.5 ){
AliCentrality *cent = event->GetCentrality();
if( ! cent ) return;
fcent = cent->GetCentralityPercentile("V0M");
fCentBin = fCard->GetBin(kCentrType, fcent);;
//cout <<"Centrality = "<< fcent <<"\t"<< fCentBin << endl;
}else{
fcent = 0.0;
fCentBin = 0;
}
if(fCentBin<0) return;
fhEvents->Fill( 6 );
Int_t nt = aodEvent->GetNumberOfTracks();
fHistos->FillCentralityHistos(fcent, fCentBin);
// clear them up for every event
fChargedList->Clear();
fIsolatedChargedList->Clear();
// Is there a better way than hard code this into card???
double sqrts = fCard->Get("Sqrts");
// Isolation method: 0 = relative, 1 = absolute
double isolMethod = fCard->Get("IsolationMethod");
// Minimum isolation pT that is considered
double minIsolationPt = fCard->Get("MinimumIsolatedPt");
// Dummy numbers; either of these is updated based on selected method (other is void)
double isolationFraction = 99999.;
double isolationThreshold = 99999.;
if( isolMethod > 0.5 ){
isolationThreshold = fCard->Get("IsolationThreshold"); // this is fixed threshold
}else{
isolationFraction = fCard->Get("IsolationFraction"); // fraction in pT, threshold updated later in a loop
}
// Isolation radius
double isolR = fCard->Get("IsolationRadius");
// Get good tracks to the list
for(Int_t it = 0; it < nt; it++) {
AliAODTrack *track = aodEvent->GetTrack(it);
if( !track ) continue;
if( !track->TestFilterBit(filterBit) ) continue;
double eta = track->Eta();
if( !fCard->IsInEtaRange( eta ) ) continue; // Do not use fiducial cut here
AliAODTrack *acceptedTrack = new AliAODTrack( *track );
double pT = acceptedTrack->Pt();
double xT = 2.*pT/sqrts;
double phi = acceptedTrack->Phi();
// TODO:
double effCorr = 1.0;
// Fill histos
fHistos->FillInclusiveHistograms(pT, xT, eta, phi, effCorr, fCentBin);
// Add an accepted track into list of inclusive charged particles
fChargedList->Add( acceptedTrack );
}
// Check isolation of the found good tracks
Int_t nAcc = fChargedList->GetEntriesFast();
// Get eta range for fiducial cut
double etaRange = fCard->Get("EtaRange");
for( Int_t it = 0; it < nAcc; it++ ){
AliAODTrack *track = (AliAODTrack*)fChargedList->At(it);
// Fiducial eta cut for isolated particles
double eta = track->Eta();
if( abs(eta) > etaRange - isolR ) continue;
// To check the isolation with cone, use TLorentzVector -routines
TLorentzVector lvTrack = TLorentzVector( track->Px(), track->Py(), track->Pz(), track->P() );
// Set isolation threshold, if relative isolation
double pT = lvTrack.Pt();
if( pT < minIsolationPt ) continue;
if( isolMethod < 0.5 ) isolationThreshold = pT * isolationFraction; // here: relative isolation
// Isolation check
double sum = 0.0;
for( Int_t ia = 0; ia < nAcc; ia++ ){
if( ia == it ) continue; // Do not count the particle itself
AliAODTrack *assocTrack = (AliAODTrack*)fChargedList->At(ia);
TLorentzVector lvAssoc = TLorentzVector( assocTrack->Px(), assocTrack->Py(), assocTrack->Pz(), assocTrack->P() );
if( lvTrack.DeltaR( lvAssoc ) < isolR ) sum += lvAssoc.Pt();
}
// Cone activity
fHistos->FillInclusiveConeActivities(pT,sum); // efficiency correction?
// If the particle was isolated, fill histograms and the list
if( sum < isolationThreshold ){
double xT = 2.*pT/sqrts;
if( fDebugMode > 0 ){
cout << "DEBUG: isolated particle found " << endl;
cout << "fCentBin = " << fCentBin << ", pT = " << pT << ", xT = " << xT << " and eta = " << eta << endl;
}
fHistos->FillIsolatedConeActivities(pT, sum); // efficiency correction?
// TODO:
double effCorr = 1.0;
// Fill histos
fHistos->FillIsolatedHistograms(pT, xT, eta, track->Phi(), effCorr, fCentBin);
// Add tracks to the isolated list
AliAODTrack *acceptedIsolatedTrack = new AliAODTrack( *track );
fIsolatedChargedList->Add( acceptedIsolatedTrack );
}
}
// For further analysis, there is now lists of all charged and isolated charged available, will be usefull.
return; // END
}
//________________________________________________________________________
void AliXtAnalysis::Terminate(Option_t *)
{
OpenFile(2);
fHistDir->Write();
cout<<"Successfully finished"<<endl;
}
//________________________________________________________________________
bool AliXtAnalysis::IsGoodEvent(AliVEvent *event) {
// This function checks that the event has the requested trigger
// and that the z-vertex is in given range
fhEvents->Fill( 0 );
if(fAnaUtils->IsPileUpEvent(event)) {
return kFALSE;
} else {
Bool_t triggeredEventMB = kFALSE; //init
fhEvents->Fill( 1 );
Bool_t triggerkMB = ((AliInputEventHandler*)(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()))->IsEventSelected() & ( AliVEvent::kMB );
if( triggerkMB ){
triggeredEventMB = kTRUE; //event triggered as minimum bias
fhEvents->Fill( 2 );
}
//--------------------------------------------------------------
// check reconstructed vertex
int ncontributors = 0;
Bool_t goodRecVertex = kFALSE;
const AliVVertex *vtx = event->GetPrimaryVertex();
if(vtx){
fhEvents->Fill( 3 );
fZVert = vtx->GetZ();
fHistos->FillRawVertexHisto(fZVert);
ncontributors = vtx->GetNContributors();
if(ncontributors > 0){
if(fCard->VertInZRange(fZVert)) {
goodRecVertex = kTRUE;
fhEvents->Fill( 4 );
fHistos->FillAcceptedVertexHisto(fZVert, fCentBin);
fZBin = fCard->GetBin(kZVertType, fZVert);
}
}
}
return triggerkMB && goodRecVertex;
}
//---------------------------------
}
<commit_msg>Modified Terminate() method (Sami)<commit_after>/**************************************************************************
* Copyright(c) 1998-2014, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/**************************************************************************
* AliXtAnalysis:
* This class constructs inclusive and isolated (based on charged tracks)
* invariant spectra. Isolated case uses a different efficiency where the
* contamination from cases where non-isolated particle appears as an
* isolated one due to finite detector efficiency is taken into account.
*
* contact: Sami Räsänen
* University of Jyväskylä, Finland
* [email protected]
**************************************************************************/
// general + root classes
#include <TList.h>
#include <TChain.h>
#include <TObjArray.h>
// AliRoot classes
#include <AliAnalysisManager.h>
#include <AliInputEventHandler.h>
#include <AliAnalysisUtils.h>
#include <AliAODTrack.h>
#include <AliAODEvent.h>
// Jyväskylä classes
#include "AliJCard.h"
#include "AliJXtHistos.h"
//#include "AliIsolatedEfficiency.h"
// This analysis
#include "AliXtAnalysis.h"
ClassImp(AliXtAnalysis)
//________________________________________________________________________
AliXtAnalysis::AliXtAnalysis()
: AliAnalysisTaskSE(), fOutputList(0x0)
{
// Constructor
fhEvents = NULL;
fAnaUtils = NULL;
fHistDir = NULL;
fHistos = NULL;
fhEvents = NULL;
//fEfficiency = NULL;
fCard = NULL;
fChargedList = NULL;
fIsolatedChargedList = NULL;
fCentBin = -1;
fZBin = -1;
fZVert = 999999.;
fevt = 0;
fDebugMode = 0;
}
//________________________________________________________________________
AliXtAnalysis::AliXtAnalysis(const char *name, const char * cardname)
: AliAnalysisTaskSE(name),
fOutputList(0x0),
fAnaUtils(0x0),
fHistDir(0x0),
fHistos(0x0),
fhEvents(0x0),
//fEfficiency(0x0),
fChargedList(0x0),
fIsolatedChargedList(0x0),
fCentBin(-1),
fZBin(-1),
fZVert(999999.),
fevt(0),
fDebugMode(0)
{
// All parameters of the analysis
fCard = new AliJCard(cardname);
fCard->PrintOut();
fAnaUtils = new AliAnalysisUtils();
fAnaUtils->SetUseOutOfBunchPileUp( kTRUE );
fAnaUtils->SetUseSPDCutInMultBins( kTRUE);
// Define input and output slots here
// Input slot #0 works with a TChain
DefineInput(0, TChain::Class());
// Output slot #0 writes into a TH1 container
DefineOutput(1, TList::Class());
// JHistos into TDirectory
DefineOutput(2, TDirectory::Class());
}
//________________________________________________________________________
AliXtAnalysis::AliXtAnalysis(const AliXtAnalysis& a):
AliAnalysisTaskSE(a.GetName()),
fOutputList(a.fOutputList),
fAnaUtils(a.fAnaUtils),
fCard(a.fCard),
fHistDir(a.fHistDir),
fHistos(a.fHistos),
fhEvents(a.fhEvents),
//fEfficiency(a.fEfficiency),
fChargedList(a.fChargedList),
fIsolatedChargedList(a.fIsolatedChargedList),
fCentBin(-1),
fZBin(-1),
fZVert(999999.),
fevt(0),
fDebugMode(0)
{
//copy constructor
fhEvents = (TH1D*) a.fhEvents->Clone(a.fhEvents->GetName());
}
//________________________________________________________________________
AliXtAnalysis& AliXtAnalysis::operator = (const AliXtAnalysis& ap){
// assignment operator
this->~AliXtAnalysis();
new(this) AliXtAnalysis(ap);
return *this;
}
//________________________________________________________________________
AliXtAnalysis::~AliXtAnalysis() {
// destructor
delete fOutputList;
delete [] fAnaUtils;
delete [] fhEvents;
delete fHistos;
//delete fEfficiency;
delete fCard;
delete fChargedList;
delete fIsolatedChargedList;
}
//________________________________________________________________________
void AliXtAnalysis::UserCreateOutputObjects(){
// Create histograms
// Called once
cout<<"\n=============== CARD =============="<<endl;
fCard->PrintOut();
cout<<"===================================\n"<<endl;
fhEvents = new TH1D("hEvents","events passing cuts", 11, -0.5, 10.5 );
fhEvents->SetXTitle( "0 - all, 1 - pileup, 2 - kMB selected, 3 - has vertex, 4 - good vertex, 5 - MB + good vertex, 6 - MB + good vertex + centrality" );
fhEvents->Sumw2();
fOutputList = new TList();
fOutputList->SetOwner(kTRUE);
//for any MC track filled with MC pt
fOutputList->Add(fhEvents);
fChargedList = new TObjArray;
fChargedList->SetOwner(kTRUE);
fIsolatedChargedList = new TObjArray;
PostData(1, fOutputList);
bool orignalTH1AdddirectoryStatus=TH1::AddDirectoryStatus();
TH1::AddDirectory(kTRUE);
if( !orignalTH1AdddirectoryStatus ) cout<<"DEBUG : TH1::AddDirectory is turned on"<<endl;
TFile * file2 = OpenFile(2);
fHistDir=gDirectory;
fHistos = new AliJXtHistos(fCard);
fHistos->CreateXtHistos();
PostData(2, fHistDir);
TH1::AddDirectory( orignalTH1AdddirectoryStatus );
cout<<"DEBUG : TH1::AddDirectory get orignal Value = "<<( orignalTH1AdddirectoryStatus?"True":"False" )<<endl;
//fEfficiency = new AliJEfficiency();
fevt = 0;
}
//________________________________________________________________________
void AliXtAnalysis::UserExec(Option_t *) {
// Main loop - called for each event
fevt++;
if(fevt % 10000 == 0) cout << "Number of event scanned = "<< fevt << endl;
Int_t filterBit = AliAODTrack::kTrkGlobal; //fCard->Get("TrackFilterBit");
AliVEvent *event = InputEvent();
if(!event) return;
// check if the event was triggered or not and vertex
if( !IsGoodEvent( event ) ) return; // fZBin is set there
fhEvents->Fill( 5 );
if(fDebugMode > 0) cout << "zvtx = " << fZVert << endl;
AliAODEvent* aodEvent = dynamic_cast<AliAODEvent*>(event);
if(!aodEvent) return;
// centrality - in case of pPb and PbPb, dictated by DataType in the card
double fcent;
if( fCard->Get("DataType") > 0.5 ){
AliCentrality *cent = event->GetCentrality();
if( ! cent ) return;
fcent = cent->GetCentralityPercentile("V0M");
fCentBin = fCard->GetBin(kCentrType, fcent);;
//cout <<"Centrality = "<< fcent <<"\t"<< fCentBin << endl;
}else{
fcent = 0.0;
fCentBin = 0;
}
if(fCentBin<0) return;
fhEvents->Fill( 6 );
Int_t nt = aodEvent->GetNumberOfTracks();
fHistos->FillCentralityHistos(fcent, fCentBin);
// clear them up for every event
fChargedList->Clear();
fIsolatedChargedList->Clear();
// Is there a better way than hard code this into card???
double sqrts = fCard->Get("Sqrts");
// Isolation method: 0 = relative, 1 = absolute
double isolMethod = fCard->Get("IsolationMethod");
// Minimum isolation pT that is considered
double minIsolationPt = fCard->Get("MinimumIsolatedPt");
// Dummy numbers; either of these is updated based on selected method (other is void)
double isolationFraction = 99999.;
double isolationThreshold = 99999.;
if( isolMethod > 0.5 ){
isolationThreshold = fCard->Get("IsolationThreshold"); // this is fixed threshold
}else{
isolationFraction = fCard->Get("IsolationFraction"); // fraction in pT, threshold updated later in a loop
}
// Isolation radius
double isolR = fCard->Get("IsolationRadius");
// Get good tracks to the list
for(Int_t it = 0; it < nt; it++) {
AliAODTrack *track = aodEvent->GetTrack(it);
if( !track ) continue;
if( !track->TestFilterBit(filterBit) ) continue;
double eta = track->Eta();
if( !fCard->IsInEtaRange( eta ) ) continue; // Do not use fiducial cut here
AliAODTrack *acceptedTrack = new AliAODTrack( *track );
double pT = acceptedTrack->Pt();
double xT = 2.*pT/sqrts;
double phi = acceptedTrack->Phi();
// TODO:
double effCorr = 1.0;
// Fill histos
fHistos->FillInclusiveHistograms(pT, xT, eta, phi, effCorr, fCentBin);
// Add an accepted track into list of inclusive charged particles
fChargedList->Add( acceptedTrack );
}
// Check isolation of the found good tracks
Int_t nAcc = fChargedList->GetEntriesFast();
// Get eta range for fiducial cut
double etaRange = fCard->Get("EtaRange");
for( Int_t it = 0; it < nAcc; it++ ){
AliAODTrack *track = (AliAODTrack*)fChargedList->At(it);
// Fiducial eta cut for isolated particles
double eta = track->Eta();
if( abs(eta) > etaRange - isolR ) continue;
// To check the isolation with cone, use TLorentzVector -routines
TLorentzVector lvTrack = TLorentzVector( track->Px(), track->Py(), track->Pz(), track->P() );
// Set isolation threshold, if relative isolation
double pT = lvTrack.Pt();
if( pT < minIsolationPt ) continue;
if( isolMethod < 0.5 ) isolationThreshold = pT * isolationFraction; // here: relative isolation
// Isolation check
double sum = 0.0;
for( Int_t ia = 0; ia < nAcc; ia++ ){
if( ia == it ) continue; // Do not count the particle itself
AliAODTrack *assocTrack = (AliAODTrack*)fChargedList->At(ia);
TLorentzVector lvAssoc = TLorentzVector( assocTrack->Px(), assocTrack->Py(), assocTrack->Pz(), assocTrack->P() );
if( lvTrack.DeltaR( lvAssoc ) < isolR ) sum += lvAssoc.Pt();
}
// Cone activity
fHistos->FillInclusiveConeActivities(pT,sum); // efficiency correction?
// If the particle was isolated, fill histograms and the list
if( sum < isolationThreshold ){
double xT = 2.*pT/sqrts;
if( fDebugMode > 0 ){
cout << "DEBUG: isolated particle found " << endl;
cout << "fCentBin = " << fCentBin << ", pT = " << pT << ", xT = " << xT << " and eta = " << eta << endl;
}
fHistos->FillIsolatedConeActivities(pT, sum); // efficiency correction?
// TODO:
double effCorr = 1.0;
// Fill histos
fHistos->FillIsolatedHistograms(pT, xT, eta, track->Phi(), effCorr, fCentBin);
// Add tracks to the isolated list
AliAODTrack *acceptedIsolatedTrack = new AliAODTrack( *track );
fIsolatedChargedList->Add( acceptedIsolatedTrack );
}
}
// For further analysis, there is now lists of all charged and isolated charged available, will be usefull.
return; // END
}
//________________________________________________________________________
void AliXtAnalysis::Terminate(Option_t *)
{
cout<<"Successfully finished"<<endl;
}
//________________________________________________________________________
bool AliXtAnalysis::IsGoodEvent(AliVEvent *event) {
// This function checks that the event has the requested trigger
// and that the z-vertex is in given range
fhEvents->Fill( 0 );
if(fAnaUtils->IsPileUpEvent(event)) {
return kFALSE;
} else {
Bool_t triggeredEventMB = kFALSE; //init
fhEvents->Fill( 1 );
Bool_t triggerkMB = ((AliInputEventHandler*)(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()))->IsEventSelected() & ( AliVEvent::kMB );
if( triggerkMB ){
triggeredEventMB = kTRUE; //event triggered as minimum bias
fhEvents->Fill( 2 );
}
//--------------------------------------------------------------
// check reconstructed vertex
int ncontributors = 0;
Bool_t goodRecVertex = kFALSE;
const AliVVertex *vtx = event->GetPrimaryVertex();
if(vtx){
fhEvents->Fill( 3 );
fZVert = vtx->GetZ();
fHistos->FillRawVertexHisto(fZVert);
ncontributors = vtx->GetNContributors();
if(ncontributors > 0){
if(fCard->VertInZRange(fZVert)) {
goodRecVertex = kTRUE;
fhEvents->Fill( 4 );
fHistos->FillAcceptedVertexHisto(fZVert, fCentBin);
fZBin = fCard->GetBin(kZVertType, fZVert);
}
}
}
return triggerkMB && goodRecVertex;
}
//---------------------------------
}
<|endoftext|> |
<commit_before>/* The libMesh Finite Element Library. */
/* Copyright (C) 2003 Benjamin S. Kirk */
/* This library is free software; you can redistribute it and/or */
/* modify it under the terms of the GNU Lesser General Public */
/* License as published by the Free Software Foundation; either */
/* version 2.1 of the License, or (at your option) any later version. */
/* This library is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU */
/* Lesser General Public License for more details. */
/* You should have received a copy of the GNU Lesser General Public */
/* License along with this library; if not, write to the Free Software */
/* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
// <h1>Adaptivity Example 1 - Solving 1D PDE Using Adaptive Mesh Refinement</h1>
//
// This example demonstrates how to solve a simple 1D problem
// using adaptive mesh refinement. The PDE that is solved is:
// -epsilon*u''(x) + u(x) = 1, on the domain [0,1] with boundary conditions
// u(0) = u(1) = 0 and where epsilon << 1.
//
// The approach used to solve 1D problems in libMesh is virtually identical to
// solving 2D or 3D problems, so in this sense this example represents a good
// starting point for new users. Note that many concepts are used in this
// example which are explained more fully in subsequent examples.
// Libmesh includes
#include "libmesh/mesh.h"
#include "libmesh/mesh_generation.h"
#include "libmesh/edge_edge3.h"
#include "libmesh/gnuplot_io.h"
#include "libmesh/equation_systems.h"
#include "libmesh/linear_implicit_system.h"
#include "libmesh/fe.h"
#include "libmesh/getpot.h"
#include "libmesh/quadrature_gauss.h"
#include "libmesh/sparse_matrix.h"
#include "libmesh/dof_map.h"
#include "libmesh/numeric_vector.h"
#include "libmesh/dense_matrix.h"
#include "libmesh/dense_vector.h"
#include "libmesh/error_vector.h"
#include "libmesh/kelly_error_estimator.h"
#include "libmesh/mesh_refinement.h"
// Bring in everything from the libMesh namespace
using namespace libMesh;
void assemble_1D(EquationSystems& es, const std::string& system_name);
int main(int argc, char** argv)
{
// Initialize the library. This is necessary because the library
// may depend on a number of other libraries (i.e. MPI and PETSc)
// that require initialization before use. When the LibMeshInit
// object goes out of scope, other libraries and resources are
// finalized.
LibMeshInit init (argc, argv);
// Skip adaptive examples on a non-adaptive libMesh build
#ifndef LIBMESH_ENABLE_AMR
libmesh_example_assert(false, "--enable-amr");
#else
// Create a new mesh
Mesh mesh;
GetPot command_line (argc, argv);
int n = 4;
if ( command_line.search(1, "-n") )
n = command_line.next(n);
// Build a 1D mesh with 4 elements from x=0 to x=1, using
// EDGE3 (i.e. quadratic) 1D elements. They are called EDGE3 elements
// because a quadratic element contains 3 nodes.
MeshTools::Generation::build_line(mesh,n,0.,1.,EDGE3);
// Define the equation systems object and the system we are going
// to solve. See Introduction Example 2 for more details.
EquationSystems equation_systems(mesh);
LinearImplicitSystem& system = equation_systems.add_system
<LinearImplicitSystem>("1D");
// Add a variable "u" to the system, using second-order approximation
system.add_variable("u",SECOND);
// Give the system a pointer to the matrix assembly function. This
// will be called when needed by the library.
system.attach_assemble_function(assemble_1D);
// Define the mesh refinement object that takes care of adaptively
// refining the mesh.
MeshRefinement mesh_refinement(mesh);
// These parameters determine the proportion of elements that will
// be refined and coarsened. Any element within 30% of the maximum
// error on any element will be refined, and any element within 30%
// of the minimum error on any element might be coarsened
mesh_refinement.refine_fraction() = 0.7;
mesh_refinement.coarsen_fraction() = 0.3;
// We won't refine any element more than 5 times in total
mesh_refinement.max_h_level() = 5;
// Initialize the data structures for the equation system.
equation_systems.init();
// Refinement parameters
const unsigned int max_r_steps = 5; // Refine the mesh 5 times
// Define the refinement loop
for(unsigned int r_step=0; r_step<=max_r_steps; r_step++)
{
// Solve the equation system
equation_systems.get_system("1D").solve();
// We need to ensure that the mesh is not refined on the last iteration
// of this loop, since we do not want to refine the mesh unless we are
// going to solve the equation system for that refined mesh.
if(r_step != max_r_steps)
{
// Error estimation objects, see Adaptivity Example 2 for details
ErrorVector error;
KellyErrorEstimator error_estimator;
// Compute the error for each active element
error_estimator.estimate_error(system, error);
// Flag elements to be refined and coarsened
mesh_refinement.flag_elements_by_error_fraction (error);
// Perform refinement and coarsening
mesh_refinement.refine_and_coarsen_elements();
// Reinitialize the equation_systems object for the newly refined
// mesh. One of the steps in this is project the solution onto the
// new mesh
equation_systems.reinit();
}
}
// Construct gnuplot plotting object, pass in mesh, title of plot
// and boolean to indicate use of grid in plot. The grid is used to
// show the edges of each element in the mesh.
GnuPlotIO plot(mesh,"Adaptivity Example 1", GnuPlotIO::GRID_ON);
// Write out script to be called from within gnuplot:
// Load gnuplot, then type "call 'gnuplot_script'" from gnuplot prompt
plot.write_equation_systems("gnuplot_script",equation_systems);
#endif // #ifndef LIBMESH_ENABLE_AMR
// All done. libMesh objects are destroyed here. Because the
// LibMeshInit object was created first, its destruction occurs
// last, and it's destructor finalizes any external libraries and
// checks for leaked memory.
return 0;
}
// Define the matrix assembly function for the 1D PDE we are solving
void assemble_1D(EquationSystems& es, const std::string& system_name)
{
#ifdef LIBMESH_ENABLE_AMR
// It is a good idea to check we are solving the correct system
libmesh_assert_equal_to (system_name, "1D");
// Get a reference to the mesh object
const MeshBase& mesh = es.get_mesh();
// The dimension we are using, i.e. dim==1
const unsigned int dim = mesh.mesh_dimension();
// Get a reference to the system we are solving
LinearImplicitSystem& system = es.get_system<LinearImplicitSystem>("1D");
// Get a reference to the DofMap object for this system. The DofMap object
// handles the index translation from node and element numbers to degree of
// freedom numbers. DofMap's are discussed in more detail in future examples.
const DofMap& dof_map = system.get_dof_map();
// Get a constant reference to the Finite Element type for the first
// (and only) variable in the system.
FEType fe_type = dof_map.variable_type(0);
// Build a finite element object of the specified type. The build
// function dynamically allocates memory so we use an AutoPtr in this case.
// An AutoPtr is a pointer that cleans up after itself. See examples 3 and 4
// for more details on AutoPtr.
AutoPtr<FEBase> fe(FEBase::build(dim, fe_type));
// Tell the finite element object to use fifth order Gaussian quadrature
QGauss qrule(dim,FIFTH);
fe->attach_quadrature_rule(&qrule);
// Here we define some references to cell-specific data that will be used to
// assemble the linear system.
// The element Jacobian * quadrature weight at each integration point.
const std::vector<Real>& JxW = fe->get_JxW();
// The element shape functions evaluated at the quadrature points.
const std::vector<std::vector<Real> >& phi = fe->get_phi();
// The element shape function gradients evaluated at the quadrature points.
const std::vector<std::vector<RealGradient> >& dphi = fe->get_dphi();
// Declare a dense matrix and dense vector to hold the element matrix
// and right-hand-side contribution
DenseMatrix<Number> Ke;
DenseVector<Number> Fe;
// This vector will hold the degree of freedom indices for the element.
// These define where in the global system the element degrees of freedom
// get mapped.
std::vector<dof_id_type> dof_indices;
// We now loop over all the active elements in the mesh in order to calculate
// the matrix and right-hand-side contribution from each element. Use a
// const_element_iterator to loop over the elements. We make
// el_end const as it is used only for the stopping condition of the loop.
MeshBase::const_element_iterator el = mesh.active_local_elements_begin();
const MeshBase::const_element_iterator el_end = mesh.active_local_elements_end();
// Note that ++el is preferred to el++ when using loops with iterators
for( ; el != el_end; ++el)
{
// It is convenient to store a pointer to the current element
const Elem* elem = *el;
// Get the degree of freedom indices for the current element.
// These define where in the global matrix and right-hand-side this
// element will contribute to.
dof_map.dof_indices(elem, dof_indices);
// Compute the element-specific data for the current element. This
// involves computing the location of the quadrature points (q_point)
// and the shape functions (phi, dphi) for the current element.
fe->reinit(elem);
// Store the number of local degrees of freedom contained in this element
const int n_dofs = dof_indices.size();
// We resize and zero out Ke and Fe (resize() also clears the matrix and
// vector). In this example, all elements in the mesh are EDGE3's, so
// Ke will always be 3x3, and Fe will always be 3x1. If the mesh contained
// different element types, then the size of Ke and Fe would change.
Ke.resize(n_dofs, n_dofs);
Fe.resize(n_dofs);
// Now loop over quadrature points to handle numerical integration
for(unsigned int qp=0; qp<qrule.n_points(); qp++)
{
// Now build the element matrix and right-hand-side using loops to
// integrate the test functions (i) against the trial functions (j).
for(unsigned int i=0; i<phi.size(); i++)
{
Fe(i) += JxW[qp]*phi[i][qp];
for(unsigned int j=0; j<phi.size(); j++)
{
Ke(i,j) += JxW[qp]*(1.e-3*dphi[i][qp]*dphi[j][qp] +
phi[i][qp]*phi[j][qp]);
}
}
}
// At this point we have completed the matrix and RHS summation. The
// final step is to apply boundary conditions, which in this case are
// simple Dirichlet conditions with u(0) = u(1) = 0.
// Define the penalty parameter used to enforce the BC's
double penalty = 1.e10;
// Loop over the sides of this element. For a 1D element, the "sides"
// are defined as the nodes on each edge of the element, i.e. 1D elements
// have 2 sides.
for(unsigned int s=0; s<elem->n_sides(); s++)
{
// If this element has a NULL neighbor, then it is on the edge of the
// mesh and we need to enforce a boundary condition using the penalty
// method.
if(elem->neighbor(s) == NULL)
{
Ke(s,s) += penalty;
Fe(s) += 0*penalty;
}
}
// This is a function call that is necessary when using adaptive
// mesh refinement. See Adaptivity Example 2 for more details.
dof_map.constrain_element_matrix_and_vector (Ke, Fe, dof_indices);
// Add Ke and Fe to the global matrix and right-hand-side.
system.matrix->add_matrix(Ke, dof_indices);
system.rhs->add_vector(Fe, dof_indices);
}
#endif // #ifdef LIBMESH_ENABLE_AMR
}
<commit_msg>Let's print a bit more from this quiet example<commit_after>/* The libMesh Finite Element Library. */
/* Copyright (C) 2003 Benjamin S. Kirk */
/* This library is free software; you can redistribute it and/or */
/* modify it under the terms of the GNU Lesser General Public */
/* License as published by the Free Software Foundation; either */
/* version 2.1 of the License, or (at your option) any later version. */
/* This library is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU */
/* Lesser General Public License for more details. */
/* You should have received a copy of the GNU Lesser General Public */
/* License along with this library; if not, write to the Free Software */
/* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
// <h1>Adaptivity Example 1 - Solving 1D PDE Using Adaptive Mesh Refinement</h1>
//
// This example demonstrates how to solve a simple 1D problem
// using adaptive mesh refinement. The PDE that is solved is:
// -epsilon*u''(x) + u(x) = 1, on the domain [0,1] with boundary conditions
// u(0) = u(1) = 0 and where epsilon << 1.
//
// The approach used to solve 1D problems in libMesh is virtually identical to
// solving 2D or 3D problems, so in this sense this example represents a good
// starting point for new users. Note that many concepts are used in this
// example which are explained more fully in subsequent examples.
// Libmesh includes
#include "libmesh/mesh.h"
#include "libmesh/mesh_generation.h"
#include "libmesh/edge_edge3.h"
#include "libmesh/gnuplot_io.h"
#include "libmesh/equation_systems.h"
#include "libmesh/linear_implicit_system.h"
#include "libmesh/fe.h"
#include "libmesh/getpot.h"
#include "libmesh/quadrature_gauss.h"
#include "libmesh/sparse_matrix.h"
#include "libmesh/dof_map.h"
#include "libmesh/numeric_vector.h"
#include "libmesh/dense_matrix.h"
#include "libmesh/dense_vector.h"
#include "libmesh/error_vector.h"
#include "libmesh/kelly_error_estimator.h"
#include "libmesh/mesh_refinement.h"
// Bring in everything from the libMesh namespace
using namespace libMesh;
void assemble_1D(EquationSystems& es, const std::string& system_name);
int main(int argc, char** argv)
{
// Initialize the library. This is necessary because the library
// may depend on a number of other libraries (i.e. MPI and PETSc)
// that require initialization before use. When the LibMeshInit
// object goes out of scope, other libraries and resources are
// finalized.
LibMeshInit init (argc, argv);
// Skip adaptive examples on a non-adaptive libMesh build
#ifndef LIBMESH_ENABLE_AMR
libmesh_example_assert(false, "--enable-amr");
#else
// Create a new mesh
Mesh mesh;
GetPot command_line (argc, argv);
int n = 4;
if ( command_line.search(1, "-n") )
n = command_line.next(n);
// Build a 1D mesh with 4 elements from x=0 to x=1, using
// EDGE3 (i.e. quadratic) 1D elements. They are called EDGE3 elements
// because a quadratic element contains 3 nodes.
MeshTools::Generation::build_line(mesh,n,0.,1.,EDGE3);
// Define the equation systems object and the system we are going
// to solve. See Introduction Example 2 for more details.
EquationSystems equation_systems(mesh);
LinearImplicitSystem& system = equation_systems.add_system
<LinearImplicitSystem>("1D");
// Add a variable "u" to the system, using second-order approximation
system.add_variable("u",SECOND);
// Give the system a pointer to the matrix assembly function. This
// will be called when needed by the library.
system.attach_assemble_function(assemble_1D);
// Define the mesh refinement object that takes care of adaptively
// refining the mesh.
MeshRefinement mesh_refinement(mesh);
// These parameters determine the proportion of elements that will
// be refined and coarsened. Any element within 30% of the maximum
// error on any element will be refined, and any element within 30%
// of the minimum error on any element might be coarsened
mesh_refinement.refine_fraction() = 0.7;
mesh_refinement.coarsen_fraction() = 0.3;
// We won't refine any element more than 5 times in total
mesh_refinement.max_h_level() = 5;
// Initialize the data structures for the equation system.
equation_systems.init();
// Refinement parameters
const unsigned int max_r_steps = 5; // Refine the mesh 5 times
// Define the refinement loop
for(unsigned int r_step=0; r_step<=max_r_steps; r_step++)
{
// Solve the equation system
equation_systems.get_system("1D").solve();
// We need to ensure that the mesh is not refined on the last iteration
// of this loop, since we do not want to refine the mesh unless we are
// going to solve the equation system for that refined mesh.
if(r_step != max_r_steps)
{
// Error estimation objects, see Adaptivity Example 2 for details
ErrorVector error;
KellyErrorEstimator error_estimator;
// Compute the error for each active element
error_estimator.estimate_error(system, error);
// Output error estimate magnitude
libMesh::out << "Error estimate\nl2 norm = " << error.l2_norm() <<
"\nmaximum = " << error.maximum() << std::endl;
// Flag elements to be refined and coarsened
mesh_refinement.flag_elements_by_error_fraction (error);
// Perform refinement and coarsening
mesh_refinement.refine_and_coarsen_elements();
// Reinitialize the equation_systems object for the newly refined
// mesh. One of the steps in this is project the solution onto the
// new mesh
equation_systems.reinit();
}
}
// Construct gnuplot plotting object, pass in mesh, title of plot
// and boolean to indicate use of grid in plot. The grid is used to
// show the edges of each element in the mesh.
GnuPlotIO plot(mesh,"Adaptivity Example 1", GnuPlotIO::GRID_ON);
// Write out script to be called from within gnuplot:
// Load gnuplot, then type "call 'gnuplot_script'" from gnuplot prompt
plot.write_equation_systems("gnuplot_script",equation_systems);
#endif // #ifndef LIBMESH_ENABLE_AMR
// All done. libMesh objects are destroyed here. Because the
// LibMeshInit object was created first, its destruction occurs
// last, and it's destructor finalizes any external libraries and
// checks for leaked memory.
return 0;
}
// Define the matrix assembly function for the 1D PDE we are solving
void assemble_1D(EquationSystems& es, const std::string& system_name)
{
#ifdef LIBMESH_ENABLE_AMR
// It is a good idea to check we are solving the correct system
libmesh_assert_equal_to (system_name, "1D");
// Get a reference to the mesh object
const MeshBase& mesh = es.get_mesh();
// The dimension we are using, i.e. dim==1
const unsigned int dim = mesh.mesh_dimension();
// Get a reference to the system we are solving
LinearImplicitSystem& system = es.get_system<LinearImplicitSystem>("1D");
// Get a reference to the DofMap object for this system. The DofMap object
// handles the index translation from node and element numbers to degree of
// freedom numbers. DofMap's are discussed in more detail in future examples.
const DofMap& dof_map = system.get_dof_map();
// Get a constant reference to the Finite Element type for the first
// (and only) variable in the system.
FEType fe_type = dof_map.variable_type(0);
// Build a finite element object of the specified type. The build
// function dynamically allocates memory so we use an AutoPtr in this case.
// An AutoPtr is a pointer that cleans up after itself. See examples 3 and 4
// for more details on AutoPtr.
AutoPtr<FEBase> fe(FEBase::build(dim, fe_type));
// Tell the finite element object to use fifth order Gaussian quadrature
QGauss qrule(dim,FIFTH);
fe->attach_quadrature_rule(&qrule);
// Here we define some references to cell-specific data that will be used to
// assemble the linear system.
// The element Jacobian * quadrature weight at each integration point.
const std::vector<Real>& JxW = fe->get_JxW();
// The element shape functions evaluated at the quadrature points.
const std::vector<std::vector<Real> >& phi = fe->get_phi();
// The element shape function gradients evaluated at the quadrature points.
const std::vector<std::vector<RealGradient> >& dphi = fe->get_dphi();
// Declare a dense matrix and dense vector to hold the element matrix
// and right-hand-side contribution
DenseMatrix<Number> Ke;
DenseVector<Number> Fe;
// This vector will hold the degree of freedom indices for the element.
// These define where in the global system the element degrees of freedom
// get mapped.
std::vector<dof_id_type> dof_indices;
// We now loop over all the active elements in the mesh in order to calculate
// the matrix and right-hand-side contribution from each element. Use a
// const_element_iterator to loop over the elements. We make
// el_end const as it is used only for the stopping condition of the loop.
MeshBase::const_element_iterator el = mesh.active_local_elements_begin();
const MeshBase::const_element_iterator el_end = mesh.active_local_elements_end();
// Note that ++el is preferred to el++ when using loops with iterators
for( ; el != el_end; ++el)
{
// It is convenient to store a pointer to the current element
const Elem* elem = *el;
// Get the degree of freedom indices for the current element.
// These define where in the global matrix and right-hand-side this
// element will contribute to.
dof_map.dof_indices(elem, dof_indices);
// Compute the element-specific data for the current element. This
// involves computing the location of the quadrature points (q_point)
// and the shape functions (phi, dphi) for the current element.
fe->reinit(elem);
// Store the number of local degrees of freedom contained in this element
const int n_dofs = dof_indices.size();
// We resize and zero out Ke and Fe (resize() also clears the matrix and
// vector). In this example, all elements in the mesh are EDGE3's, so
// Ke will always be 3x3, and Fe will always be 3x1. If the mesh contained
// different element types, then the size of Ke and Fe would change.
Ke.resize(n_dofs, n_dofs);
Fe.resize(n_dofs);
// Now loop over quadrature points to handle numerical integration
for(unsigned int qp=0; qp<qrule.n_points(); qp++)
{
// Now build the element matrix and right-hand-side using loops to
// integrate the test functions (i) against the trial functions (j).
for(unsigned int i=0; i<phi.size(); i++)
{
Fe(i) += JxW[qp]*phi[i][qp];
for(unsigned int j=0; j<phi.size(); j++)
{
Ke(i,j) += JxW[qp]*(1.e-3*dphi[i][qp]*dphi[j][qp] +
phi[i][qp]*phi[j][qp]);
}
}
}
// At this point we have completed the matrix and RHS summation. The
// final step is to apply boundary conditions, which in this case are
// simple Dirichlet conditions with u(0) = u(1) = 0.
// Define the penalty parameter used to enforce the BC's
double penalty = 1.e10;
// Loop over the sides of this element. For a 1D element, the "sides"
// are defined as the nodes on each edge of the element, i.e. 1D elements
// have 2 sides.
for(unsigned int s=0; s<elem->n_sides(); s++)
{
// If this element has a NULL neighbor, then it is on the edge of the
// mesh and we need to enforce a boundary condition using the penalty
// method.
if(elem->neighbor(s) == NULL)
{
Ke(s,s) += penalty;
Fe(s) += 0*penalty;
}
}
// This is a function call that is necessary when using adaptive
// mesh refinement. See Adaptivity Example 2 for more details.
dof_map.constrain_element_matrix_and_vector (Ke, Fe, dof_indices);
// Add Ke and Fe to the global matrix and right-hand-side.
system.matrix->add_matrix(Ke, dof_indices);
system.rhs->add_vector(Fe, dof_indices);
}
#endif // #ifdef LIBMESH_ENABLE_AMR
}
<|endoftext|> |
<commit_before>// Copyright 2019 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @file DomainParticipantFactory.cpp
*
*/
#include <fastdds/dds/domain/DomainParticipantFactory.hpp>
#include <fastdds/rtps/RTPSDomain.h>
#include <fastdds/rtps/participant/RTPSParticipant.h>
#include <fastdds/dds/domain/DomainParticipant.hpp>
#include <fastdds/domain/DomainParticipantImpl.hpp>
#include <fastdds/dds/log/Log.hpp>
#include <fastrtps/xmlparser/XMLProfileManager.h>
#include <fastrtps/types/DynamicTypeBuilderFactory.h>
#include <fastrtps/types/DynamicDataFactory.h>
#include <fastrtps/types/TypeObjectFactory.h>
using namespace eprosima::fastrtps::xmlparser;
using eprosima::fastrtps::ParticipantAttributes;
using eprosima::fastdds::dds::Log;
using eprosima::fastrtps::rtps::RTPSDomain;
using eprosima::fastrtps::rtps::RTPSParticipant;
namespace eprosima {
namespace fastdds {
namespace dds {
static void set_qos_from_attributes(
DomainParticipantQos& qos,
const eprosima::fastrtps::rtps::RTPSParticipantAttributes& attr)
{
qos.user_data().setValue(attr.userData);
qos.allocation() = attr.allocation;
qos.properties() = attr.properties;
qos.wire_protocol().prefix = attr.prefix;
qos.wire_protocol().participant_id = attr.participantID;
qos.wire_protocol().builtin = attr.builtin;
qos.wire_protocol().port = attr.port;
qos.wire_protocol().throughput_controller = attr.throughputController;
qos.wire_protocol().default_unicast_locator_list = attr.defaultUnicastLocatorList;
qos.wire_protocol().default_multicast_locator_list = attr.defaultMulticastLocatorList;
qos.transport().user_transports = attr.userTransports;
qos.transport().use_builtin_transports = attr.useBuiltinTransports;
qos.transport().send_socket_buffer_size = attr.sendSocketBufferSize;
qos.transport().listen_socket_buffer_size = attr.listenSocketBufferSize;
qos.name() = attr.getName();
}
static void set_attributes_from_qos(
fastrtps::rtps::RTPSParticipantAttributes& attr,
const DomainParticipantQos& qos)
{
attr.allocation = qos.allocation();
attr.properties = qos.properties();
attr.setName(qos.name());
attr.prefix = qos.wire_protocol().prefix;
attr.participantID = qos.wire_protocol().participant_id;
attr.builtin = qos.wire_protocol().builtin;
attr.port = qos.wire_protocol().port;
attr.throughputController = qos.wire_protocol().throughput_controller;
attr.defaultUnicastLocatorList = qos.wire_protocol().default_unicast_locator_list;
attr.defaultMulticastLocatorList = qos.wire_protocol().default_multicast_locator_list;
attr.userTransports = qos.transport().user_transports;
attr.useBuiltinTransports = qos.transport().use_builtin_transports;
attr.sendSocketBufferSize = qos.transport().send_socket_buffer_size;
attr.listenSocketBufferSize = qos.transport().listen_socket_buffer_size;
attr.userData = qos.user_data().data_vec();
}
class DomainParticipantFactoryReleaser
{
public:
~DomainParticipantFactoryReleaser()
{
DomainParticipantFactory::delete_instance();
}
};
static bool g_instance_initialized = false;
static std::mutex g_mtx;
static DomainParticipantFactoryReleaser s_releaser;
static DomainParticipantFactory* g_instance = nullptr;
DomainParticipantFactory::DomainParticipantFactory()
: default_xml_profiles_loaded(false)
, default_participant_qos_(PARTICIPANT_QOS_DEFAULT)
{
}
DomainParticipantFactory::~DomainParticipantFactory()
{
{
std::lock_guard<std::mutex> guard(mtx_participants_);
for (auto it : participants_)
{
for (auto pit : it.second)
{
pit->disable();
delete pit;
}
}
participants_.clear();
}
// Deletes DynamicTypes and TypeObject factories
fastrtps::types::DynamicTypeBuilderFactory::delete_instance();
fastrtps::types::DynamicDataFactory::delete_instance();
fastrtps::types::TypeObjectFactory::delete_instance();
std::this_thread::sleep_for(std::chrono::milliseconds(100));
eprosima::fastdds::dds::Log::KillThread();
}
DomainParticipantFactory* DomainParticipantFactory::get_instance()
{
if (!g_instance_initialized)
{
std::lock_guard<std::mutex> lock(g_mtx);
if (g_instance == nullptr)
{
g_instance = new DomainParticipantFactory();
g_instance_initialized = true;
}
}
return g_instance;
}
bool DomainParticipantFactory::delete_instance()
{
std::lock_guard<std::mutex> lock(g_mtx);
if (g_instance_initialized && g_instance != nullptr)
{
delete g_instance;
g_instance = nullptr;
g_instance_initialized = false;
return true;
}
return false;
}
ReturnCode_t DomainParticipantFactory::delete_participant(
DomainParticipant* part)
{
using PartVectorIt = std::vector<DomainParticipantImpl*>::iterator;
using VectorIt = std::map<DomainId_t, std::vector<DomainParticipantImpl*> >::iterator;
if (part != nullptr)
{
if (part->has_active_entities())
{
return ReturnCode_t::RETCODE_PRECONDITION_NOT_MET;
}
std::lock_guard<std::mutex> guard(mtx_participants_);
VectorIt vit = participants_.find(part->get_domain_id());
if (vit != participants_.end())
{
for (PartVectorIt pit = vit->second.begin(); pit != vit->second.end();)
{
if ((*pit)->get_participant() == part
|| (*pit)->get_participant()->guid() == part->guid())
{
(*pit)->disable();
delete (*pit);
PartVectorIt next_it = vit->second.erase(pit);
pit = next_it;
break;
}
else
{
++pit;
}
}
if (vit->second.empty())
{
participants_.erase(vit);
}
return ReturnCode_t::RETCODE_OK;
}
}
return ReturnCode_t::RETCODE_ERROR;
}
DomainParticipant* DomainParticipantFactory::create_participant(
DomainId_t did,
const DomainParticipantQos& qos,
DomainParticipantListener* listen,
const StatusMask& mask)
{
load_profiles();
const DomainParticipantQos& pqos = (&qos == &PARTICIPANT_QOS_DEFAULT) ? default_participant_qos_ : qos;
DomainParticipant* dom_part = new DomainParticipant(mask);
DomainParticipantImpl* dom_part_impl = new DomainParticipantImpl(dom_part, pqos, listen);
fastrtps::rtps::RTPSParticipantAttributes rtps_attr;
set_attributes_from_qos(rtps_attr, pqos);
RTPSParticipant* part = RTPSDomain::createParticipant(did, false, rtps_attr, &dom_part_impl->rtps_listener_);
if (part == nullptr)
{
logError(DOMAIN_PARTICIPANT_FACTORY, "Problem creating RTPSParticipant");
delete dom_part_impl;
return nullptr;
}
dom_part_impl->rtps_participant_ = part;
{
std::lock_guard<std::mutex> guard(mtx_participants_);
using VectorIt = std::map<DomainId_t, std::vector<DomainParticipantImpl*> >::iterator;
VectorIt vector_it = participants_.find(did);
if (vector_it == participants_.end())
{
// Insert the vector
std::vector<DomainParticipantImpl*> new_vector;
auto pair_it = participants_.insert(std::make_pair(did, std::move(new_vector)));
vector_it = pair_it.first;
}
vector_it->second.push_back(dom_part_impl);
}
if (factory_qos_.entity_factory().autoenable_created_entities)
{
dom_part->enable();
}
part->set_check_type_function(
[dom_part](const std::string& type_name) -> bool
{
return dom_part->find_type(type_name).get() != nullptr;
});
return dom_part;
}
DomainParticipant* DomainParticipantFactory::create_participant_with_profile(
DomainId_t did,
const std::string& profile_name,
DomainParticipantListener* listen,
const StatusMask& mask)
{
load_profiles();
// TODO (Miguel C): Change when we have full XML support for DDS QoS profiles
ParticipantAttributes attr;
if (XMLP_ret::XML_OK == XMLProfileManager::fillParticipantAttributes(profile_name, attr))
{
DomainParticipantQos qos = default_participant_qos_;
set_qos_from_attributes(qos, attr.rtps);
return create_participant(did, qos, listen, mask);
}
return nullptr;
}
DomainParticipant* DomainParticipantFactory::lookup_participant(
DomainId_t domain_id) const
{
std::lock_guard<std::mutex> guard(mtx_participants_);
auto it = participants_.find(domain_id);
if (it != participants_.end() && it->second.size() > 0)
{
return it->second.front()->get_participant();
}
return nullptr;
}
std::vector<DomainParticipant*> DomainParticipantFactory::lookup_participants(
DomainId_t domain_id) const
{
std::lock_guard<std::mutex> guard(mtx_participants_);
std::vector<DomainParticipant*> result;
auto it = participants_.find(domain_id);
if (it != participants_.end())
{
const std::vector<DomainParticipantImpl*>& v = it->second;
for (auto pit = v.begin(); pit != v.end(); ++pit)
{
result.push_back((*pit)->get_participant());
}
}
return result;
}
ReturnCode_t DomainParticipantFactory::get_default_participant_qos(
DomainParticipantQos& qos) const
{
qos = default_participant_qos_;
return ReturnCode_t::RETCODE_OK;
}
const DomainParticipantQos& DomainParticipantFactory::get_default_participant_qos() const
{
return default_participant_qos_;
}
ReturnCode_t DomainParticipantFactory::set_default_participant_qos(
const DomainParticipantQos& qos)
{
if (&qos == &PARTICIPANT_QOS_DEFAULT)
{
reset_default_participant_qos();
return ReturnCode_t::RETCODE_OK;
}
ReturnCode_t ret_val = DomainParticipantImpl::check_qos(qos);
if (!ret_val)
{
return ret_val;
}
DomainParticipantImpl::set_qos(default_participant_qos_, qos, true);
return ReturnCode_t::RETCODE_OK;
}
ReturnCode_t DomainParticipantFactory::load_profiles()
{
if (false == default_xml_profiles_loaded)
{
XMLProfileManager::loadDefaultXMLFile();
default_xml_profiles_loaded = true;
if (default_participant_qos_ == PARTICIPANT_QOS_DEFAULT)
{
reset_default_participant_qos();
}
}
return ReturnCode_t::RETCODE_OK;
}
ReturnCode_t DomainParticipantFactory::load_XML_profiles_file(
const std::string& xml_profile_file)
{
if (XMLP_ret::XML_ERROR == XMLProfileManager::loadXMLFile(xml_profile_file))
{
logError(DOMAIN, "Problem loading XML file '" << xml_profile_file << "'");
return ReturnCode_t::RETCODE_ERROR;
}
return ReturnCode_t::RETCODE_OK;
}
ReturnCode_t DomainParticipantFactory::get_qos(
DomainParticipantFactoryQos& qos) const
{
qos = factory_qos_;
return ReturnCode_t::RETCODE_OK;
}
ReturnCode_t DomainParticipantFactory::set_qos(
const DomainParticipantFactoryQos& qos)
{
ReturnCode_t ret_val = check_qos(qos);
if (!ret_val)
{
return ret_val;
}
if (!can_qos_be_updated(factory_qos_, qos))
{
return ReturnCode_t::RETCODE_IMMUTABLE_POLICY;
}
set_qos(factory_qos_, qos, false);
return ReturnCode_t::RETCODE_OK;
}
void DomainParticipantFactory::reset_default_participant_qos()
{
// TODO (Miguel C): Change when we have full XML support for DDS QoS profiles
DomainParticipantImpl::set_qos(default_participant_qos_, PARTICIPANT_QOS_DEFAULT, true);
if (true == default_xml_profiles_loaded)
{
eprosima::fastrtps::ParticipantAttributes attr;
XMLProfileManager::getDefaultParticipantAttributes(attr);
set_qos_from_attributes(default_participant_qos_, attr.rtps);
}
}
void DomainParticipantFactory::set_qos(
DomainParticipantFactoryQos& to,
const DomainParticipantFactoryQos& from,
bool first_time)
{
(void) first_time;
//As all the Qos can always be updated and none of them need to be sent
to = from;
}
ReturnCode_t DomainParticipantFactory::check_qos(
const DomainParticipantFactoryQos& qos)
{
(void) qos;
//There is no restriction by the moment with the contained Qos
return ReturnCode_t::RETCODE_OK;
}
bool DomainParticipantFactory::can_qos_be_updated(
const DomainParticipantFactoryQos& to,
const DomainParticipantFactoryQos& from)
{
(void) to;
(void) from;
//All the DomainParticipantFactoryQos can be updated
return true;
}
void DomainParticipantFactory::participant_has_been_deleted(
DomainParticipantImpl* part)
{
std::lock_guard<std::mutex> guard(mtx_participants_);
auto it = participants_.find(part->get_domain_id());
if (it != participants_.end())
{
for (auto pit = it->second.begin(); pit != it->second.end();)
{
if ((*pit) == part || (*pit)->guid() == part->guid())
{
it->second.erase(pit);
}
else
{
++pit;
}
}
if (it->second.empty())
{
participants_.erase(it);
}
}
}
} /* namespace dds */
} /* namespace fastdds */
} /* namespace eprosima */
<commit_msg>Fixed DomainParticipantFactory::participant_has_been_deleted (#1211)<commit_after>// Copyright 2019 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @file DomainParticipantFactory.cpp
*
*/
#include <fastdds/dds/domain/DomainParticipantFactory.hpp>
#include <fastdds/rtps/RTPSDomain.h>
#include <fastdds/rtps/participant/RTPSParticipant.h>
#include <fastdds/dds/domain/DomainParticipant.hpp>
#include <fastdds/domain/DomainParticipantImpl.hpp>
#include <fastdds/dds/log/Log.hpp>
#include <fastrtps/xmlparser/XMLProfileManager.h>
#include <fastrtps/types/DynamicTypeBuilderFactory.h>
#include <fastrtps/types/DynamicDataFactory.h>
#include <fastrtps/types/TypeObjectFactory.h>
using namespace eprosima::fastrtps::xmlparser;
using eprosima::fastrtps::ParticipantAttributes;
using eprosima::fastdds::dds::Log;
using eprosima::fastrtps::rtps::RTPSDomain;
using eprosima::fastrtps::rtps::RTPSParticipant;
namespace eprosima {
namespace fastdds {
namespace dds {
static void set_qos_from_attributes(
DomainParticipantQos& qos,
const eprosima::fastrtps::rtps::RTPSParticipantAttributes& attr)
{
qos.user_data().setValue(attr.userData);
qos.allocation() = attr.allocation;
qos.properties() = attr.properties;
qos.wire_protocol().prefix = attr.prefix;
qos.wire_protocol().participant_id = attr.participantID;
qos.wire_protocol().builtin = attr.builtin;
qos.wire_protocol().port = attr.port;
qos.wire_protocol().throughput_controller = attr.throughputController;
qos.wire_protocol().default_unicast_locator_list = attr.defaultUnicastLocatorList;
qos.wire_protocol().default_multicast_locator_list = attr.defaultMulticastLocatorList;
qos.transport().user_transports = attr.userTransports;
qos.transport().use_builtin_transports = attr.useBuiltinTransports;
qos.transport().send_socket_buffer_size = attr.sendSocketBufferSize;
qos.transport().listen_socket_buffer_size = attr.listenSocketBufferSize;
qos.name() = attr.getName();
}
static void set_attributes_from_qos(
fastrtps::rtps::RTPSParticipantAttributes& attr,
const DomainParticipantQos& qos)
{
attr.allocation = qos.allocation();
attr.properties = qos.properties();
attr.setName(qos.name());
attr.prefix = qos.wire_protocol().prefix;
attr.participantID = qos.wire_protocol().participant_id;
attr.builtin = qos.wire_protocol().builtin;
attr.port = qos.wire_protocol().port;
attr.throughputController = qos.wire_protocol().throughput_controller;
attr.defaultUnicastLocatorList = qos.wire_protocol().default_unicast_locator_list;
attr.defaultMulticastLocatorList = qos.wire_protocol().default_multicast_locator_list;
attr.userTransports = qos.transport().user_transports;
attr.useBuiltinTransports = qos.transport().use_builtin_transports;
attr.sendSocketBufferSize = qos.transport().send_socket_buffer_size;
attr.listenSocketBufferSize = qos.transport().listen_socket_buffer_size;
attr.userData = qos.user_data().data_vec();
}
class DomainParticipantFactoryReleaser
{
public:
~DomainParticipantFactoryReleaser()
{
DomainParticipantFactory::delete_instance();
}
};
static bool g_instance_initialized = false;
static std::mutex g_mtx;
static DomainParticipantFactoryReleaser s_releaser;
static DomainParticipantFactory* g_instance = nullptr;
DomainParticipantFactory::DomainParticipantFactory()
: default_xml_profiles_loaded(false)
, default_participant_qos_(PARTICIPANT_QOS_DEFAULT)
{
}
DomainParticipantFactory::~DomainParticipantFactory()
{
{
std::lock_guard<std::mutex> guard(mtx_participants_);
for (auto it : participants_)
{
for (auto pit : it.second)
{
pit->disable();
delete pit;
}
}
participants_.clear();
}
// Deletes DynamicTypes and TypeObject factories
fastrtps::types::DynamicTypeBuilderFactory::delete_instance();
fastrtps::types::DynamicDataFactory::delete_instance();
fastrtps::types::TypeObjectFactory::delete_instance();
std::this_thread::sleep_for(std::chrono::milliseconds(100));
eprosima::fastdds::dds::Log::KillThread();
}
DomainParticipantFactory* DomainParticipantFactory::get_instance()
{
if (!g_instance_initialized)
{
std::lock_guard<std::mutex> lock(g_mtx);
if (g_instance == nullptr)
{
g_instance = new DomainParticipantFactory();
g_instance_initialized = true;
}
}
return g_instance;
}
bool DomainParticipantFactory::delete_instance()
{
std::lock_guard<std::mutex> lock(g_mtx);
if (g_instance_initialized && g_instance != nullptr)
{
delete g_instance;
g_instance = nullptr;
g_instance_initialized = false;
return true;
}
return false;
}
ReturnCode_t DomainParticipantFactory::delete_participant(
DomainParticipant* part)
{
using PartVectorIt = std::vector<DomainParticipantImpl*>::iterator;
using VectorIt = std::map<DomainId_t, std::vector<DomainParticipantImpl*> >::iterator;
if (part != nullptr)
{
if (part->has_active_entities())
{
return ReturnCode_t::RETCODE_PRECONDITION_NOT_MET;
}
std::lock_guard<std::mutex> guard(mtx_participants_);
VectorIt vit = participants_.find(part->get_domain_id());
if (vit != participants_.end())
{
for (PartVectorIt pit = vit->second.begin(); pit != vit->second.end();)
{
if ((*pit)->get_participant() == part
|| (*pit)->get_participant()->guid() == part->guid())
{
(*pit)->disable();
delete (*pit);
PartVectorIt next_it = vit->second.erase(pit);
pit = next_it;
break;
}
else
{
++pit;
}
}
if (vit->second.empty())
{
participants_.erase(vit);
}
return ReturnCode_t::RETCODE_OK;
}
}
return ReturnCode_t::RETCODE_ERROR;
}
DomainParticipant* DomainParticipantFactory::create_participant(
DomainId_t did,
const DomainParticipantQos& qos,
DomainParticipantListener* listen,
const StatusMask& mask)
{
load_profiles();
const DomainParticipantQos& pqos = (&qos == &PARTICIPANT_QOS_DEFAULT) ? default_participant_qos_ : qos;
DomainParticipant* dom_part = new DomainParticipant(mask);
DomainParticipantImpl* dom_part_impl = new DomainParticipantImpl(dom_part, pqos, listen);
fastrtps::rtps::RTPSParticipantAttributes rtps_attr;
set_attributes_from_qos(rtps_attr, pqos);
RTPSParticipant* part = RTPSDomain::createParticipant(did, false, rtps_attr, &dom_part_impl->rtps_listener_);
if (part == nullptr)
{
logError(DOMAIN_PARTICIPANT_FACTORY, "Problem creating RTPSParticipant");
delete dom_part_impl;
return nullptr;
}
dom_part_impl->rtps_participant_ = part;
{
std::lock_guard<std::mutex> guard(mtx_participants_);
using VectorIt = std::map<DomainId_t, std::vector<DomainParticipantImpl*> >::iterator;
VectorIt vector_it = participants_.find(did);
if (vector_it == participants_.end())
{
// Insert the vector
std::vector<DomainParticipantImpl*> new_vector;
auto pair_it = participants_.insert(std::make_pair(did, std::move(new_vector)));
vector_it = pair_it.first;
}
vector_it->second.push_back(dom_part_impl);
}
if (factory_qos_.entity_factory().autoenable_created_entities)
{
dom_part->enable();
}
part->set_check_type_function(
[dom_part](const std::string& type_name) -> bool
{
return dom_part->find_type(type_name).get() != nullptr;
});
return dom_part;
}
DomainParticipant* DomainParticipantFactory::create_participant_with_profile(
DomainId_t did,
const std::string& profile_name,
DomainParticipantListener* listen,
const StatusMask& mask)
{
load_profiles();
// TODO (Miguel C): Change when we have full XML support for DDS QoS profiles
ParticipantAttributes attr;
if (XMLP_ret::XML_OK == XMLProfileManager::fillParticipantAttributes(profile_name, attr))
{
DomainParticipantQos qos = default_participant_qos_;
set_qos_from_attributes(qos, attr.rtps);
return create_participant(did, qos, listen, mask);
}
return nullptr;
}
DomainParticipant* DomainParticipantFactory::lookup_participant(
DomainId_t domain_id) const
{
std::lock_guard<std::mutex> guard(mtx_participants_);
auto it = participants_.find(domain_id);
if (it != participants_.end() && it->second.size() > 0)
{
return it->second.front()->get_participant();
}
return nullptr;
}
std::vector<DomainParticipant*> DomainParticipantFactory::lookup_participants(
DomainId_t domain_id) const
{
std::lock_guard<std::mutex> guard(mtx_participants_);
std::vector<DomainParticipant*> result;
auto it = participants_.find(domain_id);
if (it != participants_.end())
{
const std::vector<DomainParticipantImpl*>& v = it->second;
for (auto pit = v.begin(); pit != v.end(); ++pit)
{
result.push_back((*pit)->get_participant());
}
}
return result;
}
ReturnCode_t DomainParticipantFactory::get_default_participant_qos(
DomainParticipantQos& qos) const
{
qos = default_participant_qos_;
return ReturnCode_t::RETCODE_OK;
}
const DomainParticipantQos& DomainParticipantFactory::get_default_participant_qos() const
{
return default_participant_qos_;
}
ReturnCode_t DomainParticipantFactory::set_default_participant_qos(
const DomainParticipantQos& qos)
{
if (&qos == &PARTICIPANT_QOS_DEFAULT)
{
reset_default_participant_qos();
return ReturnCode_t::RETCODE_OK;
}
ReturnCode_t ret_val = DomainParticipantImpl::check_qos(qos);
if (!ret_val)
{
return ret_val;
}
DomainParticipantImpl::set_qos(default_participant_qos_, qos, true);
return ReturnCode_t::RETCODE_OK;
}
ReturnCode_t DomainParticipantFactory::load_profiles()
{
if (false == default_xml_profiles_loaded)
{
XMLProfileManager::loadDefaultXMLFile();
default_xml_profiles_loaded = true;
if (default_participant_qos_ == PARTICIPANT_QOS_DEFAULT)
{
reset_default_participant_qos();
}
}
return ReturnCode_t::RETCODE_OK;
}
ReturnCode_t DomainParticipantFactory::load_XML_profiles_file(
const std::string& xml_profile_file)
{
if (XMLP_ret::XML_ERROR == XMLProfileManager::loadXMLFile(xml_profile_file))
{
logError(DOMAIN, "Problem loading XML file '" << xml_profile_file << "'");
return ReturnCode_t::RETCODE_ERROR;
}
return ReturnCode_t::RETCODE_OK;
}
ReturnCode_t DomainParticipantFactory::get_qos(
DomainParticipantFactoryQos& qos) const
{
qos = factory_qos_;
return ReturnCode_t::RETCODE_OK;
}
ReturnCode_t DomainParticipantFactory::set_qos(
const DomainParticipantFactoryQos& qos)
{
ReturnCode_t ret_val = check_qos(qos);
if (!ret_val)
{
return ret_val;
}
if (!can_qos_be_updated(factory_qos_, qos))
{
return ReturnCode_t::RETCODE_IMMUTABLE_POLICY;
}
set_qos(factory_qos_, qos, false);
return ReturnCode_t::RETCODE_OK;
}
void DomainParticipantFactory::reset_default_participant_qos()
{
// TODO (Miguel C): Change when we have full XML support for DDS QoS profiles
DomainParticipantImpl::set_qos(default_participant_qos_, PARTICIPANT_QOS_DEFAULT, true);
if (true == default_xml_profiles_loaded)
{
eprosima::fastrtps::ParticipantAttributes attr;
XMLProfileManager::getDefaultParticipantAttributes(attr);
set_qos_from_attributes(default_participant_qos_, attr.rtps);
}
}
void DomainParticipantFactory::set_qos(
DomainParticipantFactoryQos& to,
const DomainParticipantFactoryQos& from,
bool first_time)
{
(void) first_time;
//As all the Qos can always be updated and none of them need to be sent
to = from;
}
ReturnCode_t DomainParticipantFactory::check_qos(
const DomainParticipantFactoryQos& qos)
{
(void) qos;
//There is no restriction by the moment with the contained Qos
return ReturnCode_t::RETCODE_OK;
}
bool DomainParticipantFactory::can_qos_be_updated(
const DomainParticipantFactoryQos& to,
const DomainParticipantFactoryQos& from)
{
(void) to;
(void) from;
//All the DomainParticipantFactoryQos can be updated
return true;
}
void DomainParticipantFactory::participant_has_been_deleted(
DomainParticipantImpl* part)
{
std::lock_guard<std::mutex> guard(mtx_participants_);
auto it = participants_.find(part->get_domain_id());
if (it != participants_.end())
{
for (auto pit = it->second.begin(); pit != it->second.end();)
{
if ((*pit) == part || (*pit)->guid() == part->guid())
{
pit = it->second.erase(pit);
}
else
{
++pit;
}
}
if (it->second.empty())
{
participants_.erase(it);
}
}
}
} /* namespace dds */
} /* namespace fastdds */
} /* namespace eprosima */
<|endoftext|> |
<commit_before>#include "hornet/java.hh"
#include "hornet/zip.hh"
#include <cassert>
#include <climits>
namespace hornet {
jar::jar(std::string filename)
: _zip(zip_open(filename.c_str()))
{
}
jar::~jar()
{
zip_close(_zip);
}
std::shared_ptr<klass> jar::load_class(std::string class_name)
{
zip_entry *entry = zip_entry_find_class(_zip, class_name.c_str());
if (!entry) {
return nullptr;
}
char *data = (char*)zip_entry_data(_zip, entry);
auto file = class_file{data, static_cast<size_t>(entry->uncomp_size)};
auto klass = file.parse();
free(data);
return klass;
}
};
<commit_msg>java: Fix sigsegv in jar::load_class<commit_after>#include "hornet/java.hh"
#include "hornet/zip.hh"
#include <cassert>
#include <climits>
namespace hornet {
jar::jar(std::string filename)
: _zip(zip_open(filename.c_str()))
{
}
jar::~jar()
{
zip_close(_zip);
}
std::shared_ptr<klass> jar::load_class(std::string class_name)
{
if (!_zip) {
return nullptr;
}
zip_entry *entry = zip_entry_find_class(_zip, class_name.c_str());
if (!entry) {
return nullptr;
}
char *data = (char*)zip_entry_data(_zip, entry);
auto file = class_file{data, static_cast<size_t>(entry->uncomp_size)};
auto klass = file.parse();
free(data);
return klass;
}
};
<|endoftext|> |
<commit_before>#include "test_common.hh"
#if HAVE_DUNE_FEM
#include <memory>
#include <dune/fem/misc/mpimanager.hh>
#include <dune/fem/space/fvspace/fvspace.hh>
#include <dune/fem/space/dgspace.hh>
#include <dune/fem/gridpart/adaptiveleafgridpart.hh>
#include <dune/fem/function/adaptivefunction.hh>
#include <dune/fem/operator/projection/l2projection.hh>
#include <dune/fem/io/file/datawriter.hh>
#include <dune/stuff/aliases.hh>
#include <dune/stuff/function.hh>
#include <dune/stuff/common/tuple.hh>
#include <dune/stuff/fem/functions/timefunction.hh>
#include <dune/stuff/fem/customprojection.hh>
#include <dune/stuff/grid/provider/cube.hh>
#include <dune/stuff/function/expression.hh>
#include <dune/stuff/function/parametric/separable/coefficient.hh>
template <int dimDomain, int rangeDim>
struct CustomFunction : public DSFu::Interface< double, dimDomain, double, rangeDim > {
typedef DSFu::Interface< double, dimDomain, double, rangeDim > Base;
using Base::evaluate;
template <class IntersectionType>
void evaluate( const typename Base::DomainType& /*arg*/, typename Base::RangeType& ret, const IntersectionType& face ) const
{
ret = typename Base::RangeType(face.geometry().volume());
}
};
template <int dimDomain, int rangeDim>
struct CustomFunctionT : public DSFu::Interface< double, dimDomain, double, rangeDim > {
typedef DSFu::Interface< double, dimDomain, double, rangeDim > Base;
using Base::evaluate;
void evaluate( const double time, const typename Base::DomainType& /*arg*/,typename Base::RangeType& ret ) const
{
ret = typename Base::RangeType(time);
}
void evaluate( const typename Base::DomainType& /*arg*/, typename Base::RangeType& ret ) const
{
ret = typename Base::RangeType(0.0f);
}
};
template <class GridDim, class RangeDim>
struct ProjectionFixture {
public:
static const int range_dim = RangeDim::value;
static const int pol_order = 1;
typedef DSG::Provider::GenericCube<Dune::SGrid< GridDim::value, GridDim::value >> GridProviderType;
typedef typename GridProviderType::GridType GridType;
typedef DSFu::Expression< double, GridType::dimension, double, range_dim > FunctionType;
typedef typename FunctionType::FunctionSpaceType FunctionSpaceType;
typedef Dune::AdaptiveLeafGridPart< GridType > GridPartType;
typedef Dune::DiscontinuousGalerkinSpace< FunctionSpaceType,
GridPartType,
pol_order>
DiscreteFunctionSpaceType;
typedef Dune::AdaptiveDiscreteFunction< DiscreteFunctionSpaceType > DiscreteFunctionType;
GridProviderType gridProvider_;
GridPartType gridPart_;
DiscreteFunctionSpaceType disc_space_;
DiscreteFunctionType disc_function;
ProjectionFixture()
: gridProvider_(GridProviderType(0.0f, 1.0f, 32u))
, gridPart_(*(gridProvider_.grid()))
, disc_space_(gridPart_)
, disc_function("disc_function", disc_space_)
{}
};
struct RunBetterL2Projection {
template <class GridDim, class RangeDim>
static void run()
{
typedef ProjectionFixture<GridDim, RangeDim> TestType;
TestType test;
CustomFunctionT<GridDim::value, RangeDim::value> f;
DSFe::BetterL2Projection::project(f, test.disc_function);
const double time = 0.0f;
DSFe::BetterL2Projection::project(time, f, test.disc_function);
DSFe::ConstTimeProvider tp(0.0f);
DSFe::BetterL2Projection::project(tp, f, test.disc_function);
}
};
struct RunCustomProjection {
template <class GridDim, class RangeDim>
static void run()
{
typedef ProjectionFixture<GridDim, RangeDim> TestType;
TestType test;
CustomFunction<GridDim::value, RangeDim::value> f;
DSFe::CustomProjection::project(f, test.disc_function);
}
};
template <class TestFunctor>
struct ProjectionTest : public ::testing::Test {
typedef boost::mpl::vector< Int<1>, Int<2>, Int<3>> GridDims;
typedef GridDims RangeDims;
typedef typename DSC::TupleProduct::Combine< GridDims, RangeDims, TestFunctor
>::template Generate<> base_generator_type;
void run() {
base_generator_type::Run();
}
};
typedef ::testing::Types<RunBetterL2Projection, RunCustomProjection> TestParameter;
TYPED_TEST_CASE(ProjectionTest, TestParameter);
TYPED_TEST(ProjectionTest, All) {
this->run();
}
#endif
int main(int argc, char** argv)
{
test_init(argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>[test.fem_project] update<commit_after>#include "test_common.hh"
#if HAVE_DUNE_FEM
#include <memory>
#include <dune/fem/misc/mpimanager.hh>
#include <dune/fem/space/fvspace/fvspace.hh>
#include <dune/fem/space/dgspace.hh>
#include <dune/fem/gridpart/adaptiveleafgridpart.hh>
#include <dune/fem/function/adaptivefunction.hh>
#include <dune/fem/operator/projection/l2projection.hh>
#include <dune/fem/io/file/datawriter.hh>
#include <dune/stuff/aliases.hh>
#include <dune/stuff/function.hh>
#include <dune/stuff/common/tuple.hh>
#include <dune/stuff/fem/functions/timefunction.hh>
#include <dune/stuff/fem/customprojection.hh>
#include <dune/stuff/grid/provider/cube.hh>
#include <dune/stuff/function/expression.hh>
#include <dune/stuff/function/affineparametric/coefficient.hh>
template <int dimDomain, int rangeDim>
struct CustomFunction : public DSFu::Interface< double, dimDomain, double, rangeDim > {
typedef DSFu::Interface< double, dimDomain, double, rangeDim > Base;
using Base::evaluate;
template <class IntersectionType>
void evaluate( const typename Base::DomainType& /*arg*/, typename Base::RangeType& ret, const IntersectionType& face ) const
{
ret = typename Base::RangeType(face.geometry().volume());
}
};
template <int dimDomain, int rangeDim>
struct CustomFunctionT : public DSFu::Interface< double, dimDomain, double, rangeDim > {
typedef DSFu::Interface< double, dimDomain, double, rangeDim > Base;
using Base::evaluate;
void evaluate( const double time, const typename Base::DomainType& /*arg*/,typename Base::RangeType& ret ) const
{
ret = typename Base::RangeType(time);
}
void evaluate( const typename Base::DomainType& /*arg*/, typename Base::RangeType& ret ) const
{
ret = typename Base::RangeType(0.0f);
}
};
template <class GridDim, class RangeDim>
struct ProjectionFixture {
public:
static const int range_dim = RangeDim::value;
static const int pol_order = 1;
typedef DSG::Provider::GenericCube<Dune::SGrid< GridDim::value, GridDim::value >> GridProviderType;
typedef typename GridProviderType::GridType GridType;
typedef DSFu::Expression< double, GridType::dimension, double, range_dim > FunctionType;
typedef typename FunctionType::FunctionSpaceType FunctionSpaceType;
typedef Dune::AdaptiveLeafGridPart< GridType > GridPartType;
typedef Dune::DiscontinuousGalerkinSpace< FunctionSpaceType,
GridPartType,
pol_order>
DiscreteFunctionSpaceType;
typedef Dune::AdaptiveDiscreteFunction< DiscreteFunctionSpaceType > DiscreteFunctionType;
GridProviderType gridProvider_;
GridPartType gridPart_;
DiscreteFunctionSpaceType disc_space_;
DiscreteFunctionType disc_function;
ProjectionFixture()
: gridProvider_(GridProviderType(0.0f, 1.0f, 32u))
, gridPart_(*(gridProvider_.grid()))
, disc_space_(gridPart_)
, disc_function("disc_function", disc_space_)
{}
};
struct RunBetterL2Projection {
template <class GridDim, class RangeDim>
static void run()
{
typedef ProjectionFixture<GridDim, RangeDim> TestType;
TestType test;
CustomFunctionT<GridDim::value, RangeDim::value> f;
DSFe::BetterL2Projection::project(f, test.disc_function);
const double time = 0.0f;
DSFe::BetterL2Projection::project(time, f, test.disc_function);
DSFe::ConstTimeProvider tp(0.0f);
DSFe::BetterL2Projection::project(tp, f, test.disc_function);
}
};
struct RunCustomProjection {
template <class GridDim, class RangeDim>
static void run()
{
typedef ProjectionFixture<GridDim, RangeDim> TestType;
TestType test;
CustomFunction<GridDim::value, RangeDim::value> f;
DSFe::CustomProjection::project(f, test.disc_function);
}
};
template <class TestFunctor>
struct ProjectionTest : public ::testing::Test {
typedef boost::mpl::vector< Int<1>, Int<2>, Int<3>> GridDims;
typedef GridDims RangeDims;
typedef typename DSC::TupleProduct::Combine< GridDims, RangeDims, TestFunctor
>::template Generate<> base_generator_type;
void run() {
base_generator_type::Run();
}
};
typedef ::testing::Types<RunBetterL2Projection, RunCustomProjection> TestParameter;
TYPED_TEST_CASE(ProjectionTest, TestParameter);
TYPED_TEST(ProjectionTest, All) {
this->run();
}
#endif
int main(int argc, char** argv)
{
test_init(argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before><commit_msg>drawingML export: write TextShape fill properties<commit_after><|endoftext|> |
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include <cassert>
#include <sstream>
#include <iostream>
#include "OpenSimAuth.h"
#ifdef WIN32
#include <winsock2.h>
#include <iphlpapi.h>
#endif
//using namespace std;
namespace ProtocolUtilities
{
///\todo Find a way for other OS's.
std::string GetMACaddressString()
{
//#ifdef WIN32
// IP_ADAPTER_INFO AdapterInfo[16];
//
// DWORD dwBufLen = sizeof(AdapterInfo);
//
// DWORD dwStatus = GetAdaptersInfo(AdapterInfo, &dwBufLen);
// if (dwStatus != ERROR_SUCCESS)
// {
// ///\todo Log error.
// assert(false && "GetAdaptersInfo failed!");
// return "";
// }
//
// PIP_ADAPTER_INFO pAdapterInfo = AdapterInfo;
//
// std::stringstream ss;
// while(pAdapterInfo)
// {
// ss << hex << pAdapterInfo->Address[0] <<
// hex << pAdapterInfo->Address[1] <<
// hex << pAdapterInfo->Address[2] <<
// hex << pAdapterInfo->Address[3] <<
// hex << pAdapterInfo->Address[4] <<
// hex << pAdapterInfo->Address[5];
// pAdapterInfo = pAdapterInfo->Next;
// }
//
// return ss.str();
//#else
return "01234567";
//#endif
}
///\todo Find a way for other OS's
std::string GetId0String()
{
#ifdef WIN32
std::stringstream serial;
DWORD dwVolSerial;
BOOL bIsRetrieved;
bIsRetrieved = GetVolumeInformation(L"C:\\", 0, 0, &dwVolSerial, 0, 0, 0, 0);
if (bIsRetrieved)
{
serial << std::hex << dwVolSerial;
return serial.str();
}
else
{
printf("Error: Could not retrieve serial number of the HDD!");
return std::string("");
}
#else
return "76543210";
#endif
}
std::string GetPlatform()
{
#ifdef Q_WS_WIN
return "Win";
#endif
#ifdef Q_WS_X11
return "X11";
#endif
#ifdef Q_WS_MAC
return "Mac";
#endif
return "";
}
}<commit_msg>Fix unreachable code warning.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include <cassert>
#include <sstream>
#include <iostream>
#include "OpenSimAuth.h"
#ifdef WIN32
#include <winsock2.h>
#include <iphlpapi.h>
#endif
//using namespace std;
namespace ProtocolUtilities
{
///\todo Find a way for other OS's.
std::string GetMACaddressString()
{
//#ifdef WIN32
// IP_ADAPTER_INFO AdapterInfo[16];
//
// DWORD dwBufLen = sizeof(AdapterInfo);
//
// DWORD dwStatus = GetAdaptersInfo(AdapterInfo, &dwBufLen);
// if (dwStatus != ERROR_SUCCESS)
// {
// ///\todo Log error.
// assert(false && "GetAdaptersInfo failed!");
// return "";
// }
//
// PIP_ADAPTER_INFO pAdapterInfo = AdapterInfo;
//
// std::stringstream ss;
// while(pAdapterInfo)
// {
// ss << hex << pAdapterInfo->Address[0] <<
// hex << pAdapterInfo->Address[1] <<
// hex << pAdapterInfo->Address[2] <<
// hex << pAdapterInfo->Address[3] <<
// hex << pAdapterInfo->Address[4] <<
// hex << pAdapterInfo->Address[5];
// pAdapterInfo = pAdapterInfo->Next;
// }
//
// return ss.str();
//#else
return "01234567";
//#endif
}
///\todo Find a way for other OS's
std::string GetId0String()
{
#ifdef WIN32
std::stringstream serial;
DWORD dwVolSerial;
BOOL bIsRetrieved;
bIsRetrieved = GetVolumeInformation(L"C:\\", 0, 0, &dwVolSerial, 0, 0, 0, 0);
if (bIsRetrieved)
{
serial << std::hex << dwVolSerial;
return serial.str();
}
else
{
printf("Error: Could not retrieve serial number of the HDD!");
return std::string("");
}
#else
return "76543210";
#endif
}
std::string GetPlatform()
{
#if defined(Q_WS_WIN)
return "Win";
#elif defined(Q_WS_X11)
return "X11";
#elif defined(Q_WS_MAC)
return "Mac";
#else
return "";
#endif
}
}
<|endoftext|> |
<commit_before>/*
* opencog/atomspace/AtomSpace.cc
*
* Copyright (c) 2008-2010 OpenCog Foundation
* Copyright (c) 2009, 2013 Linas Vepstas
* All Rights Reserved
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <string>
#include <iostream>
#include <fstream>
#include <list>
#include <stdlib.h>
#include <opencog/util/Logger.h>
#include <opencog/util/oc_assert.h>
#include <opencog/atoms/base/ClassServer.h>
#include <opencog/atoms/base/Link.h>
#include <opencog/atoms/base/Node.h>
#include <opencog/atoms/base/types.h>
#include "AtomSpace.h"
//#define DPRINTF printf
#define DPRINTF(...)
using std::string;
using std::cerr;
using std::cout;
using std::endl;
using std::min;
using std::max;
using namespace opencog;
// ====================================================================
/**
* Transient atomspaces skip some of the initialization steps,
* so that they can be constructed more quickly. Transient atomspaces
* are typically used as scratch spaces, to hold temporary results
* during evaluation, pattern matching and inference. Such temporary
* spaces don't need some of the heavier-weight crud that atomspaces
* are festooned with.
*/
AtomSpace::AtomSpace(AtomSpace* parent, bool transient) :
_atom_table(parent? &parent->_atom_table : NULL, this, transient),
_backing_store(NULL),
_transient(transient)
{
}
AtomSpace::~AtomSpace()
{
}
AtomSpace::AtomSpace(const AtomSpace&) :
_atom_table(NULL),
_backing_store(NULL)
{
throw opencog::RuntimeException(TRACE_INFO,
"AtomSpace - Cannot copy an object of this class");
}
void AtomSpace::ready_transient(AtomSpace* parent)
{
_atom_table.ready_transient(parent? &parent->_atom_table : NULL, this);
}
void AtomSpace::clear_transient()
{
_atom_table.clear_transient();
}
AtomSpace& AtomSpace::operator=(const AtomSpace&)
{
throw opencog::RuntimeException(TRACE_INFO,
"AtomSpace - Cannot copy an object of this class");
}
bool AtomSpace::compare_atomspaces(const AtomSpace& space_first,
const AtomSpace& space_second,
bool check_truth_values,
bool emit_diagnostics)
{
// Compare sizes
if (space_first.get_size() != space_second.get_size())
{
if (emit_diagnostics)
std::cout << "compare_atomspaces - size " <<
space_first.get_size() << " != size " <<
space_second.get_size() << std::endl;
return false;
}
// Compare node count
if (space_first.get_num_nodes() != space_second.get_num_nodes())
{
if (emit_diagnostics)
std::cout << "compare_atomspaces - node count " <<
space_first.get_num_nodes() << " != node count " <<
space_second.get_num_nodes() << std::endl;
return false;
}
// Compare link count
if (space_first.get_num_links() != space_second.get_num_links())
{
if (emit_diagnostics)
std::cout << "compare_atomspaces - link count " <<
space_first.get_num_links() << " != link count " <<
space_second.get_num_links() << std::endl;
return false;
}
// If we get this far, we need to compare each individual atom.
// Get the atoms in each atomspace.
HandleSeq atomsInFirstSpace, atomsInSecondSpace;
space_first.get_all_atoms(atomsInFirstSpace);
space_second.get_all_atoms(atomsInSecondSpace);
// Uncheck each atom in the second atomspace.
for (auto atom : atomsInSecondSpace)
atom->setUnchecked();
// Loop to see if each atom in the first has a match in the second.
const AtomTable& table_second = space_second._atom_table;
for (auto atom_first : atomsInFirstSpace)
{
Handle atom_second = table_second.getHandle(atom_first);
if( false)
{
Handle atom_second;
if (atom_first->isNode())
{
atom_second = table_second.getHandle(atom_first->getType(),
atom_first->getName());
}
else if (atom_first->isLink())
{
atom_second = table_second.getHandle(atom_first->getType(),
atom_first->getOutgoingSet());
}
else
{
throw opencog::RuntimeException(TRACE_INFO,
"AtomSpace::compare_atomspaces - atom not Node or Link");
}
}
// If the atoms don't match because one of them is NULL.
if ((atom_first and not atom_second) or
(atom_second and not atom_first))
{
if (emit_diagnostics)
{
if (atom_first)
std::cout << "compare_atomspaces - first atom " <<
atom_first->toString() << " != NULL " <<
std::endl;
if (atom_second)
std::cout << "compare_atomspaces - first atom " <<
"NULL != second atom " <<
atom_second->toString() << std::endl;
}
return false;
}
// If the atoms don't match... Compare the atoms not the pointers
// which is the default if we just use Handle operator ==.
if (*((AtomPtr) atom_first) != *((AtomPtr) atom_second))
{
if (emit_diagnostics)
std::cout << "compare_atomspaces - first atom " <<
atom_first->toString() << " != second atom " <<
atom_second->toString() << std::endl;
return false;
}
// Check the truth values...
if (check_truth_values)
{
TruthValuePtr truth_first = atom_first->getTruthValue();
TruthValuePtr truth_second = atom_second->getTruthValue();
if (*truth_first != *truth_second)
{
if (emit_diagnostics)
std::cout << "compare_atomspaces - first truth " <<
atom_first->toString() << " != second truth " <<
atom_second->toString() << std::endl;
return false;
}
}
// Set the check for the second atom.
atom_second->setChecked();
}
// Make sure each atom in the second atomspace has been checked.
bool all_checked = true;
for (auto atom : atomsInSecondSpace)
{
if (!atom->isChecked())
{
if (emit_diagnostics)
std::cout << "compare_atomspaces - unchecked space atom " <<
atom->toString() << std::endl;
all_checked = false;
}
}
if (!all_checked)
return false;
// If we get this far, then the spaces are equal.
return true;
}
bool AtomSpace::operator==(const AtomSpace& other) const
{
return compare_atomspaces(*this, other, CHECK_TRUTH_VALUES,
DONT_EMIT_DIAGNOSTICS);
}
bool AtomSpace::operator!=(const AtomSpace& other) const
{
return not operator==(other);
}
// ====================================================================
void AtomSpace::registerBackingStore(BackingStore *bs)
{
_backing_store = bs;
}
void AtomSpace::unregisterBackingStore(BackingStore *bs)
{
if (bs == _backing_store) _backing_store = NULL;
}
// ====================================================================
Handle AtomSpace::add_atom(const Handle& h, bool async)
{
// If it is a DeleteLink, then the addition will fail. Deal with it.
Handle rh;
try {
rh = _atom_table.add(h, async);
}
catch (const DeleteException& ex) {
// Atom deletion has not been implemented in the backing store
// This is a major to-do item.
if (_backing_store)
// Under construction ....
throw RuntimeException(TRACE_INFO, "Not implemented!!!");
}
return rh;
}
Handle AtomSpace::add_node(Type t, const string& name,
bool async)
{
return _atom_table.add(createNode(t, name), async);
}
Handle AtomSpace::get_node(Type t, const string& name)
{
return _atom_table.getHandle(t, name);
}
Handle AtomSpace::add_link(Type t, const HandleSeq& outgoing, bool async)
{
// If it is a DeleteLink, then the addition will fail. Deal with it.
Handle rh;
try {
rh = _atom_table.add(createLink(t, outgoing), async);
}
catch (const DeleteException& ex) {
// Atom deletion has not been implemented in the backing store
// This is a major to-do item.
if (_backing_store)
// Under construction ....
throw RuntimeException(TRACE_INFO, "Not implemented!!!");
}
return rh;
}
Handle AtomSpace::get_link(Type t, const HandleSeq& outgoing)
{
return _atom_table.getHandle(t, outgoing);
}
void AtomSpace::store_atom(const Handle& h)
{
if (nullptr == _backing_store)
throw RuntimeException(TRACE_INFO, "No backing store");
_backing_store->storeAtom(h);
}
Handle AtomSpace::fetch_atom(const Handle& h)
{
if (nullptr == _backing_store)
throw RuntimeException(TRACE_INFO, "No backing store");
if (nullptr == h) return Handle::UNDEFINED;
// We deal with two distinct cases.
// 1) If atom table already knows about this atom, then this
// function returns the atom-table's version of the atom.
// In particular, no attempt is made to reconcile the possibly
// differing truth values in the atomtable vs. backing store.
// Why? Because it is likely that the user plans to over-write
// what is in the backend.
// 2) If (1) does not hold, i.e. the atom is not in this table, nor
// it's environs, then assume that atom is from some previous
// (recursive) query; do fetch it from backing store (i.e. fetch
// the TV) and add it to the atomtable.
// For case 2, if the atom is a link, then it's outgoing set is
// fetched as well, as currently, a link cannot be added to the
// atomtable, unless all of its outgoing set already is in the
// atomtable.
// Case 1:
Handle hb(_atom_table.getHandle(h));
if (_atom_table.holds(hb))
return hb;
// Case 2: Atom is in some other atom table. Just copy it to here.
if (h->getAtomTable())
return _atom_table.add(h, false);
// Case 3:
// This atom is not yet in any (this??) atomspace; go get it.
TruthValuePtr tv;
if (h->isNode()) {
tv = _backing_store->getNode(h->getType(),
h->getName().c_str());
}
else if (h->isLink()) {
tv = _backing_store->getLink(h);
}
// If we still don't have an atom, then the requested atom
// was "insane", that is, unknown by either the atom table
// (case 1) or the backend.
if (nullptr == tv)
throw RuntimeException(TRACE_INFO,
"Asked backend for non-existant atom %s\n",
h->toString().c_str());
Handle hc(h);
hc->setTruthValue(tv);
return _atom_table.add(hc, false);
}
Handle AtomSpace::fetch_incoming_set(Handle h, bool recursive)
{
if (nullptr == _backing_store)
throw RuntimeException(TRACE_INFO, "No backing store");
h = get_atom(h);
if (nullptr == h) return Handle::UNDEFINED;
// Get everything from the backing store.
HandleSeq iset = _backing_store->getIncomingSet(h);
size_t isz = iset.size();
for (size_t i=0; i<isz; i++) {
Handle hi(iset[i]);
if (recursive) {
fetch_incoming_set(hi, true);
} else {
add_atom(hi);
}
}
return h;
}
bool AtomSpace::remove_atom(Handle h, bool recursive)
{
if (_backing_store) {
// Atom deletion has not been implemented in the backing store
// This is a major to-do item.
// Under construction ....
throw RuntimeException(TRACE_INFO, "Not implemented!!!");
}
return 0 < _atom_table.extract(h, recursive).size();
}
std::string AtomSpace::to_string() const
{
std::stringstream ss;
ss << *this;
return ss.str();
}
namespace std {
ostream& operator<<(ostream& out, const opencog::AtomSpace& as) {
list<opencog::Handle> results;
as.get_handles_by_type(back_inserter(results), opencog::ATOM, true);
for (const opencog::Handle& h : results)
if (h->getIncomingSetSize() == 0)
out << h->toString() << endl;
return out;
}
} // namespace std
<commit_msg>The fetch logic was insane.<commit_after>/*
* opencog/atomspace/AtomSpace.cc
*
* Copyright (c) 2008-2010 OpenCog Foundation
* Copyright (c) 2009, 2013 Linas Vepstas
* All Rights Reserved
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <string>
#include <iostream>
#include <fstream>
#include <list>
#include <stdlib.h>
#include <opencog/util/Logger.h>
#include <opencog/util/oc_assert.h>
#include <opencog/atoms/base/ClassServer.h>
#include <opencog/atoms/base/Link.h>
#include <opencog/atoms/base/Node.h>
#include <opencog/atoms/base/types.h>
#include "AtomSpace.h"
//#define DPRINTF printf
#define DPRINTF(...)
using std::string;
using std::cerr;
using std::cout;
using std::endl;
using std::min;
using std::max;
using namespace opencog;
// ====================================================================
/**
* Transient atomspaces skip some of the initialization steps,
* so that they can be constructed more quickly. Transient atomspaces
* are typically used as scratch spaces, to hold temporary results
* during evaluation, pattern matching and inference. Such temporary
* spaces don't need some of the heavier-weight crud that atomspaces
* are festooned with.
*/
AtomSpace::AtomSpace(AtomSpace* parent, bool transient) :
_atom_table(parent? &parent->_atom_table : NULL, this, transient),
_backing_store(NULL),
_transient(transient)
{
}
AtomSpace::~AtomSpace()
{
}
AtomSpace::AtomSpace(const AtomSpace&) :
_atom_table(NULL),
_backing_store(NULL)
{
throw opencog::RuntimeException(TRACE_INFO,
"AtomSpace - Cannot copy an object of this class");
}
void AtomSpace::ready_transient(AtomSpace* parent)
{
_atom_table.ready_transient(parent? &parent->_atom_table : NULL, this);
}
void AtomSpace::clear_transient()
{
_atom_table.clear_transient();
}
AtomSpace& AtomSpace::operator=(const AtomSpace&)
{
throw opencog::RuntimeException(TRACE_INFO,
"AtomSpace - Cannot copy an object of this class");
}
bool AtomSpace::compare_atomspaces(const AtomSpace& space_first,
const AtomSpace& space_second,
bool check_truth_values,
bool emit_diagnostics)
{
// Compare sizes
if (space_first.get_size() != space_second.get_size())
{
if (emit_diagnostics)
std::cout << "compare_atomspaces - size " <<
space_first.get_size() << " != size " <<
space_second.get_size() << std::endl;
return false;
}
// Compare node count
if (space_first.get_num_nodes() != space_second.get_num_nodes())
{
if (emit_diagnostics)
std::cout << "compare_atomspaces - node count " <<
space_first.get_num_nodes() << " != node count " <<
space_second.get_num_nodes() << std::endl;
return false;
}
// Compare link count
if (space_first.get_num_links() != space_second.get_num_links())
{
if (emit_diagnostics)
std::cout << "compare_atomspaces - link count " <<
space_first.get_num_links() << " != link count " <<
space_second.get_num_links() << std::endl;
return false;
}
// If we get this far, we need to compare each individual atom.
// Get the atoms in each atomspace.
HandleSeq atomsInFirstSpace, atomsInSecondSpace;
space_first.get_all_atoms(atomsInFirstSpace);
space_second.get_all_atoms(atomsInSecondSpace);
// Uncheck each atom in the second atomspace.
for (auto atom : atomsInSecondSpace)
atom->setUnchecked();
// Loop to see if each atom in the first has a match in the second.
const AtomTable& table_second = space_second._atom_table;
for (auto atom_first : atomsInFirstSpace)
{
Handle atom_second = table_second.getHandle(atom_first);
if( false)
{
Handle atom_second;
if (atom_first->isNode())
{
atom_second = table_second.getHandle(atom_first->getType(),
atom_first->getName());
}
else if (atom_first->isLink())
{
atom_second = table_second.getHandle(atom_first->getType(),
atom_first->getOutgoingSet());
}
else
{
throw opencog::RuntimeException(TRACE_INFO,
"AtomSpace::compare_atomspaces - atom not Node or Link");
}
}
// If the atoms don't match because one of them is NULL.
if ((atom_first and not atom_second) or
(atom_second and not atom_first))
{
if (emit_diagnostics)
{
if (atom_first)
std::cout << "compare_atomspaces - first atom " <<
atom_first->toString() << " != NULL " <<
std::endl;
if (atom_second)
std::cout << "compare_atomspaces - first atom " <<
"NULL != second atom " <<
atom_second->toString() << std::endl;
}
return false;
}
// If the atoms don't match... Compare the atoms not the pointers
// which is the default if we just use Handle operator ==.
if (*((AtomPtr) atom_first) != *((AtomPtr) atom_second))
{
if (emit_diagnostics)
std::cout << "compare_atomspaces - first atom " <<
atom_first->toString() << " != second atom " <<
atom_second->toString() << std::endl;
return false;
}
// Check the truth values...
if (check_truth_values)
{
TruthValuePtr truth_first = atom_first->getTruthValue();
TruthValuePtr truth_second = atom_second->getTruthValue();
if (*truth_first != *truth_second)
{
if (emit_diagnostics)
std::cout << "compare_atomspaces - first truth " <<
atom_first->toString() << " != second truth " <<
atom_second->toString() << std::endl;
return false;
}
}
// Set the check for the second atom.
atom_second->setChecked();
}
// Make sure each atom in the second atomspace has been checked.
bool all_checked = true;
for (auto atom : atomsInSecondSpace)
{
if (!atom->isChecked())
{
if (emit_diagnostics)
std::cout << "compare_atomspaces - unchecked space atom " <<
atom->toString() << std::endl;
all_checked = false;
}
}
if (!all_checked)
return false;
// If we get this far, then the spaces are equal.
return true;
}
bool AtomSpace::operator==(const AtomSpace& other) const
{
return compare_atomspaces(*this, other, CHECK_TRUTH_VALUES,
DONT_EMIT_DIAGNOSTICS);
}
bool AtomSpace::operator!=(const AtomSpace& other) const
{
return not operator==(other);
}
// ====================================================================
void AtomSpace::registerBackingStore(BackingStore *bs)
{
_backing_store = bs;
}
void AtomSpace::unregisterBackingStore(BackingStore *bs)
{
if (bs == _backing_store) _backing_store = NULL;
}
// ====================================================================
Handle AtomSpace::add_atom(const Handle& h, bool async)
{
// If it is a DeleteLink, then the addition will fail. Deal with it.
Handle rh;
try {
rh = _atom_table.add(h, async);
}
catch (const DeleteException& ex) {
// Atom deletion has not been implemented in the backing store
// This is a major to-do item.
if (_backing_store)
// Under construction ....
throw RuntimeException(TRACE_INFO, "Not implemented!!!");
}
return rh;
}
Handle AtomSpace::add_node(Type t, const string& name,
bool async)
{
return _atom_table.add(createNode(t, name), async);
}
Handle AtomSpace::get_node(Type t, const string& name)
{
return _atom_table.getHandle(t, name);
}
Handle AtomSpace::add_link(Type t, const HandleSeq& outgoing, bool async)
{
// If it is a DeleteLink, then the addition will fail. Deal with it.
Handle rh;
try {
rh = _atom_table.add(createLink(t, outgoing), async);
}
catch (const DeleteException& ex) {
// Atom deletion has not been implemented in the backing store
// This is a major to-do item.
if (_backing_store)
// Under construction ....
throw RuntimeException(TRACE_INFO, "Not implemented!!!");
}
return rh;
}
Handle AtomSpace::get_link(Type t, const HandleSeq& outgoing)
{
return _atom_table.getHandle(t, outgoing);
}
void AtomSpace::store_atom(const Handle& h)
{
if (nullptr == _backing_store)
throw RuntimeException(TRACE_INFO, "No backing store");
_backing_store->storeAtom(h);
}
Handle AtomSpace::fetch_atom(const Handle& h)
{
if (nullptr == _backing_store)
throw RuntimeException(TRACE_INFO, "No backing store");
if (nullptr == h) return Handle::UNDEFINED;
// Case 1:
// Try to get the atom from the backing store.
TruthValuePtr tv;
if (h->isNode()) {
tv = _backing_store->getNode(h->getType(),
h->getName().c_str());
}
else if (h->isLink()) {
tv = _backing_store->getLink(h);
}
if (tv) {
Handle hc(h);
hc->setTruthValue(tv);
return _atom_table.add(hc, false);
}
// Case 2: Its not in the backing store. Whatever. Make sure that
// it really is in the atomspace, and return to user.
return _atom_table.add(h, false);
}
Handle AtomSpace::fetch_incoming_set(Handle h, bool recursive)
{
if (nullptr == _backing_store)
throw RuntimeException(TRACE_INFO, "No backing store");
h = get_atom(h);
if (nullptr == h) return Handle::UNDEFINED;
// Get everything from the backing store.
HandleSeq iset = _backing_store->getIncomingSet(h);
size_t isz = iset.size();
for (size_t i=0; i<isz; i++) {
Handle hi(iset[i]);
if (recursive) {
fetch_incoming_set(hi, true);
} else {
add_atom(hi);
}
}
return h;
}
bool AtomSpace::remove_atom(Handle h, bool recursive)
{
if (_backing_store) {
// Atom deletion has not been implemented in the backing store
// This is a major to-do item.
// Under construction ....
throw RuntimeException(TRACE_INFO, "Not implemented!!!");
}
return 0 < _atom_table.extract(h, recursive).size();
}
std::string AtomSpace::to_string() const
{
std::stringstream ss;
ss << *this;
return ss.str();
}
namespace std {
ostream& operator<<(ostream& out, const opencog::AtomSpace& as) {
list<opencog::Handle> results;
as.get_handles_by_type(back_inserter(results), opencog::ATOM, true);
for (const opencog::Handle& h : results)
if (h->getIncomingSetSize() == 0)
out << h->toString() << endl;
return out;
}
} // namespace std
<|endoftext|> |
<commit_before>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CUBED_SPHERE_USER_H
#define CUBED_SPHERE_USER_H
#include <amr_forestclaw.H>
extern "C"
{
void mapc2m_cubedsphere_(const double *xc, const double *yc,
double *xp, double *yp, double *zp);
void mapc2m_(const double *xc, const double *yc,
double *xp, double *yp, double *zp);
void cubed_sphere_tag4refinement_(const int& mx,const int& my,const int& mbc,
const int& meqn, const double& xlower,
const double& ylower, const double& dx, const double& dy,
double q[], const int& init_flag, const int& blockno,
int& tag_patch);
void cubed_sphere_tag4coarsening_(const int& mx,const int& my,const int& mbc,
const int& meqn,const double& xlower,
const double& ylower, const double& dx, const double& dy,
double qcoarsened[], int& tag_patch);
void qinit_manifold_(const int& maxmx, const int& maxmy, const int& meqn,
const int& mbc, const int& mx, const int& my,
const double& xlower, const double& ylower,
const double& dx, const double& dy,
double q[], const int& maux, double aux[],
double xp[], double yp[], double zp[]);
void setaux_manifold_(const int& maxmx, const int& maxmy, const int& mbc,
const int& mx, const int& my,
const double& xlower, const double& ylower,
const double& dx, const double& dy,
const int& maux, double aux[],
double xp[], double yp[], double zp[],
double xd[], double yd[], double zd[],double area[]);
void b4step2_manifold_(const int& maxmx, const int& maxmy, const int& mbc,
const int& mx, const int& my,
const double& dx, const double& dy,
const double& t, const int& maux, double aux[],
double xd[], double yd[], double zd[]);
void cubed_sphere_write_tfile_(const int& iframe,const double& time,
const int& mfields,const int& ngrids,
const int& maux);
void cubed_sphere_write_qfile_(const int& maxmx, const int& maxmy,const int& meqn,
const int& mbc, const int& mx,const int& my,
const double& xlower,const double& ylower,
const double& dx, const double& dy,
double q[], const int& iframe,const int& patch_num,
const int& level,const int& blockno,
const int& mpirank);
}
#ifdef __cplusplus
extern "C"
{
#if 0
}
#endif
#endif
void cubed_sphere_link_solvers(fclaw2d_domain_t *domain);
void cubed_sphere_problem_setup(fclaw2d_domain_t* domain);
void cubed_sphere_patch_setup(fclaw2d_domain_t *domain,
fclaw2d_patch_t *this_patch,
int this_block_idx,
int this_patch_idx);
void cubed_sphere_qinit(fclaw2d_domain_t *domain,
fclaw2d_patch_t *this_patch,
int this_block_idx,
int this_patch_idx);
void cubed_sphere_b4step2(fclaw2d_domain_t *domain,
fclaw2d_patch_t *this_patch,
int this_block_idx,
int this_patch_idx,
double t,
double dt);
void cubed_sphere_patch_physical_bc(fclaw2d_domain *domain,
fclaw2d_patch_t *this_patch,
int this_block_idx,
int this_patch_idx,
double t,
double dt,
fclaw_bool intersects_bc[]);
double cubed_sphere_update(fclaw2d_domain_t *domain,
fclaw2d_patch_t *this_patch,
int this_block_idx,
int this_patch_idx,
double t,
double dt);
fclaw_bool cubed_sphere_patch_tag4refinement(fclaw2d_domain_t *domain,
fclaw2d_patch_t *this_patch,
int this_block_idx, int this_patch_idx,
int initflag);
fclaw_bool cubed_sphere_patch_tag4coarsening(fclaw2d_domain_t *domain,
fclaw2d_patch_t *this_patch,
int blockno,
int patchno);
void cubed_sphere_parallel_write_header(fclaw2d_domain_t* domain, int iframe, int ngrids);
void cubed_sphere_parallel_write_output(fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch,
int this_block_idx, int this_patch_idx,
int iframe,int num,int level);
#ifdef __cplusplus
#if 0
{
#endif
}
#endif
#endif
<commit_msg>Removed cubedsphere header and added to fclaw2d_map.h<commit_after>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CUBED_SPHERE_USER_H
#define CUBED_SPHERE_USER_H
#include <amr_forestclaw.H>
extern "C"
{
void mapc2m_(const double *xc, const double *yc,
double *xp, double *yp, double *zp);
void cubed_sphere_tag4refinement_(const int& mx,const int& my,const int& mbc,
const int& meqn, const double& xlower,
const double& ylower, const double& dx, const double& dy,
double q[], const int& init_flag, const int& blockno,
int& tag_patch);
void cubed_sphere_tag4coarsening_(const int& mx,const int& my,const int& mbc,
const int& meqn,const double& xlower,
const double& ylower, const double& dx, const double& dy,
double qcoarsened[], int& tag_patch);
void qinit_manifold_(const int& maxmx, const int& maxmy, const int& meqn,
const int& mbc, const int& mx, const int& my,
const double& xlower, const double& ylower,
const double& dx, const double& dy,
double q[], const int& maux, double aux[],
double xp[], double yp[], double zp[]);
void setaux_manifold_(const int& maxmx, const int& maxmy, const int& mbc,
const int& mx, const int& my,
const double& xlower, const double& ylower,
const double& dx, const double& dy,
const int& maux, double aux[],
double xp[], double yp[], double zp[],
double xd[], double yd[], double zd[],double area[]);
void b4step2_manifold_(const int& maxmx, const int& maxmy, const int& mbc,
const int& mx, const int& my,
const double& dx, const double& dy,
const double& t, const int& maux, double aux[],
double xd[], double yd[], double zd[]);
void cubed_sphere_write_tfile_(const int& iframe,const double& time,
const int& mfields,const int& ngrids,
const int& maux);
void cubed_sphere_write_qfile_(const int& maxmx, const int& maxmy,const int& meqn,
const int& mbc, const int& mx,const int& my,
const double& xlower,const double& ylower,
const double& dx, const double& dy,
double q[], const int& iframe,const int& patch_num,
const int& level,const int& blockno,
const int& mpirank);
}
#ifdef __cplusplus
extern "C"
{
#if 0
}
#endif
#endif
void cubed_sphere_link_solvers(fclaw2d_domain_t *domain);
void cubed_sphere_problem_setup(fclaw2d_domain_t* domain);
void cubed_sphere_patch_setup(fclaw2d_domain_t *domain,
fclaw2d_patch_t *this_patch,
int this_block_idx,
int this_patch_idx);
void cubed_sphere_qinit(fclaw2d_domain_t *domain,
fclaw2d_patch_t *this_patch,
int this_block_idx,
int this_patch_idx);
void cubed_sphere_b4step2(fclaw2d_domain_t *domain,
fclaw2d_patch_t *this_patch,
int this_block_idx,
int this_patch_idx,
double t,
double dt);
void cubed_sphere_patch_physical_bc(fclaw2d_domain *domain,
fclaw2d_patch_t *this_patch,
int this_block_idx,
int this_patch_idx,
double t,
double dt,
fclaw_bool intersects_bc[]);
double cubed_sphere_update(fclaw2d_domain_t *domain,
fclaw2d_patch_t *this_patch,
int this_block_idx,
int this_patch_idx,
double t,
double dt);
fclaw_bool cubed_sphere_patch_tag4refinement(fclaw2d_domain_t *domain,
fclaw2d_patch_t *this_patch,
int this_block_idx, int this_patch_idx,
int initflag);
fclaw_bool cubed_sphere_patch_tag4coarsening(fclaw2d_domain_t *domain,
fclaw2d_patch_t *this_patch,
int blockno,
int patchno);
void cubed_sphere_parallel_write_header(fclaw2d_domain_t* domain, int iframe, int ngrids);
void cubed_sphere_parallel_write_output(fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch,
int this_block_idx, int this_patch_idx,
int iframe,int num,int level);
#ifdef __cplusplus
#if 0
{
#endif
}
#endif
#endif
<|endoftext|> |
<commit_before>/*
The MIT License (MIT)
Copyright (c) 2015 winlin
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <dlp_core_proxy.hpp>
using namespace std;
#include <st.h>
DlpProxyContext::DlpProxyContext()
{
_port = -1;
_fd = -1;
}
DlpProxyContext::~DlpProxyContext()
{
::close(_fd);
std::vector<DlpProxySrs*>::iterator it;
for (it = sports.begin(); it != sports.end(); ++it) {
DlpProxySrs* srs = *it;
dlp_freep(srs);
}
sports.clear();
}
int DlpProxyContext::initialize(int p, int f, vector<int> sps)
{
int ret = ERROR_SUCCESS;
_port = p;
_fd = f;
for (int i = 0; i < (int)sps.size(); i++) {
DlpProxySrs* srs = new DlpProxySrs();
srs->port = sps.at(i);
srs->load = 0;
sports.push_back(srs);
}
return ret;
}
int DlpProxyContext::fd()
{
return _fd;
}
int DlpProxyContext::port()
{
return _port;
}
DlpProxySrs* DlpProxyContext::choose_srs()
{
DlpProxySrs* match = NULL;
std::vector<DlpProxySrs*>::iterator it;
for (it = sports.begin(); it != sports.end(); ++it) {
DlpProxySrs* srs = *it;
if (!match || match->load > srs->load) {
match = srs;
}
}
if (match) {
match->load++;
}
return match;
}
void DlpProxyContext::release_srs(DlpProxySrs* srs)
{
std::vector<DlpProxySrs*>::iterator it;
it = std::find(sports.begin(), sports.end(), srs);
if (it != sports.end()) {
srs->load--;
}
}
DlpProxyConnection::DlpProxyConnection()
{
_context = NULL;
stfd = NULL;
}
DlpProxyConnection::~DlpProxyConnection()
{
dlp_close_stfd(stfd);
}
int DlpProxyConnection::initilaize(DlpProxyContext* c, st_netfd_t s)
{
int ret = ERROR_SUCCESS;
_context = c;
stfd = s;
return ret;
}
int DlpProxyConnection::fd()
{
return st_netfd_fileno(stfd);
}
DlpProxyContext* DlpProxyConnection::context()
{
return _context;
}
int DlpProxyConnection::proxy(st_netfd_t srs)
{
int ret = ERROR_SUCCESS;
DlpStSocket skt_client(stfd);
DlpStSocket skt_srs(srs);
skt_client.set_recv_timeout(300 * 1000);
skt_srs.set_recv_timeout(1500 * 1000);
char buf[4096];
for (;;) {
// proxy client ==> srs.
ssize_t nread = 0;
for (;;) {
nread = 0;
if ((ret = skt_client.read(buf, 4096, &nread)) != ERROR_SUCCESS) {
if (ret != ERROR_SOCKET_TIMEOUT) {
return ret;
}
}
if (nread <= 0) {
break;
}
if ((ret = skt_srs.write(buf, nread, NULL)) != ERROR_SUCCESS) {
return ret;
}
}
// proxy srs ==> client
for (;;) {
nread = 0;
if ((ret = skt_srs.read(buf, 4096, &nread)) != ERROR_SUCCESS) {
if (ret != ERROR_SOCKET_TIMEOUT) {
return ret;
}
}
if (nread <= 0) {
break;
}
if ((ret = skt_client.write(buf, nread, NULL)) != ERROR_SUCCESS) {
return ret;
}
}
}
return ret;
}
int dlp_connection_proxy(DlpProxyConnection* conn)
{
int ret = ERROR_SUCCESS;
DlpProxyContext* context = conn->context();
// discovery client information.
int fd = conn->fd();
std::string ip = dlp_get_peer_ip(fd);
// choose the best SRS service por
DlpProxySrs* srs = context->choose_srs();
dlp_assert(srs);
dlp_trace("woker serve %s, fd=%d, srs_port=%d", ip.c_str(), fd, srs->port);
// try to connect to srs.
// TODO: FIXME: use timeout.
// TODO: FIXME: retry next srs when error.
st_netfd_t stfd = NULL;
if ((ret = dlp_socket_connect("127.0.0.1", srs->port, ST_UTIME_NO_TIMEOUT, &stfd)) != ERROR_SUCCESS) {
return ret;
}
// do proxy.
ret = conn->proxy(stfd);
context->release_srs(srs);
dlp_close_stfd(stfd);
return ret;
}
void* dlp_connection_pfn(void* arg)
{
DlpProxyConnection* conn = (DlpProxyConnection*)arg;
dlp_assert(conn);
int ret = ERROR_SUCCESS;
if ((ret = dlp_connection_proxy(conn)) != ERROR_SUCCESS) {
dlp_warn("worker proxy connection failed, ret=%d", ret);
} else {
dlp_trace("worker proxy connection completed.");
}
dlp_freep(conn);
return NULL;
}
int dlp_context_proxy(DlpProxyContext* context)
{
int ret = ERROR_SUCCESS;
dlp_trace("dolphin worker serve port=%d, fd=%d", context->port(), context->fd());
st_netfd_t stfd = NULL;
if ((stfd = st_netfd_open_socket(context->fd())) == NULL) {
ret = ERROR_ST_OPEN_FD;
dlp_error("worker open stfd failed. ret=%d", ret);
return ret;
}
dlp_info("worker open fd ok, fd=%d", context->fd());
for (;;) {
dlp_verbose("worker proecess serve at port %d", context->port());
st_netfd_t cfd = NULL;
if ((cfd = st_accept(stfd, NULL, NULL, ST_UTIME_NO_TIMEOUT)) == NULL) {
dlp_warn("ignore worker accept client error.");
continue;
}
DlpProxyConnection* conn = new DlpProxyConnection();
if ((ret = conn->initilaize(context, cfd)) != ERROR_SUCCESS) {
return ret;
}
st_thread_t trd = NULL;
if ((trd = st_thread_create(dlp_connection_pfn, conn, 0, 0)) == NULL) {
dlp_freep(conn);
dlp_warn("ignore worker thread create error.");
continue;
}
}
return ret;
}
void* dlp_context_fpn(void* arg)
{
DlpProxyContext* context = (DlpProxyContext*)arg;
dlp_assert(context);
int ret = ERROR_SUCCESS;
if ((ret = dlp_context_proxy(context)) != ERROR_SUCCESS) {
dlp_warn("worker proxy context failed, ret=%d", ret);
} else {
dlp_trace("worker proxy context completed.");
}
dlp_freep(context);
return NULL;
}
int dlp_run_proxyer(vector<int> ports, std::vector<int> fds, std::vector<int> sports)
{
int ret = ERROR_SUCCESS;
if ((ret = dlp_st_init()) != ERROR_SUCCESS) {
return ret;
}
dlp_assert(ports.size() == fds.size());
for (int i = 0; i < (int)ports.size(); i++) {
int port = ports.at(i);
int fd = fds.at(i);
DlpProxyContext* context = new DlpProxyContext();
if ((ret = context->initialize(port, fd, sports)) != ERROR_SUCCESS) {
dlp_freep(context);
return ret;
}
st_thread_t trd = NULL;
if ((trd = st_thread_create(dlp_context_fpn, context, 0, 0)) == NULL) {
dlp_freep(context);
ret = ERROR_ST_TRHEAD;
dlp_warn("worker thread create error. ret=%d", ret);
return ret;
}
}
st_thread_exit(NULL);
return ret;
}
<commit_msg>use smaller timeout for proxy.<commit_after>/*
The MIT License (MIT)
Copyright (c) 2015 winlin
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <dlp_core_proxy.hpp>
using namespace std;
#include <st.h>
DlpProxyContext::DlpProxyContext()
{
_port = -1;
_fd = -1;
}
DlpProxyContext::~DlpProxyContext()
{
::close(_fd);
std::vector<DlpProxySrs*>::iterator it;
for (it = sports.begin(); it != sports.end(); ++it) {
DlpProxySrs* srs = *it;
dlp_freep(srs);
}
sports.clear();
}
int DlpProxyContext::initialize(int p, int f, vector<int> sps)
{
int ret = ERROR_SUCCESS;
_port = p;
_fd = f;
for (int i = 0; i < (int)sps.size(); i++) {
DlpProxySrs* srs = new DlpProxySrs();
srs->port = sps.at(i);
srs->load = 0;
sports.push_back(srs);
}
return ret;
}
int DlpProxyContext::fd()
{
return _fd;
}
int DlpProxyContext::port()
{
return _port;
}
DlpProxySrs* DlpProxyContext::choose_srs()
{
DlpProxySrs* match = NULL;
std::vector<DlpProxySrs*>::iterator it;
for (it = sports.begin(); it != sports.end(); ++it) {
DlpProxySrs* srs = *it;
if (!match || match->load > srs->load) {
match = srs;
}
}
if (match) {
match->load++;
}
return match;
}
void DlpProxyContext::release_srs(DlpProxySrs* srs)
{
std::vector<DlpProxySrs*>::iterator it;
it = std::find(sports.begin(), sports.end(), srs);
if (it != sports.end()) {
srs->load--;
}
}
DlpProxyConnection::DlpProxyConnection()
{
_context = NULL;
stfd = NULL;
}
DlpProxyConnection::~DlpProxyConnection()
{
dlp_close_stfd(stfd);
}
int DlpProxyConnection::initilaize(DlpProxyContext* c, st_netfd_t s)
{
int ret = ERROR_SUCCESS;
_context = c;
stfd = s;
return ret;
}
int DlpProxyConnection::fd()
{
return st_netfd_fileno(stfd);
}
DlpProxyContext* DlpProxyConnection::context()
{
return _context;
}
int DlpProxyConnection::proxy(st_netfd_t srs)
{
int ret = ERROR_SUCCESS;
DlpStSocket skt_client(stfd);
DlpStSocket skt_srs(srs);
skt_client.set_recv_timeout(0);
skt_srs.set_recv_timeout(500 * 1000);
char buf[4096];
for (;;) {
ssize_t nread = 0;
// proxy client ==> srs.
if (true) {
nread = 0;
if ((ret = skt_client.read(buf, 4096, &nread)) != ERROR_SUCCESS) {
if (ret != ERROR_SOCKET_TIMEOUT) {
return ret;
}
}
if (nread > 0 && (ret = skt_srs.write(buf, nread, NULL)) != ERROR_SUCCESS) {
return ret;
}
}
// proxy srs ==> client
if (true) {
nread = 0;
if ((ret = skt_srs.read(buf, 4096, &nread)) != ERROR_SUCCESS) {
if (ret != ERROR_SOCKET_TIMEOUT) {
return ret;
}
}
if (nread > 0 && (ret = skt_client.write(buf, nread, NULL)) != ERROR_SUCCESS) {
return ret;
}
}
}
return ret;
}
int dlp_connection_proxy(DlpProxyConnection* conn)
{
int ret = ERROR_SUCCESS;
DlpProxyContext* context = conn->context();
// discovery client information.
int fd = conn->fd();
std::string ip = dlp_get_peer_ip(fd);
// choose the best SRS service por
DlpProxySrs* srs = context->choose_srs();
dlp_assert(srs);
dlp_trace("woker serve %s, fd=%d, srs_port=%d", ip.c_str(), fd, srs->port);
// try to connect to srs.
// TODO: FIXME: use timeout.
// TODO: FIXME: retry next srs when error.
st_netfd_t stfd = NULL;
if ((ret = dlp_socket_connect("127.0.0.1", srs->port, ST_UTIME_NO_TIMEOUT, &stfd)) != ERROR_SUCCESS) {
return ret;
}
// do proxy.
ret = conn->proxy(stfd);
context->release_srs(srs);
dlp_close_stfd(stfd);
return ret;
}
void* dlp_connection_pfn(void* arg)
{
DlpProxyConnection* conn = (DlpProxyConnection*)arg;
dlp_assert(conn);
int ret = ERROR_SUCCESS;
if ((ret = dlp_connection_proxy(conn)) != ERROR_SUCCESS) {
dlp_warn("worker proxy connection failed, ret=%d", ret);
} else {
dlp_trace("worker proxy connection completed.");
}
dlp_freep(conn);
return NULL;
}
int dlp_context_proxy(DlpProxyContext* context)
{
int ret = ERROR_SUCCESS;
dlp_trace("dolphin worker serve port=%d, fd=%d", context->port(), context->fd());
st_netfd_t stfd = NULL;
if ((stfd = st_netfd_open_socket(context->fd())) == NULL) {
ret = ERROR_ST_OPEN_FD;
dlp_error("worker open stfd failed. ret=%d", ret);
return ret;
}
dlp_info("worker open fd ok, fd=%d", context->fd());
for (;;) {
dlp_verbose("worker proecess serve at port %d", context->port());
st_netfd_t cfd = NULL;
if ((cfd = st_accept(stfd, NULL, NULL, ST_UTIME_NO_TIMEOUT)) == NULL) {
dlp_warn("ignore worker accept client error.");
continue;
}
DlpProxyConnection* conn = new DlpProxyConnection();
if ((ret = conn->initilaize(context, cfd)) != ERROR_SUCCESS) {
return ret;
}
st_thread_t trd = NULL;
if ((trd = st_thread_create(dlp_connection_pfn, conn, 0, 0)) == NULL) {
dlp_freep(conn);
dlp_warn("ignore worker thread create error.");
continue;
}
}
return ret;
}
void* dlp_context_fpn(void* arg)
{
DlpProxyContext* context = (DlpProxyContext*)arg;
dlp_assert(context);
int ret = ERROR_SUCCESS;
if ((ret = dlp_context_proxy(context)) != ERROR_SUCCESS) {
dlp_warn("worker proxy context failed, ret=%d", ret);
} else {
dlp_trace("worker proxy context completed.");
}
dlp_freep(context);
return NULL;
}
int dlp_run_proxyer(vector<int> ports, std::vector<int> fds, std::vector<int> sports)
{
int ret = ERROR_SUCCESS;
if ((ret = dlp_st_init()) != ERROR_SUCCESS) {
return ret;
}
dlp_assert(ports.size() == fds.size());
for (int i = 0; i < (int)ports.size(); i++) {
int port = ports.at(i);
int fd = fds.at(i);
DlpProxyContext* context = new DlpProxyContext();
if ((ret = context->initialize(port, fd, sports)) != ERROR_SUCCESS) {
dlp_freep(context);
return ret;
}
st_thread_t trd = NULL;
if ((trd = st_thread_create(dlp_context_fpn, context, 0, 0)) == NULL) {
dlp_freep(context);
ret = ERROR_ST_TRHEAD;
dlp_warn("worker thread create error. ret=%d", ret);
return ret;
}
}
st_thread_exit(NULL);
return ret;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: embeddoc.hxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: rt $ $Date: 2006-02-09 13:37:27 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _EMBEDDOC_HXX_
#define _EMBEDDOC_HXX_
#if defined(_MSC_VER) && (_MSC_VER >= 1300)
#undef _DEBUG
#endif
#include "common.h"
#include <oleidl.h>
#include <hash_map>
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_
#include <com/sun/star/uno/SEQUENCE.h>
#endif
#include "docholder.hxx"
typedef ::std::hash_map< DWORD, IAdviseSink* > AdviseSinkHashMap;
typedef ::std::hash_map< DWORD, IAdviseSink* >::iterator AdviseSinkHashMapIterator;
class GDIMetaFile;
class CIIAObj;
class EmbedDocument_Impl
: public IPersistStorage,
public IDataObject,
public IOleObject,
public IOleInPlaceObject,
public IPersistFile,
public IDispatch
{
protected:
::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >
fillArgsForLoading_Impl( ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > xStream,
DWORD nStreamMode,
LPCOLESTR pFilePath = NULL );
::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >
fillArgsForStoring_Impl( ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream > xStream );
HRESULT SaveTo_Impl( IStorage* pStg );
sal_uInt64 getMetaFileHandle_Impl( sal_Bool isEnhMeta );
public:
EmbedDocument_Impl( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& smgr,
const GUID* guid );
~EmbedDocument_Impl();
/* IUnknown methods */
STDMETHOD(QueryInterface)(REFIID riid, LPVOID FAR * ppvObj);
STDMETHOD_(ULONG, AddRef)();
STDMETHOD_(ULONG, Release)();
/* IPersistMethod */
STDMETHOD(GetClassID)(CLSID *pClassID);
/* IPersistStorage methods */
STDMETHOD(IsDirty) ();
STDMETHOD(InitNew) ( IStorage *pStg );
STDMETHOD(Load) ( IStorage* pStr );
STDMETHOD(Save) ( IStorage *pStgSave, BOOL fSameAsLoad );
STDMETHOD(SaveCompleted) ( IStorage *pStgNew );
STDMETHOD(HandsOffStorage) (void);
/* IDataObject methods */
STDMETHOD(GetData) ( FORMATETC * pFormatetc, STGMEDIUM * pMedium );
STDMETHOD(GetDataHere) ( FORMATETC * pFormatetc, STGMEDIUM * pMedium );
STDMETHOD(QueryGetData) ( FORMATETC * pFormatetc );
STDMETHOD(GetCanonicalFormatEtc) ( FORMATETC * pFormatetcIn, FORMATETC * pFormatetcOut );
STDMETHOD(SetData) ( FORMATETC * pFormatetc, STGMEDIUM * pMedium, BOOL fRelease );
STDMETHOD(EnumFormatEtc) ( DWORD dwDirection, IEnumFORMATETC ** ppFormatetc );
STDMETHOD(DAdvise) ( FORMATETC * pFormatetc, DWORD advf, IAdviseSink * pAdvSink, DWORD * pdwConnection );
STDMETHOD(DUnadvise) ( DWORD dwConnection );
STDMETHOD(EnumDAdvise) ( IEnumSTATDATA ** ppenumAdvise );
/* IOleObject methods */
STDMETHOD(SetClientSite) ( IOleClientSite* pSite );
STDMETHOD(GetClientSite) ( IOleClientSite** pSite );
STDMETHOD(SetHostNames) ( LPCOLESTR szContainerApp, LPCOLESTR szContainerObj );
STDMETHOD(Close) ( DWORD dwSaveOption);
STDMETHOD(SetMoniker) ( DWORD dwWhichMoniker, IMoniker *pmk );
STDMETHOD(GetMoniker) ( DWORD dwAssign, DWORD dwWhichMoniker, IMoniker **ppmk );
STDMETHOD(InitFromData) ( IDataObject *pDataObject, BOOL fCreation, DWORD dwReserved );
STDMETHOD(GetClipboardData) ( DWORD dwReserved, IDataObject **ppDataObject );
STDMETHOD(DoVerb) ( LONG iVerb, LPMSG lpmsg, IOleClientSite *pActiveSite, LONG lindex, HWND hwndParent, LPCRECT lprcPosRect );
STDMETHOD(EnumVerbs) ( IEnumOLEVERB **ppEnumOleVerb );
STDMETHOD(Update) ();
STDMETHOD(IsUpToDate) ();
STDMETHOD(GetUserClassID) ( CLSID *pClsid );
STDMETHOD(GetUserType) ( DWORD dwFormOfType, LPOLESTR *pszUserType );
STDMETHOD(SetExtent) ( DWORD dwDrawAspect, SIZEL *psizel );
STDMETHOD(GetExtent) ( DWORD dwDrawAspect, SIZEL *psizel );
STDMETHOD(Advise) ( IAdviseSink *pAdvSink, DWORD *pdwConnection );
STDMETHOD(Unadvise) ( DWORD dwConnection );
STDMETHOD(EnumAdvise) ( IEnumSTATDATA **ppenumAdvise );
STDMETHOD(GetMiscStatus) ( DWORD dwAspect, DWORD *pdwStatus );
STDMETHOD(SetColorScheme) ( LOGPALETTE *pLogpal );
/* IOleInPlaceObject methods */
STDMETHOD(GetWindow)(HWND *);
STDMETHOD(ContextSensitiveHelp)(BOOL);
STDMETHOD(InPlaceDeactivate)();
STDMETHOD(UIDeactivate)();
STDMETHOD(SetObjectRects)(LPCRECT, LPCRECT);
STDMETHOD(ReactivateAndUndo)();
/* IPersistFile methods */
STDMETHOD(Load) ( LPCOLESTR pszFileName, DWORD dwMode );
STDMETHOD(Save) ( LPCOLESTR pszFileName, BOOL fRemember );
STDMETHOD(SaveCompleted) ( LPCOLESTR pszFileName );
STDMETHOD(GetCurFile) ( LPOLESTR *ppszFileName );
/* IDispatch methods */
STDMETHOD(GetTypeInfoCount) ( unsigned int FAR* pctinfo );
STDMETHOD(GetTypeInfo) ( unsigned int iTInfo, LCID lcid, ITypeInfo FAR* FAR* ppTInfo );
STDMETHOD(GetIDsOfNames) ( REFIID riid, OLECHAR FAR* FAR* rgszNames, unsigned int cNames, LCID lcid, DISPID FAR* rgDispId );
STDMETHOD(Invoke) ( DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS FAR* pDispParams, VARIANT FAR* pVarResult, EXCEPINFO FAR* pExcepInfo, unsigned int FAR* puArgErr );
// c++ - methods
void notify( bool bDataChanged = true );
HRESULT SaveObject();
HRESULT ShowObject();
GUID GetGUID() const { return m_guid; }
protected:
oslInterlockedCount m_refCount;
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xFactory;
DocumentHolder* m_pDocHolder;
::rtl::OUString m_aFileName;
CComPtr< IStorage > m_pMasterStorage;
CComPtr< IStream > m_pOwnStream;
CComPtr< IStream > m_pExtStream;
GUID m_guid;
sal_Bool m_bIsDirty;
CComPtr< IOleClientSite > m_pClientSite;
CComPtr< IDataAdviseHolder > m_pDAdviseHolder;
AdviseSinkHashMap m_aAdviseHashMap;
DWORD m_nAdviseNum;
};
#endif //_EMBEDDOC_HXX_
<commit_msg>INTEGRATION: CWS fwkc03fixes (1.12.4); FILE MERGED 2006/04/28 13:11:41 mav 1.12.4.1: #134455# fix objects crosslinking<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: embeddoc.hxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: rt $ $Date: 2006-05-05 09:56:40 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _EMBEDDOC_HXX_
#define _EMBEDDOC_HXX_
#if defined(_MSC_VER) && (_MSC_VER >= 1300)
#undef _DEBUG
#endif
#include "common.h"
#include <oleidl.h>
#include <hash_map>
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_
#include <com/sun/star/uno/SEQUENCE.h>
#endif
#include "embeddocaccess.hxx"
#include "docholder.hxx"
typedef ::std::hash_map< DWORD, IAdviseSink* > AdviseSinkHashMap;
typedef ::std::hash_map< DWORD, IAdviseSink* >::iterator AdviseSinkHashMapIterator;
class GDIMetaFile;
class CIIAObj;
class EmbedDocument_Impl
: public IPersistStorage,
public IDataObject,
public IOleObject,
public IOleInPlaceObject,
public IPersistFile,
public IDispatch
{
protected:
::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >
fillArgsForLoading_Impl( ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > xStream,
DWORD nStreamMode,
LPCOLESTR pFilePath = NULL );
::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >
fillArgsForStoring_Impl( ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream > xStream );
HRESULT SaveTo_Impl( IStorage* pStg );
sal_uInt64 getMetaFileHandle_Impl( sal_Bool isEnhMeta );
public:
EmbedDocument_Impl( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& smgr,
const GUID* guid );
~EmbedDocument_Impl();
/* IUnknown methods */
STDMETHOD(QueryInterface)(REFIID riid, LPVOID FAR * ppvObj);
STDMETHOD_(ULONG, AddRef)();
STDMETHOD_(ULONG, Release)();
/* IPersistMethod */
STDMETHOD(GetClassID)(CLSID *pClassID);
/* IPersistStorage methods */
STDMETHOD(IsDirty) ();
STDMETHOD(InitNew) ( IStorage *pStg );
STDMETHOD(Load) ( IStorage* pStr );
STDMETHOD(Save) ( IStorage *pStgSave, BOOL fSameAsLoad );
STDMETHOD(SaveCompleted) ( IStorage *pStgNew );
STDMETHOD(HandsOffStorage) (void);
/* IDataObject methods */
STDMETHOD(GetData) ( FORMATETC * pFormatetc, STGMEDIUM * pMedium );
STDMETHOD(GetDataHere) ( FORMATETC * pFormatetc, STGMEDIUM * pMedium );
STDMETHOD(QueryGetData) ( FORMATETC * pFormatetc );
STDMETHOD(GetCanonicalFormatEtc) ( FORMATETC * pFormatetcIn, FORMATETC * pFormatetcOut );
STDMETHOD(SetData) ( FORMATETC * pFormatetc, STGMEDIUM * pMedium, BOOL fRelease );
STDMETHOD(EnumFormatEtc) ( DWORD dwDirection, IEnumFORMATETC ** ppFormatetc );
STDMETHOD(DAdvise) ( FORMATETC * pFormatetc, DWORD advf, IAdviseSink * pAdvSink, DWORD * pdwConnection );
STDMETHOD(DUnadvise) ( DWORD dwConnection );
STDMETHOD(EnumDAdvise) ( IEnumSTATDATA ** ppenumAdvise );
/* IOleObject methods */
STDMETHOD(SetClientSite) ( IOleClientSite* pSite );
STDMETHOD(GetClientSite) ( IOleClientSite** pSite );
STDMETHOD(SetHostNames) ( LPCOLESTR szContainerApp, LPCOLESTR szContainerObj );
STDMETHOD(Close) ( DWORD dwSaveOption);
STDMETHOD(SetMoniker) ( DWORD dwWhichMoniker, IMoniker *pmk );
STDMETHOD(GetMoniker) ( DWORD dwAssign, DWORD dwWhichMoniker, IMoniker **ppmk );
STDMETHOD(InitFromData) ( IDataObject *pDataObject, BOOL fCreation, DWORD dwReserved );
STDMETHOD(GetClipboardData) ( DWORD dwReserved, IDataObject **ppDataObject );
STDMETHOD(DoVerb) ( LONG iVerb, LPMSG lpmsg, IOleClientSite *pActiveSite, LONG lindex, HWND hwndParent, LPCRECT lprcPosRect );
STDMETHOD(EnumVerbs) ( IEnumOLEVERB **ppEnumOleVerb );
STDMETHOD(Update) ();
STDMETHOD(IsUpToDate) ();
STDMETHOD(GetUserClassID) ( CLSID *pClsid );
STDMETHOD(GetUserType) ( DWORD dwFormOfType, LPOLESTR *pszUserType );
STDMETHOD(SetExtent) ( DWORD dwDrawAspect, SIZEL *psizel );
STDMETHOD(GetExtent) ( DWORD dwDrawAspect, SIZEL *psizel );
STDMETHOD(Advise) ( IAdviseSink *pAdvSink, DWORD *pdwConnection );
STDMETHOD(Unadvise) ( DWORD dwConnection );
STDMETHOD(EnumAdvise) ( IEnumSTATDATA **ppenumAdvise );
STDMETHOD(GetMiscStatus) ( DWORD dwAspect, DWORD *pdwStatus );
STDMETHOD(SetColorScheme) ( LOGPALETTE *pLogpal );
/* IOleInPlaceObject methods */
STDMETHOD(GetWindow)(HWND *);
STDMETHOD(ContextSensitiveHelp)(BOOL);
STDMETHOD(InPlaceDeactivate)();
STDMETHOD(UIDeactivate)();
STDMETHOD(SetObjectRects)(LPCRECT, LPCRECT);
STDMETHOD(ReactivateAndUndo)();
/* IPersistFile methods */
STDMETHOD(Load) ( LPCOLESTR pszFileName, DWORD dwMode );
STDMETHOD(Save) ( LPCOLESTR pszFileName, BOOL fRemember );
STDMETHOD(SaveCompleted) ( LPCOLESTR pszFileName );
STDMETHOD(GetCurFile) ( LPOLESTR *ppszFileName );
/* IDispatch methods */
STDMETHOD(GetTypeInfoCount) ( unsigned int FAR* pctinfo );
STDMETHOD(GetTypeInfo) ( unsigned int iTInfo, LCID lcid, ITypeInfo FAR* FAR* ppTInfo );
STDMETHOD(GetIDsOfNames) ( REFIID riid, OLECHAR FAR* FAR* rgszNames, unsigned int cNames, LCID lcid, DISPID FAR* rgDispId );
STDMETHOD(Invoke) ( DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS FAR* pDispParams, VARIANT FAR* pVarResult, EXCEPINFO FAR* pExcepInfo, unsigned int FAR* puArgErr );
// c++ - methods
void notify( bool bDataChanged = true );
HRESULT SaveObject();
HRESULT ShowObject();
GUID GetGUID() const { return m_guid; }
protected:
oslInterlockedCount m_refCount;
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xFactory;
DocumentHolder* m_pDocHolder;
::rtl::OUString m_aFileName;
CComPtr< IStorage > m_pMasterStorage;
CComPtr< IStream > m_pOwnStream;
CComPtr< IStream > m_pExtStream;
GUID m_guid;
sal_Bool m_bIsDirty;
CComPtr< IOleClientSite > m_pClientSite;
CComPtr< IDataAdviseHolder > m_pDAdviseHolder;
AdviseSinkHashMap m_aAdviseHashMap;
DWORD m_nAdviseNum;
::rtl::Reference< EmbeddedDocumentInstanceAccess_Impl > m_xOwnAccess;
};
#endif //_EMBEDDOC_HXX_
<|endoftext|> |
<commit_before>//===========================================
// Lumina-DE source code
// Copyright (c) 2015, Ken Moore
// Available under the 3-clause BSD license
// See the LICENSE file for full details
//===========================================
#include "LStartButton.h"
#include "../../LSession.h"
#include <LuminaXDG.h>
#include <LUtils.h> //This contains the "ResizeMenu" class
LStartButtonPlugin::LStartButtonPlugin(QWidget *parent, QString id, bool horizontal) : LPPlugin(parent, id, horizontal){
button = new QToolButton(this);
button->setAutoRaise(true);
button->setToolButtonStyle(Qt::ToolButtonIconOnly);
button->setPopupMode(QToolButton::DelayedPopup); //make sure it runs the update routine first
connect(button, SIGNAL(clicked()), this, SLOT(openMenu()));
this->layout()->setContentsMargins(0,0,0,0);
this->layout()->addWidget(button);
menu = new ResizeMenu(this);
menu->setContentsMargins(1,1,1,1);
connect(menu, SIGNAL(aboutToHide()), this, SIGNAL(MenuClosed()));
connect(menu, SIGNAL(MenuResized(QSize)), this, SLOT(SaveMenuSize(QSize)) );
startmenu = new StartMenu(this);
connect(startmenu, SIGNAL(CloseMenu()), this, SLOT(closeMenu()) );
connect(startmenu, SIGNAL(UpdateQuickLaunch(QStringList)), this, SLOT(updateQuickLaunch(QStringList)));
menu->setContents(startmenu);
QRect screenSize = QApplication::desktop()->availableGeometry(this);
QSize saved = LSession::handle()->DesktopPluginSettings()->value("panelPlugs/"+this->type()+"/MenuSize", QSize(screenSize.width() * 0.2, screenSize.height() * 0.2)).toSize();
if(!saved.isNull()){ startmenu->setFixedSize(saved); } //re-load the previously saved value
button->setMenu(menu);
connect(menu, SIGNAL(aboutToHide()), this, SLOT(updateButtonVisuals()) );
QTimer::singleShot(0,this, SLOT(OrientationChange())); //Update icons/sizes
QTimer::singleShot(0, startmenu, SLOT(ReLoadQuickLaunch()) );
//Setup the global shortcut handling for opening the start menu
connect(QApplication::instance(), SIGNAL(StartButtonActivated()), this, SLOT(shortcutActivated()) );
LSession::handle()->registerStartButton(this->type());
}
LStartButtonPlugin::~LStartButtonPlugin(){
LSession::handle()->unregisterStartButton(this->type());
}
void LStartButtonPlugin::updateButtonVisuals(){
button->setToolTip(tr(""));
button->setText( SYSTEM::user() );
button->setIcon( LXDG::findIcon("start-here-lumina","Lumina-DE") ); //force icon refresh
}
void LStartButtonPlugin::updateQuickLaunch(QStringList apps){
//First clear any obsolete apps
QStringList old;
//qDebug() << "Update QuickLaunch Buttons";
for(int i=0; i<QUICKL.length(); i++){
if( !apps.contains(QUICKL[i]->whatsThis()) ){
//App was removed
QUICKL.takeAt(i)->deleteLater();
i--;
}else{
//App still listed - update the button
old << QUICKL[i]->whatsThis(); //add the list of current buttons
LFileInfo info(QUICKL[i]->whatsThis());
QUICKL[i]->setIcon( LXDG::findIcon(info.iconfile(),"unknown") );
if(info.isDesktopFile()){ QUICKL[i]->setToolTip( info.XDG()->name ); }
else{ QUICKL[i]->setToolTip( info.fileName() ); }
}
}
//Now go through and create any new buttons
for(int i=0; i<apps.length(); i++){
if( !old.contains(apps[i]) ){
//New App
LQuickLaunchButton *tmp = new LQuickLaunchButton(apps[i], this);
QUICKL << tmp;
LFileInfo info(apps[i]);
tmp->setIcon( LXDG::findIcon( info.iconfile() ) );
if(info.isDesktopFile()){ tmp->setToolTip( info.XDG()->name ); }
else{ tmp->setToolTip( info.fileName() ); }
//Now add the button to the layout and connect the signal/slots
this->layout()->insertWidget(i+1,tmp); //"button" is always in slot 0
connect(tmp, SIGNAL(Launch(QString)), this, SLOT(LaunchQuick(QString)) );
connect(tmp, SIGNAL(Remove(QString)), this, SLOT(RemoveQuick(QString)) );
}
}
//qDebug() << " - Done updateing QuickLaunch Buttons";
QTimer::singleShot(0,this, SLOT(OrientationChange())); //Update icons/sizes
}
void LStartButtonPlugin::LaunchQuick(QString file){
//Need to get which button was clicked
//qDebug() << "Quick Launch triggered:" << file;
if(!file.isEmpty()){
LSession::LaunchApplication("lumina-open \""+file+"\"");
emit MenuClosed();
}
}
void LStartButtonPlugin::RemoveQuick(QString file){
//qDebug() << "Remove Quicklaunch Button:" << file;
if(!file.isEmpty()){
startmenu->UpdateQuickLaunch(file, false); //always a removal
emit MenuClosed();
}
}
void LStartButtonPlugin::SaveMenuSize(QSize sz){
//Save this size for the menu
LSession::handle()->DesktopPluginSettings()->setValue("panelPlugs/"+this->type()+"/MenuSize", sz);
}
// ========================
// PRIVATE FUNCTIONS
// ========================
void LStartButtonPlugin::openMenu(){
if(menu->isVisible()){ return; } //don't re-show it - already open
//TESTING CODE TO SEE IF THIS MAKES IT RECOVER MEMORY
/*StartMenu *old = startmenu;
startmenu = new StartMenu(this);
connect(startmenu, SIGNAL(CloseMenu()), this, SLOT(closeMenu()) );
connect(startmenu, SIGNAL(UpdateQuickLaunch(QStringList)), this, SLOT(updateQuickLaunch(QStringList)));
menu->setContents(startmenu);
if(old!=0){ old->deleteLater(); }*/
//--------
startmenu->UpdateMenu();
button->showMenu();
}
void LStartButtonPlugin::closeMenu(){
menu->hide();
}
void LStartButtonPlugin::shortcutActivated(){
if(LSession::handle()->registerStartButton(this->type())){
if(menu->isVisible()){ closeMenu(); }
else{ this->activateWindow(); openMenu(); }
}
}
<commit_msg>fix height for start menu<commit_after>//===========================================
// Lumina-DE source code
// Copyright (c) 2015, Ken Moore
// Available under the 3-clause BSD license
// See the LICENSE file for full details
//===========================================
#include "LStartButton.h"
#include "../../LSession.h"
#include <LuminaXDG.h>
#include <LUtils.h> //This contains the "ResizeMenu" class
LStartButtonPlugin::LStartButtonPlugin(QWidget *parent, QString id, bool horizontal) : LPPlugin(parent, id, horizontal){
button = new QToolButton(this);
button->setAutoRaise(true);
button->setToolButtonStyle(Qt::ToolButtonIconOnly);
button->setPopupMode(QToolButton::DelayedPopup); //make sure it runs the update routine first
connect(button, SIGNAL(clicked()), this, SLOT(openMenu()));
this->layout()->setContentsMargins(0,0,0,0);
this->layout()->addWidget(button);
menu = new ResizeMenu(this);
menu->setContentsMargins(1,1,1,1);
connect(menu, SIGNAL(aboutToHide()), this, SIGNAL(MenuClosed()));
connect(menu, SIGNAL(MenuResized(QSize)), this, SLOT(SaveMenuSize(QSize)) );
startmenu = new StartMenu(this);
connect(startmenu, SIGNAL(CloseMenu()), this, SLOT(closeMenu()) );
connect(startmenu, SIGNAL(UpdateQuickLaunch(QStringList)), this, SLOT(updateQuickLaunch(QStringList)));
menu->setContents(startmenu);
QRect screenSize = QApplication::desktop()->availableGeometry(this);
QSize saved = LSession::handle()->DesktopPluginSettings()->value("panelPlugs/"+this->type()+"/MenuSize", QSize(screenSize.width() * 0.2, screenSize.height())).toSize();
if(!saved.isNull()){ startmenu->setFixedSize(saved); } //re-load the previously saved value
button->setMenu(menu);
connect(menu, SIGNAL(aboutToHide()), this, SLOT(updateButtonVisuals()) );
QTimer::singleShot(0,this, SLOT(OrientationChange())); //Update icons/sizes
QTimer::singleShot(0, startmenu, SLOT(ReLoadQuickLaunch()) );
//Setup the global shortcut handling for opening the start menu
connect(QApplication::instance(), SIGNAL(StartButtonActivated()), this, SLOT(shortcutActivated()) );
LSession::handle()->registerStartButton(this->type());
}
LStartButtonPlugin::~LStartButtonPlugin(){
LSession::handle()->unregisterStartButton(this->type());
}
void LStartButtonPlugin::updateButtonVisuals(){
button->setToolTip(tr(""));
button->setText( SYSTEM::user() );
button->setIcon( LXDG::findIcon("start-here-lumina","Lumina-DE") ); //force icon refresh
}
void LStartButtonPlugin::updateQuickLaunch(QStringList apps){
//First clear any obsolete apps
QStringList old;
//qDebug() << "Update QuickLaunch Buttons";
for(int i=0; i<QUICKL.length(); i++){
if( !apps.contains(QUICKL[i]->whatsThis()) ){
//App was removed
QUICKL.takeAt(i)->deleteLater();
i--;
}else{
//App still listed - update the button
old << QUICKL[i]->whatsThis(); //add the list of current buttons
LFileInfo info(QUICKL[i]->whatsThis());
QUICKL[i]->setIcon( LXDG::findIcon(info.iconfile(),"unknown") );
if(info.isDesktopFile()){ QUICKL[i]->setToolTip( info.XDG()->name ); }
else{ QUICKL[i]->setToolTip( info.fileName() ); }
}
}
//Now go through and create any new buttons
for(int i=0; i<apps.length(); i++){
if( !old.contains(apps[i]) ){
//New App
LQuickLaunchButton *tmp = new LQuickLaunchButton(apps[i], this);
QUICKL << tmp;
LFileInfo info(apps[i]);
tmp->setIcon( LXDG::findIcon( info.iconfile() ) );
if(info.isDesktopFile()){ tmp->setToolTip( info.XDG()->name ); }
else{ tmp->setToolTip( info.fileName() ); }
//Now add the button to the layout and connect the signal/slots
this->layout()->insertWidget(i+1,tmp); //"button" is always in slot 0
connect(tmp, SIGNAL(Launch(QString)), this, SLOT(LaunchQuick(QString)) );
connect(tmp, SIGNAL(Remove(QString)), this, SLOT(RemoveQuick(QString)) );
}
}
//qDebug() << " - Done updateing QuickLaunch Buttons";
QTimer::singleShot(0,this, SLOT(OrientationChange())); //Update icons/sizes
}
void LStartButtonPlugin::LaunchQuick(QString file){
//Need to get which button was clicked
//qDebug() << "Quick Launch triggered:" << file;
if(!file.isEmpty()){
LSession::LaunchApplication("lumina-open \""+file+"\"");
emit MenuClosed();
}
}
void LStartButtonPlugin::RemoveQuick(QString file){
//qDebug() << "Remove Quicklaunch Button:" << file;
if(!file.isEmpty()){
startmenu->UpdateQuickLaunch(file, false); //always a removal
emit MenuClosed();
}
}
void LStartButtonPlugin::SaveMenuSize(QSize sz){
//Save this size for the menu
LSession::handle()->DesktopPluginSettings()->setValue("panelPlugs/"+this->type()+"/MenuSize", sz);
}
// ========================
// PRIVATE FUNCTIONS
// ========================
void LStartButtonPlugin::openMenu(){
if(menu->isVisible()){ return; } //don't re-show it - already open
//TESTING CODE TO SEE IF THIS MAKES IT RECOVER MEMORY
/*StartMenu *old = startmenu;
startmenu = new StartMenu(this);
connect(startmenu, SIGNAL(CloseMenu()), this, SLOT(closeMenu()) );
connect(startmenu, SIGNAL(UpdateQuickLaunch(QStringList)), this, SLOT(updateQuickLaunch(QStringList)));
menu->setContents(startmenu);
if(old!=0){ old->deleteLater(); }*/
//--------
startmenu->UpdateMenu();
button->showMenu();
}
void LStartButtonPlugin::closeMenu(){
menu->hide();
}
void LStartButtonPlugin::shortcutActivated(){
if(LSession::handle()->registerStartButton(this->type())){
if(menu->isVisible()){ closeMenu(); }
else{ this->activateWindow(); openMenu(); }
}
}
<|endoftext|> |
<commit_before>#include "..\header\Player.h"
Player::Player(game_state* GameState){
LogManager& l = LogManager::getInstance();
ResourceManager& r = ResourceManager::getInstance();
WorldManager& w = WorldManager::getInstance();
if (!l.isStarted() || !r.isStarted() || !w.isStarted()){
l.writeLog("Manager was not started. Order by: %s %s %s", BoolToString(l.isStarted()), BoolToString(r.isStarted()), BoolToString(w.isStarted()));
w.markForDelete(this);
return;
}
//No need for a sprite. A simple character will do.
setType(TYPE_PLAYER);
setTransparency();
setSolidness(Solidness::HARD);
Position pos(GameState->PlayerState.x, GameState->PlayerState.y);
setPosition(pos);
registerInterest(DF_KEYBOARD_EVENT);
registerInterest(DF_STEP_EVENT);
this->GameState = GameState;
setVisible(true);
l.writeLog("[Player] Successfully loaded Player entity.");
}
//TODO: Add collision detection/response.
int Player::eventHandler(Event* e){
LogManager& l = LogManager::getInstance();
if (e->getType() == DF_KEYBOARD_EVENT){
EventKeyboard* keyboard = dynamic_cast<EventKeyboard*>(e);
int key = keyboard->getKey();
switch (key){
case 'a':{
int x = this->getPosition().getX();
this->setPosition(Position(--x, this->getPosition().getY()));
break;
}
case 'd':{
int x = this->getPosition().getX();
this->setPosition(Position(++x, this->getPosition().getY()));
break;
}
default:{
return 0;
}
}
return 1;
}
else if (e->getType() == DF_STEP_EVENT){
//Current location
int x = this->getPosition().getX();
int y = this->getPosition().getY();
if (this->GameState && this->GameState->Stage1.layout){
//Gravity affected movement.
int pitch = y * this->GameState->Stage1.width + x;
if (*((this->GameState->Stage1.layout) + pitch) == 0){
y++;
}
}
//Checks to see if the location is within bounds.
if (x <= this->GameState->PlayerState.minX){
x = this->GameState->PlayerState.minX + 1;
}
if (y <= this->GameState->PlayerState.minY){
y = this->GameState->PlayerState.minY + 1;
}
if (x >= this->GameState->PlayerState.maxX){
x = this->GameState->PlayerState.maxX - 1;
}
if (y > this->GameState->PlayerState.maxY){
y = this->GameState->PlayerState.maxY;
}
//Set new position.
this->GameState->PlayerState.x = x;
this->GameState->PlayerState.y = y;
this->setPosition(Position(x, y));
l.writeLog("Player Pos: %d, %d, State %d %d, %d %d", x, y, GameState->PlayerState.minX, GameState->PlayerState.minY, GameState->PlayerState.maxX, GameState->PlayerState.maxY);
return 1;
}
return 0;
}
void Player::draw(){
LogManager& l = LogManager::getInstance();
GraphicsManager& g = GraphicsManager::getInstance();
g.drawCh(this->getPosition(), '@', 0);
return;
}
void Player::initializeState(game_state* GameState){
this->GameState = GameState;
return;
}
void Player::setGameBounds(int x, int y, int w, int h){
if (this->GameState){
this->GameState->PlayerState.minX = x;
this->GameState->PlayerState.minY = y;
this->GameState->PlayerState.maxX = w;
this->GameState->PlayerState.maxY = h;
LogManager& l = LogManager::getInstance();
l.writeLog("setGameBounds = %d, %d, %d, %d", x, y, w, h);
}
}<commit_msg>Fixed player not being reset to its initial location.<commit_after>#include "..\header\Player.h"
Player::Player(game_state* GameState){
LogManager& l = LogManager::getInstance();
ResourceManager& r = ResourceManager::getInstance();
WorldManager& w = WorldManager::getInstance();
if (!l.isStarted() || !r.isStarted() || !w.isStarted()){
l.writeLog("Manager was not started. Order by: %s %s %s", BoolToString(l.isStarted()), BoolToString(r.isStarted()), BoolToString(w.isStarted()));
w.markForDelete(this);
return;
}
//No need for a sprite. A simple character will do.
setType(TYPE_PLAYER);
setTransparency();
setSolidness(Solidness::HARD);
Position pos(GameState->PlayerState.x, GameState->PlayerState.y);
setPosition(pos);
registerInterest(DF_KEYBOARD_EVENT);
registerInterest(DF_STEP_EVENT);
this->GameState = GameState;
setVisible(true);
l.writeLog("[Player] Successfully loaded Player entity.");
}
//TODO: Add collision detection/response.
int Player::eventHandler(Event* e){
LogManager& l = LogManager::getInstance();
if (e->getType() == DF_KEYBOARD_EVENT){
EventKeyboard* keyboard = dynamic_cast<EventKeyboard*>(e);
int key = keyboard->getKey();
switch (key){
case 'a':{
int x = this->getPosition().getX();
int* layout = this->GameState->Stage1.layout;
int width = this->GameState->Stage1.width;
int layoutX = x - this->GameState->PlayerState.minX - 1;
int layoutY = this->getPosition().getY() - this->GameState->PlayerState.minY;
int check = *(layout + (layoutY *width + layoutX));
if (check == 0){
x--;
}
this->setPosition(Position(x, this->getPosition().getY()));
break;
}
case 'd':{
int x = this->getPosition().getX();
int* layout = this->GameState->Stage1.layout;
int width = this->GameState->Stage1.width;
int layoutX = x - this->GameState->PlayerState.minX + 1;
int layoutY = this->getPosition().getY() - this->GameState->PlayerState.minY;
int check = *(layout + (layoutY *width + layoutX));
if (check == 0){
x++;
}
this->setPosition(Position(x, this->getPosition().getY()));
break;
}
default:{
return 0;
}
}
return 1;
}
else if (e->getType() == DF_STEP_EVENT){
//Current location
int x = this->getPosition().getX();
int y = this->getPosition().getY();
if (this->GameState && this->GameState->Stage1.layout){
int layoutX = (x - this->GameState->PlayerState.minX);
int layoutY = (y - this->GameState->PlayerState.minY);
int width = this->GameState->Stage1.width;
int* layout = this->GameState->Stage1.layout;
//Gravity affected movement.
if (layoutY + 1 < this->GameState->PlayerState.maxY){
int check = *(layout + ((layoutY+1)*width + layoutX));
l.writeLog("Test: %d", check);
if (check == 0 && check < 10 && check > -1){
y++;
}
}
}
//Checks to see if the location is within bounds.
if (x <= this->GameState->PlayerState.minX){
x = this->GameState->PlayerState.minX + 1;
}
if (y <= this->GameState->PlayerState.minY){
y = this->GameState->PlayerState.minY + 1;
}
if (x >= this->GameState->PlayerState.maxX){
x = this->GameState->PlayerState.maxX - 1;
}
if (y > this->GameState->PlayerState.maxY){
y = this->GameState->PlayerState.maxY;
}
//Set new position.
this->GameState->PlayerState.x = x;
this->GameState->PlayerState.y = y;
this->setPosition(Position(x, y));
return 1;
}
return 0;
}
void Player::draw(){
LogManager& l = LogManager::getInstance();
GraphicsManager& g = GraphicsManager::getInstance();
g.drawCh(this->getPosition(), '@', 0);
return;
}
void Player::initializeState(game_state* GameState){
this->GameState = GameState;
this->setPosition(Position(GameState->PlayerState.x, GameState->PlayerState.y));
return;
}
void Player::setGameBounds(int x, int y, int w, int h){
if (this->GameState){
this->GameState->PlayerState.minX = x;
this->GameState->PlayerState.minY = y;
this->GameState->PlayerState.maxX = w;
this->GameState->PlayerState.maxY = h;
LogManager& l = LogManager::getInstance();
l.writeLog("setGameBounds = %d, %d, %d, %d", x, y, w, h);
}
}<|endoftext|> |
<commit_before>#include <fstream>
#include <iostream>
#include <omp.h>
#include <stdio.h>
#include <string>
#include <time.h>
#include "Neural_Networks.h"
using namespace std;
void Read_MNIST(string training_set_images, string training_set_labels, string test_set_images, string test_set_labels, int number_training, int number_test, float **input, float **output) {
ifstream file(training_set_images, ifstream::binary);
if (file.is_open()) {
for (int h = 0, value; h < 4; h++) {
file.read((char*)(&value), sizeof(int));
}
for (int h = 0; h < number_training; h++) {
unsigned char pixel;
for (int j = 0; j < 28 * 28; j++) {
file.read((char*)(&pixel), 1);
input[h][j] = pixel / 255.0;
}
}
file.close();
}
else {
cerr << "[Read_MNIST], " + training_set_images + " not found" << endl;
}
file.open(training_set_labels, ifstream::binary);
if (file.is_open()) {
for (int h = 0, value; h < 2; h++) {
file.read((char*)(&value), sizeof(int));
}
for (int h = 0; h < number_training; h++) {
unsigned char label;
file.read((char*)(&label), 1);
for (int j = 0; j < 10; j++) {
output[h][j] = (j == label);
}
}
file.close();
}
else {
cerr << "[Read_MNIST], " + training_set_labels + " not found" << endl;
}
file.open(test_set_images, ifstream::binary);
if (file.is_open()) {
for (int h = 0, value; h < 4; h++) {
file.read((char*)(&value), sizeof(int));
}
for (int h = number_training; h < number_training + number_test; h++) {
unsigned char pixel;
for (int j = 0; j < 28 * 28; j++) {
file.read((char*)(&pixel), 1);
input[h][j] = pixel / 255.0;
}
}
file.close();
}
else {
cerr << "[Read_MNIST], " + test_set_images + " not found" << endl;
}
file.open(test_set_labels, ifstream::binary);
if (file.is_open()) {
for (int h = 0, value; h < 2; h++) {
file.read((char*)(&value), sizeof(int));
}
for (int h = number_training; h < number_training + number_test; h++) {
unsigned char label;
file.read((char*)(&label), 1);
for (int j = 0; j < 10; j++) {
output[h][j] = (j == label);
}
}
file.close();
}
else {
cerr << "[Read_MNIST], " + test_set_labels + " not found" << endl;
}
}
int main() {
int batch_size = 128;
int epochs = 30;
int number_threads = 6;
int number_training = 60000;
int number_test = 10000;
int number_nodes[] = { 784, 10 };
float **x_data = new float*[number_training + number_test];
float **y_data = new float*[number_training + number_test];
float **x_train = x_data;
float **y_train = y_data;
float **x_test = &x_data[number_training];
float **y_test = &y_data[number_training];
double learning_rate = 0.1;
double momentum = 0.9;
string path;
Neural_Networks NN = Neural_Networks();
cout << "path where MNIST handwritten digits dataset is : ";
getline(cin, path);
for (int h = 0; h < number_training + number_test; h++) {
x_data[h] = new float[number_nodes[0]];
y_data[h] = new float[number_nodes[1]];
}
Read_MNIST(path + "train-images.idx3-ubyte", path + "train-labels.idx1-ubyte", path + "t10k-images.idx3-ubyte", path + "t10k-labels.idx1-ubyte", number_training, number_test, x_data, y_data);
omp_set_num_threads(number_threads);
srand(0);
NN.Add( 1, 28, 28);
NN.Add(24, 12, 12)->Activation(Activation::relu);
NN.Add(512)->Activation(Activation::relu);
NN.Add(number_nodes[1])->Activation(Activation::softmax);
NN.Connect(1, 0, "W,kernel(5x5),stride(2x2)")->Initialize(0.1);
NN.Connect(2, 1, "W")->Initialize(0.01);
NN.Connect(3, 2, "W")->Initialize(0.01);
NN.Compile(Loss::cross_entropy, new Optimizer(Optimizer::Nesterov(learning_rate, momentum)));
for (int e = 0, time = clock(); e < epochs; e++) {
int score[2] = { 0, };
float **_input = new float*[batch_size];
float **output = new float*[batch_size];
double loss[2] = { NN.Fit(x_train, y_train, number_training, batch_size), NN.Evaluate(x_test, y_test, number_test, batch_size) };
for (int h = 0; h < batch_size; h++) {
output[h] = new float[number_nodes[1]];
}
for (int h = 0, i = 0; i < number_training + number_test; i++) {
_input[h] = x_data[i];
if (++h == batch_size || i == number_training + number_test - 1) {
NN.Predict(_input, output, h);
for (int argmax, index = i - h + 1; --h >= 0;) {
double max = 0;
for (int j = 0; j < number_nodes[1]; j++) {
if (j == 0 || max < output[h][j]) {
max = output[h][argmax = j];
}
}
score[(index + h < number_training) ? (0) : (1)] += (int)y_data[index + h][argmax];
}
h = 0;
}
}
printf("loss: %.4f / %.4f accuracy: %.4f / %.4f step %d %.2f sec\n", loss[0], loss[1], 1.0 * score[0] / number_training, 1.0 * score[1] / number_test, e + 1, (double)(clock() - time) / CLOCKS_PER_SEC);
for (int h = 0; h < batch_size; h++) {
delete[] output[h];
}
delete[] _input;
delete[] output;
}
for (int i = 0; i < number_training + number_test; i++) {
delete[] x_data[i];
delete[] y_data[i];
}
delete[] x_data;
delete[] y_data;
}<commit_msg>Update main.cpp<commit_after>#include <fstream>
#include <iostream>
#include <omp.h>
#include <stdio.h>
#include <string>
#include <time.h>
#include "Neural_Networks.h"
using namespace std;
void Read_MNIST(string training_set_images, string training_set_labels, string test_set_images, string test_set_labels, int number_training, int number_test, float **input, float **output) {
ifstream file(training_set_images, ifstream::binary);
if (file.is_open()) {
for (int h = 0, value; h < 4; h++) {
file.read((char*)(&value), sizeof(int));
}
for (int h = 0; h < number_training; h++) {
unsigned char pixel;
for (int j = 0; j < 28 * 28; j++) {
file.read((char*)(&pixel), 1);
input[h][j] = pixel / 255.0;
}
}
file.close();
}
else {
cerr << "[Read_MNIST], " + training_set_images + " not found" << endl;
}
file.open(training_set_labels, ifstream::binary);
if (file.is_open()) {
for (int h = 0, value; h < 2; h++) {
file.read((char*)(&value), sizeof(int));
}
for (int h = 0; h < number_training; h++) {
unsigned char label;
file.read((char*)(&label), 1);
for (int j = 0; j < 10; j++) {
output[h][j] = (j == label);
}
}
file.close();
}
else {
cerr << "[Read_MNIST], " + training_set_labels + " not found" << endl;
}
file.open(test_set_images, ifstream::binary);
if (file.is_open()) {
for (int h = 0, value; h < 4; h++) {
file.read((char*)(&value), sizeof(int));
}
for (int h = number_training; h < number_training + number_test; h++) {
unsigned char pixel;
for (int j = 0; j < 28 * 28; j++) {
file.read((char*)(&pixel), 1);
input[h][j] = pixel / 255.0;
}
}
file.close();
}
else {
cerr << "[Read_MNIST], " + test_set_images + " not found" << endl;
}
file.open(test_set_labels, ifstream::binary);
if (file.is_open()) {
for (int h = 0, value; h < 2; h++) {
file.read((char*)(&value), sizeof(int));
}
for (int h = number_training; h < number_training + number_test; h++) {
unsigned char label;
file.read((char*)(&label), 1);
for (int j = 0; j < 10; j++) {
output[h][j] = (j == label);
}
}
file.close();
}
else {
cerr << "[Read_MNIST], " + test_set_labels + " not found" << endl;
}
}
int main() {
int batch_size = 128;
int epochs = 30;
int number_threads = 4;
int number_training = 60000;
int number_test = 10000;
int number_nodes[] = { 784, 10 };
float **x_data = new float*[number_training + number_test];
float **y_data = new float*[number_training + number_test];
float **x_train = x_data;
float **y_train = y_data;
float **x_test = &x_data[number_training];
float **y_test = &y_data[number_training];
double learning_rate = 0.1;
double momentum = 0.9;
string path;
Neural_Networks NN = Neural_Networks();
cout << "path where MNIST handwritten digits dataset is : ";
getline(cin, path);
for (int h = 0; h < number_training + number_test; h++) {
x_data[h] = new float[number_nodes[0]];
y_data[h] = new float[number_nodes[1]];
}
Read_MNIST(path + "train-images.idx3-ubyte", path + "train-labels.idx1-ubyte", path + "t10k-images.idx3-ubyte", path + "t10k-labels.idx1-ubyte", number_training, number_test, x_data, y_data);
omp_set_num_threads(number_threads);
srand(0);
NN.Add(1, 28, 28);
NN.Add(24, 12, 12)->Activation(Activation::relu);
NN.Add(512)->Activation(Activation::relu);
NN.Add(number_nodes[1])->Activation(Activation::softmax);
NN.Connect(1, 0, "W,kernel(5x5),stride(2x2)")->Initializer(RandomUniform(-0.1, 0.1));
NN.Connect(2, 1, "W")->Initializer(RandomUniform(-0.01, 0.01));
NN.Connect(3, 2, "W")->Initializer(RandomUniform(-0.01, 0.01));
NN.Compile(Loss::cross_entropy, Optimizer(Nesterov(learning_rate, momentum)));
for (int e = 0, time = clock(); e < epochs; e++) {
int score[2] = { 0, };
float **_input = new float*[batch_size];
float **output = new float*[batch_size];
double loss[2] = { NN.Fit(x_train, y_train, number_training, batch_size), NN.Evaluate(x_test, y_test, number_test, batch_size) };
for (int h = 0; h < batch_size; h++) {
output[h] = new float[number_nodes[1]];
}
for (int h = 0, i = 0; i < number_training + number_test; i++) {
_input[h] = x_data[i];
if (++h == batch_size || i == number_training + number_test - 1) {
NN.Predict(_input, output, h);
for (int argmax, index = i - h + 1; --h >= 0;) {
double max = 0;
for (int j = 0; j < number_nodes[1]; j++) {
if (j == 0 || max < output[h][j]) {
max = output[h][argmax = j];
}
}
score[(index + h < number_training) ? (0) : (1)] += (int)y_data[index + h][argmax];
}
h = 0;
}
}
printf("loss: %.4f / %.4f accuracy: %.4f / %.4f step %d %.2f sec\n", loss[0], loss[1], 1.0 * score[0] / number_training, 1.0 * score[1] / number_test, e + 1, (double)(clock() - time) / CLOCKS_PER_SEC);
for (int h = 0; h < batch_size; h++) {
delete[] output[h];
}
delete[] _input;
delete[] output;
}
for (int i = 0; i < number_training + number_test; i++) {
delete[] x_data[i];
delete[] y_data[i];
}
delete[] x_data;
delete[] y_data;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2014 MUGEN SAS
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <osc/reader/types/OscBlob.h>
#include <tools/ByteBuffer.h>
#include <osc/exceptions/CharConversionException.h>
#include <osc/exceptions/DoubleConversionException.h>
#include <osc/exceptions/IntegerConversionException.h>
#include <osc/exceptions/FloatConversionException.h>
#include <osc/exceptions/LongConversionException.h>
#include <osc/exceptions/StringConversionException.h>
OscBlob::OscBlob(ByteBuffer* packet, qint32 pos)
: OscValue('b', packet, pos)
{
try
{
get();
}
catch (const QException& e)
{
throw e;
}
}
/**
* Returns the blob data.
*
* @return a blob data.
*/
QByteArray& OscBlob::get()
{
try
{
mBlobSize = mPacket->getInt(mPos);
mData = QByteArray(mBlobSize, 0);
mPacket->setPosition(mPos + 4);
mPacket->get(&mData, 0, mBlobSize);
return mData;
}
catch (const QException& e)
{
throw e;
}
}
bool OscBlob::toBoolean()
{
return (get().length() != 0);
}
QByteArray OscBlob::toBytes()
{
return get();
}
char OscBlob::toChar()
{
throw CharConversionException();
}
double OscBlob::toDouble()
{
throw DoubleConversionException();
}
float OscBlob::toFloat()
{
throw FloatConversionException();
}
qint32 OscBlob::toInteger()
{
throw IntegerConversionException();
}
qint64 OscBlob::toLong()
{
throw LongConversionException();
}
QString OscBlob::toString()
{
throw StringConversionException();
}
<commit_msg>fix: Blob Reading<commit_after>/*
* Copyright (c) 2014 MUGEN SAS
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <osc/reader/types/OscBlob.h>
#include <tools/ByteBuffer.h>
#include <osc/exceptions/CharConversionException.h>
#include <osc/exceptions/DoubleConversionException.h>
#include <osc/exceptions/IntegerConversionException.h>
#include <osc/exceptions/FloatConversionException.h>
#include <osc/exceptions/LongConversionException.h>
#include <osc/exceptions/StringConversionException.h>
OscBlob::OscBlob(ByteBuffer* packet, qint32 pos)
: OscValue('b', packet, pos)
{
try
{
get();
}
catch (const QException& e)
{
throw e;
}
}
/**
* Returns the blob data.
*
* @return a blob data.
*/
QByteArray& OscBlob::get()
{
try
{
mBlobSize = mPacket->getInt(mPos);
mData = QByteArray(mBlobSize, 0);
mPacket->setPosition(mPos + 4);
mPacket->get(&mData, 0, mBlobSize);
qint32 alignedEnd = (mPos + 4 + mBlobSize + 4) & ~((qint32)0x03);
mPacket->setPosition(alignedEnd);
return mData;
}
catch (const QException& e)
{
throw e;
}
}
bool OscBlob::toBoolean()
{
return (get().length() != 0);
}
QByteArray OscBlob::toBytes()
{
return get();
}
char OscBlob::toChar()
{
throw CharConversionException();
}
double OscBlob::toDouble()
{
throw DoubleConversionException();
}
float OscBlob::toFloat()
{
throw FloatConversionException();
}
qint32 OscBlob::toInteger()
{
throw IntegerConversionException();
}
qint64 OscBlob::toLong()
{
throw LongConversionException();
}
QString OscBlob::toString()
{
throw StringConversionException();
}
<|endoftext|> |
<commit_before>//
// main.cpp
// parsetool
//
// Created by Andrew Hunter on 24/09/2011.
// Copyright 2011-2012 Andrew Hunter. All rights reserved.
//
#include "TameParse/TameParse.h"
#include "boost_console.h"
#include <iostream>
#include <memory>
using namespace std;
using namespace dfa;
using namespace lr;
using namespace tameparse;
using namespace language;
using namespace compiler;
int main (int argc, const char * argv[])
{
// Create the console
boost_console console(argc, argv);
console_container cons(&console, false);
try {
// Give up if the console is set not to start
if (!console.can_start()) {
return 1;
}
// Startup message
console.message_stream() << L"TameParse " << version::major_version << "." << version::minor_version << "." << version::revision << endl;
console.verbose_stream() << endl;
// Parse the input file
parser_stage parserStage(cons, console.input_file());
parserStage.compile();
// Stop if we have an error
if (console.exit_code()) {
return console.exit_code();
}
// The definition file should exist
if (!parserStage.definition_file().item()) {
console.report_error(error(error::sev_bug, console.input_file(), L"BUG_NO_FILE_DATA", L"File did not produce any data", position(-1, -1, -1)));
return error::sev_bug;
}
// Parse any imported files
import_stage importStage(cons, console.input_file(), parserStage.definition_file());
importStage.compile();
// Stop if we have an error
if (console.exit_code()) {
return console.exit_code();
}
// Run any tests that were specified
if (!console.get_option(L"run-tests").empty()) {
test_stage tests(cons, console.input_file(), parserStage.definition_file(), &importStage);
tests.compile();
// Stop if we have an error
if (console.exit_code()) {
return console.exit_code();
}
// If --run-tests is specified and no explicit options for generating an output file is supplied then stop here
if (console.get_option(L"output-file").empty()
&& console.get_option(L"start-symbol").empty()
&& console.get_option(L"output-language").empty()
&& console.get_option(L"test").empty()
&& console.get_option(L"show-parser").empty()) {
return console.exit_code();
}
}
// Convert to grammars & NDFAs
language_builder_stage builderStage(cons, console.input_file(), &importStage);
builderStage.compile();
// Stop if we have an error
if (console.exit_code()) {
return console.exit_code();
}
// Work out the name of the language to build and the start symbols
wstring buildLanguageName = console.get_option(L"compile-language");
wstring buildClassName = console.get_option(L"class-name");
vector<wstring> startSymbols = console.get_option_list(L"start-symbol");
wstring targetLanguage = console.get_option(L"target-language");
wstring buildNamespaceName = console.get_option(L"namespace-name");
position parseBlockPosition = position(-1, -1, -1);
// Use the options by default
if (console.get_option(L"compile-language").empty()) {
// TODO: get information from the parser block
// TODO: the class-name option overrides the name specified in the parser block (but gives a warning)
// TODO: use the position of the parser block to report
// TODO: deal with multiple parser blocks somehow (error? generate multiple classes?)
}
// If there is only one language in the original file and none specified, then we will generate that
if (buildLanguageName.empty()) {
int languageCount = 0;
// Find all of the language blocks
for (definition_file::iterator defnBlock = parserStage.definition_file()->begin(); defnBlock != parserStage.definition_file()->end(); ++defnBlock) {
if ((*defnBlock)->language()) {
++languageCount;
if (languageCount > 1) {
// Multiple languages: can't infer one
buildLanguageName.clear();
break;
} else {
// This is the first language: use its identifier as the language to build
buildLanguageName = (*defnBlock)->language()->identifier();
}
}
}
// Tell the user about this
if (!buildLanguageName.empty()) {
wstringstream msg;
msg << L"Language name not explicitly specified: will use '" << buildLanguageName << L"'";
console.report_error(error(error::sev_info, console.input_file(), L"INFERRED_LANGUAGE", msg.str(), parseBlockPosition));
}
}
// Error if there is no language specified
if (buildLanguageName.empty()) {
console.report_error(error(error::sev_error, console.input_file(), L"NO_LANGUAGE_SPECIFIED", L"Could not determine which language block to compile", parseBlockPosition));
return error::sev_error;
}
// Infer the class name to use if none is specified (same as the language name)
if (buildClassName.empty()) {
buildClassName = buildLanguageName;
}
// Get the language that we're going to compile
const language_block* compileLanguage = importStage.language_with_name(buildLanguageName);
language_stage* compileLanguageStage = builderStage.language_with_name(buildLanguageName);
if (!compileLanguage || !compileLanguageStage) {
// The language could not be found
wstringstream msg;
msg << L"Could not find the target language '" << buildLanguageName << L"'";
console.report_error(error(error::sev_error, console.input_file(), L"MISSING_TARGET_LANGUAGE", msg.str(), parseBlockPosition));
return error::sev_error;
}
// Report any unused symbols in the language
compileLanguageStage->report_unused_symbols();
// Infer the start symbols if there are none
if (startSymbols.empty()) {
// TODO: Use the first nonterminal defined in the language block
// TODO: warn if we establish a start symbol this way
}
if (startSymbols.empty()) {
// Error if we can't find any start symbols at all
console.report_error(error(error::sev_error, console.input_file(), L"NO_START_SYMBOLS", L"Could not determine a start symbol for the language (use the start-symbol option to specify one manually)", parseBlockPosition));
return error::sev_error;
}
// Generate the lexer for the target language
lexer_stage lexerStage(cons, importStage.file_with_language(buildLanguageName), compileLanguageStage);
lexerStage.compile();
// Stop if we have an error
if (console.exit_code()) {
return console.exit_code();
}
// Generate the parser
lr_parser_stage lrParserStage(cons, importStage.file_with_language(buildLanguageName), compileLanguageStage, &lexerStage, startSymbols);
lrParserStage.compile();
// Write the parser out if requested
if (!console.get_option(L"show-parser").empty() || !console.get_option(L"show-parser-closure").empty()) {
wcout << endl << L"== Parser tables:" << endl << formatter::to_string(*lrParserStage.get_parser(), *compileLanguageStage->grammar(), *compileLanguageStage->terminals(), !console.get_option(L"show-parser-closure").empty()) << endl;
}
// Display the propagation tables if requested
if (!console.get_option(L"show-propagation").empty()) {
// Get the parser builder
lalr_builder* builder = lrParserStage.get_parser();
typedef lalr_builder::lr_item_id lr_item_id;
if (builder) {
// Write out a header
wcout << endl << L"== Symbol propagation:" << endl;
// Iterate through the states
for (int stateId = 0; stateId < builder->machine().count_states(); stateId++) {
const lalr_state& state = *builder->machine().state_with_id(stateId);
// Write out the state ID
wcout << L"State #" << stateId << endl;
// Go through the items
for (int itemId = 0; itemId < state.count_items(); itemId++) {
// Get the spontaneous lookahead generation for this item
const set<lr_item_id>& spontaneous = builder->spontaneous_for_item(stateId, itemId);
const set<lr_item_id>& propagate = builder->propagations_for_item(stateId, itemId);
// Ignore any items that have no items in them
if (spontaneous.empty() && propagate.empty()) continue;
wcout << L" "
<< formatter::to_string(*state[itemId], *compileLanguageStage->grammar(), *compileLanguageStage->terminals())
<< L" " << formatter::to_string(state.lookahead_for(itemId), *compileLanguageStage->grammar(), *compileLanguageStage->terminals())
<< endl;
// Write out which items generate spontaneous lookaheads
for (set<lr_item_id>::const_iterator spont = spontaneous.begin(); spont != spontaneous.end(); spont++) {
wcout << L" Spontaneous -> state #" << spont->first << ": "
<< formatter::to_string(*(*builder->machine().state_with_id(spont->first))[spont->second], *compileLanguageStage->grammar(), *compileLanguageStage->terminals())
<< endl;
}
// Write out which items propagate lookaheads
for (set<lr_item_id>::const_iterator prop = propagate.begin(); prop != propagate.end(); prop++) {
wcout << L" Propagate -> state #" << prop->first << ": "
<< formatter::to_string(*(*builder->machine().state_with_id(prop->first))[prop->second], *compileLanguageStage->grammar(), *compileLanguageStage->terminals())
<< endl;
}
}
}
}
}
// Stop if we have an error
if (console.exit_code()) {
return console.exit_code();
}
// The --test option sets the target language to 'test'
if (!console.get_option(L"test").empty()) {
targetLanguage = L"test";
}
// Target language is C++ if no language is specified
if (targetLanguage.empty()) {
targetLanguage = L"cplusplus";
}
// Work out the prefix filename
wstring prefixFilename = console.get_option(L"output-language");
if (prefixFilename.empty()) {
// Derive from the input file
// This works provided the target language
prefixFilename = console.input_file();
}
// Create the output stage
auto_ptr<output_stage> outputStage(NULL);
if (targetLanguage == L"cplusplus") {
// Use the C++ language generator
outputStage = auto_ptr<output_stage>(new output_cplusplus(cons, importStage.file_with_language(buildLanguageName), &lexerStage, compileLanguageStage, &lrParserStage, prefixFilename, buildClassName, buildNamespaceName));
} else if (targetLanguage == L"test") {
// Special case: read from stdin, and try to parse the source language
ast_parser parser(*lrParserStage.get_tables());
// Create the parser
lexeme_stream* stdinStream = lexerStage.get_lexer()->create_stream_from(wcin);
ast_parser::state* stdInParser = parser.create_parser(new ast_parser_actions(stdinStream));
// Parse stdin
if (stdInParser->parse()) {
console.verbose_stream() << formatter::to_string(*stdInParser->get_item(), *compileLanguageStage->grammar(), *compileLanguageStage->terminals()) << endl;
} else {
position failPos(-1, -1, -1);
if (stdInParser->look().item()) {
failPos = stdInParser->look()->pos();
}
console.report_error(error(error::sev_error, L"stdin", L"TEST_PARSER_ERROR", L"Syntax error", failPos));
}
} else {
// Unknown target language
wstringstream msg;
msg << L"Output language '" << targetLanguage << L"' is not known";
console.report_error(error(error::sev_error, console.input_file(), L"UNKNOWN_OUTPUT_LANGUAGE_TYPE", msg.str(), position(-1, -1, -1)));
return error::sev_error;
}
// Compile the final output
if (outputStage.get()) {
outputStage->compile();
}
// Done
return console.exit_code();
} catch (...) {
console.report_error(error(error::sev_bug, L"", L"BUG_UNCAUGHT_EXCEPTION", L"Uncaught exception", position(-1, -1, -1)));
throw;
}
}
<commit_msg>Changed lr_item_id from a pair to a structure with explicit field names; this is more verbose but makes the code much more readable<commit_after>//
// main.cpp
// parsetool
//
// Created by Andrew Hunter on 24/09/2011.
// Copyright 2011-2012 Andrew Hunter. All rights reserved.
//
#include "TameParse/TameParse.h"
#include "boost_console.h"
#include <iostream>
#include <memory>
using namespace std;
using namespace dfa;
using namespace lr;
using namespace tameparse;
using namespace language;
using namespace compiler;
int main (int argc, const char * argv[])
{
// Create the console
boost_console console(argc, argv);
console_container cons(&console, false);
try {
// Give up if the console is set not to start
if (!console.can_start()) {
return 1;
}
// Startup message
console.message_stream() << L"TameParse " << version::major_version << "." << version::minor_version << "." << version::revision << endl;
console.verbose_stream() << endl;
// Parse the input file
parser_stage parserStage(cons, console.input_file());
parserStage.compile();
// Stop if we have an error
if (console.exit_code()) {
return console.exit_code();
}
// The definition file should exist
if (!parserStage.definition_file().item()) {
console.report_error(error(error::sev_bug, console.input_file(), L"BUG_NO_FILE_DATA", L"File did not produce any data", position(-1, -1, -1)));
return error::sev_bug;
}
// Parse any imported files
import_stage importStage(cons, console.input_file(), parserStage.definition_file());
importStage.compile();
// Stop if we have an error
if (console.exit_code()) {
return console.exit_code();
}
// Run any tests that were specified
if (!console.get_option(L"run-tests").empty()) {
test_stage tests(cons, console.input_file(), parserStage.definition_file(), &importStage);
tests.compile();
// Stop if we have an error
if (console.exit_code()) {
return console.exit_code();
}
// If --run-tests is specified and no explicit options for generating an output file is supplied then stop here
if (console.get_option(L"output-file").empty()
&& console.get_option(L"start-symbol").empty()
&& console.get_option(L"output-language").empty()
&& console.get_option(L"test").empty()
&& console.get_option(L"show-parser").empty()) {
return console.exit_code();
}
}
// Convert to grammars & NDFAs
language_builder_stage builderStage(cons, console.input_file(), &importStage);
builderStage.compile();
// Stop if we have an error
if (console.exit_code()) {
return console.exit_code();
}
// Work out the name of the language to build and the start symbols
wstring buildLanguageName = console.get_option(L"compile-language");
wstring buildClassName = console.get_option(L"class-name");
vector<wstring> startSymbols = console.get_option_list(L"start-symbol");
wstring targetLanguage = console.get_option(L"target-language");
wstring buildNamespaceName = console.get_option(L"namespace-name");
position parseBlockPosition = position(-1, -1, -1);
// Use the options by default
if (console.get_option(L"compile-language").empty()) {
// TODO: get information from the parser block
// TODO: the class-name option overrides the name specified in the parser block (but gives a warning)
// TODO: use the position of the parser block to report
// TODO: deal with multiple parser blocks somehow (error? generate multiple classes?)
}
// If there is only one language in the original file and none specified, then we will generate that
if (buildLanguageName.empty()) {
int languageCount = 0;
// Find all of the language blocks
for (definition_file::iterator defnBlock = parserStage.definition_file()->begin(); defnBlock != parserStage.definition_file()->end(); ++defnBlock) {
if ((*defnBlock)->language()) {
++languageCount;
if (languageCount > 1) {
// Multiple languages: can't infer one
buildLanguageName.clear();
break;
} else {
// This is the first language: use its identifier as the language to build
buildLanguageName = (*defnBlock)->language()->identifier();
}
}
}
// Tell the user about this
if (!buildLanguageName.empty()) {
wstringstream msg;
msg << L"Language name not explicitly specified: will use '" << buildLanguageName << L"'";
console.report_error(error(error::sev_info, console.input_file(), L"INFERRED_LANGUAGE", msg.str(), parseBlockPosition));
}
}
// Error if there is no language specified
if (buildLanguageName.empty()) {
console.report_error(error(error::sev_error, console.input_file(), L"NO_LANGUAGE_SPECIFIED", L"Could not determine which language block to compile", parseBlockPosition));
return error::sev_error;
}
// Infer the class name to use if none is specified (same as the language name)
if (buildClassName.empty()) {
buildClassName = buildLanguageName;
}
// Get the language that we're going to compile
const language_block* compileLanguage = importStage.language_with_name(buildLanguageName);
language_stage* compileLanguageStage = builderStage.language_with_name(buildLanguageName);
if (!compileLanguage || !compileLanguageStage) {
// The language could not be found
wstringstream msg;
msg << L"Could not find the target language '" << buildLanguageName << L"'";
console.report_error(error(error::sev_error, console.input_file(), L"MISSING_TARGET_LANGUAGE", msg.str(), parseBlockPosition));
return error::sev_error;
}
// Report any unused symbols in the language
compileLanguageStage->report_unused_symbols();
// Infer the start symbols if there are none
if (startSymbols.empty()) {
// TODO: Use the first nonterminal defined in the language block
// TODO: warn if we establish a start symbol this way
}
if (startSymbols.empty()) {
// Error if we can't find any start symbols at all
console.report_error(error(error::sev_error, console.input_file(), L"NO_START_SYMBOLS", L"Could not determine a start symbol for the language (use the start-symbol option to specify one manually)", parseBlockPosition));
return error::sev_error;
}
// Generate the lexer for the target language
lexer_stage lexerStage(cons, importStage.file_with_language(buildLanguageName), compileLanguageStage);
lexerStage.compile();
// Stop if we have an error
if (console.exit_code()) {
return console.exit_code();
}
// Generate the parser
lr_parser_stage lrParserStage(cons, importStage.file_with_language(buildLanguageName), compileLanguageStage, &lexerStage, startSymbols);
lrParserStage.compile();
// Write the parser out if requested
if (!console.get_option(L"show-parser").empty() || !console.get_option(L"show-parser-closure").empty()) {
wcout << endl << L"== Parser tables:" << endl << formatter::to_string(*lrParserStage.get_parser(), *compileLanguageStage->grammar(), *compileLanguageStage->terminals(), !console.get_option(L"show-parser-closure").empty()) << endl;
}
// Display the propagation tables if requested
if (!console.get_option(L"show-propagation").empty()) {
// Get the parser builder
lalr_builder* builder = lrParserStage.get_parser();
typedef lalr_builder::lr_item_id lr_item_id;
if (builder) {
// Write out a header
wcout << endl << L"== Symbol propagation:" << endl;
// Iterate through the states
for (int stateId = 0; stateId < builder->machine().count_states(); stateId++) {
const lalr_state& state = *builder->machine().state_with_id(stateId);
// Write out the state ID
wcout << L"State #" << stateId << endl;
// Go through the items
for (int itemId = 0; itemId < state.count_items(); itemId++) {
// Get the spontaneous lookahead generation for this item
const set<lr_item_id>& spontaneous = builder->spontaneous_for_item(stateId, itemId);
const set<lr_item_id>& propagate = builder->propagations_for_item(stateId, itemId);
// Ignore any items that have no items in them
if (spontaneous.empty() && propagate.empty()) continue;
wcout << L" "
<< formatter::to_string(*state[itemId], *compileLanguageStage->grammar(), *compileLanguageStage->terminals())
<< L" " << formatter::to_string(state.lookahead_for(itemId), *compileLanguageStage->grammar(), *compileLanguageStage->terminals())
<< endl;
// Write out which items generate spontaneous lookaheads
for (set<lr_item_id>::const_iterator spont = spontaneous.begin(); spont != spontaneous.end(); spont++) {
wcout << L" Spontaneous -> state #" << spont->state_id << ": "
<< formatter::to_string(*(*builder->machine().state_with_id(spont->state_id))[spont->item_id], *compileLanguageStage->grammar(), *compileLanguageStage->terminals())
<< endl;
}
// Write out which items propagate lookaheads
for (set<lr_item_id>::const_iterator prop = propagate.begin(); prop != propagate.end(); prop++) {
wcout << L" Propagate -> state #" << prop->state_id << ": "
<< formatter::to_string(*(*builder->machine().state_with_id(prop->state_id))[prop->item_id], *compileLanguageStage->grammar(), *compileLanguageStage->terminals())
<< endl;
}
}
}
}
}
// Stop if we have an error
if (console.exit_code()) {
return console.exit_code();
}
// The --test option sets the target language to 'test'
if (!console.get_option(L"test").empty()) {
targetLanguage = L"test";
}
// Target language is C++ if no language is specified
if (targetLanguage.empty()) {
targetLanguage = L"cplusplus";
}
// Work out the prefix filename
wstring prefixFilename = console.get_option(L"output-language");
if (prefixFilename.empty()) {
// Derive from the input file
// This works provided the target language
prefixFilename = console.input_file();
}
// Create the output stage
auto_ptr<output_stage> outputStage(NULL);
if (targetLanguage == L"cplusplus") {
// Use the C++ language generator
outputStage = auto_ptr<output_stage>(new output_cplusplus(cons, importStage.file_with_language(buildLanguageName), &lexerStage, compileLanguageStage, &lrParserStage, prefixFilename, buildClassName, buildNamespaceName));
} else if (targetLanguage == L"test") {
// Special case: read from stdin, and try to parse the source language
ast_parser parser(*lrParserStage.get_tables());
// Create the parser
lexeme_stream* stdinStream = lexerStage.get_lexer()->create_stream_from(wcin);
ast_parser::state* stdInParser = parser.create_parser(new ast_parser_actions(stdinStream));
// Parse stdin
if (stdInParser->parse()) {
console.verbose_stream() << formatter::to_string(*stdInParser->get_item(), *compileLanguageStage->grammar(), *compileLanguageStage->terminals()) << endl;
} else {
position failPos(-1, -1, -1);
if (stdInParser->look().item()) {
failPos = stdInParser->look()->pos();
}
console.report_error(error(error::sev_error, L"stdin", L"TEST_PARSER_ERROR", L"Syntax error", failPos));
}
} else {
// Unknown target language
wstringstream msg;
msg << L"Output language '" << targetLanguage << L"' is not known";
console.report_error(error(error::sev_error, console.input_file(), L"UNKNOWN_OUTPUT_LANGUAGE_TYPE", msg.str(), position(-1, -1, -1)));
return error::sev_error;
}
// Compile the final output
if (outputStage.get()) {
outputStage->compile();
}
// Done
return console.exit_code();
} catch (...) {
console.report_error(error(error::sev_bug, L"", L"BUG_UNCAUGHT_EXCEPTION", L"Uncaught exception", position(-1, -1, -1)));
throw;
}
}
<|endoftext|> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.