text
stringlengths
54
60.6k
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkExtractGrid.h Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/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 notice for more information. =========================================================================*/ #include "vtkExtractStructuredGridHelper.h" // VTK includes #include "vtkBoundingBox.h" #include "vtkCellData.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkPoints.h" #include "vtkStructuredData.h" #include "vtkStructuredExtent.h" // C/C++ includes #include <cassert> #include <vector> // Some usefull extent macros #define IMIN(ext) ext[0] #define IMAX(ext) ext[1] #define JMIN(ext) ext[2] #define JMAX(ext) ext[3] #define KMIN(ext) ext[4] #define KMAX(ext) ext[5] #define I(ijk) ijk[0] #define J(ijk) ijk[1] #define K(ijk) ijk[2] namespace vtk { namespace detail { struct vtkIndexMap { std::vector<int> Mapping[3]; }; } // End namespace detail } // End namespace vtk vtkStandardNewMacro(vtkExtractStructuredGridHelper); //----------------------------------------------------------------------------- vtkExtractStructuredGridHelper::vtkExtractStructuredGridHelper() { this->IndexMap = new vtk::detail::vtkIndexMap; this->Invalidate(); } //----------------------------------------------------------------------------- vtkExtractStructuredGridHelper::~vtkExtractStructuredGridHelper() { delete this->IndexMap; } //----------------------------------------------------------------------------- void vtkExtractStructuredGridHelper::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } //----------------------------------------------------------------------------- void vtkExtractStructuredGridHelper::Invalidate() { this->OutputWholeExtent[0]= 0; this->OutputWholeExtent[1]=-1; this->OutputWholeExtent[2]= 0; this->OutputWholeExtent[3]=-1; this->OutputWholeExtent[4]= 0; this->OutputWholeExtent[5]=-1; } //----------------------------------------------------------------------------- void vtkExtractStructuredGridHelper::Initialize( int voi[6], int wholeExtent[6], int sampleRate[3], bool includeBoundary) { assert("pre: NULL index map" && (this->IndexMap != NULL) ); vtkBoundingBox wExtB(wholeExtent[0], wholeExtent[1], wholeExtent[2], wholeExtent[3], wholeExtent[4], wholeExtent[5]); vtkBoundingBox voiB(voi[0],voi[1],voi[2],voi[3],voi[4],voi[5]); if(!wExtB.Intersects(voiB)) { for(int i=0; i < 3; ++i) { this->IndexMap->Mapping[ i ].clear(); } this->Invalidate(); return; } // Clamp VOI to Whole Extent vtkStructuredExtent::Clamp(voi,wholeExtent); // Create mapping between output extent and input extent. // Compute the output whole extent in the process. for(int dim=0; dim < 3; ++dim) { this->IndexMap->Mapping[dim].resize(voi[2*dim+1]-voi[2*dim]+2); int idx,i; for(idx=0, i=voi[2*dim]; i <= voi[2*dim+1]; i+=sampleRate[dim]) { this->IndexMap->Mapping[dim][idx++] = i; } // END for all points in this dimension, strided by the sample rate if(includeBoundary && this->IndexMap->Mapping[dim][idx-1] != voi[2*dim+1]) { this->IndexMap->Mapping[dim][idx++] = voi[2*dim+1]; } this->IndexMap->Mapping[dim].resize(idx); // Update output whole extent this->OutputWholeExtent[2*dim] = 0; this->OutputWholeExtent[2*dim+1] = static_cast<int>( this->IndexMap->Mapping[dim].size()-1 ); } // END for all dimensions } //----------------------------------------------------------------------------- int vtkExtractStructuredGridHelper::GetMapping(const int dim, const int i) { // Sanity Checks assert( "pre: dimension dim is out-of-bounds!" && (dim >= 0) && (dim < 3) ); assert( "pre: point index out-of-bounds!" && (i >= 0) && (i < this->GetSize(dim) ) ); return( this->IndexMap->Mapping[ dim ][ i ] ); } //----------------------------------------------------------------------------- int vtkExtractStructuredGridHelper::GetSize(const int dim) { assert("pre: dimension dim is out-of-bounds!" && (dim >= 0) && (dim < 3) ); return( static_cast<int>( this->IndexMap->Mapping[ dim ].size() ) ); } //----------------------------------------------------------------------------- namespace { int roundToInt(double r) { return r > 0.0 ? r + 0.5 : r - 0.5; } } //----------------------------------------------------------------------------- void vtkExtractStructuredGridHelper::ComputeBeginAndEnd( int inExt[6], int voi[6], int begin[3], int end[3]) { vtkBoundingBox inExtB(inExt[0],inExt[1],inExt[2],inExt[3],inExt[4],inExt[5]); vtkBoundingBox uExtB(voi[0],voi[1],voi[2],voi[3],voi[4],voi[5]); std::fill(begin,begin+3,0); std::fill(end,end+3,-1); int uExt[6]; if( uExtB.IntersectBox(inExtB) ) { for(int i=0; i < 6; ++i) { uExt[i] = static_cast<int>( roundToInt(uExtB.GetBound(i) ) ); } // Find the first and last indices in the map that are // within data extents. These are the extents of the // output data. for(int dim=0; dim < 3; ++dim) { for(int idx=0; idx < this->GetSize(dim); ++idx) { if( this->GetMapping(dim,idx) >= uExt[2*dim] && this->GetMapping(dim,idx) <= uExt[2*dim+1] ) { begin[dim] = idx; break; } } // END for all indices with for(int idx=this->GetSize(dim)-1; idx >= 0; --idx) { if( this->GetMapping(dim,idx) <= uExt[2*dim+1] && this->GetMapping(dim,idx) >= uExt[2*dim] ) { end[dim] = idx; break; } } // END for all indices } // END for all dimensions } // END if box intersects } //----------------------------------------------------------------------------- void vtkExtractStructuredGridHelper::CopyPointsAndPointData( int inExt[6], int outExt[6], vtkPointData* pd, vtkPoints* inpnts, vtkPointData* outPD, vtkPoints* outpnts, bool useMapping) { assert("pre: NULL input point-data!" && (pd != NULL) ); assert("pre: NULL output point-data!" && (outPD != NULL) ); // short-circuit if( (pd->GetNumberOfArrays()==0) && (inpnts==NULL) ) { // nothing to copy return; } // Get input and output data description int inputDesc = vtkStructuredData::GetDataDescriptionFromExtent(inExt); int outDesc = vtkStructuredData::GetDataDescriptionFromExtent(outExt); // Get the size of the input and output vtkIdType inSize = vtkStructuredData::GetNumberOfPoints(inExt); vtkIdType outSize = vtkStructuredData::GetNumberOfPoints(outExt); (void)inSize; // Prevent warnings, this is only used in debug builds. // Get the size of the input and output vtkIdType inSize = vtkStructuredData::GetNumberOfPoints(inExt,inputDesc); vtkIdType outSize = vtkStructuredData::GetNumberOfPoints(outExt,outDesc); if( inpnts != NULL ) { assert("pre: output points data-structure is NULL!" && (outpnts != NULL) ); outpnts->SetDataType( inpnts->GetDataType() ); outpnts->SetNumberOfPoints( outSize ); } outPD->CopyAllocate(pd,outSize,outSize); int ijk[3]; int src_ijk[3]; for( K(ijk)=KMIN(outExt); K(ijk) <= KMAX(outExt); ++K(ijk) ) { K(src_ijk) = (useMapping)? this->GetMapping(2,K(ijk)) : K(ijk); for( J(ijk)=JMIN(outExt); J(ijk) <= JMAX(outExt); ++J(ijk) ) { J(src_ijk) = (useMapping)? this->GetMapping(1,J(ijk)) : J(ijk); for( I(ijk)=IMIN(outExt); I(ijk) <= IMAX(outExt); ++I(ijk) ) { I(src_ijk) = (useMapping)? this->GetMapping(0,I(ijk)) : I(ijk); vtkIdType srcIdx = vtkStructuredData::ComputePointIdForExtent(inExt,src_ijk,inputDesc); vtkIdType targetIdx = vtkStructuredData::ComputePointIdForExtent(outExt,ijk,outDesc); // Sanity checks assert( "pre: srcIdx out of bounds" && (srcIdx >= 0) && (srcIdx < inSize) ); assert( "pre: targetIdx out of bounds" && (targetIdx >= 0) && (targetIdx < outSize) ); if( inpnts != NULL ) { outpnts->SetPoint(targetIdx,inpnts->GetPoint(srcIdx)); } // END if outPD->CopyData(pd,srcIdx,targetIdx); } // END for all i } // END for all j } // END for all k } //----------------------------------------------------------------------------- void vtkExtractStructuredGridHelper::CopyCellData( int inExt[6], int outExt[6], vtkCellData* cd, vtkCellData* outCD, bool useMapping) { assert("pre: NULL input cell-data!" && (cd != NULL) ); assert("pre: NULL output cell-data!" && (outCD != NULL) ); // short-circuit if( cd->GetNumberOfArrays()==0 ) { // nothing to copy return; } // Get input and output data description int inputDesc = vtkStructuredData::GetDataDescriptionFromExtent(inExt); int outDesc = vtkStructuredData::GetDataDescriptionFromExtent(outExt); // Get the size of the output & allocate output vtkIdType inSize = vtkStructuredData::GetNumberOfCells(inExt); (void)inSize; // Prevent warnings, this is only used in debug builds. outCD->CopyAllocate(cd,outSize,outSize); int inpCellExt[6]; vtkStructuredData::GetCellExtentFromPointExtent(inExt,inpCellExt,inputDesc); int outCellExt[6]; vtkStructuredData::GetCellExtentFromPointExtent(outExt,outCellExt,outDesc); int ijk[3]; int src_ijk[3]; for( K(ijk)=KMIN(outCellExt); K(ijk) <= KMAX(outCellExt); ++K(ijk) ) { K(src_ijk) = (useMapping)? this->GetMapping(2,K(ijk)) : K(ijk); for( J(ijk)=JMIN(outCellExt); J(ijk) <= JMAX(outCellExt); ++J(ijk) ) { J(src_ijk) = (useMapping)? this->GetMapping(1,J(ijk)) : J(ijk); for( I(ijk)=IMIN(outCellExt); I(ijk) <= IMAX(outCellExt); ++I(ijk) ) { I(src_ijk) = (useMapping)? this->GetMapping(0,I(ijk)) : I(ijk); // NOTE: since we are operating on cell extents, ComputePointID below // really returns the cell ID vtkIdType srcIdx = vtkStructuredData::ComputePointIdForExtent( inpCellExt,src_ijk,inputDesc); vtkIdType targetIdx = vtkStructuredData::ComputePointIdForExtent(outCellExt,ijk,outDesc); outCD->CopyData(cd,srcIdx,targetIdx); } // END for all i } // END for all j } // END for all k } <commit_msg>Update vtkExtractStructuredGridHelper to remove data descriptions args.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkExtractGrid.h Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/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 notice for more information. =========================================================================*/ #include "vtkExtractStructuredGridHelper.h" // VTK includes #include "vtkBoundingBox.h" #include "vtkCellData.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkPoints.h" #include "vtkStructuredData.h" #include "vtkStructuredExtent.h" // C/C++ includes #include <cassert> #include <vector> // Some usefull extent macros #define IMIN(ext) ext[0] #define IMAX(ext) ext[1] #define JMIN(ext) ext[2] #define JMAX(ext) ext[3] #define KMIN(ext) ext[4] #define KMAX(ext) ext[5] #define I(ijk) ijk[0] #define J(ijk) ijk[1] #define K(ijk) ijk[2] namespace vtk { namespace detail { struct vtkIndexMap { std::vector<int> Mapping[3]; }; } // End namespace detail } // End namespace vtk vtkStandardNewMacro(vtkExtractStructuredGridHelper); //----------------------------------------------------------------------------- vtkExtractStructuredGridHelper::vtkExtractStructuredGridHelper() { this->IndexMap = new vtk::detail::vtkIndexMap; this->Invalidate(); } //----------------------------------------------------------------------------- vtkExtractStructuredGridHelper::~vtkExtractStructuredGridHelper() { delete this->IndexMap; } //----------------------------------------------------------------------------- void vtkExtractStructuredGridHelper::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } //----------------------------------------------------------------------------- void vtkExtractStructuredGridHelper::Invalidate() { this->OutputWholeExtent[0]= 0; this->OutputWholeExtent[1]=-1; this->OutputWholeExtent[2]= 0; this->OutputWholeExtent[3]=-1; this->OutputWholeExtent[4]= 0; this->OutputWholeExtent[5]=-1; } //----------------------------------------------------------------------------- void vtkExtractStructuredGridHelper::Initialize( int voi[6], int wholeExtent[6], int sampleRate[3], bool includeBoundary) { assert("pre: NULL index map" && (this->IndexMap != NULL) ); vtkBoundingBox wExtB(wholeExtent[0], wholeExtent[1], wholeExtent[2], wholeExtent[3], wholeExtent[4], wholeExtent[5]); vtkBoundingBox voiB(voi[0],voi[1],voi[2],voi[3],voi[4],voi[5]); if(!wExtB.Intersects(voiB)) { for(int i=0; i < 3; ++i) { this->IndexMap->Mapping[ i ].clear(); } this->Invalidate(); return; } // Clamp VOI to Whole Extent vtkStructuredExtent::Clamp(voi,wholeExtent); // Create mapping between output extent and input extent. // Compute the output whole extent in the process. for(int dim=0; dim < 3; ++dim) { this->IndexMap->Mapping[dim].resize(voi[2*dim+1]-voi[2*dim]+2); int idx,i; for(idx=0, i=voi[2*dim]; i <= voi[2*dim+1]; i+=sampleRate[dim]) { this->IndexMap->Mapping[dim][idx++] = i; } // END for all points in this dimension, strided by the sample rate if(includeBoundary && this->IndexMap->Mapping[dim][idx-1] != voi[2*dim+1]) { this->IndexMap->Mapping[dim][idx++] = voi[2*dim+1]; } this->IndexMap->Mapping[dim].resize(idx); // Update output whole extent this->OutputWholeExtent[2*dim] = 0; this->OutputWholeExtent[2*dim+1] = static_cast<int>( this->IndexMap->Mapping[dim].size()-1 ); } // END for all dimensions } //----------------------------------------------------------------------------- int vtkExtractStructuredGridHelper::GetMapping(const int dim, const int i) { // Sanity Checks assert( "pre: dimension dim is out-of-bounds!" && (dim >= 0) && (dim < 3) ); assert( "pre: point index out-of-bounds!" && (i >= 0) && (i < this->GetSize(dim) ) ); return( this->IndexMap->Mapping[ dim ][ i ] ); } //----------------------------------------------------------------------------- int vtkExtractStructuredGridHelper::GetSize(const int dim) { assert("pre: dimension dim is out-of-bounds!" && (dim >= 0) && (dim < 3) ); return( static_cast<int>( this->IndexMap->Mapping[ dim ].size() ) ); } //----------------------------------------------------------------------------- namespace { int roundToInt(double r) { return r > 0.0 ? r + 0.5 : r - 0.5; } } //----------------------------------------------------------------------------- void vtkExtractStructuredGridHelper::ComputeBeginAndEnd( int inExt[6], int voi[6], int begin[3], int end[3]) { vtkBoundingBox inExtB(inExt[0],inExt[1],inExt[2],inExt[3],inExt[4],inExt[5]); vtkBoundingBox uExtB(voi[0],voi[1],voi[2],voi[3],voi[4],voi[5]); std::fill(begin,begin+3,0); std::fill(end,end+3,-1); int uExt[6]; if( uExtB.IntersectBox(inExtB) ) { for(int i=0; i < 6; ++i) { uExt[i] = static_cast<int>( roundToInt(uExtB.GetBound(i) ) ); } // Find the first and last indices in the map that are // within data extents. These are the extents of the // output data. for(int dim=0; dim < 3; ++dim) { for(int idx=0; idx < this->GetSize(dim); ++idx) { if( this->GetMapping(dim,idx) >= uExt[2*dim] && this->GetMapping(dim,idx) <= uExt[2*dim+1] ) { begin[dim] = idx; break; } } // END for all indices with for(int idx=this->GetSize(dim)-1; idx >= 0; --idx) { if( this->GetMapping(dim,idx) <= uExt[2*dim+1] && this->GetMapping(dim,idx) >= uExt[2*dim] ) { end[dim] = idx; break; } } // END for all indices } // END for all dimensions } // END if box intersects } //----------------------------------------------------------------------------- void vtkExtractStructuredGridHelper::CopyPointsAndPointData( int inExt[6], int outExt[6], vtkPointData* pd, vtkPoints* inpnts, vtkPointData* outPD, vtkPoints* outpnts, bool useMapping) { assert("pre: NULL input point-data!" && (pd != NULL) ); assert("pre: NULL output point-data!" && (outPD != NULL) ); // short-circuit if( (pd->GetNumberOfArrays()==0) && (inpnts==NULL) ) { // nothing to copy return; } // Get the size of the input and output vtkIdType inSize = vtkStructuredData::GetNumberOfPoints(inExt); vtkIdType outSize = vtkStructuredData::GetNumberOfPoints(outExt); (void)inSize; // Prevent warnings, this is only used in debug builds. if( inpnts != NULL ) { assert("pre: output points data-structure is NULL!" && (outpnts != NULL) ); outpnts->SetDataType( inpnts->GetDataType() ); outpnts->SetNumberOfPoints( outSize ); } outPD->CopyAllocate(pd,outSize,outSize); int ijk[3]; int src_ijk[3]; for( K(ijk)=KMIN(outExt); K(ijk) <= KMAX(outExt); ++K(ijk) ) { K(src_ijk) = (useMapping)? this->GetMapping(2,K(ijk)) : K(ijk); for( J(ijk)=JMIN(outExt); J(ijk) <= JMAX(outExt); ++J(ijk) ) { J(src_ijk) = (useMapping)? this->GetMapping(1,J(ijk)) : J(ijk); for( I(ijk)=IMIN(outExt); I(ijk) <= IMAX(outExt); ++I(ijk) ) { I(src_ijk) = (useMapping)? this->GetMapping(0,I(ijk)) : I(ijk); vtkIdType srcIdx = vtkStructuredData::ComputePointIdForExtent(inExt,src_ijk); vtkIdType targetIdx = vtkStructuredData::ComputePointIdForExtent(outExt,ijk); // Sanity checks assert( "pre: srcIdx out of bounds" && (srcIdx >= 0) && (srcIdx < inSize) ); assert( "pre: targetIdx out of bounds" && (targetIdx >= 0) && (targetIdx < outSize) ); if( inpnts != NULL ) { outpnts->SetPoint(targetIdx,inpnts->GetPoint(srcIdx)); } // END if outPD->CopyData(pd,srcIdx,targetIdx); } // END for all i } // END for all j } // END for all k } //----------------------------------------------------------------------------- void vtkExtractStructuredGridHelper::CopyCellData( int inExt[6], int outExt[6], vtkCellData* cd, vtkCellData* outCD, bool useMapping) { assert("pre: NULL input cell-data!" && (cd != NULL) ); assert("pre: NULL output cell-data!" && (outCD != NULL) ); // short-circuit if( cd->GetNumberOfArrays()==0 ) { // nothing to copy return; } // Get the size of the output & allocate output vtkIdType inSize = vtkStructuredData::GetNumberOfCells(inExt); vtkIdType outSize = vtkStructuredData::GetNumberOfCells(outExt); (void)inSize; // Prevent warnings, this is only used in debug builds. outCD->CopyAllocate(cd,outSize,outSize); int inpCellExt[6]; vtkStructuredData::GetCellExtentFromPointExtent(inExt,inpCellExt); int outCellExt[6]; vtkStructuredData::GetCellExtentFromPointExtent(outExt,outCellExt); int ijk[3]; int src_ijk[3]; for( K(ijk)=KMIN(outCellExt); K(ijk) <= KMAX(outCellExt); ++K(ijk) ) { K(src_ijk) = (useMapping)? this->GetMapping(2,K(ijk)) : K(ijk); for( J(ijk)=JMIN(outCellExt); J(ijk) <= JMAX(outCellExt); ++J(ijk) ) { J(src_ijk) = (useMapping)? this->GetMapping(1,J(ijk)) : J(ijk); for( I(ijk)=IMIN(outCellExt); I(ijk) <= IMAX(outCellExt); ++I(ijk) ) { I(src_ijk) = (useMapping)? this->GetMapping(0,I(ijk)) : I(ijk); // NOTE: since we are operating on cell extents, ComputePointID below // really returns the cell ID vtkIdType srcIdx = vtkStructuredData::ComputePointIdForExtent(inpCellExt, src_ijk); vtkIdType targetIdx = vtkStructuredData::ComputePointIdForExtent(outCellExt, ijk); outCD->CopyData(cd,srcIdx,targetIdx); } // END for all i } // END for all j } // END for all k } <|endoftext|>
<commit_before>struct e { int sz; long long ans; e combine(e l, e r) { if (l.sz == 0) return r; if (r.sz == 0) return l; e res; res.sz = l.sz + r.sz; res.ans = l.ans + r.ans; return res; } e operator+(e r) { return combine(*this, r); } e(): sz(0), ans(0) {} }; class segtree{ public: int n; // array size vector<e> t; void build(vector<int> &v) { // build the tree for (int i = n; i < 2 * n; i++) { t[i] = e(v[i - n]); } for (int i = n - 1; i > 0; --i) t[i] = t[i<<1] + t[i<<1|1]; } e query(int l, int r) { // sum on interval [l, r) e ansl, ansr; for (l += n, r += n; l < r; l >>= 1, r >>= 1) { if (l&1) ansl = ansl + t[l++]; if (r&1) ansr = t[--r] + ansr; } return ansl + ansr; } segtree(int n):n(n),t(){ t.resize(n << 1); } }; <commit_msg>segtree operator nomodify updated<commit_after>struct e { int sz; int pos; int mn; e combine(e l, e r) { if (l.sz == 0) return r; if (r.sz == 0) return l; e res; res.sz = l.sz + r.sz; if (l.mn < r.mn) { res.pos = l.pos; res.mn = l.mn; } else { res.pos = r.pos; res.mn = r.mn; } return res; } e operator+(e r) { return combine(*this, r); } e(): sz(0), ans(0) {} e(int x, int y): sz(1), pos(y), mn(x) {} }; class segtree{ public: int n; // array size vector<e> t; void build(vector<int> &v) { // build the tree for (int i = n; i < 2 * n; i++) { t[i] = e(v[i - n], i - n); } for (int i = n - 1; i > 0; --i) t[i] = t[i<<1] + t[i<<1|1]; } e query(int l, int r) { // sum on interval [l, r) e ansl, ansr; for (l += n, r += n; l < r; l >>= 1, r >>= 1) { if (l&1) ansl = ansl + t[l++]; if (r&1) ansr = t[--r] + ansr; } return ansl + ansr; } segtree(int n):n(n),t(){ t.resize(n << 1); } }; <|endoftext|>
<commit_before>#ifndef VIENNAGRID_ALGORITHM_QUANTITY_TRANSFER_HPP #define VIENNAGRID_ALGORITHM_QUANTITY_TRANSFER_HPP /* ======================================================================= Copyright (c) 2011-2014, 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 <vector> #include "viennagrid/forwards.hpp" #include "viennagrid/mesh/mesh.hpp" /** @file viennagrid/algorithm/quantity_transfer.hpp @brief Provides routines for transferring quantities defined for elements of one topological dimensions to elements of other topological dimension. */ namespace viennagrid { namespace detail { /** @brief Indicates a transfer from higher to lower topological dimension (boundary operation) */ struct boundary_quantity_transfer_tag {}; /** @brief Indicates a transfer from lower to higher topological dimension (coboundary operation) */ struct coboundary_quantity_transfer_tag {}; template <typename SourceTag, typename DestinationTag, bool less_than = (SourceTag::dim < DestinationTag::dim), bool larger_than = (SourceTag::dim > DestinationTag::dim)> struct quantity_transfer_dispatcher {}; template <typename SourceTag, typename DestinationTag> struct quantity_transfer_dispatcher<SourceTag, DestinationTag, false, true> { typedef boundary_quantity_transfer_tag type; }; template <typename SourceTag, typename DestinationTag> struct quantity_transfer_dispatcher<SourceTag, DestinationTag, true, false> { typedef coboundary_quantity_transfer_tag type; }; // Implementation for boundary transfer template <typename SourceTag, typename DestinationTag, typename MeshOrSegmentT, typename SourceAccessorT, typename DestinationSetterT, typename AveragerT, typename SourceFilterT, typename DestinationFilterT> void quantity_transfer(MeshOrSegmentT const & mesh_or_segment, SourceAccessorT const & accessor_src, DestinationSetterT & setter_dest, AveragerT const & averager, SourceFilterT const & filter_src, DestinationFilterT const & filter_dest, boundary_quantity_transfer_tag) { typedef typename viennagrid::result_of::element<MeshOrSegmentT, SourceTag>::type SourceElementType; typedef typename viennagrid::result_of::element<MeshOrSegmentT, DestinationTag>::type DestElementType; typedef typename viennagrid::result_of::const_element_range<MeshOrSegmentT, SourceTag>::type SourceContainer; typedef typename viennagrid::result_of::iterator<SourceContainer>::type SourceIterator; typedef typename viennagrid::result_of::const_element_range<SourceElementType, DestinationTag>::type DestOnSrcContainer; typedef typename viennagrid::result_of::iterator<DestOnSrcContainer>::type DestOnSrcIterator; typedef typename SourceAccessorT::value_type value_type; typedef std::map<DestElementType const *, std::vector<value_type> > DestinationValueMap; //Think about adding customization options for std::vector<double> SourceContainer source_cells(mesh_or_segment); DestinationValueMap values_for_destination_cells; // Step 1: Push all values from source cells to their destination boundary. // Note that a coboundary-iteration over destination cells has a higher memory footprint, thus this lightweight-variant using only boundary-iterations is used for (SourceIterator sit = source_cells.begin(); sit != source_cells.end(); ++sit) { if ( filter_src(*sit) ) { DestOnSrcContainer dest_on_src(*sit); for (DestOnSrcIterator dosit = dest_on_src.begin(); dosit != dest_on_src.end(); ++dosit) { if (filter_dest(*dosit)) values_for_destination_cells[&(*dosit)].push_back(accessor_src(*sit)); } } } // Step 2: Now average over values on destination cells for (typename DestinationValueMap::const_iterator dest_values_it = values_for_destination_cells.begin(); dest_values_it != values_for_destination_cells.end(); ++dest_values_it) { setter_dest(*(dest_values_it->first), averager(dest_values_it->second)); } } // Implementation for quantity transfer template <typename SourceTag, typename DestinationTag, typename MeshOrSegmentT, typename SourceAccessorT, typename DestinationSetterT, typename AveragerT, typename SourceFilterT, typename DestinationFilterT> void quantity_transfer(MeshOrSegmentT const & mesh_or_segment, SourceAccessorT const & accessor_src, DestinationSetterT & setter_dest, AveragerT const & averager, SourceFilterT const & filter_src, DestinationFilterT const & filter_dest, coboundary_quantity_transfer_tag) { typedef typename viennagrid::result_of::element<MeshOrSegmentT, DestinationTag>::type DestElementType; typedef typename viennagrid::result_of::const_element_range<MeshOrSegmentT, DestinationTag>::type DestContainer; typedef typename viennagrid::result_of::iterator<DestContainer>::type DestIterator; typedef typename viennagrid::result_of::const_element_range<DestElementType, SourceTag>::type SrcOnDestContainer; typedef typename viennagrid::result_of::iterator<SrcOnDestContainer>::type SrcOnDestIterator; typedef typename SourceAccessorT::value_type value_type; DestContainer dest_cells(mesh_or_segment); // Iterate over all dest n-cells, push values from source cell to container, then compute final value for (DestIterator dit = dest_cells.begin(); dit != dest_cells.end(); ++dit) { if ( filter_dest(*dit) ) // only consider destination cells accepted by the filter { std::vector<value_type> destination_value_container; // Push all values from adjacent source cells to the container SrcOnDestContainer src_on_dest(*dit); for (SrcOnDestIterator sodit = src_on_dest.begin(); sodit != src_on_dest.end(); ++sodit) { if (filter_src(*sodit)) destination_value_container.push_back(accessor_src(*dit)); } // setter_dest(*dit, averager(destination_value_container)); } } } } /** @brief Transfers data defined on 'source' elements to 'destination' elements. For example, values defined on cells are tranferred to vertices. * * Even though this functionality is sometimes referred to as interpolation, it is not an interpolation in the strict mathematical sense. * * @tparam SourceTypeOrTag Topological source element or tag, e.g., cell_tag * @tparam DestinationTypeOrTag Topological destination element or tag, e.g., vertex_tag * @param mesh_or_segment A mesh or segment, in which the source and destination elements reside * @param accessor_src An accessor functor for retrieving the data defined on each source element * @param setter_dest A setter for storing the data on each destination element (first argument is the destination n-cell, second argument is the value) * @param averager A functor which computes the value of the destination element from an STL-compatible container holding the values of all adjacent source elements * @param filter_src A functor which returns true for all source elements considered for the transfer, false otherwise * @param filter_dest A functor which returns true for all destination elements considered for the transfer, false otherwise */ template <typename SourceTypeOrTag, typename DestinationTypeOrTag, typename MeshOrSegmentT, typename SourceAccessorT, typename DestinationSetterT, typename AveragerT, typename SourceFilterT, typename DestinationFilterT> void quantity_transfer(MeshOrSegmentT const & mesh_or_segment, SourceAccessorT const & accessor_src, DestinationSetterT & setter_dest, AveragerT const & averager, SourceFilterT const & filter_src, DestinationFilterT const & filter_dest) { typedef typename viennagrid::result_of::element_tag<SourceTypeOrTag>::type SourceTag; typedef typename viennagrid::result_of::element_tag<DestinationTypeOrTag>::type DestinationTag; detail::quantity_transfer<SourceTag, DestinationTag>(mesh_or_segment, accessor_src, setter_dest, averager, filter_src, filter_dest, typename detail::quantity_transfer_dispatcher<SourceTag, DestinationTag>::type()); } } #endif <commit_msg>Delete quantity_transfer.hpp<commit_after><|endoftext|>
<commit_before>#include "zcm.h" #include "transport_zmq_ipc.h" #include "threadsafe_queue.hpp" #include <unistd.h> #include <cassert> #include <cstring> #include <unordered_map> #include <condition_variable> #include <iostream> #include <thread> using namespace std; // A C++ class that manages a zcm_msg_t struct Msg { zcm_msg_t msg; Msg(zcm_msg_t m) { msg.channel = strdup(m.channel); msg.len = m.len; msg.buf = (char*)malloc(msg.len); memcpy(msg.buf, m.buf, msg.len); } ~Msg() { if (msg.channel) free((void*)msg.channel); if (msg.buf) free((void*)msg.buf); memset(&msg, 0, sizeof(msg)); } zcm_msg_t *get() { return &msg; } private: // Disable all copying and moving Msg(const Msg& other) = delete; Msg(Msg&& other) = delete; Msg& operator=(const Msg& other) = delete; Msg& operator=(Msg&& other) = delete; }; struct Sub { zcm_callback_t *cb; void *usr; }; struct zcm_t { zcm_trans_t *zt; unordered_map<string, Sub> subs; thread sendThread; thread recvThread; static constexpr size_t QUEUE_SIZE = 16; ThreadsafeQueue<Msg> sendQueue {QUEUE_SIZE}; ThreadsafeQueue<Msg> recvQueue {QUEUE_SIZE}; zcm_t() { zt = zcm_trans_ipc_create(); startThreads(); } void startThreads() { sendThread = thread{&zcm_t::recvThreadFunc, this}; recvThread = thread{&zcm_t::sendThreadFunc, this}; } void recvThreadFunc() { while (true) { zcm_msg_t *msg = sendQueue.top().get(); int ret = zcm_trans_sendmsg(zt, *msg); assert(ret == ZCM_EOK); sendQueue.pop(); } } void sendThreadFunc() { while (true) { zcm_msg_t msg; int rc = zcm_trans_recvmsg(zt, &msg, 100); if (rc == ZCM_EOK) recvQueue.push(msg); } } int publish(const string& channel, const char *data, size_t len) { if (!sendQueue.hasFreeSpace()) return 1; zcm_msg_t msg; msg.channel = channel.c_str(); msg.len = len; msg.buf = (char*)data; sendQueue.push(msg); return 0; } int subscribe(const string& channel, zcm_callback_t *cb, void *usr) { zcm_trans_recvmsg_enable(zt, channel.c_str(), true); subs.emplace(channel, Sub{cb, usr}); return 0; } void dispatchMsg(zcm_msg_t *msg) { auto it = subs.find(msg->channel); if (it != subs.end()) { auto& sub = it->second; zcm_recv_buf_t rbuf; rbuf.zcm = this; rbuf.utime = 0; rbuf.len = msg->len; rbuf.data = (char*)msg->buf; sub.cb(&rbuf, msg->channel, sub.usr); } } int handle() { auto& msg = recvQueue.top(); dispatchMsg(msg.get()); recvQueue.pop(); return 0; } }; /////////////// C Interface Functions //////////////// zcm_t *zcm_create(void) { return new zcm_t(); } void zcm_destroy(zcm_t *zcm) { if (zcm) delete zcm; } int zcm_publish(zcm_t *zcm, const char *channel, char *data, size_t len) { return zcm->publish(channel, data, len); } int zcm_subscribe(zcm_t *zcm, const char *channel, zcm_callback_t *cb, void *usr) { return zcm->subscribe(channel, cb, usr); } int zcm_handle(zcm_t *zcm) { return zcm->handle(); } int zcm_poll(zcm_t *zcm, uint ms) { assert(0 && "deprecated!"); } <commit_msg>some small cleanup<commit_after>#include "zcm.h" #include "transport_zmq_ipc.h" #include "threadsafe_queue.hpp" #include <unistd.h> #include <cassert> #include <cstring> #include <unordered_map> #include <condition_variable> #include <iostream> #include <thread> using namespace std; // A C++ class that manages a zcm_msg_t struct Msg { zcm_msg_t msg; // NOTE: copy the provided data into this object Msg(const char *channel, size_t len, const char *buf) { msg.channel = strdup(channel); msg.len = len; msg.buf = (char*)malloc(len); memcpy(msg.buf, buf, len); } Msg(zcm_msg_t *msg) : Msg(msg->channel, msg->len, msg->buf) {} ~Msg() { if (msg.channel) free((void*)msg.channel); if (msg.buf) free((void*)msg.buf); memset(&msg, 0, sizeof(msg)); } zcm_msg_t *get() { return &msg; } private: // Disable all copying and moving Msg(const Msg& other) = delete; Msg(Msg&& other) = delete; Msg& operator=(const Msg& other) = delete; Msg& operator=(Msg&& other) = delete; }; struct Sub { zcm_callback_t *cb; void *usr; }; struct zcm_t { zcm_trans_t *zt; unordered_map<string, Sub> subs; thread sendThread; thread recvThread; static constexpr size_t QUEUE_SIZE = 16; ThreadsafeQueue<Msg> sendQueue {QUEUE_SIZE}; ThreadsafeQueue<Msg> recvQueue {QUEUE_SIZE}; zcm_t() { zt = zcm_trans_ipc_create(); startThreads(); } void startThreads() { sendThread = thread{&zcm_t::recvThreadFunc, this}; recvThread = thread{&zcm_t::sendThreadFunc, this}; } void recvThreadFunc() { while (true) { zcm_msg_t *msg = sendQueue.top().get(); int ret = zcm_trans_sendmsg(zt, *msg); assert(ret == ZCM_EOK); sendQueue.pop(); } } void sendThreadFunc() { while (true) { zcm_msg_t msg; int rc = zcm_trans_recvmsg(zt, &msg, 100); if (rc == ZCM_EOK) recvQueue.push(&msg); } } int publish(const string& channel, const char *data, size_t len) { if (!sendQueue.hasFreeSpace()) return 1; sendQueue.push(channel.c_str(), len, data); return 0; } int subscribe(const string& channel, zcm_callback_t *cb, void *usr) { zcm_trans_recvmsg_enable(zt, channel.c_str(), true); subs.emplace(channel, Sub{cb, usr}); return 0; } void dispatchMsg(zcm_msg_t *msg) { auto it = subs.find(msg->channel); if (it != subs.end()) { auto& sub = it->second; zcm_recv_buf_t rbuf; rbuf.zcm = this; rbuf.utime = 0; rbuf.len = msg->len; rbuf.data = (char*)msg->buf; sub.cb(&rbuf, msg->channel, sub.usr); } } int handle() { auto& msg = recvQueue.top(); dispatchMsg(msg.get()); recvQueue.pop(); return 0; } }; /////////////// C Interface Functions //////////////// zcm_t *zcm_create(void) { return new zcm_t(); } void zcm_destroy(zcm_t *zcm) { if (zcm) delete zcm; } int zcm_publish(zcm_t *zcm, const char *channel, char *data, size_t len) { return zcm->publish(channel, data, len); } int zcm_subscribe(zcm_t *zcm, const char *channel, zcm_callback_t *cb, void *usr) { return zcm->subscribe(channel, cb, usr); } int zcm_handle(zcm_t *zcm) { return zcm->handle(); } int zcm_poll(zcm_t *zcm, uint ms) { assert(0 && "deprecated!"); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: SlsCacheConfiguration.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-11-11 10:47:58 $ * * 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 * ************************************************************************/ #include "SlsCacheConfiguration.hxx" #include <vos/mutex.hxx> #include <vcl/svapp.hxx> #include <comphelper/processfactory.hxx> #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XHIERARCHICALNAMEACCESS_HPP_ #include <com/sun/star/container/XHierarchicalNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif using namespace ::com::sun::star; using namespace ::com::sun::star::uno; namespace sd { namespace slidesorter { namespace cache { ::boost::shared_ptr<CacheConfiguration> CacheConfiguration::mpInstance; ::boost::weak_ptr<CacheConfiguration> CacheConfiguration::mpWeakInstance; Timer CacheConfiguration::maReleaseTimer; ::boost::shared_ptr<CacheConfiguration> CacheConfiguration::Instance (void) { ::vos::OGuard aSolarGuard (Application::GetSolarMutex()); if (mpInstance.get() == NULL) { // Maybe somebody else kept a previously created instance alive. if ( ! mpWeakInstance.expired()) mpInstance = ::boost::shared_ptr<CacheConfiguration>(mpWeakInstance); if (mpInstance.get() == NULL) { // We have to create a new instance. mpInstance.reset(new CacheConfiguration()); mpWeakInstance = mpInstance; // Prepare to release this instance in the near future. maReleaseTimer.SetTimeoutHdl( LINK(mpInstance.get(),CacheConfiguration,TimerCallback)); maReleaseTimer.SetTimeout(5000 /* 5s */); maReleaseTimer.Start(); } } return mpInstance; } CacheConfiguration::CacheConfiguration (void) { // Get the cache size from configuration. const ::rtl::OUString sConfigurationProviderServiceName( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.configuration.ConfigurationProvider")); const ::rtl::OUString sPathToImpressConfigurationRoot( RTL_CONSTASCII_USTRINGPARAM("/org.openoffice.Office.Impress/")); const ::rtl::OUString sPathToNode( RTL_CONSTASCII_USTRINGPARAM( "MultiPaneGUI/SlideSorter/PreviewCache")); try { do { // Obtain access to the configuration. Reference<lang::XMultiServiceFactory> xProvider ( ::comphelper::getProcessServiceFactory()->createInstance( sConfigurationProviderServiceName), UNO_QUERY); if ( ! xProvider.is()) break; // Obtain access to Impress configuration. Sequence<Any> aCreationArguments(3); aCreationArguments[0] = makeAny(beans::PropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("nodepath")), 0, makeAny(sPathToImpressConfigurationRoot), beans::PropertyState_DIRECT_VALUE)); aCreationArguments[1] = makeAny(beans::PropertyValue( ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("depth")), 0, makeAny((sal_Int32)-1), beans::PropertyState_DIRECT_VALUE)); aCreationArguments[2] = makeAny(beans::PropertyValue( ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("lazywrite")), 0, makeAny(true), beans::PropertyState_DIRECT_VALUE)); ::rtl::OUString sAccessService (::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.configuration.ConfigurationAccess"))); Reference<XInterface> xRoot (xProvider->createInstanceWithArguments( sAccessService, aCreationArguments)); if ( ! xRoot.is()) break; Reference<container::XHierarchicalNameAccess> xHierarchy (xRoot, UNO_QUERY); if ( ! xHierarchy.is()) break; // Get the node for the slide sorter preview cache. mxCacheNode = Reference<container::XNameAccess>( xHierarchy->getByHierarchicalName(sPathToNode), UNO_QUERY); } while (false); } catch (RuntimeException aException) { (void)aException; } catch (Exception aException) { (void)aException; } } Any CacheConfiguration::GetValue (const ::rtl::OUString& rName) { Any aResult; if (mxCacheNode != NULL) { try { aResult = mxCacheNode->getByName(rName); } catch (Exception aException) { (void)aException; } } return aResult; } IMPL_LINK(CacheConfiguration,TimerCallback, Timer*,pTimer) { // Release out reference to the instance. mpInstance.reset(); return 0; } } } } // end of namespace ::sd::slidesorter::cache <commit_msg>INTEGRATION: CWS pchfix02 (1.3.232); FILE MERGED 2006/09/01 17:37:16 kaib 1.3.232.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * $RCSfile: SlsCacheConfiguration.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2006-09-16 19:04:04 $ * * 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 * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #include "SlsCacheConfiguration.hxx" #include <vos/mutex.hxx> #include <vcl/svapp.hxx> #include <comphelper/processfactory.hxx> #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XHIERARCHICALNAMEACCESS_HPP_ #include <com/sun/star/container/XHierarchicalNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif using namespace ::com::sun::star; using namespace ::com::sun::star::uno; namespace sd { namespace slidesorter { namespace cache { ::boost::shared_ptr<CacheConfiguration> CacheConfiguration::mpInstance; ::boost::weak_ptr<CacheConfiguration> CacheConfiguration::mpWeakInstance; Timer CacheConfiguration::maReleaseTimer; ::boost::shared_ptr<CacheConfiguration> CacheConfiguration::Instance (void) { ::vos::OGuard aSolarGuard (Application::GetSolarMutex()); if (mpInstance.get() == NULL) { // Maybe somebody else kept a previously created instance alive. if ( ! mpWeakInstance.expired()) mpInstance = ::boost::shared_ptr<CacheConfiguration>(mpWeakInstance); if (mpInstance.get() == NULL) { // We have to create a new instance. mpInstance.reset(new CacheConfiguration()); mpWeakInstance = mpInstance; // Prepare to release this instance in the near future. maReleaseTimer.SetTimeoutHdl( LINK(mpInstance.get(),CacheConfiguration,TimerCallback)); maReleaseTimer.SetTimeout(5000 /* 5s */); maReleaseTimer.Start(); } } return mpInstance; } CacheConfiguration::CacheConfiguration (void) { // Get the cache size from configuration. const ::rtl::OUString sConfigurationProviderServiceName( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.configuration.ConfigurationProvider")); const ::rtl::OUString sPathToImpressConfigurationRoot( RTL_CONSTASCII_USTRINGPARAM("/org.openoffice.Office.Impress/")); const ::rtl::OUString sPathToNode( RTL_CONSTASCII_USTRINGPARAM( "MultiPaneGUI/SlideSorter/PreviewCache")); try { do { // Obtain access to the configuration. Reference<lang::XMultiServiceFactory> xProvider ( ::comphelper::getProcessServiceFactory()->createInstance( sConfigurationProviderServiceName), UNO_QUERY); if ( ! xProvider.is()) break; // Obtain access to Impress configuration. Sequence<Any> aCreationArguments(3); aCreationArguments[0] = makeAny(beans::PropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("nodepath")), 0, makeAny(sPathToImpressConfigurationRoot), beans::PropertyState_DIRECT_VALUE)); aCreationArguments[1] = makeAny(beans::PropertyValue( ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("depth")), 0, makeAny((sal_Int32)-1), beans::PropertyState_DIRECT_VALUE)); aCreationArguments[2] = makeAny(beans::PropertyValue( ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("lazywrite")), 0, makeAny(true), beans::PropertyState_DIRECT_VALUE)); ::rtl::OUString sAccessService (::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.configuration.ConfigurationAccess"))); Reference<XInterface> xRoot (xProvider->createInstanceWithArguments( sAccessService, aCreationArguments)); if ( ! xRoot.is()) break; Reference<container::XHierarchicalNameAccess> xHierarchy (xRoot, UNO_QUERY); if ( ! xHierarchy.is()) break; // Get the node for the slide sorter preview cache. mxCacheNode = Reference<container::XNameAccess>( xHierarchy->getByHierarchicalName(sPathToNode), UNO_QUERY); } while (false); } catch (RuntimeException aException) { (void)aException; } catch (Exception aException) { (void)aException; } } Any CacheConfiguration::GetValue (const ::rtl::OUString& rName) { Any aResult; if (mxCacheNode != NULL) { try { aResult = mxCacheNode->getByName(rName); } catch (Exception aException) { (void)aException; } } return aResult; } IMPL_LINK(CacheConfiguration,TimerCallback, Timer*,pTimer) { // Release out reference to the instance. mpInstance.reset(); return 0; } } } } // end of namespace ::sd::slidesorter::cache <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: SlsCacheConfiguration.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-10-24 07:40:37 $ * * 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 SD_SLIDESORTER_CACHE_CONFIGURATION_HXX #define SD_SLIDESORTER_CACHE_CONFIGURATION_HXX #include <com/sun/star/uno/Any.hxx> #include <vcl/timer.hxx> #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #include <boost/shared_ptr.hpp> #include <boost/weak_ptr.hpp> namespace sd { namespace slidesorter { namespace cache { /** A very simple and easy-to-use access to configuration entries regarding the slide sorter cache. */ class CacheConfiguration { public: /** Return an instance to this class. The reference is released after 5 seconds. Subsequent calls to this function will create a new instance. */ static ::boost::shared_ptr<CacheConfiguration> Instance (void); /** Look up the specified value in MultiPaneGUI/SlideSorter/PreviewCache. When the specified value does not exist then an empty Any is returned. */ ::com::sun::star::uno::Any GetValue (const ::rtl::OUString& rName); private: static ::boost::shared_ptr<CacheConfiguration> mpInstance; /** When a caller holds a reference after we have released ours we use this weak pointer to avoid creating a new instance. */ static ::boost::weak_ptr<CacheConfiguration> mpWeakInstance; static Timer maReleaseTimer; ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess> mxCacheNode; CacheConfiguration (void); DECL_LINK(TimerCallback, Timer*); }; } } } // end of namespace ::sd::slidesorter::cache #endif <commit_msg>INTEGRATION: CWS pj42 (1.2.20); FILE MERGED 2005/11/10 21:59:16 pjanik 1.2.20.1: #i57567#: Remove SISSL license.<commit_after>/************************************************************************* * * $RCSfile: SlsCacheConfiguration.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-11-11 10:48:14 $ * * 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 SD_SLIDESORTER_CACHE_CONFIGURATION_HXX #define SD_SLIDESORTER_CACHE_CONFIGURATION_HXX #include <com/sun/star/uno/Any.hxx> #include <vcl/timer.hxx> #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #include <boost/shared_ptr.hpp> #include <boost/weak_ptr.hpp> namespace sd { namespace slidesorter { namespace cache { /** A very simple and easy-to-use access to configuration entries regarding the slide sorter cache. */ class CacheConfiguration { public: /** Return an instance to this class. The reference is released after 5 seconds. Subsequent calls to this function will create a new instance. */ static ::boost::shared_ptr<CacheConfiguration> Instance (void); /** Look up the specified value in MultiPaneGUI/SlideSorter/PreviewCache. When the specified value does not exist then an empty Any is returned. */ ::com::sun::star::uno::Any GetValue (const ::rtl::OUString& rName); private: static ::boost::shared_ptr<CacheConfiguration> mpInstance; /** When a caller holds a reference after we have released ours we use this weak pointer to avoid creating a new instance. */ static ::boost::weak_ptr<CacheConfiguration> mpWeakInstance; static Timer maReleaseTimer; ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess> mxCacheNode; CacheConfiguration (void); DECL_LINK(TimerCallback, Timer*); }; } } } // end of namespace ::sd::slidesorter::cache #endif <|endoftext|>
<commit_before># Items marked with "*" need compiler extensions to handle # Experimental -- run with # ./motto.byte --disable_inlining --disable_var_erasure --no_type_check \ # -o test examples/hadoop_more1.cp type k_v : record key : integer {hadoop_vint = true} value : integer {hadoop_vint = true} #fun peek : (type k_v/- c) -> (type k_v) # ? c # should be a peek -- not a receive fun peek : (c : type k_v) -> (type k_v) c fun send : (c : type k_v, x : type k_v) -> () c x # FIXME fun consume : (c : type k_v) -> (type k_v) c #fun Wc_node : (type k_v/- x, type k_v/- y, -/type k_v z) -> () fun Wc_node : (x : type k_v, y : type k_v, z : type k_v) -> () # Instead of "vs" could have pattern matching, to give v1 and v2 # let vs = peek_all () #([x, y]) # let v1 = vs[0] # * check if can project from lists like this # let v2 = vs[1] let v1 = peek (x) let v2 = peek (y) if v1.key = 0-1 and v2.key = 0-1: # * i think "-" cannot be prefix # z ! ? x # ? y send (z, consume (x)) consume (y) else: if v1.key = 0-1: # z ! ? y send (z, consume (y)) else: if v2.key = 0-1: # z ! ? x send (z, consume (x)) else: if v1.key < v2.key: # z ! ? x send (z, consume (x)) else: if v2.key < v1.key: # z ! ? y send (z, consume (y)) else: # z ! v1 with value = v1.value + v2.value # send (z, 5) # need record update send (z, v1 with value = v1.value + v2.value) # ? x # ? y consume (x) consume (y) x # FIXME should be <> <commit_msg>tuned example;<commit_after># Items marked with "*" need compiler extensions to handle # Experimental -- run with # ./motto.byte --disable_inlining --disable_var_erasure --no_type_check \ # -o test examples/hadoop_more1.cp type k_v : record key : integer {hadoop_vint = true} value : integer {hadoop_vint = true} #fun peek : (type k_v/- c) -> (type k_v) # ? c # should be a peek -- not a receive fun peek : (c''' : type k_v) -> (type k_v) c''' fun send : (c'' : type k_v, x' : type k_v) -> () c'' x' # FIXME fun consume : (c' : type k_v) -> (type k_v) c' #fun Wc_node : (type k_v/- x, type k_v/- y, -/type k_v z) -> () fun Wc_node : (x : type k_v, y : type k_v, z : type k_v) -> () # Instead of "vs" could have pattern matching, to give v1 and v2 # let vs = peek_all () #([x, y]) # let v1 = vs[0] # * check if can project from lists like this # let v2 = vs[1] let v1 = peek (x) let v2 = peek (y) if v1.key = 0-1 and v2.key = 0-1: # * i think "-" cannot be prefix # z ! ? x # ? y send (z, consume (x)) consume (y) <> else: if v1.key = 0-1: # z ! ? y send (z, consume (y)) <> else: if v2.key = 0-1: # z ! ? x send (z, consume (x)) <> else: if v1.key < v2.key: # z ! ? x send (z, consume (x)) <> else: if v2.key < v1.key: # z ! ? y send (z, consume (y)) <> else: # z ! v1 with value = v1.value + v2.value # send (z, 5) # need record update send (z, v1 with value = v1.value + v2.value) # ? x # ? y consume (x) consume (y) # NOTE experimental area #x := y let v = x <> #x # FIXME should be <> <|endoftext|>
<commit_before>// Copyright Joshua Boyce 2010-2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // This file is part of HadesMem. // <http://www.raptorfactor.com/> <raptorfactor@raptorfactor.com> #include <memory> #include <string> #include <vector> #include <iostream> #include <hadesmem/detail/warning_disable_prefix.hpp> #include <boost/filesystem.hpp> #include <boost/program_options.hpp> #include <hadesmem/detail/warning_disable_suffix.hpp> #include <hadesmem/error.hpp> #include <hadesmem/module.hpp> #include <hadesmem/process.hpp> #include <hadesmem/injector.hpp> #include <hadesmem/detail/self_path.hpp> #include "../common/initialize.hpp" // TODO: Add support for CreateAndInject. namespace { std::wstring PtrToString(void const* const ptr) { std::wostringstream str; str.imbue(std::locale::classic()); str << std::hex << reinterpret_cast<DWORD_PTR>(ptr); return str.str(); } } int main() { try { DisableUserModeCallbackExceptionFilter(); EnableCrtDebugFlags(); EnableTerminationOnHeapCorruption(); EnableBottomUpRand(); ImbueAllDefault(); std::cout << "HadesMem Injector\n"; boost::program_options::options_description opts_desc( "General options"); opts_desc.add_options() ("help", "produce help message") ("pid", boost::program_options::value<DWORD>(), "process id") ("module", boost::program_options::wvalue<std::wstring>(), "module path") ("path-resolution", "perform path resolution") ("export", boost::program_options::value<std::string>(), "export name") ("free", "unload module") ("add-path", "add module dir to serach order") ; std::vector<std::wstring> const args = boost::program_options:: split_winmain(GetCommandLine()); boost::program_options::variables_map var_map; boost::program_options::store(boost::program_options::wcommand_line_parser( args).options(opts_desc).run(), var_map); boost::program_options::notify(var_map); if (var_map.count("help")) { std::cout << '\n' << opts_desc << '\n'; return 1; } if (!var_map.count("pid")) { std::cerr << "Error! Process ID must be specified.\n"; return 1; } if (!var_map.count("module")) { std::cerr << "Error! Module path must be specified.\n"; return 1; } DWORD const pid = var_map["pid"].as<DWORD>(); try { hadesmem::GetSeDebugPrivilege(); std::wcout << "\nAcquired SeDebugPrivilege.\n"; } catch (std::exception const& /*e*/) { std::wcout << "\nFailed to acquire SeDebugPrivilege.\n"; } hadesmem::Process const process(pid); std::wstring const path = var_map["module"].as<std::wstring>(); bool const path_resolution = var_map.count("path-resolution") != 0; bool const add_path = var_map.count("add-path") != 0; bool const inject = var_map.count("free") == 0; HMODULE module = nullptr; if (inject) { int flags = hadesmem::InjectFlags::kNone; if (path_resolution) { flags |= hadesmem::InjectFlags::kPathResolution; } if (add_path) { flags |= hadesmem::InjectFlags::kAddToSearchOrder; } module = hadesmem::InjectDll(process, path, flags); std::wcout << "\nSuccessfully injected module at base address " << PtrToString(module) << ".\n"; } else { boost::filesystem::path path_real(path); if (path_resolution && path_real.is_relative()) { path_real = boost::filesystem::absolute(path_real, hadesmem::detail::GetSelfDirPath()); } path_real.make_preferred(); hadesmem::Module const remote_module(&process, path_real.native()); module = remote_module.GetHandle(); } if (var_map.count("export")) { std::string const export_name = var_map["export"].as<std::string>(); std::pair<DWORD_PTR, DWORD> const export_ret = hadesmem::CallExport( process, module, export_name, module); std::wcout << "Successfully called module export.\n"; std::wcout << "Return: " << export_ret.first << ".\n"; std::wcout << "LastError: " << export_ret.second << ".\n"; } if (!inject) { hadesmem::FreeDll(process, module); } } catch (std::exception const& e) { std::cerr << "Error!\n"; std::cerr << boost::diagnostic_information(e) << "\n"; return 1; } } <commit_msg>* Add CreateAndInject support to Injector example.<commit_after>// Copyright Joshua Boyce 2010-2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // This file is part of HadesMem. // <http://www.raptorfactor.com/> <raptorfactor@raptorfactor.com> #include <memory> #include <string> #include <vector> #include <iostream> #include <hadesmem/detail/warning_disable_prefix.hpp> #include <boost/filesystem.hpp> #include <boost/program_options.hpp> #include <hadesmem/detail/warning_disable_suffix.hpp> #include <hadesmem/error.hpp> #include <hadesmem/module.hpp> #include <hadesmem/process.hpp> #include <hadesmem/injector.hpp> #include <hadesmem/detail/self_path.hpp> #include "../common/initialize.hpp" // TODO: Add support for for passing args, work dir, etc to CreateAndInject. // e.g. exe-arg0, exe-arg1, exe-arg2, ..., exe-argN? namespace { std::wstring PtrToString(void const* const ptr) { std::wostringstream str; str.imbue(std::locale::classic()); str << std::hex << reinterpret_cast<DWORD_PTR>(ptr); return str.str(); } } int main() { try { DisableUserModeCallbackExceptionFilter(); EnableCrtDebugFlags(); EnableTerminationOnHeapCorruption(); EnableBottomUpRand(); ImbueAllDefault(); std::cout << "HadesMem Injector\n"; boost::program_options::options_description opts_desc( "General options"); opts_desc.add_options() ("help", "produce help message") ("pid", boost::program_options::value<DWORD>(), "process id") ("module", boost::program_options::wvalue<std::wstring>(), "module path") ("path-resolution", "perform path resolution") ("export", boost::program_options::value<std::string>(), "export name") ("free", "unload module") ("add-path", "add module dir to serach order") ("exe-path", boost::program_options::wvalue<std::wstring>(), "process exe path") ; std::vector<std::wstring> const args = boost::program_options:: split_winmain(GetCommandLine()); boost::program_options::variables_map var_map; boost::program_options::store(boost::program_options::wcommand_line_parser( args).options(opts_desc).run(), var_map); boost::program_options::notify(var_map); if (var_map.count("help")) { std::cout << '\n' << opts_desc << '\n'; return 1; } if (!var_map.count("module")) { std::cerr << "Error! Module path must be specified.\n"; return 1; } bool const has_pid = var_map.count("pid") != 0; bool const has_exe_path = var_map.count("exe-path") != 0; if ((has_pid && has_exe_path) || (!has_pid && !has_exe_path)) { std::cerr << "Error! A process ID or an executable path must be " "specified.\n"; return 1; } bool const inject = var_map.count("free") == 0; if (!inject && has_exe_path) { std::cerr << "Error! Modules can only be unloaded from running " "targets.\n"; return 1; } std::wstring const module_path = var_map["module"].as<std::wstring>(); bool const path_resolution = var_map.count("path-resolution") != 0; bool const add_path = var_map.count("add-path") != 0; int flags = hadesmem::InjectFlags::kNone; if (path_resolution) { flags |= hadesmem::InjectFlags::kPathResolution; } if (add_path) { flags |= hadesmem::InjectFlags::kAddToSearchOrder; } if (has_pid) { try { hadesmem::GetSeDebugPrivilege(); std::wcout << "\nAcquired SeDebugPrivilege.\n"; } catch (std::exception const& /*e*/) { std::wcout << "\nFailed to acquire SeDebugPrivilege.\n"; } DWORD const pid = var_map["pid"].as<DWORD>(); hadesmem::Process const process(pid); HMODULE module = nullptr; if (inject) { module = hadesmem::InjectDll(process, module_path, flags); std::wcout << "\nSuccessfully injected module at base address " << PtrToString(module) << ".\n"; } else { boost::filesystem::path path_real(module_path); if (path_resolution && path_real.is_relative()) { path_real = boost::filesystem::absolute(path_real, hadesmem::detail::GetSelfDirPath()); } path_real.make_preferred(); hadesmem::Module const remote_module(&process, path_real.native()); module = remote_module.GetHandle(); } if (var_map.count("export")) { std::string const export_name = var_map["export"].as<std::string>(); std::pair<DWORD_PTR, DWORD> const export_ret = hadesmem::CallExport( process, module, export_name, nullptr); std::wcout << "Successfully called module export.\n"; std::wcout << "Return: " << export_ret.first << ".\n"; std::wcout << "LastError: " << export_ret.second << ".\n"; } if (!inject) { hadesmem::FreeDll(process, module); } } else { std::wstring const exe_path = var_map["exe-path"].as<std::wstring>(); std::string const export_name = var_map.count("export") ? var_map["export"].as<std::string>() : ""; hadesmem::CreateAndInjectData const inject_data = hadesmem::CreateAndInject(exe_path, L"", std::vector<std::wstring>(), module_path, export_name, nullptr, flags); } } catch (std::exception const& e) { std::cerr << "Error!\n"; std::cerr << boost::diagnostic_information(e) << "\n"; return 1; } } <|endoftext|>
<commit_before> #ifndef __SERIALIZER_LOG_LBA_DISK_FORMAT__ #define __SERIALIZER_LOG_LBA_DISK_FORMAT__ #include "serializer/serializer.hpp" // An off64_t with the highest bit saying that a block is deleted. // Deleted blocks still have an offset, since there's a zero block // sitting in place for them. The remaining 63 bits give the offset // to the block (whether it is deleted or not). union flagged_off64_t { off64_t whole_value; struct { // The actual offset into the file. off64_t value : 63; // This block id was deleted, and the offset points to a zeroed // out buffer. int is_delete : 1; } parts; static inline flagged_off64_t unused() { flagged_off64_t ret; ret.whole_value = -1; return ret; } static inline flagged_off64_t padding() { flagged_off64_t ret; ret.whole_value = -1; return ret; } static inline bool is_padding(flagged_off64_t offset) { return offset.whole_value == -1; } static inline flagged_off64_t real(off64_t offset) { flagged_off64_t ret; ret.parts.value = offset; ret.parts.is_delete = 0; return ret; } static inline flagged_off64_t deleteblock(off64_t offset) { flagged_off64_t ret; ret.parts.value = offset; ret.parts.is_delete = 1; return ret; } static inline bool has_value(flagged_off64_t offset) { offset.parts.is_delete = 1; return offset.whole_value != off64_t(-1); } static inline bool can_be_gced(flagged_off64_t offset) { return has_value(offset); } }; struct lba_shard_metablock_t { /* Reference to the last lba extent (that's currently being * written to). Once the extent is filled, the reference is * moved to the lba superblock, and the next block gets a * reference to the clean extent. */ off64_t last_lba_extent_offset; int32_t last_lba_extent_entries_count; int32_t padding1; /* Reference to the LBA superblock and its size */ off64_t lba_superblock_offset; int32_t lba_superblock_entries_count; int32_t padding2; }; struct lba_metablock_mixin_t { lba_shard_metablock_t shards[LBA_SHARD_FACTOR]; }; // PADDING_BLOCK_ID and flagged_off64_t::padding() indicate that an entry in the LBA list only exists to fill // out a DEVICE_BLOCK_SIZE-sized chunk of the extent. static const ser_block_id_t PADDING_BLOCK_ID = ser_block_id_t::null(); struct lba_entry_t { ser_block_id_t block_id; repli_timestamp recency; // An offset into the file, with is_delete set appropriately. flagged_off64_t offset; static inline lba_entry_t make(ser_block_id_t block_id, repli_timestamp recency, flagged_off64_t offset) { lba_entry_t entry; entry.block_id = block_id; entry.recency = recency; entry.offset = offset; return entry; } static inline bool is_padding(const lba_entry_t* entry) { return entry->block_id == PADDING_BLOCK_ID && flagged_off64_t::is_padding(entry->offset); } static inline lba_entry_t make_padding_entry() { return make(PADDING_BLOCK_ID, repli_timestamp::invalid, flagged_off64_t::padding()); } } __attribute((__packed__)); #define LBA_MAGIC_SIZE 8 static const char lba_magic[LBA_MAGIC_SIZE] = {'l', 'b', 'a', 'm', 'a', 'g', 'i', 'c'}; struct lba_extent_t { // Header needs to be padded to a multiple of sizeof(lba_entry_t) struct header_t { char magic[LBA_MAGIC_SIZE]; char padding[sizeof(lba_entry_t) - (1 + (sizeof(LBA_MAGIC_SIZE) - 1) % sizeof(lba_entry_t))]; } header; lba_entry_t entries[0]; }; struct lba_superblock_entry_t { off64_t offset; int64_t lba_entries_count; }; #define LBA_SUPER_MAGIC_SIZE 8 static const char lba_super_magic[LBA_SUPER_MAGIC_SIZE] = {'l', 'b', 'a', 's', 'u', 'p', 'e', 'r'}; struct lba_superblock_t { // Header needs to be padded to a multiple of sizeof(lba_superblock_entry_t) char magic[LBA_SUPER_MAGIC_SIZE]; char padding[sizeof(lba_superblock_entry_t) - (1 + (sizeof(LBA_SUPER_MAGIC_SIZE) - 1) % sizeof(lba_superblock_entry_t))]; /* The superblock contains references to all the extents * except the last. The reference to the last extent is * maintained in the metablock. This is done in order to be * able to store the number of entries in the last extent as * it's being filled up without rewriting the superblock. */ lba_superblock_entry_t entries[0]; static int entry_count_to_file_size(int nentries) { return sizeof(lba_superblock_entry_t) * nentries + offsetof(lba_superblock_t, entries[0]); } }; #endif /* __SERIALIZER_LOG_LBA_DISK_FORMAT__ */ <commit_msg>I fucked this up really badly. Sorry.<commit_after> #ifndef __SERIALIZER_LOG_LBA_DISK_FORMAT__ #define __SERIALIZER_LOG_LBA_DISK_FORMAT__ #include "serializer/serializer.hpp" // An off64_t with the highest bit saying that a block is deleted. // Deleted blocks still have an offset, since there's a zero block // sitting in place for them. The remaining 63 bits give the offset // to the block (whether it is deleted or not). union flagged_off64_t { off64_t whole_value; struct { // The actual offset into the file. off64_t value : 63; // This block id was deleted, and the offset points to a zeroed // out buffer. int is_delete : 1; } parts; static inline flagged_off64_t unused() { flagged_off64_t ret; ret.whole_value = -1; return ret; } static inline flagged_off64_t padding() { flagged_off64_t ret; ret.whole_value = -1; return ret; } static inline bool is_padding(flagged_off64_t offset) { return offset.whole_value == -1; } static inline flagged_off64_t real(off64_t offset) { flagged_off64_t ret; ret.parts.value = offset; ret.parts.is_delete = 0; return ret; } static inline flagged_off64_t deleteblock(off64_t offset) { flagged_off64_t ret; ret.parts.value = offset; ret.parts.is_delete = 1; return ret; } static inline bool has_value(flagged_off64_t offset) { offset.parts.is_delete = 1; return offset.whole_value != off64_t(-1); } static inline bool can_be_gced(flagged_off64_t offset) { return has_value(offset); } }; struct lba_shard_metablock_t { /* Reference to the last lba extent (that's currently being * written to). Once the extent is filled, the reference is * moved to the lba superblock, and the next block gets a * reference to the clean extent. */ off64_t last_lba_extent_offset; int32_t last_lba_extent_entries_count; int32_t padding1; /* Reference to the LBA superblock and its size */ off64_t lba_superblock_offset; int32_t lba_superblock_entries_count; int32_t padding2; }; struct lba_metablock_mixin_t { lba_shard_metablock_t shards[LBA_SHARD_FACTOR]; }; // PADDING_BLOCK_ID and flagged_off64_t::padding() indicate that an entry in the LBA list only exists to fill // out a DEVICE_BLOCK_SIZE-sized chunk of the extent. static const ser_block_id_t PADDING_BLOCK_ID = ser_block_id_t::null(); struct lba_entry_t { ser_block_id_t block_id; repli_timestamp recency; // An offset into the file, with is_delete set appropriately. flagged_off64_t offset; static inline lba_entry_t make(ser_block_id_t block_id, repli_timestamp recency, flagged_off64_t offset) { lba_entry_t entry; entry.block_id = block_id; entry.recency = recency; entry.offset = offset; return entry; } static inline bool is_padding(const lba_entry_t* entry) { return entry->block_id == PADDING_BLOCK_ID && flagged_off64_t::is_padding(entry->offset); } static inline lba_entry_t make_padding_entry() { return make(PADDING_BLOCK_ID, repli_timestamp::invalid, flagged_off64_t::padding()); } } __attribute((__packed__)); #define LBA_MAGIC_SIZE 8 static const char lba_magic[LBA_MAGIC_SIZE] = {'l', 'b', 'a', 'm', 'a', 'g', 'i', 'c'}; struct lba_extent_t { // Header needs to be padded to a multiple of sizeof(lba_entry_t) struct header_t { char magic[LBA_MAGIC_SIZE]; char padding[sizeof(lba_entry_t) - (1 + (LBA_MAGIC_SIZE - 1) % sizeof(lba_entry_t))]; } header; lba_entry_t entries[0]; }; struct lba_superblock_entry_t { off64_t offset; int64_t lba_entries_count; }; #define LBA_SUPER_MAGIC_SIZE 8 static const char lba_super_magic[LBA_SUPER_MAGIC_SIZE] = {'l', 'b', 'a', 's', 'u', 'p', 'e', 'r'}; struct lba_superblock_t { // Header needs to be padded to a multiple of sizeof(lba_superblock_entry_t) char magic[LBA_SUPER_MAGIC_SIZE]; char padding[sizeof(lba_superblock_entry_t) - (1 + (LBA_SUPER_MAGIC_SIZE - 1) % sizeof(lba_superblock_entry_t))]; /* The superblock contains references to all the extents * except the last. The reference to the last extent is * maintained in the metablock. This is done in order to be * able to store the number of entries in the last extent as * it's being filled up without rewriting the superblock. */ lba_superblock_entry_t entries[0]; static int entry_count_to_file_size(int nentries) { return sizeof(lba_superblock_entry_t) * nentries + offsetof(lba_superblock_t, entries[0]); } }; #endif /* __SERIALIZER_LOG_LBA_DISK_FORMAT__ */ <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (C) 2004 by Stanislav Karchebny * * Stanislav.Karchebny@kdemail.net * * * * Licensed under GPL. * ***************************************************************************/ #include "akregator.h" #include "trayicon.h" #include "akregatorconfig.h" #include <kkeydialog.h> #include <kfiledialog.h> #include <kprogress.h> #include <kconfig.h> #include <kurl.h> #include <kparts/browserextension.h> #include <kedittoolbar.h> #include <kaction.h> #include <kstdaction.h> #include <klibloader.h> #include <kmessagebox.h> #include <kstatusbar.h> #include <klocale.h> #include <kdebug.h> using namespace Akregator; aKregator::aKregator() : KParts::MainWindow( 0L, "aKregator" ) , m_quit(false) { // set the shell's ui resource file setXMLFile("akregator_shell.rc"); // then, setup our actions setupActions(); // and a status bar statusBar()->show(); m_progressBar = new KProgress( this ); m_progressBar->setMaximumHeight(fontMetrics().height()); m_progressBar->hide(); statusBar()->addWidget( m_progressBar, 0, true); // this routine will find and load our Part. it finds the Part by // name which is a bad idea usually.. but it's alright in this // case since our Part is made for this Shell KLibFactory *factory = KLibLoader::self()->factory("libakregatorpart"); if (factory) { // now that the Part is loaded, we cast it to a Part to get // our hands on it m_part = static_cast<aKregatorPart*>(factory->create(this, "akregator_part", "KParts::ReadWritePart" )); if (m_part) { // tell the KParts::MainWindow that this is indeed the main widget setCentralWidget(m_part->widget()); connect (m_part, SIGNAL(partChanged(KParts::Part *)), this, SLOT(partChanged(KParts::Part *))); connect( m_part->extension, SIGNAL(loadingProgress(int)), this, SLOT(loadingProgress(int)) ); // and integrate the part's GUI with the shell's createGUI(m_part); } } else { // if we couldn't find our Part, we exit since the Shell by // itself can't do anything useful KMessageBox::error(this, i18n("Could not find our part.")); kapp->quit(); // we return here, cause kapp->quit() only means "exit the // next time we enter the event loop... return; } TrayIcon *icon = new TrayIcon(this); icon->show(); connect(icon, SIGNAL(quitSelected()), this, SLOT(quitProgram())); // apply the saved mainwindow settings, if any, and ask the mainwindow // to automatically save settings if changed: window size, toolbar // position, icon size, etc. setAutoSaveSettings(); load( Settings::lastOpenFile() ); } aKregator::~aKregator() { Settings::setLastOpenFile( m_part->url().url() ); Settings::writeConfig(); } void aKregator::partChanged(KParts::Part *p) { createGUI(p); } void aKregator::load(const KURL& url) { m_part->openURL( url ); } void aKregator::setupActions() { KStdAction::openNew(this, SLOT(fileNew()), actionCollection()); KStdAction::open(this, SLOT(fileOpen()), actionCollection()); KStdAction::quit(this, SLOT(quitProgram()), actionCollection()); m_toolbarAction = KStdAction::showToolbar(this, SLOT(optionsShowToolbar()), actionCollection()); m_statusbarAction = KStdAction::showStatusbar(this, SLOT(optionsShowStatusbar()), actionCollection()); KStdAction::keyBindings(this, SLOT(optionsConfigureKeys()), actionCollection()); KStdAction::configureToolbars(this, SLOT(optionsConfigureToolbars()), actionCollection()); } void aKregator::saveProperties(KConfig* /*config*/) { // the 'config' object points to the session managed // config file. anything you write here will be available // later when this app is restored } void aKregator::readProperties(KConfig* /*config*/) { // the 'config' object points to the session managed // config file. this function is automatically called whenever // the app is being restored. read in here whatever you wrote // in 'saveProperties' } void aKregator::fileNew() { // this slot is called whenever the File->New menu is selected, // the New shortcut is pressed (usually CTRL+N) or the New toolbar // button is clicked // About this function, the style guide ( // http://developer.kde.org/documentation/standards/kde/style/basics/index.html ) // says that it should open a new window if the document is _not_ // in its initial state. This is what we do here.. if ( ! m_part->url().isEmpty() || m_part->isModified() ) { (new aKregator)->show(); }; } void aKregator::optionsShowToolbar() { // this is all very cut and paste code for showing/hiding the // toolbar if (m_toolbarAction->isChecked()) toolBar()->show(); else toolBar()->hide(); } void aKregator::optionsShowStatusbar() { // this is all very cut and paste code for showing/hiding the // statusbar if (m_statusbarAction->isChecked()) statusBar()->show(); else statusBar()->hide(); } void aKregator::optionsConfigureKeys() { KKeyDialog::configure(actionCollection()/*, "akregator_shell.rc"*/); } void aKregator::optionsConfigureToolbars() { #if defined(KDE_MAKE_VERSION) # if KDE_VERSION >= KDE_MAKE_VERSION(3,1,0) saveMainWindowSettings(KGlobal::config(), autoSaveGroup()); # else saveMainWindowSettings(KGlobal::config() ); # endif #else saveMainWindowSettings(KGlobal::config() ); #endif // use the standard toolbar editor KEditToolbar dlg(factory()); connect(&dlg, SIGNAL(newToolbarConfig()), this, SLOT(applyNewToolbarConfig())); dlg.exec(); } void aKregator::applyNewToolbarConfig() { #if defined(KDE_MAKE_VERSION) # if KDE_VERSION >= KDE_MAKE_VERSION(3,1,0) applyMainWindowSettings(KGlobal::config(), autoSaveGroup()); # else applyMainWindowSettings(KGlobal::config()); # endif #else applyMainWindowSettings(KGlobal::config()); #endif } void aKregator::fileOpen() { // this slot is called whenever the File->Open menu is selected, // the Open shortcut is pressed (usually CTRL+O) or the Open toolbar // button is clicked KURL url = KFileDialog::getOpenURL( QString::null, QString::null, this ); if (url.isEmpty() == false) { // About this function, the style guide ( // http://developer.kde.org/documentation/standards/kde/style/basics/index.html ) // says that it should open a new window if the document is _not_ // in its initial state. This is what we do here.. if ( m_part->url().isEmpty() && ! m_part->isModified() ) { // we open the file in this window... load( url ); } else { // we open the file in a new window... aKregator* newWin = new aKregator; newWin->load( url ); newWin->show(); } } } void aKregator::quitProgram() { // will call queryClose() m_quit = true; close(); } // from KonqFrameStatusBar void aKregator::fontChange(const QFont & /* oldFont */) { int h = fontMetrics().height(); if ( h < 13 ) h = 13; m_progressBar->setFixedHeight( h + 2 ); } void aKregator::loadingProgress(int percent) { if ( percent != -1 && percent != 100 ) // hide on 100 too { if ( !m_progressBar->isVisible() ) m_progressBar->show(); } else m_progressBar->hide(); m_progressBar->setValue( percent ); } void aKregator::closeEvent(QCloseEvent* e) { if (!m_quit) { KMessageBox::information(this, i18n( "<qt>Closing the main window will keep aKregator running in the system tray. Use 'Quit' from the 'File' menu to quit the application.</qt>" ), i18n( "Docking in System Tray" ), "hideOnCloseInfo"); hide(); e->ignore(); } else { if (m_part->queryClose()) KMainWindow::closeEvent(e); } } #include "akregator.moc" <commit_msg>Resets m_quit state if users cancels queryClose dialog.<commit_after>/*************************************************************************** * Copyright (C) 2004 by Stanislav Karchebny * * Stanislav.Karchebny@kdemail.net * * * * Licensed under GPL. * ***************************************************************************/ #include "akregator.h" #include "trayicon.h" #include "akregatorconfig.h" #include <kkeydialog.h> #include <kfiledialog.h> #include <kprogress.h> #include <kconfig.h> #include <kurl.h> #include <kparts/browserextension.h> #include <kedittoolbar.h> #include <kaction.h> #include <kstdaction.h> #include <klibloader.h> #include <kmessagebox.h> #include <kstatusbar.h> #include <klocale.h> #include <kdebug.h> using namespace Akregator; aKregator::aKregator() : KParts::MainWindow( 0L, "aKregator" ) , m_quit(false) { // set the shell's ui resource file setXMLFile("akregator_shell.rc"); // then, setup our actions setupActions(); // and a status bar statusBar()->show(); m_progressBar = new KProgress( this ); m_progressBar->setMaximumHeight(fontMetrics().height()); m_progressBar->hide(); statusBar()->addWidget( m_progressBar, 0, true); // this routine will find and load our Part. it finds the Part by // name which is a bad idea usually.. but it's alright in this // case since our Part is made for this Shell KLibFactory *factory = KLibLoader::self()->factory("libakregatorpart"); if (factory) { // now that the Part is loaded, we cast it to a Part to get // our hands on it m_part = static_cast<aKregatorPart*>(factory->create(this, "akregator_part", "KParts::ReadWritePart" )); if (m_part) { // tell the KParts::MainWindow that this is indeed the main widget setCentralWidget(m_part->widget()); connect (m_part, SIGNAL(partChanged(KParts::Part *)), this, SLOT(partChanged(KParts::Part *))); connect( m_part->extension, SIGNAL(loadingProgress(int)), this, SLOT(loadingProgress(int)) ); // and integrate the part's GUI with the shell's createGUI(m_part); } } else { // if we couldn't find our Part, we exit since the Shell by // itself can't do anything useful KMessageBox::error(this, i18n("Could not find our part.")); kapp->quit(); // we return here, cause kapp->quit() only means "exit the // next time we enter the event loop... return; } TrayIcon *icon = new TrayIcon(this); icon->show(); connect(icon, SIGNAL(quitSelected()), this, SLOT(quitProgram())); // apply the saved mainwindow settings, if any, and ask the mainwindow // to automatically save settings if changed: window size, toolbar // position, icon size, etc. setAutoSaveSettings(); load( Settings::lastOpenFile() ); } aKregator::~aKregator() { Settings::setLastOpenFile( m_part->url().url() ); Settings::writeConfig(); } void aKregator::partChanged(KParts::Part *p) { createGUI(p); } void aKregator::load(const KURL& url) { m_part->openURL( url ); } void aKregator::setupActions() { KStdAction::openNew(this, SLOT(fileNew()), actionCollection()); KStdAction::open(this, SLOT(fileOpen()), actionCollection()); KStdAction::quit(this, SLOT(quitProgram()), actionCollection()); m_toolbarAction = KStdAction::showToolbar(this, SLOT(optionsShowToolbar()), actionCollection()); m_statusbarAction = KStdAction::showStatusbar(this, SLOT(optionsShowStatusbar()), actionCollection()); KStdAction::keyBindings(this, SLOT(optionsConfigureKeys()), actionCollection()); KStdAction::configureToolbars(this, SLOT(optionsConfigureToolbars()), actionCollection()); } void aKregator::saveProperties(KConfig* /*config*/) { // the 'config' object points to the session managed // config file. anything you write here will be available // later when this app is restored } void aKregator::readProperties(KConfig* /*config*/) { // the 'config' object points to the session managed // config file. this function is automatically called whenever // the app is being restored. read in here whatever you wrote // in 'saveProperties' } void aKregator::fileNew() { // this slot is called whenever the File->New menu is selected, // the New shortcut is pressed (usually CTRL+N) or the New toolbar // button is clicked // About this function, the style guide ( // http://developer.kde.org/documentation/standards/kde/style/basics/index.html ) // says that it should open a new window if the document is _not_ // in its initial state. This is what we do here.. if ( ! m_part->url().isEmpty() || m_part->isModified() ) { (new aKregator)->show(); }; } void aKregator::optionsShowToolbar() { // this is all very cut and paste code for showing/hiding the // toolbar if (m_toolbarAction->isChecked()) toolBar()->show(); else toolBar()->hide(); } void aKregator::optionsShowStatusbar() { // this is all very cut and paste code for showing/hiding the // statusbar if (m_statusbarAction->isChecked()) statusBar()->show(); else statusBar()->hide(); } void aKregator::optionsConfigureKeys() { KKeyDialog::configure(actionCollection()/*, "akregator_shell.rc"*/); } void aKregator::optionsConfigureToolbars() { #if defined(KDE_MAKE_VERSION) # if KDE_VERSION >= KDE_MAKE_VERSION(3,1,0) saveMainWindowSettings(KGlobal::config(), autoSaveGroup()); # else saveMainWindowSettings(KGlobal::config() ); # endif #else saveMainWindowSettings(KGlobal::config() ); #endif // use the standard toolbar editor KEditToolbar dlg(factory()); connect(&dlg, SIGNAL(newToolbarConfig()), this, SLOT(applyNewToolbarConfig())); dlg.exec(); } void aKregator::applyNewToolbarConfig() { #if defined(KDE_MAKE_VERSION) # if KDE_VERSION >= KDE_MAKE_VERSION(3,1,0) applyMainWindowSettings(KGlobal::config(), autoSaveGroup()); # else applyMainWindowSettings(KGlobal::config()); # endif #else applyMainWindowSettings(KGlobal::config()); #endif } void aKregator::fileOpen() { // this slot is called whenever the File->Open menu is selected, // the Open shortcut is pressed (usually CTRL+O) or the Open toolbar // button is clicked KURL url = KFileDialog::getOpenURL( QString::null, QString::null, this ); if (url.isEmpty() == false) { // About this function, the style guide ( // http://developer.kde.org/documentation/standards/kde/style/basics/index.html ) // says that it should open a new window if the document is _not_ // in its initial state. This is what we do here.. if ( m_part->url().isEmpty() && ! m_part->isModified() ) { // we open the file in this window... load( url ); } else { // we open the file in a new window... aKregator* newWin = new aKregator; newWin->load( url ); newWin->show(); } } } void aKregator::quitProgram() { // will call queryClose() m_quit = true; close(); } // from KonqFrameStatusBar void aKregator::fontChange(const QFont & /* oldFont */) { int h = fontMetrics().height(); if ( h < 13 ) h = 13; m_progressBar->setFixedHeight( h + 2 ); } void aKregator::loadingProgress(int percent) { if ( percent != -1 && percent != 100 ) // hide on 100 too { if ( !m_progressBar->isVisible() ) m_progressBar->show(); } else m_progressBar->hide(); m_progressBar->setValue( percent ); } void aKregator::closeEvent(QCloseEvent* e) { if (!m_quit) { KMessageBox::information(this, i18n( "<qt>Closing the main window will keep aKregator running in the system tray. Use 'Quit' from the 'File' menu to quit the application.</qt>" ), i18n( "Docking in System Tray" ), "hideOnCloseInfo"); hide(); e->ignore(); } else { if (m_part->queryClose()) KMainWindow::closeEvent(e); } m_quit = false; } #include "akregator.moc" <|endoftext|>
<commit_before>#pragma once #include <memory> #include <tudocomp/compressors/esp/TypedBlock.hpp> namespace tdc {namespace esp { class DebugContextBase { struct Data { std::ostream* m_out; bool print_enabled = true; bool print_early = true; std::vector<std::function<void(std::ostream&)>> m_print_instructions; }; std::shared_ptr<Data> m_data; protected: template<typename T> static std::vector<size_t> cast_vec(const T& v) { std::vector<size_t> r; r.reserve(v.size()); for (auto e : v) { r.push_back(e); } return r; } template<typename F> void print(F f) { m_data->m_print_instructions.push_back(f); // TODO: Could add wrappers here if (m_data->print_enabled && m_data->print_early) { m_data->m_print_instructions.back()(*(m_data->m_out)); } /* print([m_data](std::ostream& o) { }) */ } DebugContextBase(std::ostream& o, bool p_en, bool p_ea): m_data(std::make_shared<Data>(Data { &o, p_en, p_ea })) {} DebugContextBase(DebugContextBase& parent): DebugContextBase(*(parent.m_data->m_out), parent.m_data->print_enabled, parent.m_data->print_early) {} public: DebugContextBase(const DebugContextBase& other): m_data(other.m_data) {} void print_all() const { if (m_data->print_enabled & !m_data->print_early) { for (auto& f : m_data->m_print_instructions) { f(*(m_data->m_out)); } } } }; //////////////////////////////////////////////////////////////////////////////// class DebugMetablockContext: public DebugContextBase { struct Data { size_t alphabet_size; std::vector<size_t> metablock; size_t type; size_t offset; std::vector<TypedBlock> unadjusted_blocks; std::vector<size_t> mb2_initial; std::vector<std::shared_ptr<std::vector<size_t>>> mb2_reduce_to_6_steps; std::vector<std::shared_ptr<std::vector<size_t>>> mb2_reduce_to_3_steps; std::vector<size_t> mb2_high_landmarks; std::vector<size_t> mb2_high_and_low_landmarks; }; std::shared_ptr<Data> m_data; public: DebugMetablockContext(std::ostream& o, bool p_en, bool p_ea, size_t alphabet_size): DebugContextBase(o, p_en, p_ea), m_data(std::make_shared<Data>(Data {})) { m_data->alphabet_size = alphabet_size; } DebugMetablockContext(DebugContextBase& parent, size_t alphabet_size): DebugContextBase(parent), m_data(std::make_shared<Data>(Data {})) { m_data->alphabet_size = alphabet_size; } template<typename T> void init(size_t type, const T& string, size_t offset) { m_data->type = type; m_data->offset = offset; m_data->metablock = cast_vec(string); print([m_data = m_data](std::ostream& o) { o << " type: " << m_data->type << ", offset: " << m_data->offset << ", metablock: " << vec_to_debug_string(m_data->metablock) << "\n"; }); } void block(size_t width, size_t type) { auto b = TypedBlock { uint8_t(width), uint8_t(type) }; m_data->unadjusted_blocks.push_back(b); print([m_data = m_data, b](std::ostream& o) { o << " block: " << b << "\n"; }); } template<typename T> void mb2_initial(const T& buf) { m_data->mb2_initial = cast_vec(buf); print([m_data = m_data](std::ostream& o) { o << " Alphabet reduction initial:\n" << " " << vec_to_debug_string(m_data->mb2_initial) << "\n"; }); } void mb2_reduce_to_6_start() { print([m_data = m_data](std::ostream& o) { o << " Reduce to 6:\n"; }); } template<typename T> void mb2_reduce_to_6_step(const T& buf) { auto p = std::make_shared<std::vector<size_t>>(cast_vec(buf)); m_data->mb2_reduce_to_6_steps.push_back(p); print([m_data = m_data, p](std::ostream& o) { o << " " << vec_to_debug_string(*p) << "\n"; }); } void mb2_reduce_to_3_start() { print([m_data = m_data](std::ostream& o) { o << " Reduce to 3:\n"; }); } template<typename T> void mb2_reduce_to_3_step(const T& buf) { auto p = std::make_shared<std::vector<size_t>>(cast_vec(buf)); m_data->mb2_reduce_to_3_steps.push_back(p); print([m_data = m_data, p](std::ostream& o) { o << " " << vec_to_debug_string(*p) << "\n"; }); } template<typename T> void mb2_high_landmarks(const T& buf) { m_data->mb2_high_landmarks = cast_vec(buf); print([m_data = m_data](std::ostream& o) { o << " High landmarks:\n" << " " << vec_to_debug_string(m_data->mb2_high_landmarks) << "\n"; }); } template<typename T> void mb2_high_and_low_landmarks(const T& buf) { m_data->mb2_high_and_low_landmarks = cast_vec(buf); print([m_data = m_data](std::ostream& o) { o << " High and low landmarks:\n" << " " << vec_to_debug_string(m_data->mb2_high_and_low_landmarks) << "\n"; }); } }; class DebugRoundContext: public DebugContextBase { struct Data { size_t number; std::vector<size_t> string; size_t root_node = 0; bool empty = false; std::vector<DebugMetablockContext> metablocks; size_t alphabet_size; std::vector<TypedBlock> adjusted_blocks; std::vector<std::shared_ptr<std::pair<std::vector<size_t>, size_t>>> slice_symbol_map; }; std::shared_ptr<Data> m_data; public: DebugRoundContext(std::ostream& o, bool p_en, bool p_ea): DebugContextBase(o, p_en, p_ea), m_data(std::make_shared<Data>(Data {})) {} DebugRoundContext(DebugContextBase& parent): DebugContextBase(parent), m_data(std::make_shared<Data>(Data {})) {} void init(size_t number, const std::vector<size_t>& string, size_t alphabet_size) { m_data->number = number; m_data->string = string; m_data->alphabet_size = alphabet_size; print([m_data = m_data](std::ostream& o) { o << "\n[Round #" << m_data->number << "]:\n" << " " << vec_to_debug_string(m_data->string) << "\n"; o << " Alphabet size: " << m_data->alphabet_size << "\n"; }); } void last_round(size_t rn, bool empty) { m_data->root_node = rn; m_data->empty = empty; print([m_data = m_data](std::ostream& o) { if (m_data->empty) { o << " DONE, empty input\n"; } else { o << " DONE, root node: " << m_data->root_node << "\n"; } }); } DebugMetablockContext metablock() { DebugMetablockContext m_data_child(*this, m_data->alphabet_size); m_data->metablocks.push_back(m_data_child); print([m_data_child](std::ostream& o) { m_data_child.print_all(); }); return m_data_child; } void adjusted_blocks(const ConstGenericView<TypedBlock>& buf) { m_data->adjusted_blocks = buf; print([m_data = m_data](std::ostream& o) { o << " Adjusted blocks:\n"; for (auto b : m_data->adjusted_blocks) { o << " block: " << b << "\n"; } }); } void slice_symbol_map_start() { print([m_data = m_data](std::ostream& o) { o << " Slice-Symbol map:\n"; }); } template<typename T> void slice_symbol_map(const T& slice, size_t symbol) { auto p = std::make_shared<std::pair<std::vector<size_t>, size_t>>( std::pair<std::vector<size_t>, size_t> { cast_vec(slice), symbol, } ); m_data->slice_symbol_map.push_back(p); print([m_data = m_data, p](std::ostream& o) { o << " " << vec_to_debug_string(p->first) << " -> " << p->second << "\n"; }); } }; class DebugContext: public DebugContextBase { struct Data { std::string input; std::vector<DebugRoundContext> rounds; bool empty; size_t root_node; size_t encode_max_value; size_t encode_max_value_bits; size_t encode_root_node; std::vector<std::shared_ptr<std::vector<size_t>>> encode_slp; }; std::shared_ptr<Data> m_data; public: DebugContext(std::ostream& o, bool p_en, bool p_ea): DebugContextBase(o, p_en, p_ea), m_data(std::make_shared<Data>(Data {})) {} void input_string(string_ref s) { m_data->input = s; print([m_data = m_data](std::ostream& o) { o << "\n[Input]:\n\"" << m_data->input << "\"\n"; }); } void generate_grammar(bool empty, size_t root_node) { m_data->empty = empty; m_data->root_node = root_node; print([m_data = m_data](std::ostream& o) { o << "\n[Grammar]:\n" << " Is empty: " << (m_data->empty? "yes" : "no") << "\n" << " Root node: " << m_data->root_node << "\n"; }); } void encode_start() { print([m_data = m_data](std::ostream& o) { o << "\n[Encode]:\n"; }); } void encode_max_value(size_t value, size_t bits) { m_data->encode_max_value = value; m_data->encode_max_value_bits = bits; print([m_data = m_data](std::ostream& o) { o << " Max value: " << m_data->encode_max_value << "\n"; o << " Bits: " << m_data->encode_max_value_bits << "\n"; }); } void encode_root_node(size_t node) { m_data->encode_root_node = node; print([m_data = m_data](std::ostream& o) { o << " Root node: " << m_data->encode_root_node << "\n"; }); } void encode_rule_start() { print([m_data = m_data](std::ostream& o) { o << "\n [SLP]:\n"; }); } template<typename T> void encode_rule(const T& rule) { auto p = std::make_shared<std::vector<size_t>>(cast_vec(rule)); m_data->encode_slp.push_back(p); print([m_data = m_data, p](std::ostream& o) { o << " " << vec_to_debug_string(*p) << "\n"; }); } DebugRoundContext round() { DebugRoundContext m_data_child(*this); m_data->rounds.push_back(m_data_child); print([m_data_child](std::ostream& o) { m_data_child.print_all(); }); return m_data_child; } }; }} <commit_msg>wip add recursing template pattern<commit_after>#pragma once #include <memory> #include <tudocomp/compressors/esp/TypedBlock.hpp> namespace tdc {namespace esp { template<typename T> class DebugContextBase { struct Data { std::ostream* m_out; bool print_enabled = true; bool print_early = true; std::vector<std::function<void(std::ostream&)>> m_print_instructions; T m_child_data; }; std::shared_ptr<Data> m_data; protected: template<typename F> void with_child(F f) { if (m_data) { f(m_data->m_child_data); } } template<typename U> static std::vector<size_t> cast_vec(const U& v) { std::vector<size_t> r; r.reserve(v.size()); for (auto e : v) { r.push_back(e); } return r; } template<typename F> void print(F f) { m_data->m_print_instructions.push_back(f); // TODO: Could add wrappers here if (m_data->print_enabled && m_data->print_early) { m_data->m_print_instructions.back()(*(m_data->m_out)); } /* print([m_data](std::ostream& o) { }) */ } DebugContextBase(std::ostream& o, bool p_en, bool p_ea): m_data(std::make_shared<Data>(Data { &o, p_en, p_ea })) {} DebugContextBase(DebugContextBase& parent): DebugContextBase(*(parent.m_data->m_out), parent.m_data->print_enabled, parent.m_data->print_early) {} public: DebugContextBase(const DebugContextBase& other): m_data(other.m_data) {} void print_all() const { if (m_data->print_enabled & !m_data->print_early) { for (auto& f : m_data->m_print_instructions) { f(*(m_data->m_out)); } } } }; //////////////////////////////////////////////////////////////////////////////// struct DebugMetablockContextData { size_t alphabet_size; std::vector<size_t> metablock; size_t type; size_t offset; std::vector<TypedBlock> unadjusted_blocks; std::vector<size_t> mb2_initial; std::vector<std::shared_ptr<std::vector<size_t>>> mb2_reduce_to_6_steps; std::vector<std::shared_ptr<std::vector<size_t>>> mb2_reduce_to_3_steps; std::vector<size_t> mb2_high_landmarks; std::vector<size_t> mb2_high_and_low_landmarks; }; class DebugMetablockContext: public DebugContextBase<DebugMetablockContextData> { using Data = DebugMetablockContextData; std::shared_ptr<Data> m_data; public: DebugMetablockContext(std::ostream& o, bool p_en, bool p_ea, size_t alphabet_size): DebugContextBase(o, p_en, p_ea), m_data(std::make_shared<Data>(Data {})) { m_data->alphabet_size = alphabet_size; } DebugMetablockContext(DebugContextBase& parent, size_t alphabet_size): DebugContextBase(parent), m_data(std::make_shared<Data>(Data {})) { m_data->alphabet_size = alphabet_size; } template<typename T> void init(size_t type, const T& string, size_t offset) { m_data->type = type; m_data->offset = offset; m_data->metablock = cast_vec(string); print([m_data = m_data](std::ostream& o) { o << " type: " << m_data->type << ", offset: " << m_data->offset << ", metablock: " << vec_to_debug_string(m_data->metablock) << "\n"; }); } void block(size_t width, size_t type) { auto b = TypedBlock { uint8_t(width), uint8_t(type) }; m_data->unadjusted_blocks.push_back(b); print([m_data = m_data, b](std::ostream& o) { o << " block: " << b << "\n"; }); } template<typename T> void mb2_initial(const T& buf) { m_data->mb2_initial = cast_vec(buf); print([m_data = m_data](std::ostream& o) { o << " Alphabet reduction initial:\n" << " " << vec_to_debug_string(m_data->mb2_initial) << "\n"; }); } void mb2_reduce_to_6_start() { print([m_data = m_data](std::ostream& o) { o << " Reduce to 6:\n"; }); } template<typename T> void mb2_reduce_to_6_step(const T& buf) { auto p = std::make_shared<std::vector<size_t>>(cast_vec(buf)); m_data->mb2_reduce_to_6_steps.push_back(p); print([m_data = m_data, p](std::ostream& o) { o << " " << vec_to_debug_string(*p) << "\n"; }); } void mb2_reduce_to_3_start() { print([m_data = m_data](std::ostream& o) { o << " Reduce to 3:\n"; }); } template<typename T> void mb2_reduce_to_3_step(const T& buf) { auto p = std::make_shared<std::vector<size_t>>(cast_vec(buf)); m_data->mb2_reduce_to_3_steps.push_back(p); print([m_data = m_data, p](std::ostream& o) { o << " " << vec_to_debug_string(*p) << "\n"; }); } template<typename T> void mb2_high_landmarks(const T& buf) { m_data->mb2_high_landmarks = cast_vec(buf); print([m_data = m_data](std::ostream& o) { o << " High landmarks:\n" << " " << vec_to_debug_string(m_data->mb2_high_landmarks) << "\n"; }); } template<typename T> void mb2_high_and_low_landmarks(const T& buf) { m_data->mb2_high_and_low_landmarks = cast_vec(buf); print([m_data = m_data](std::ostream& o) { o << " High and low landmarks:\n" << " " << vec_to_debug_string(m_data->mb2_high_and_low_landmarks) << "\n"; }); } }; struct DebugRoundContextData { size_t number; std::vector<size_t> string; size_t root_node = 0; bool empty = false; std::vector<DebugMetablockContext> metablocks; size_t alphabet_size; std::vector<TypedBlock> adjusted_blocks; std::vector<std::shared_ptr<std::pair<std::vector<size_t>, size_t>>> slice_symbol_map; }; class DebugRoundContext: public DebugContextBase<DebugRoundContextData> { using Data = DebugRoundContextData; std::shared_ptr<Data> m_data; public: DebugRoundContext(std::ostream& o, bool p_en, bool p_ea): DebugContextBase(o, p_en, p_ea), m_data(std::make_shared<Data>(Data {})) {} DebugRoundContext(DebugContextBase& parent): DebugContextBase(parent), m_data(std::make_shared<Data>(Data {})) {} void init(size_t number, const std::vector<size_t>& string, size_t alphabet_size) { m_data->number = number; m_data->string = string; m_data->alphabet_size = alphabet_size; print([m_data = m_data](std::ostream& o) { o << "\n[Round #" << m_data->number << "]:\n" << " " << vec_to_debug_string(m_data->string) << "\n"; o << " Alphabet size: " << m_data->alphabet_size << "\n"; }); } void last_round(size_t rn, bool empty) { m_data->root_node = rn; m_data->empty = empty; print([m_data = m_data](std::ostream& o) { if (m_data->empty) { o << " DONE, empty input\n"; } else { o << " DONE, root node: " << m_data->root_node << "\n"; } }); } DebugMetablockContext metablock() { DebugMetablockContext m_data_child(*this, m_data->alphabet_size); m_data->metablocks.push_back(m_data_child); print([m_data_child](std::ostream& o) { m_data_child.print_all(); }); return m_data_child; } void adjusted_blocks(const ConstGenericView<TypedBlock>& buf) { m_data->adjusted_blocks = buf; print([m_data = m_data](std::ostream& o) { o << " Adjusted blocks:\n"; for (auto b : m_data->adjusted_blocks) { o << " block: " << b << "\n"; } }); } void slice_symbol_map_start() { print([m_data = m_data](std::ostream& o) { o << " Slice-Symbol map:\n"; }); } template<typename T> void slice_symbol_map(const T& slice, size_t symbol) { auto p = std::make_shared<std::pair<std::vector<size_t>, size_t>>( std::pair<std::vector<size_t>, size_t> { cast_vec(slice), symbol, } ); m_data->slice_symbol_map.push_back(p); print([m_data = m_data, p](std::ostream& o) { o << " " << vec_to_debug_string(p->first) << " -> " << p->second << "\n"; }); } }; struct DebugContextData { std::string input; std::vector<DebugRoundContext> rounds; bool empty; size_t root_node; size_t encode_max_value; size_t encode_max_value_bits; size_t encode_root_node; std::vector<std::shared_ptr<std::vector<size_t>>> encode_slp; }; class DebugContext: public DebugContextBase<DebugContextData> { using Data = DebugContextData; std::shared_ptr<Data> m_data; public: DebugContext(std::ostream& o, bool p_en, bool p_ea): DebugContextBase(o, p_en, p_ea), m_data(std::make_shared<Data>(Data {})) {} void input_string(string_ref s) { m_data->input = s; print([m_data = m_data](std::ostream& o) { o << "\n[Input]:\n\"" << m_data->input << "\"\n"; }); } void generate_grammar(bool empty, size_t root_node) { m_data->empty = empty; m_data->root_node = root_node; print([m_data = m_data](std::ostream& o) { o << "\n[Grammar]:\n" << " Is empty: " << (m_data->empty? "yes" : "no") << "\n" << " Root node: " << m_data->root_node << "\n"; }); } void encode_start() { print([m_data = m_data](std::ostream& o) { o << "\n[Encode]:\n"; }); } void encode_max_value(size_t value, size_t bits) { m_data->encode_max_value = value; m_data->encode_max_value_bits = bits; print([m_data = m_data](std::ostream& o) { o << " Max value: " << m_data->encode_max_value << "\n"; o << " Bits: " << m_data->encode_max_value_bits << "\n"; }); } void encode_root_node(size_t node) { m_data->encode_root_node = node; print([m_data = m_data](std::ostream& o) { o << " Root node: " << m_data->encode_root_node << "\n"; }); } void encode_rule_start() { print([m_data = m_data](std::ostream& o) { o << "\n [SLP]:\n"; }); } template<typename T> void encode_rule(const T& rule) { auto p = std::make_shared<std::vector<size_t>>(cast_vec(rule)); m_data->encode_slp.push_back(p); print([m_data = m_data, p](std::ostream& o) { o << " " << vec_to_debug_string(*p) << "\n"; }); } DebugRoundContext round() { DebugRoundContext m_data_child(*this); m_data->rounds.push_back(m_data_child); print([m_data_child](std::ostream& o) { m_data_child.print_all(); }); return m_data_child; } }; }} <|endoftext|>
<commit_before>// An "Antiafk" program that prevents the character from timing out in-game. // For World of Warcraft version 3.3.5 123450 #include <iostream> #include <thread> #include <distant/virtual_memory.hpp> #include <distant/privileges.hpp> int main() { using distant::process_rights; using distant::page_protection; // Open the process with pid 137016. // For simplicity, this is assumed to be the target wow.exe, version 3.3.5 123450. const distant::process<distant::vm_r_op> wow(137016); if (!wow) { std::cerr << "Unable to open wow\n"; return 0; } // Static addresses corresponding to the last action in-game, and the current timestamp. constexpr distant::address last_action_address = 0x00B499A4; constexpr distant::address timestamp_address = 0x00B1D618; // Get a reference to the last time we moved the mouse in-game auto& last_action = distant::make_virtual_reference<int>(wow, last_action_address); // Get a reference to the current wow time const auto& timestamp = distant::make_virtual_reference<int>(wow, timestamp_address); try { while (true) { // Wait 1 second std::this_thread::sleep_for(std::chrono::seconds(1)); // Read the current time int current_time = timestamp; // This amounts to the following code: current_time = distant::memory::read<int>(wow, timestamp_address); // Write the current time to the last action. last_action = current_time; // This amounts to the following code: distant::memory::write<int>(wow, last_action_address, current_time); std::cout << "Last action: " << last_action << '\n'; std::cout << "Timestamp: " << timestamp << "\n\n"; } } catch (std::system_error& e) { std::cout << e.what() << e.code() << '\n'; } } // https://wowgaming.altervista.org/aowow <commit_msg>Update wow_antiafk.cpp<commit_after>// An "Antiafk" program that prevents the character from timing out in-game. // For World of Warcraft version 3.3.5 123450 #include <iostream> #include <thread> #include <distant/virtual_memory.hpp> #include <distant/privileges.hpp> int main() { using distant::process_rights; using distant::page_protection; // Open the process with pid 137016. // For simplicity, this is assumed to be the target wow.exe, version 3.3.5 123450. const distant::process<distant::vm_rw_op> wow(137016); if (!wow) { std::cerr << "Unable to open wow\n"; return 0; } // Static addresses corresponding to the last action in-game, and the current timestamp. constexpr distant::address last_action_address = 0x00B499A4; constexpr distant::address timestamp_address = 0x00B1D618; // Get a reference to the last time we moved the mouse in-game auto& last_action = distant::make_virtual_reference<int>(wow, last_action_address); // Get a reference to the current wow time const auto& timestamp = distant::make_virtual_reference<int>(wow, timestamp_address); try { while (true) { // Wait 1 second std::this_thread::sleep_for(std::chrono::seconds(1)); // Read the current time int current_time = timestamp; // This amounts to the following code: current_time = distant::memory::read<int>(wow, timestamp_address); // Write the current time to the last action. last_action = current_time; // This amounts to the following code: distant::memory::write<int>(wow, last_action_address, current_time); std::cout << "Last action: " << last_action << '\n'; std::cout << "Timestamp: " << timestamp << "\n\n"; } } catch (std::system_error& e) { std::cout << e.what() << e.code() << '\n'; } } // https://wowgaming.altervista.org/aowow <|endoftext|>
<commit_before>/* Copyright libCellML Contributors 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 "test_utils.h" #include "gtest/gtest.h" #include <libcellml> TEST(Generator, isolatedFirstOrderModel) { // This test resulted from https://github.com/cellml/libcellml/issues/432 // 1.a Create the model instance. libcellml::ModelPtr model = libcellml::Model::create(); model->setName("Tutorial4_FirstOrderModel"); // 1.b Create a component and add it into the model. libcellml::ComponentPtr component = libcellml::Component::create(); component->setName("IonChannel"); model->addComponent(component); // 2.a Define the mathematics. const std::string mathHeader = "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" xmlns:cellml=\"http://www.cellml.org/cellml/2.0#\">"; // dy/dt = alpha_y*(1-y) - beta_y*y const std::string equation1 = "<apply>\n" " <eq/>\n" " <apply>\n" " <diff/>\n" " <bvar>\n" " <ci>t</ci>\n" " </bvar>\n" " <ci>y</ci>\n" " </apply>\n" " <apply>\n" " <minus/>\n" " <apply>\n" " <times/>\n" " <ci>alpha_y</ci>\n" " <apply>\n" " <minus/>\n" " <cn cellml:units=\"dimensionless\">1</cn>\n" " <ci>y</ci>\n" " </apply>\n" " </apply>\n" " <apply>\n" " <times/>\n" " <ci>beta_y</ci>\n" " <ci>y</ci>\n" " </apply>\n" " </apply>\n" "</apply>\n"; // i_y = g_y*power(y,gamma)*(V-E_y) const std::string equation2 = "<apply>\n" " <eq/>\n" " <ci>i_y</ci>\n" " <apply>\n" " <times/>\n" " <ci>g_y</ci>\n" " <apply>\n" " <minus/>\n" " <ci>V</ci>\n" " <ci>E_y</ci>\n" " </apply>\n" " <apply>\n" " <power/>\n" " <ci>y</ci>\n" " <ci>gamma</ci>\n" " </apply>\n" " </apply>\n" "</apply>"; const std::string mathFooter = "</math>"; // 2.b Add the maths to the component. Note that there is only one maths // string stored, so parts which are appended must create a viable // MathML string when concantenated. To clear any string, which is // already stored, simply call setMath("") with an empty string. component->setMath(mathHeader); component->appendMath(equation1); component->appendMath(equation2); component->appendMath(mathFooter); // 3.a,b Declaring the variables, their names, units, and initial conditions // Note that the names given to variables must be the same as that used // within the <ci> blocks in the MathML string we created in step 2.a. libcellml::VariablePtr t = libcellml::Variable::create(); t->setName("t"); t->setUnits("millisecond"); // Note: time is our integration base variable so it is not initialised. libcellml::VariablePtr V = libcellml::Variable::create(); V->setName("V"); V->setUnits("millivolt"); V->setInitialValue(0.0); libcellml::VariablePtr alpha_y = libcellml::Variable::create(); alpha_y->setName("alpha_y"); alpha_y->setUnits("per_millisecond"); alpha_y->setInitialValue(1.0); libcellml::VariablePtr beta_y = libcellml::Variable::create(); beta_y->setName("beta_y"); beta_y->setUnits("per_millisecond"); beta_y->setInitialValue(2.0); libcellml::VariablePtr y = libcellml::Variable::create(); y->setName("y"); y->setUnits("dimensionless"); y->setInitialValue(1.0); libcellml::VariablePtr E_y = libcellml::Variable::create(); E_y->setName("E_y"); E_y->setUnits("millivolt"); E_y->setInitialValue(-85.0); libcellml::VariablePtr i_y = libcellml::Variable::create(); i_y->setName("i_y"); i_y->setUnits("microA_per_cm2"); // Note that no initial value is needed for this variable as its value // is defined by equation2. libcellml::VariablePtr g_y = libcellml::Variable::create(); g_y->setName("g_y"); g_y->setUnits("milliS_per_cm2"); g_y->setInitialValue(36.0); libcellml::VariablePtr gamma = libcellml::Variable::create(); gamma->setName("gamma"); gamma->setUnits("dimensionless"); gamma->setInitialValue(4.0); // 3.c Adding the variables to the component. Note that Variables are // added by their pointer (cf. their name). component->addVariable(t); component->addVariable(V); component->addVariable(E_y); component->addVariable(gamma); component->addVariable(i_y); component->addVariable(g_y); component->addVariable(alpha_y); component->addVariable(beta_y); component->addVariable(y); // 4.a Defining the units of millisecond, millivolt, per_millisecond, // microA_per_cm2, and milliS_per_cm2. Note that the dimensionless // units are part of those built-in already, so they don't need to be // defined here. libcellml::UnitsPtr ms = libcellml::Units::create(); ms->setName("millisecond"); ms->addUnit("second", "milli"); libcellml::UnitsPtr mV = libcellml::Units::create(); mV->setName("millivolt"); mV->addUnit("volt", "milli"); libcellml::UnitsPtr per_ms = libcellml::Units::create(); per_ms->setName("per_millisecond"); per_ms->addUnit("millisecond", -1.0); libcellml::UnitsPtr microA_per_cm2 = libcellml::Units::create(); microA_per_cm2->setName("microA_per_cm2"); microA_per_cm2->addUnit("ampere", "micro"); microA_per_cm2->addUnit("metre", "centi", -2.0); libcellml::UnitsPtr mS_per_cm2 = libcellml::Units::create(); mS_per_cm2->setName("milliS_per_cm2"); mS_per_cm2->addUnit("siemens", "milli"); mS_per_cm2->addUnit("metre", "centi", -2.0); // 4.b Add these units into the model. model->addUnits(ms); model->addUnits(mV); model->addUnits(per_ms); model->addUnits(microA_per_cm2); model->addUnits(mS_per_cm2); // Link the units used by variables in the model to // units added to the model. model->linkUnits(); // 4.c Validate the final arrangement. No issues are expected at this stage. libcellml::ValidatorPtr validator = libcellml::Validator::create(); validator->validateModel(model); EXPECT_EQ(size_t(0), validator->issueCount()); // 5.a Create a Generator instance. By default the options set in the // generator constructor are: // - profile() return "C" (cf "PYTHON"); and // - modelType() returns "ODE". libcellml::AnalyserPtr analyser = libcellml::Analyser::create(); analyser->analyseModel(model); // 5.b Check whether the generator has encountered any issues. EXPECT_EQ(size_t(0), analyser->issueCount()); } <commit_msg>Generator test: fixed a typo.<commit_after>/* Copyright libCellML Contributors 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 "test_utils.h" #include "gtest/gtest.h" #include <libcellml> TEST(Generator, isolatedFirstOrderModel) { // This test resulted from https://github.com/cellml/libcellml/issues/432 // 1.a Create the model instance. libcellml::ModelPtr model = libcellml::Model::create(); model->setName("Tutorial4_FirstOrderModel"); // 1.b Create a component and add it into the model. libcellml::ComponentPtr component = libcellml::Component::create(); component->setName("IonChannel"); model->addComponent(component); // 2.a Define the mathematics. const std::string mathHeader = "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" xmlns:cellml=\"http://www.cellml.org/cellml/2.0#\">"; // dy/dt = alpha_y*(1-y) - beta_y*y const std::string equation1 = "<apply>\n" " <eq/>\n" " <apply>\n" " <diff/>\n" " <bvar>\n" " <ci>t</ci>\n" " </bvar>\n" " <ci>y</ci>\n" " </apply>\n" " <apply>\n" " <minus/>\n" " <apply>\n" " <times/>\n" " <ci>alpha_y</ci>\n" " <apply>\n" " <minus/>\n" " <cn cellml:units=\"dimensionless\">1</cn>\n" " <ci>y</ci>\n" " </apply>\n" " </apply>\n" " <apply>\n" " <times/>\n" " <ci>beta_y</ci>\n" " <ci>y</ci>\n" " </apply>\n" " </apply>\n" "</apply>\n"; // i_y = g_y*power(y,gamma)*(V-E_y) const std::string equation2 = "<apply>\n" " <eq/>\n" " <ci>i_y</ci>\n" " <apply>\n" " <times/>\n" " <ci>g_y</ci>\n" " <apply>\n" " <minus/>\n" " <ci>V</ci>\n" " <ci>E_y</ci>\n" " </apply>\n" " <apply>\n" " <power/>\n" " <ci>y</ci>\n" " <ci>gamma</ci>\n" " </apply>\n" " </apply>\n" "</apply>"; const std::string mathFooter = "</math>"; // 2.b Add the maths to the component. Note that there is only one maths // string stored, so parts which are appended must create a viable // MathML string when concatenated. To clear any string, which is // already stored, simply call setMath("") with an empty string. component->setMath(mathHeader); component->appendMath(equation1); component->appendMath(equation2); component->appendMath(mathFooter); // 3.a,b Declaring the variables, their names, units, and initial conditions // Note that the names given to variables must be the same as that used // within the <ci> blocks in the MathML string we created in step 2.a. libcellml::VariablePtr t = libcellml::Variable::create(); t->setName("t"); t->setUnits("millisecond"); // Note: time is our integration base variable so it is not initialised. libcellml::VariablePtr V = libcellml::Variable::create(); V->setName("V"); V->setUnits("millivolt"); V->setInitialValue(0.0); libcellml::VariablePtr alpha_y = libcellml::Variable::create(); alpha_y->setName("alpha_y"); alpha_y->setUnits("per_millisecond"); alpha_y->setInitialValue(1.0); libcellml::VariablePtr beta_y = libcellml::Variable::create(); beta_y->setName("beta_y"); beta_y->setUnits("per_millisecond"); beta_y->setInitialValue(2.0); libcellml::VariablePtr y = libcellml::Variable::create(); y->setName("y"); y->setUnits("dimensionless"); y->setInitialValue(1.0); libcellml::VariablePtr E_y = libcellml::Variable::create(); E_y->setName("E_y"); E_y->setUnits("millivolt"); E_y->setInitialValue(-85.0); libcellml::VariablePtr i_y = libcellml::Variable::create(); i_y->setName("i_y"); i_y->setUnits("microA_per_cm2"); // Note that no initial value is needed for this variable as its value // is defined by equation2. libcellml::VariablePtr g_y = libcellml::Variable::create(); g_y->setName("g_y"); g_y->setUnits("milliS_per_cm2"); g_y->setInitialValue(36.0); libcellml::VariablePtr gamma = libcellml::Variable::create(); gamma->setName("gamma"); gamma->setUnits("dimensionless"); gamma->setInitialValue(4.0); // 3.c Adding the variables to the component. Note that Variables are // added by their pointer (cf. their name). component->addVariable(t); component->addVariable(V); component->addVariable(E_y); component->addVariable(gamma); component->addVariable(i_y); component->addVariable(g_y); component->addVariable(alpha_y); component->addVariable(beta_y); component->addVariable(y); // 4.a Defining the units of millisecond, millivolt, per_millisecond, // microA_per_cm2, and milliS_per_cm2. Note that the dimensionless // units are part of those built-in already, so they don't need to be // defined here. libcellml::UnitsPtr ms = libcellml::Units::create(); ms->setName("millisecond"); ms->addUnit("second", "milli"); libcellml::UnitsPtr mV = libcellml::Units::create(); mV->setName("millivolt"); mV->addUnit("volt", "milli"); libcellml::UnitsPtr per_ms = libcellml::Units::create(); per_ms->setName("per_millisecond"); per_ms->addUnit("millisecond", -1.0); libcellml::UnitsPtr microA_per_cm2 = libcellml::Units::create(); microA_per_cm2->setName("microA_per_cm2"); microA_per_cm2->addUnit("ampere", "micro"); microA_per_cm2->addUnit("metre", "centi", -2.0); libcellml::UnitsPtr mS_per_cm2 = libcellml::Units::create(); mS_per_cm2->setName("milliS_per_cm2"); mS_per_cm2->addUnit("siemens", "milli"); mS_per_cm2->addUnit("metre", "centi", -2.0); // 4.b Add these units into the model. model->addUnits(ms); model->addUnits(mV); model->addUnits(per_ms); model->addUnits(microA_per_cm2); model->addUnits(mS_per_cm2); // Link the units used by variables in the model to // units added to the model. model->linkUnits(); // 4.c Validate the final arrangement. No issues are expected at this stage. libcellml::ValidatorPtr validator = libcellml::Validator::create(); validator->validateModel(model); EXPECT_EQ(size_t(0), validator->issueCount()); // 5.a Create a Generator instance. By default the options set in the // generator constructor are: // - profile() return "C" (cf "PYTHON"); and // - modelType() returns "ODE". libcellml::AnalyserPtr analyser = libcellml::Analyser::create(); analyser->analyseModel(model); // 5.b Check whether the generator has encountered any issues. EXPECT_EQ(size_t(0), analyser->issueCount()); } <|endoftext|>
<commit_before>#include "pkgcache.h" /* * call-seq: gen_caches() -> bool * * Call the main cache generator. * * Debian::AptPkg::PkgCache.gen_caches # => false * **/ static VALUE gen_caches(VALUE self) { pkgCacheFile CacheFile; int res = CacheFile.BuildCaches(NULL, true); return INT2BOOL(res); } /* * call-seq: pkg_names() -> array * * List the names of all packages in the system. * * Debian::AptPkg::PkgCache.pkg_names('gcolor2') # => ["gcolor2"] * **/ static VALUE pkg_names(int argc, VALUE* argv, VALUE self) { if (argc > 1 || argc == 0) { rb_raise(rb_eArgError, "You must give at least one search argument"); } VALUE name; rb_scan_args(argc, argv, "01", &name); if (NIL_P(name) || RSTRING_LEN(name) < 1) { rb_raise(rb_eArgError, "You must give at least one search pattern"); } VALUE result = rb_ary_new(); pkgCacheFile CacheFile; pkgCache::GrpIterator I = CacheFile.GetPkgCache()->GrpBegin(); const char *pkgname = StringValuePtr(name); for (;I.end() != true; ++I) { if (strncmp(I.Name(), pkgname, strlen(pkgname)) == 0) { rb_ary_push(result, rb_str_new2(I.Name())); } } return result; } void init_apt_pkg_pkgcache() { VALUE rb_mDebian = rb_define_module("Debian"); VALUE rb_mDebianAptPkg = rb_define_module_under(rb_mDebian, "AptPkg"); VALUE rb_mDebianAptPkgConfiguration = rb_define_module_under(rb_mDebianAptPkg, "PkgCache"); rb_define_singleton_method(rb_mDebianAptPkgConfiguration, "gen_caches", RUBY_METHOD_FUNC(gen_caches), 0); rb_define_singleton_method(rb_mDebianAptPkgConfiguration, "pkg_names", RUBY_METHOD_FUNC(pkg_names), -1); } <commit_msg>Avoid segfault when cache is not generated<commit_after>#include "pkgcache.h" /* * call-seq: gen_caches() -> bool * * Call the main cache generator. * * Debian::AptPkg::PkgCache.gen_caches # => false * **/ static VALUE gen_caches(VALUE self) { pkgCacheFile CacheFile; int res = CacheFile.BuildCaches(NULL, true); return INT2BOOL(res); } /* * call-seq: pkg_names() -> array, nil * * List the names of all packages in the system. * Return nil when cache is not generated. * * Debian::AptPkg::PkgCache.pkg_names('gcolor2') # => ["gcolor2"] * **/ static VALUE pkg_names(int argc, VALUE* argv, VALUE self) { if (argc > 1 || argc == 0) { rb_raise(rb_eArgError, "You must give at least one search argument"); } VALUE name; rb_scan_args(argc, argv, "01", &name); if (NIL_P(name) || RSTRING_LEN(name) < 1) { rb_raise(rb_eArgError, "You must give at least one search pattern"); } VALUE result = rb_ary_new(); pkgCacheFile CacheFile; if (CacheFile.GetPkgCache() == 0) { return Qnil; } pkgCache::GrpIterator I = CacheFile.GetPkgCache()->GrpBegin(); const char *pkgname = StringValuePtr(name); for (;I.end() != true; ++I) { if (strncmp(I.Name(), pkgname, strlen(pkgname)) == 0) { rb_ary_push(result, rb_str_new2(I.Name())); } } return result; } void init_apt_pkg_pkgcache() { VALUE rb_mDebian = rb_define_module("Debian"); VALUE rb_mDebianAptPkg = rb_define_module_under(rb_mDebian, "AptPkg"); VALUE rb_mDebianAptPkgConfiguration = rb_define_module_under(rb_mDebianAptPkg, "PkgCache"); rb_define_singleton_method(rb_mDebianAptPkgConfiguration, "gen_caches", RUBY_METHOD_FUNC(gen_caches), 0); rb_define_singleton_method(rb_mDebianAptPkgConfiguration, "pkg_names", RUBY_METHOD_FUNC(pkg_names), -1); } <|endoftext|>
<commit_before>/* v.0.12 4 August 2015 * Kevin CAIN, www.insightdigital.org * Adapted from the openMVG libraries, * Copyright (c) 2012, 2013 Pierre MOULON. * * 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/. */ #include "openMVG/sfm/sfm.hpp" #include "openMVG/image/image.hpp" using namespace openMVG; using namespace openMVG::cameras; using namespace openMVG::geometry; using namespace openMVG::image; using namespace openMVG::sfm; using namespace openMVG::features; #include "third_party/cmdLine/cmdLine.h" #include "third_party/progress/progress.hpp" #include <stdlib.h> #include <stdio.h> #include <cmath> #include <iterator> #include <iomanip> /* Notes: * - An MVE2 scene appears to duplicate camera rot matrix and trans vector per-view data in 'meta.ini' * within the first section of 'synth_0.out'. * - We do not save the original, instead we rely on the undistorted image from openMPV. * - We do not output thumbnails or EXIF blobs, as these appear only to be used only for the GUI UMVE. * - To avoid encoding loss, openMPV images should be written as .PNG if undistorted images are *not* computed. * * For information on the target for this conversion, please see the MVE (v2) File format: * https://github.com/simonfuhrmann/mve/wiki/MVE-File-Format */ bool exportToMVE2Format( const SfM_Data & sfm_data, const std::string & sOutDirectory // Output MVE2 files directory ) { bool bOk = true; // Create basis directory structure if (!stlplus::is_folder(sOutDirectory)) { cout << "\033[1;31mCreating directory: " << sOutDirectory << "\033[0m\n"; stlplus::folder_create(sOutDirectory); bOk = stlplus::is_folder(sOutDirectory); } if (!bOk) { std::cerr << "Cannot access one of the desired output directories" << std::endl; return false; } else { // Create 'views' subdirectory string sOutViewsDirectory = stlplus::folder_append_separator(sOutDirectory) + "views"; cout << "\033[1;31mCreating directory: " << sOutViewsDirectory << "\033[0m\n"; stlplus::folder_create(sOutViewsDirectory); // Prepare to write bundle file // Get cameras and features from OpenMPV int cameraCount = std::distance(sfm_data.GetViews().begin(), sfm_data.GetViews().end()); // Tally global set of feature landmarks const Landmarks & landmarks = sfm_data.GetLandmarks(); int featureCount = std::distance(landmarks.begin(), landmarks.end()); string filename = "synth_0.out"; std::cout << "Writing bundle (" << cameraCount << " cameras, " << featureCount << " features): to " << filename << "...\n"; std::ofstream out(stlplus::folder_append_separator(sOutDirectory) + filename); out << "drews 1.0\n"; // MVE expects this header out << cameraCount << " " << featureCount << "\n"; // Export data : C_Progress_display my_progress_bar( sfm_data.GetViews().size()*2 ); // MVE, like CMPMVS, requires a contiguous camera index. In openMPV, some views may have some missing poses; // here we reindex the poses to ensure a contiguous pose list. Hash_Map<IndexT, IndexT> map_viewIdToContiguous; // Export valid views as Projective Cameras: for(Views::const_iterator iter = sfm_data.GetViews().begin(); iter != sfm_data.GetViews().end(); ++iter, ++my_progress_bar) { const View * view = iter->second.get(); if (!sfm_data.IsPoseAndIntrinsicDefined(view)) continue; const Pose3 pose = sfm_data.GetPoseOrDie(view); Intrinsics::const_iterator iterIntrinsic = sfm_data.GetIntrinsics().find(view->id_intrinsic); // View Id re-indexing map_viewIdToContiguous.insert(std::make_pair(view->id_view, map_viewIdToContiguous.size())); } // Export (calibrated) views as undistorted images std::pair<int,int> w_h_image_size; Image<RGBColor> image, image_ud; string sOutViewIteratorDirectory; for(Views::const_iterator iter = sfm_data.GetViews().begin(); iter != sfm_data.GetViews().end(); ++iter, ++my_progress_bar) { const View * view = iter->second.get(); if (!sfm_data.IsPoseAndIntrinsicDefined(view)) continue; // Create current view subdirectory 'view_xxxx.mve' std::ostringstream padding; padding << std::setw(4) << std::setfill('0') << map_viewIdToContiguous[view->id_view]; sOutViewIteratorDirectory = stlplus::folder_append_separator(sOutViewsDirectory) + "view_" + padding.str() + ".mve"; stlplus::folder_create(sOutViewIteratorDirectory); Intrinsics::const_iterator iterIntrinsic = sfm_data.GetIntrinsics().find(view->id_intrinsic); // We have a valid view with a corresponding camera & pose const std::string srcImage = stlplus::create_filespec(sfm_data.s_root_path, view->s_Img_path); std::ostringstream os; os << std::setw(5) << std::setfill('0') << map_viewIdToContiguous[view->id_view]; std::string dstImage = stlplus::create_filespec( stlplus::folder_append_separator(sOutViewIteratorDirectory), "undistorted","png"); const IntrinsicBase * cam = iterIntrinsic->second.get(); if (map_viewIdToContiguous[view->id_view] == 0) w_h_image_size = std::make_pair(cam->w(), cam->h()); else { // check that there is no image sizing change -- do we need to enforce this for MVE? if (cam->w() != w_h_image_size.first || cam->h() != w_h_image_size.second) { std::cerr << "CMPMVS support only image having the same image size"; return false; } } if (cam->have_disto()) { // Undistort and save the image ReadImage(srcImage.c_str(), &image); UndistortImage(image, cam, image_ud, BLACK); WriteImage(dstImage.c_str(), image_ud); } else // (no distortion) { // If extensions match, copy the PNG image if (stlplus::extension_part(srcImage) == "PNG" || stlplus::extension_part(srcImage) == "png") { stlplus::file_copy(srcImage, dstImage); } else { ReadImage( srcImage.c_str(), &image); WriteImage( dstImage.c_str(), image); } } // Prepare to write an MVE 'meta.ini' file for the current view const Pose3 pose = sfm_data.GetPoseOrDie(view); Mat34 P = cam->get_projective_equivalent(pose); for ( int i = 1; i < 3 ; ++i) for ( int j = 0; j < 4; ++j) P(i, j) *= -1.; Mat3 R, K; Vec3 t; KRt_From_P( P, &K, &R, &t); // Output translation via optical center vector for given pose const Vec3 optical_center = R.transpose() * t; // Pixel aspect = pixel width divided by the pixel height const float pixelAspect = cam->w()/cam->h(); // Focal length and principal point are embedded into the calibration matrix K: // focal_length = K(0,0) // const std::vector<double> pp = {_K(0,2), _K(1,2)} // their values are normalized (0..1) const float flen = cam->h()/K(0, 0); const float ppX = abs(K(0,2)/cam->w()); const float ppY = abs(K(1,2)/cam->h()); std::ostringstream fileOut; fileOut << "#MVE view meta data is stored in INI-file syntax." << fileOut.widen('\n') << "#This file is generated, formatting will get lost." << fileOut.widen('\n') << fileOut.widen('\n') << "[camera]" << fileOut.widen('\n') << "focal_length = " << flen << fileOut.widen('\n') << "pixel_aspect = " << pixelAspect << fileOut.widen('\n') << "principal_point = " << ppX << " " << ppY << fileOut.widen('\n') << "rotation = " << R(0, 0) << " " << R(0, 1) << " " << R(0, 2) << " " << R(1, 0) << " " << R(1, 1) << " " << R(1, 2) << " " << R(2, 0) << " " << R(2, 1) << " " << R(2, 2) << fileOut.widen('\n') << "translation = " << optical_center[0] << " " << optical_center[1] << " " << optical_center[2] << " " << fileOut.widen('\n') << "[view]" << fileOut.widen('\n') << "id = " << view->id_view << fileOut.widen('\n') << "name = " << srcImage.c_str() << fileOut.widen('\n'); // To do: trim any extra separator(s) from openMPV name we receive, e.g.: // '/home/insight/openMVG_KevinCain/openMVG_Build/software/SfM/ImageDataset_SceauxCastle/images//100_7100.JPG' std::ofstream file( stlplus::create_filespec(stlplus::folder_append_separator(sOutViewIteratorDirectory), "meta","ini").c_str()); file << fileOut.str(); file.close(); // Save a thumbnail image "thumbnail.png", 50x50 pixels // For now, we ignore thumbnails under the assumption that they are used only by UMVE // Pierre Moulon suggested we resample as per: https://github.com/openMVG/openMVG/blob/develop/src/openMVG/image/image_resampling_test.cpp#L24 // For each camera, write to bundle: focal length, radial distortion[0-1], rotation matrix[0-8], translation vector[0-2] // To do: add more rigorous camera sanity checks, as per: // https://github.com/simonfuhrmann/mve/blob/e3db7bc60ce93fe51702ba77ef480e151f927c23/libs/mve/bundle_io.cc if (flen == 0.0f) { for (int i = 0; i < 5 * 3; ++i) out << "0" << (i % 3 == 2 ? "\n" : " "); continue; } out << flen << " " << "0" << " " << "0" << "\n"; // Write '0' distortion values for pre-corrected images out << R(0, 0) << " " << R(0, 1) << " " << R(0, 2) << "\n"; out << R(1, 0) << " " << R(1, 1) << " " << R(1, 2) << "\n"; out << R(2, 0) << " " << R(2, 1) << " " << R(2, 2) << "\n"; out << optical_center[0] << " " << optical_center[1] << " " << optical_center[2] << "\n"; } // For each feature, write to bundle: position XYZ[0-3], color RGB[0-2], all ref.view_id & ref.feature_id // The following method is adapted from Simon Fuhrmann's MVE project: // https://github.com/simonfuhrmann/mve/blob/e3db7bc60ce93fe51702ba77ef480e151f927c23/libs/mve/bundle_io.cc for (Landmarks::const_iterator iterLandmarks = landmarks.begin(); iterLandmarks != landmarks.end(); ++iterLandmarks) { const Vec3 exportPoint = iterLandmarks->second.X; out << exportPoint.x() << " " << exportPoint.y() << " " << exportPoint.z() << "\n"; out << 250 << " " << 100 << " " << 150 << "\n"; // Write arbitrary RGB color, see above note // Tally set of feature observations const Observations & obs = iterLandmarks->second.obs; int featureCount = std::distance(obs.begin(), obs.end()); out << featureCount; // MVE equivalent: p.refs.size(); for (Observations::const_iterator itObs = obs.begin(); itObs != obs.end(); ++itObs) { const IndexT viewId = itObs->first; const IndexT featId = itObs->second.id_feat; out << " " << viewId << " " << featId << " 0"; } out << "\n"; } out.close(); } return bOk; } int main(int argc, char *argv[]) { CmdLine cmd; std::string sSfM_Data_Filename; std::string sOutDir = ""; cmd.add( make_option('i', sSfM_Data_Filename, "sfmdata") ); cmd.add( make_option('o', sOutDir, "outdir") ); cout << "Note: this program writes output in MVE file format v2.\n"; try { if (argc == 1) throw std::string("Invalid command line parameter."); cmd.process(argc, argv); } catch(const std::string& s) { std::cerr << "Usage: " << argv[0] << '\n' << "[-i|--sfmdata] filename, the SfM_Data file to convert\n" << "[-o|--outdir] path\n" << std::endl; std::cerr << s << std::endl; return EXIT_FAILURE; } // Create output dir if (!stlplus::folder_exists(sOutDir)) stlplus::folder_create( sOutDir ); // Read the input SfM scene SfM_Data sfm_data; if (!Load(sfm_data, sSfM_Data_Filename, ESfM_Data(ALL))) { std::cerr << std::endl << "The input SfM_Data file \""<< sSfM_Data_Filename << "\" cannot be read." << std::endl; return EXIT_FAILURE; } if (exportToMVE2Format(sfm_data, stlplus::folder_append_separator(sOutDir) + "MVE")) return( EXIT_SUCCESS ); else return( EXIT_FAILURE ); } <commit_msg>Numerous improvements -- for notes, please see: https://github.com/openMVG/openMVG/pull/351<commit_after>/* v.0.12 5 August 2015 * Kevin CAIN, www.insightdigital.org * Adapted from the openMVG libraries, * Copyright (c) 2012-2015 Pierre MOULON. * * 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/. */ #include "openMVG/sfm/sfm.hpp" #include "openMVG/image/image.hpp" using namespace openMVG; using namespace openMVG::cameras; using namespace openMVG::geometry; using namespace openMVG::image; using namespace openMVG::sfm; using namespace openMVG::features; #include "third_party/cmdLine/cmdLine.h" #include "third_party/progress/progress.hpp" #include <stdlib.h> #include <stdio.h> #include <cmath> #include <iterator> #include <iomanip> /* Notes: * - An MVE2 scene appears to duplicate camera rot matrix and trans vector per-view data in 'meta.ini' * within the first section of 'synth_0.out'. * - We do not save the original, instead we rely on the undistorted image from openMVG. * - We do not output thumbnails or EXIF blobs, as these appear only to be used only for the GUI UMVE. * - To avoid encoding loss, openMVG images should be written as .PNG if undistorted images are *not* computed. * * For information on the target for this conversion, please see the MVE (v2) File format: * https://github.com/simonfuhrmann/mve/wiki/MVE-File-Format */ bool exportToMVE2Format( const SfM_Data & sfm_data, const std::string & sOutDirectory // Output MVE2 files directory ) { bool bOk = true; // Create basis directory structure if (!stlplus::is_folder(sOutDirectory)) { cout << "\033[1;31mCreating directory: " << sOutDirectory << "\033[0m\n"; stlplus::folder_create(sOutDirectory); bOk = stlplus::is_folder(sOutDirectory); } if (!bOk) { std::cerr << "Cannot access one of the desired output directories" << std::endl; return false; } else { // Create 'views' subdirectory string sOutViewsDirectory = stlplus::folder_append_separator(sOutDirectory) + "views"; cout << "\033[1;31mCreating directory: " << sOutViewsDirectory << "\033[0m\n"; stlplus::folder_create(sOutViewsDirectory); // Prepare to write bundle file // Get cameras and features from OpenMVG int cameraCount = std::distance(sfm_data.GetViews().begin(), sfm_data.GetViews().end()); // Tally global set of feature landmarks const Landmarks & landmarks = sfm_data.GetLandmarks(); int featureCount = std::distance(landmarks.begin(), landmarks.end()); string filename = "synth_0.out"; std::cout << "Writing bundle (" << cameraCount << " cameras, " << featureCount << " features): to " << filename << "...\n"; std::ofstream out(stlplus::folder_append_separator(sOutDirectory) + filename); out << "drews 1.0\n"; // MVE expects this header out << cameraCount << " " << featureCount << "\n"; // Export data : C_Progress_display my_progress_bar( sfm_data.GetViews().size()*2 ); // MVE, like CMPMVS, requires a contiguous camera index. In openMPV, some views may have some missing poses; // here we reindex the poses to ensure a contiguous pose list. Hash_Map<IndexT, IndexT> map_viewIdToContiguous; // Export valid views as Projective Cameras: for(Views::const_iterator iter = sfm_data.GetViews().begin(); iter != sfm_data.GetViews().end(); ++iter, ++my_progress_bar) { const View * view = iter->second.get(); if (!sfm_data.IsPoseAndIntrinsicDefined(view)) continue; const Pose3 pose = sfm_data.GetPoseOrDie(view); Intrinsics::const_iterator iterIntrinsic = sfm_data.GetIntrinsics().find(view->id_intrinsic); // View Id re-indexing map_viewIdToContiguous.insert(std::make_pair(view->id_view, map_viewIdToContiguous.size())); } // Export (calibrated) views as undistorted images std::pair<int,int> w_h_image_size; Image<RGBColor> image, image_ud; string sOutViewIteratorDirectory; for(Views::const_iterator iter = sfm_data.GetViews().begin(); iter != sfm_data.GetViews().end(); ++iter, ++my_progress_bar) { const View * view = iter->second.get(); if (!sfm_data.IsPoseAndIntrinsicDefined(view)) continue; // Create current view subdirectory 'view_xxxx.mve' std::ostringstream padding; padding << std::setw(4) << std::setfill('0') << map_viewIdToContiguous[view->id_view]; sOutViewIteratorDirectory = stlplus::folder_append_separator(sOutViewsDirectory) + "view_" + padding.str() + ".mve"; stlplus::folder_create(sOutViewIteratorDirectory); Intrinsics::const_iterator iterIntrinsic = sfm_data.GetIntrinsics().find(view->id_intrinsic); // We have a valid view with a corresponding camera & pose const std::string srcImage = stlplus::create_filespec(sfm_data.s_root_path, view->s_Img_path); //std::ostringstream os; //os << std::setw(5) << std::setfill('0') << map_viewIdToContiguous[view->id_view]; std::string dstImage = stlplus::create_filespec( stlplus::folder_append_separator(sOutViewIteratorDirectory), "undistorted","png"); const IntrinsicBase * cam = iterIntrinsic->second.get(); if (map_viewIdToContiguous[view->id_view] == 0) w_h_image_size = std::make_pair(cam->w(), cam->h()); if (cam->have_disto()) { // Undistort and save the image ReadImage(srcImage.c_str(), &image); UndistortImage(image, cam, image_ud, BLACK); WriteImage(dstImage.c_str(), image_ud); } else // (no distortion) { // If extensions match, copy the PNG image if (stlplus::extension_part(srcImage) == "PNG" || stlplus::extension_part(srcImage) == "png") { stlplus::file_copy(srcImage, dstImage); } else { ReadImage( srcImage.c_str(), &image); WriteImage( dstImage.c_str(), image); } } // Prepare to write an MVE 'meta.ini' file for the current view const Pose3 pose = sfm_data.GetPoseOrDie(view); Mat34 P = cam->get_projective_equivalent(pose); Mat3 R, K; Vec3 t; KRt_From_P(P, &K, &R, &t); Mat3 rotation = pose.rotation(); const Vec3 translation = pose.translation(); // Pixel aspect = pixel width divided by the pixel height const float pixelAspect = cam->w()/cam->h(); // Focal length and principal point are embedded within calibration matrix K: // focal_length = K(0,0) // principal point = {_K(0,2), _K(1,2)} // their values are normalized (0..1) const float flen = K(0,0) / static_cast<double>(std::max(cam->w(), cam->h())); const float ppX = abs(K(0,2)/cam->w()); const float ppY = abs(K(1,2)/cam->h()); std::ostringstream fileOut; fileOut << "#MVE view meta data is stored in INI-file syntax." << fileOut.widen('\n') << "#This file is generated, formatting will get lost." << fileOut.widen('\n') << fileOut.widen('\n') << "[camera]" << fileOut.widen('\n') << "focal_length = " << flen << fileOut.widen('\n') << "pixel_aspect = " << pixelAspect << fileOut.widen('\n') << "principal_point = " << ppX << " " << ppY << fileOut.widen('\n') << "rotation = " << rotation(0, 0) << " " << rotation(0, 1) << " " << rotation(0, 2) << " " << rotation(1, 0) << " " << rotation(1, 1) << " " << rotation(1, 2) << " " << rotation(2, 0) << " " << rotation(2, 1) << " " << rotation(2, 2) << fileOut.widen('\n') << "translation = " << translation[0] << " " << translation[1] << " " << translation[2] << " " << fileOut.widen('\n') << "[view]" << fileOut.widen('\n') << "id = " << view->id_view << fileOut.widen('\n') << "name = " << srcImage.c_str() << fileOut.widen('\n'); // To do: trim any extra separator(s) from openMVG name we receive, e.g.: // '/home/insight/openMVG_KevinCain/openMVG_Build/software/SfM/ImageDataset_SceauxCastle/images//100_7100.JPG' std::ofstream file( stlplus::create_filespec(stlplus::folder_append_separator(sOutViewIteratorDirectory), "meta","ini").c_str()); file << fileOut.str(); file.close(); // Save a thumbnail image "thumbnail.png", 50x50 pixels // For now, we ignore thumbnails under the assumption that they are used only by UMVE // Pierre Moulon suggested we resample as per: https://github.com/openMVG/openMVG/blob/develop/src/openMVG/image/image_resampling_test.cpp#L24 // For each camera, write to bundle: focal length, radial distortion[0-1], rotation matrix[0-8], translation vector[0-2] // To do: add more rigorous camera sanity checks, as per: // https://github.com/simonfuhrmann/mve/blob/e3db7bc60ce93fe51702ba77ef480e151f927c23/libs/mve/bundle_io.cc if (flen == 0.0f) { for (int i = 0; i < 5 * 3; ++i) out << "0" << (i % 3 == 2 ? "\n" : " "); continue; } out << flen << " " << "0" << " " << "0" << "\n"; // Write '0' distortion values for pre-corrected images out << R(0, 0) << " " << R(0, 1) << " " << R(0, 2) << "\n"; out << R(1, 0) << " " << R(1, 1) << " " << R(1, 2) << "\n"; out << R(2, 0) << " " << R(2, 1) << " " << R(2, 2) << "\n"; out << translation[0] << " " << translation[1] << " " << translation[2] << "\n"; } // For each feature, write to bundle: position XYZ[0-3], color RGB[0-2], all ref.view_id & ref.feature_id // The following method is adapted from Simon Fuhrmann's MVE project: // https://github.com/simonfuhrmann/mve/blob/e3db7bc60ce93fe51702ba77ef480e151f927c23/libs/mve/bundle_io.cc for (Landmarks::const_iterator iterLandmarks = landmarks.begin(); iterLandmarks != landmarks.end(); ++iterLandmarks) { const Vec3 exportPoint = iterLandmarks->second.X; out << exportPoint.x() << " " << exportPoint.y() << " " << exportPoint.z() << "\n"; out << 250 << " " << 100 << " " << 150 << "\n"; // Write arbitrary RGB color, see above note // Tally set of feature observations const Observations & obs = iterLandmarks->second.obs; int featureCount = std::distance(obs.begin(), obs.end()); out << featureCount; for (Observations::const_iterator itObs = obs.begin(); itObs != obs.end(); ++itObs) { const IndexT viewId = itObs->first; const IndexT featId = itObs->second.id_feat; out << " " << viewId << " " << featId << " 0"; } out << "\n"; } out.close(); } return bOk; } int main(int argc, char *argv[]) { CmdLine cmd; std::string sSfM_Data_Filename; std::string sOutDir = ""; cmd.add( make_option('i', sSfM_Data_Filename, "sfmdata") ); cmd.add( make_option('o', sOutDir, "outdir") ); cout << "Note: this program writes output in MVE file format v2.\n"; try { if (argc == 1) throw std::string("Invalid command line parameter."); cmd.process(argc, argv); } catch(const std::string& s) { std::cerr << "Usage: " << argv[0] << '\n' << "[-i|--sfmdata] filename, the SfM_Data file to convert\n" << "[-o|--outdir] path\n" << std::endl; std::cerr << s << std::endl; return EXIT_FAILURE; } // Create output dir if (!stlplus::folder_exists(sOutDir)) stlplus::folder_create( sOutDir ); // Read the input SfM scene SfM_Data sfm_data; if (!Load(sfm_data, sSfM_Data_Filename, ESfM_Data(ALL))) { std::cerr << std::endl << "The input SfM_Data file \""<< sSfM_Data_Filename << "\" cannot be read." << std::endl; return EXIT_FAILURE; } if (exportToMVE2Format(sfm_data, stlplus::folder_append_separator(sOutDir) + "MVE")) return( EXIT_SUCCESS ); else return( EXIT_FAILURE ); } <|endoftext|>
<commit_before>/* This test is part of pocl. * Author: Kalle Raiskila, 2014 * * Test the OpenCL-C 'shuffle' command by looping * over all permutations of data and mask vector * lengths. Only one data type at a time is tested, * the type to test is passed as command line argument * (this allows for more interactive testsuite, and * non-supported types (e.g. half, double) are easier * to filter out). * The data to be shuffled is vectors where the elemnet * data equals the element index (i.e. [0,1,2,3]) but * the shuffle pattern masks are generated with rand(). */ #include "poclu.h" #include <cstdio> #include <cstring> #include <CL/cl.h> #include <iostream> #include <cmath> #include <cstdlib> cl_context ctx; cl_device_id did; cl_platform_id pid; cl_command_queue queue; #define ERRCHECK() if (check_cl_error(errcode, __LINE__, __FUNCTION__)) abort(); static const unsigned vecelts[] = {2,4,8,16}; static const int stimuli[] = {4, 2, 69, 4, 5, 0, 45, 16, 4, 6, 1, 18, 28, 14, 22, 16, 8, 2, 0, 31, 42, 11, 62, 88, 99, 23, 13}; template <typename D, typename M> class TestShuffle { cl_mem mem_in1, mem_in2, mem_out, mem_mask1, mem_mask2; cl_program prog; D in1 [16] __attribute__ ((aligned (128))); D in2 [16] __attribute__ ((aligned (128))); D out [16] __attribute__ ((aligned (128))); M mask1 [16] __attribute__ ((aligned (128))); M mask2 [16] __attribute__ ((aligned (128))); const char* ocl_type; unsigned size; cl_int errcode; private: /* Prints into std::string all the OpenCL kernel sources for each n,m combo */ void testcase_src(std::string & src) { char buf[1024]; int rv; unsigned n, m; const char* mask_type; switch(sizeof(M)) { case 1: mask_type = "uchar"; break; case 2: mask_type = "ushort"; break; case 4: mask_type = "uint"; break; case 8: mask_type = "ulong"; break; default: mask_type = "UNKNOWN_MASK"; } for(unsigned n_loop=0; n_loop<4; n_loop++) { for(unsigned m_loop=0; m_loop<4; m_loop++) { n = vecelts[n_loop]; m = vecelts[m_loop]; rv = 0; buf[0] = 0; rv=sprintf(buf, "__kernel void test_shuffle_%d_%d(" "__global %s%d *in, __global %s%d *mask, __global %s%d *out) {\n" "*out = shuffle( *in, *mask);\n}\n", m, n, ocl_type, m, mask_type, n, ocl_type, n); rv+=sprintf(buf+rv, "__kernel void test_shuffle2_%d_%d(" "__global %s%d *in1, __global %s%d *in2, __global %s%d *mask, __global %s%d *out) {\n" "*out = shuffle2( *in1, *in2, *mask);\n}\n", m, n, ocl_type, m, ocl_type, m, mask_type, n, ocl_type, n); src.append(buf); } } } #define nsize (n==3?4:n) #define msize (m==3?4:m) // assume out is filled with 'shuffle(in, mask)' // return true if ok bool output_matches_1(unsigned n, unsigned m) { bool error=false; for(unsigned i=0; i<n; i++) { unsigned mm = mask1[i] % msize; error |= (out[i] != in1[mm]); } return !error; } // assume out is filled with 'shuffle2(in1, in2, mask)' // return true if ok bool output_matches_2(unsigned n, unsigned m) { bool error=false; for(unsigned i=0; i<n; i++) { unsigned msk = mask2[i] % (2*msize); D correct = (msk < msize) ? in1[msk] : in2[msk-msize]; if (out[i] != correct) { error |= true; printf("element %d should be %d (mask %d), got %d\n", i, (int)correct, (int)mask2[i], (int)out[i]); } } return !error; } // helpers: prints a vector as [0, 1, 2] // cast to int, so vectors of 'char' come out correctly void print_in1(unsigned n, unsigned m) { std::cout << "["<<(int)in1[0]; for(unsigned i=1; i<m; i++) std::cout << ", " <<(int)in1[i]; std::cout << "]"; } void print_in2(unsigned n, unsigned m) { std::cout << "["<<(int)in2[0]; for(unsigned i=1; i<m; i++) std::cout << ", " <<(int)in2[i]; std::cout << "]"; } void print_mask1(unsigned n, unsigned m) { std::cout << "["<<(int)mask1[0]; for(unsigned i=1; i<n; i++) std::cout << ", " <<(int)mask1[i]; std::cout << "]"; } void print_mask2(unsigned n, unsigned m) { std::cout << "["<<(int)mask2[0]; for(unsigned i=1; i<n; i++) std::cout << ", " <<(int)mask2[i]; std::cout << "]"; } void print_out(unsigned n, unsigned m) { std::cout << "["<<(int)out[0]; for(unsigned i=1; i<n; i++) std::cout << ", " <<(int)out[i]; std::cout << "]"; } /* Run one shuffle test, return true if successful*/ bool run_single_test(unsigned n, unsigned m){ bool rv=true; cl_kernel krn, krn2; char kern_name[128], kern_name2[128]; snprintf(kern_name, 128, "test_shuffle_%d_%d", m, n); krn = clCreateKernel(prog, kern_name, &errcode); ERRCHECK() errcode = clSetKernelArg( krn, 0, sizeof(cl_mem), &mem_in1 ); ERRCHECK() errcode = clSetKernelArg( krn, 1, sizeof(cl_mem), &mem_mask1 ); ERRCHECK() errcode = clSetKernelArg( krn, 2, sizeof(cl_mem), &mem_out ); ERRCHECK() errcode = clEnqueueTask( queue, krn, 0, NULL, NULL ); ERRCHECK() errcode = clEnqueueReadBuffer( queue, mem_out, CL_TRUE, 0, size, out, 0, NULL, NULL ); ERRCHECK() errcode = clFinish(queue); ERRCHECK() if(!output_matches_1(n, m)) { std::cout << "Error in shuffle " << ocl_type << " " << m; std::cout << " => " << ocl_type << " " << n << " :"; print_out(n, m); std::cout << " = shuffle( "; print_in1(n, m); std::cout << ", "; print_mask1(n, m); std::cout << ");" << std::endl; rv=false; } // Now test shuffle2() clReleaseKernel(krn); snprintf(kern_name2, 128, "test_shuffle2_%d_%d", m, n); krn2 = clCreateKernel(prog, kern_name2, &errcode); ERRCHECK() errcode = clSetKernelArg( krn2, 0, sizeof(cl_mem), &mem_in1 ); ERRCHECK() errcode = clSetKernelArg( krn2, 1, sizeof(cl_mem), &mem_in2 ); ERRCHECK() errcode = clSetKernelArg( krn2, 2, sizeof(cl_mem), &mem_mask2 ); ERRCHECK() errcode = clSetKernelArg( krn2, 3, sizeof(cl_mem), &mem_out ); ERRCHECK() errcode = clEnqueueTask( queue, krn2, 0, NULL, NULL ); ERRCHECK() errcode = clEnqueueReadBuffer( queue, mem_out, CL_TRUE, 0, size, out, 0, NULL, NULL ); ERRCHECK() errcode = clFinish(queue); ERRCHECK() if(!output_matches_2(n, m)) { std::cout << "Error in shuffle2 " << ocl_type << " " << m; std::cout << " => " << ocl_type << " " << n << " :"; print_out(n, m); std::cout << " = shuffle2( "; print_in1(n, m); std::cout << ", "; print_in2(n, m); std::cout << ", "; print_mask2(n, m); std::cout << ");" << std::endl; rv=false; } clReleaseKernel(krn2); return rv; } public: TestShuffle(const char* type) { ocl_type = type; size = sizeof(D) * 16; for(unsigned i=0; i<16; i++) { mask1[i] = (M)stimuli[i]; mask2[i] = (M)stimuli[i]; } } unsigned run() { // Fixed pseudorandom stimuli to make the test deterministic. // Random stimuli leads to randomly appearing/disappearing // problems which are irritating and hard to reproduce. Values which reduce // to element 3 might produce an undefined value in case of 3 element inputs so // let's not use them in the stimulus. mem_in1 = clCreateBuffer(ctx, CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, size, in1, &errcode); ERRCHECK() mem_in2 = clCreateBuffer(ctx, CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, size, in2, &errcode); ERRCHECK() mem_mask1 = clCreateBuffer(ctx, CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, size, mask1, &errcode); ERRCHECK() mem_mask2 = clCreateBuffer(ctx, CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, size, mask2, &errcode); ERRCHECK() mem_out = clCreateBuffer(ctx, CL_MEM_WRITE_ONLY, size, NULL, &errcode); ERRCHECK() std::string source; testcase_src(source); const char *c_src = source.c_str(); size_t srclen = source.size(); prog = clCreateProgramWithSource(ctx, 1, &c_src, &srclen, &errcode); ERRCHECK() errcode = clBuildProgram(prog, 0, NULL, NULL, NULL, NULL); ERRCHECK() unsigned errors = 0; for(unsigned n_loop=0; n_loop<4; n_loop++) { for(unsigned m_loop=0; m_loop<4; m_loop++) { unsigned m = vecelts[m_loop]; for(unsigned i=0; i<m; i++) { in2[i]=(D)(i+m); in1[i] = (D)i; } if (!run_single_test(vecelts[n_loop], vecelts[m_loop])) errors++; } } clReleaseMemObject(mem_in1); clReleaseMemObject(mem_in2); clReleaseMemObject(mem_mask1); clReleaseMemObject(mem_mask2); clReleaseMemObject(mem_out); clReleaseProgram(prog); return errors; } }; int main( int argc, char *argv[]) { unsigned num_errors = 0; if( argc != 2 ) { std::cout << "give element type"<<std::endl; exit(-1); } poclu_get_any_device( &ctx, &did, &queue); #if (__GNUC__ > 5) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wignored-attributes" #endif /* Loop over input (m) and output (n) vector lengths. * The big if-else is needed to pass the string * representation to runtest. * This cannot be fully templated, as there is a * 'typedef short int half', which would cause the * templating mechanism to create the test for shorts instead * of halfs. */ if( strcmp("char", argv[1]) == 0 ) { TestShuffle<cl_char, cl_uchar> t("char"); num_errors = t.run(); } else if( strcmp("uchar", argv[1]) == 0 ) { TestShuffle<cl_uchar, cl_uchar> t("uchar"); num_errors = t.run(); } else if( strcmp("short", argv[1]) == 0 ) { TestShuffle<cl_short, cl_ushort> t("short"); num_errors = t.run(); } else if( strcmp("ushort", argv[1]) == 0 ) { TestShuffle<cl_ushort, cl_ushort> t("ushort"); num_errors = t.run(); } else if( strcmp("int", argv[1]) == 0 ) { TestShuffle<cl_int, cl_uint> t("int"); num_errors = t.run(); } else if( strcmp("uint", argv[1]) == 0 ) { TestShuffle<cl_uint, cl_uint> t("uint"); num_errors = t.run(); } else if( strcmp("long", argv[1]) == 0 ) { TestShuffle<cl_long, cl_ulong> t("long"); num_errors = t.run(); } else if( strcmp("ulong", argv[1]) == 0 ) { TestShuffle<cl_ulong, cl_ulong> t("ulong"); num_errors = t.run(); } else if( strcmp("half", argv[1]) == 0 ) { TestShuffle<cl_half, cl_ushort> t("half"); num_errors = t.run(); } else if( strcmp("float", argv[1]) == 0 ) { TestShuffle<cl_float, cl_uint> t("float"); num_errors = t.run(); } else if( strcmp("double", argv[1]) == 0 ) { TestShuffle<cl_double, cl_ulong> t("double"); num_errors = t.run(); } else { std::cout << "Error: unknown type " << argv[1] << ": use OCL-C types"<<std::endl; return -1; } #if (__GNUC__ > 5) #pragma GCC diagnostic pop #endif if( num_errors == 0) std::cout << "OK" << std::endl; return num_errors; } <commit_msg>Fix memleaks in test_shuffle<commit_after>/* This test is part of pocl. * Author: Kalle Raiskila, 2014 * * Test the OpenCL-C 'shuffle' command by looping * over all permutations of data and mask vector * lengths. Only one data type at a time is tested, * the type to test is passed as command line argument * (this allows for more interactive testsuite, and * non-supported types (e.g. half, double) are easier * to filter out). * The data to be shuffled is vectors where the elemnet * data equals the element index (i.e. [0,1,2,3]) but * the shuffle pattern masks are generated with rand(). */ #include "poclu.h" #include <cstdio> #include <cstring> #include <CL/cl.h> #include <iostream> #include <cmath> #include <cstdlib> cl_context ctx; cl_device_id did; cl_platform_id pid; cl_command_queue queue; #define ERRCHECK() if (check_cl_error(errcode, __LINE__, __FUNCTION__)) abort(); static const unsigned vecelts[] = {2,4,8,16}; static const int stimuli[] = {4, 2, 69, 4, 5, 0, 45, 16, 4, 6, 1, 18, 28, 14, 22, 16, 8, 2, 0, 31, 42, 11, 62, 88, 99, 23, 13}; template <typename D, typename M> class TestShuffle { cl_mem mem_in1, mem_in2, mem_out, mem_mask1, mem_mask2; cl_program prog; D in1 [16] __attribute__ ((aligned (128))); D in2 [16] __attribute__ ((aligned (128))); D out [16] __attribute__ ((aligned (128))); M mask1 [16] __attribute__ ((aligned (128))); M mask2 [16] __attribute__ ((aligned (128))); const char* ocl_type; unsigned size; cl_int errcode; private: /* Prints into std::string all the OpenCL kernel sources for each n,m combo */ void testcase_src(std::string & src) { char buf[1024]; int rv; unsigned n, m; const char* mask_type; switch(sizeof(M)) { case 1: mask_type = "uchar"; break; case 2: mask_type = "ushort"; break; case 4: mask_type = "uint"; break; case 8: mask_type = "ulong"; break; default: mask_type = "UNKNOWN_MASK"; } for(unsigned n_loop=0; n_loop<4; n_loop++) { for(unsigned m_loop=0; m_loop<4; m_loop++) { n = vecelts[n_loop]; m = vecelts[m_loop]; rv = 0; buf[0] = 0; rv=sprintf(buf, "__kernel void test_shuffle_%d_%d(" "__global %s%d *in, __global %s%d *mask, __global %s%d *out) {\n" "*out = shuffle( *in, *mask);\n}\n", m, n, ocl_type, m, mask_type, n, ocl_type, n); rv+=sprintf(buf+rv, "__kernel void test_shuffle2_%d_%d(" "__global %s%d *in1, __global %s%d *in2, __global %s%d *mask, __global %s%d *out) {\n" "*out = shuffle2( *in1, *in2, *mask);\n}\n", m, n, ocl_type, m, ocl_type, m, mask_type, n, ocl_type, n); src.append(buf); } } } #define nsize (n==3?4:n) #define msize (m==3?4:m) // assume out is filled with 'shuffle(in, mask)' // return true if ok bool output_matches_1(unsigned n, unsigned m) { bool error=false; for(unsigned i=0; i<n; i++) { unsigned mm = mask1[i] % msize; error |= (out[i] != in1[mm]); } return !error; } // assume out is filled with 'shuffle2(in1, in2, mask)' // return true if ok bool output_matches_2(unsigned n, unsigned m) { bool error=false; for(unsigned i=0; i<n; i++) { unsigned msk = mask2[i] % (2*msize); D correct = (msk < msize) ? in1[msk] : in2[msk-msize]; if (out[i] != correct) { error |= true; printf("element %d should be %d (mask %d), got %d\n", i, (int)correct, (int)mask2[i], (int)out[i]); } } return !error; } // helpers: prints a vector as [0, 1, 2] // cast to int, so vectors of 'char' come out correctly void print_in1(unsigned n, unsigned m) { std::cout << "["<<(int)in1[0]; for(unsigned i=1; i<m; i++) std::cout << ", " <<(int)in1[i]; std::cout << "]"; } void print_in2(unsigned n, unsigned m) { std::cout << "["<<(int)in2[0]; for(unsigned i=1; i<m; i++) std::cout << ", " <<(int)in2[i]; std::cout << "]"; } void print_mask1(unsigned n, unsigned m) { std::cout << "["<<(int)mask1[0]; for(unsigned i=1; i<n; i++) std::cout << ", " <<(int)mask1[i]; std::cout << "]"; } void print_mask2(unsigned n, unsigned m) { std::cout << "["<<(int)mask2[0]; for(unsigned i=1; i<n; i++) std::cout << ", " <<(int)mask2[i]; std::cout << "]"; } void print_out(unsigned n, unsigned m) { std::cout << "["<<(int)out[0]; for(unsigned i=1; i<n; i++) std::cout << ", " <<(int)out[i]; std::cout << "]"; } /* Run one shuffle test, return true if successful*/ bool run_single_test(unsigned n, unsigned m){ bool rv=true; cl_kernel krn, krn2; char kern_name[128], kern_name2[128]; snprintf(kern_name, 128, "test_shuffle_%d_%d", m, n); krn = clCreateKernel(prog, kern_name, &errcode); ERRCHECK() errcode = clSetKernelArg( krn, 0, sizeof(cl_mem), &mem_in1 ); ERRCHECK() errcode = clSetKernelArg( krn, 1, sizeof(cl_mem), &mem_mask1 ); ERRCHECK() errcode = clSetKernelArg( krn, 2, sizeof(cl_mem), &mem_out ); ERRCHECK() errcode = clEnqueueTask( queue, krn, 0, NULL, NULL ); ERRCHECK() errcode = clEnqueueReadBuffer( queue, mem_out, CL_TRUE, 0, size, out, 0, NULL, NULL ); ERRCHECK() errcode = clFinish(queue); ERRCHECK() if(!output_matches_1(n, m)) { std::cout << "Error in shuffle " << ocl_type << " " << m; std::cout << " => " << ocl_type << " " << n << " :"; print_out(n, m); std::cout << " = shuffle( "; print_in1(n, m); std::cout << ", "; print_mask1(n, m); std::cout << ");" << std::endl; rv=false; } // Now test shuffle2() clReleaseKernel(krn); snprintf(kern_name2, 128, "test_shuffle2_%d_%d", m, n); krn2 = clCreateKernel(prog, kern_name2, &errcode); ERRCHECK() errcode = clSetKernelArg( krn2, 0, sizeof(cl_mem), &mem_in1 ); ERRCHECK() errcode = clSetKernelArg( krn2, 1, sizeof(cl_mem), &mem_in2 ); ERRCHECK() errcode = clSetKernelArg( krn2, 2, sizeof(cl_mem), &mem_mask2 ); ERRCHECK() errcode = clSetKernelArg( krn2, 3, sizeof(cl_mem), &mem_out ); ERRCHECK() errcode = clEnqueueTask( queue, krn2, 0, NULL, NULL ); ERRCHECK() errcode = clEnqueueReadBuffer( queue, mem_out, CL_TRUE, 0, size, out, 0, NULL, NULL ); ERRCHECK() errcode = clFinish(queue); ERRCHECK() if(!output_matches_2(n, m)) { std::cout << "Error in shuffle2 " << ocl_type << " " << m; std::cout << " => " << ocl_type << " " << n << " :"; print_out(n, m); std::cout << " = shuffle2( "; print_in1(n, m); std::cout << ", "; print_in2(n, m); std::cout << ", "; print_mask2(n, m); std::cout << ");" << std::endl; rv=false; } clReleaseKernel(krn2); return rv; } public: TestShuffle(const char* type) { ocl_type = type; size = sizeof(D) * 16; for(unsigned i=0; i<16; i++) { mask1[i] = (M)stimuli[i]; mask2[i] = (M)stimuli[i]; } } unsigned run() { // Fixed pseudorandom stimuli to make the test deterministic. // Random stimuli leads to randomly appearing/disappearing // problems which are irritating and hard to reproduce. Values which reduce // to element 3 might produce an undefined value in case of 3 element inputs so // let's not use them in the stimulus. mem_in1 = clCreateBuffer(ctx, CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, size, in1, &errcode); ERRCHECK() mem_in2 = clCreateBuffer(ctx, CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, size, in2, &errcode); ERRCHECK() mem_mask1 = clCreateBuffer(ctx, CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, size, mask1, &errcode); ERRCHECK() mem_mask2 = clCreateBuffer(ctx, CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, size, mask2, &errcode); ERRCHECK() mem_out = clCreateBuffer(ctx, CL_MEM_WRITE_ONLY, size, NULL, &errcode); ERRCHECK() std::string source; testcase_src(source); const char *c_src = source.c_str(); size_t srclen = source.size(); prog = clCreateProgramWithSource(ctx, 1, &c_src, &srclen, &errcode); ERRCHECK() errcode = clBuildProgram(prog, 0, NULL, NULL, NULL, NULL); ERRCHECK() unsigned errors = 0; for(unsigned n_loop=0; n_loop<4; n_loop++) { for(unsigned m_loop=0; m_loop<4; m_loop++) { unsigned m = vecelts[m_loop]; for(unsigned i=0; i<m; i++) { in2[i]=(D)(i+m); in1[i] = (D)i; } if (!run_single_test(vecelts[n_loop], vecelts[m_loop])) errors++; } } clReleaseMemObject(mem_in1); clReleaseMemObject(mem_in2); clReleaseMemObject(mem_mask1); clReleaseMemObject(mem_mask2); clReleaseMemObject(mem_out); clReleaseProgram(prog); return errors; } }; int main( int argc, char *argv[]) { unsigned num_errors = 0; if( argc != 2 ) { std::cout << "give element type"<<std::endl; exit(-1); } poclu_get_any_device( &ctx, &did, &queue); #if (__GNUC__ > 5) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wignored-attributes" #endif /* Loop over input (m) and output (n) vector lengths. * The big if-else is needed to pass the string * representation to runtest. * This cannot be fully templated, as there is a * 'typedef short int half', which would cause the * templating mechanism to create the test for shorts instead * of halfs. */ if( strcmp("char", argv[1]) == 0 ) { TestShuffle<cl_char, cl_uchar> t("char"); num_errors = t.run(); } else if( strcmp("uchar", argv[1]) == 0 ) { TestShuffle<cl_uchar, cl_uchar> t("uchar"); num_errors = t.run(); } else if( strcmp("short", argv[1]) == 0 ) { TestShuffle<cl_short, cl_ushort> t("short"); num_errors = t.run(); } else if( strcmp("ushort", argv[1]) == 0 ) { TestShuffle<cl_ushort, cl_ushort> t("ushort"); num_errors = t.run(); } else if( strcmp("int", argv[1]) == 0 ) { TestShuffle<cl_int, cl_uint> t("int"); num_errors = t.run(); } else if( strcmp("uint", argv[1]) == 0 ) { TestShuffle<cl_uint, cl_uint> t("uint"); num_errors = t.run(); } else if( strcmp("long", argv[1]) == 0 ) { TestShuffle<cl_long, cl_ulong> t("long"); num_errors = t.run(); } else if( strcmp("ulong", argv[1]) == 0 ) { TestShuffle<cl_ulong, cl_ulong> t("ulong"); num_errors = t.run(); } else if( strcmp("half", argv[1]) == 0 ) { TestShuffle<cl_half, cl_ushort> t("half"); num_errors = t.run(); } else if( strcmp("float", argv[1]) == 0 ) { TestShuffle<cl_float, cl_uint> t("float"); num_errors = t.run(); } else if( strcmp("double", argv[1]) == 0 ) { TestShuffle<cl_double, cl_ulong> t("double"); num_errors = t.run(); } else { std::cout << "Error: unknown type " << argv[1] << ": use OCL-C types"<<std::endl; return -1; } #if (__GNUC__ > 5) #pragma GCC diagnostic pop #endif clReleaseCommandQueue(queue); clReleaseContext(ctx); if( num_errors == 0) std::cout << "OK" << std::endl; return num_errors; } <|endoftext|>
<commit_before>#ifndef STAN_SERVICES_UTIL_MCMC_WRITER_HPP #define STAN_SERVICES_UTIL_MCMC_WRITER_HPP #include <stan/mcmc/base_mcmc.hpp> #include <stan/mcmc/sample.hpp> #include <stan/model/prob_grad.hpp> #include <sstream> #include <iomanip> #include <string> #include <vector> namespace stan { namespace services { namespace util { /** * mcmc_writer writes out headers and samples * * @tparam Model Model class */ class mcmc_writer { private: callbacks::writer& sample_writer_; callbacks::writer& diagnostic_writer_; callbacks::writer& message_writer_; public: /** * Constructor. * * @param[in,out] sample_writer samples are "written" to this stream * @param[in,out] diagnostic_writer diagnostic info is "written" to this * stream * @param[in,out] message_writer messages are written to this stream */ mcmc_writer(callbacks::writer& sample_writer, callbacks::writer& diagnostic_writer, callbacks::writer& message_writer) : sample_writer_(sample_writer), diagnostic_writer_(diagnostic_writer), message_writer_(message_writer) { } /** * Outputs parameter string names. First outputs the names stored in * the sample object (stan::mcmc::sample), then uses the sampler * provided to output sampler specific names, then adds the model * constrained parameter names. * * The names are written to the sample_stream as comma separated values * with a newline at the end. * * @param[in] sample a sample (unconstrained) that works with the model * @param[in] sampler a stan::mcmc::base_mcmc object * @param[in] model the model */ template <class Model> void write_sample_names(stan::mcmc::sample& sample, stan::mcmc::base_mcmc& sampler, Model& model) { std::vector<std::string> names; sample.get_sample_param_names(names); sampler.get_sampler_param_names(names); model.constrained_param_names(names, true, true); sample_writer_(names); } /** * Outputs samples. First outputs the values of the sample params * from a stan::mcmc::sample, then outputs the values of the sampler * params from a stan::mcmc::base_mcmc, then finally outputs the values * of the model. * * The samples are written to the sample_stream as comma separated * values with a newline at the end. * * @param[in,out] rng random number generator (used by * model.write_array()) * @param[in] sample the sample in constrained space * @param[in] sampler the sampler * @param[in] model the model */ template <class Model, class RNG> void write_sample_params(RNG& rng, stan::mcmc::sample& sample, stan::mcmc::base_mcmc& sampler, Model& model) { std::vector<double> values; sample.get_sample_params(values); sampler.get_sampler_params(values); Eigen::VectorXd model_values; std::stringstream ss; try { model.write_array(rng, const_cast<Eigen::VectorXd&>(sample.cont_params()), model_values, true, true, &ss); } catch (const std::exception& e) { if (ss.str().length() > 0) message_writer_(ss.str()); message_writer_(e.what()); return; } if (ss.str().length() > 0) message_writer_(ss.str()); for (int i = 0; i < model_values.size(); ++i) values.push_back(model_values(i)); sample_writer_(values); } /** * Prints additional info to the streams * * Prints to the sample stream * * @param[in] sampler sampler */ void write_adapt_finish(stan::mcmc::base_mcmc& sampler) { sample_writer_("Adaptation terminated"); sampler.write_sampler_state(sample_writer_); } /** * Print diagnostic names * * @param[in] sample unconstrained sample * @param[in] sampler sampler * @param[in] model model */ template <class Model> void write_diagnostic_names(stan::mcmc::sample sample, stan::mcmc::base_mcmc& sampler, Model& model) { std::vector<std::string> names; sample.get_sample_param_names(names); sampler.get_sampler_param_names(names); std::vector<std::string> model_names; model.unconstrained_param_names(model_names, false, false); sampler.get_sampler_diagnostic_names(model_names, names); diagnostic_writer_(names); } /** * Print diagnostic params to the diagnostic stream. * * @param[in] sample unconstrained sample * @param[in] sampler sampler */ void write_diagnostic_params(stan::mcmc::sample& sample, stan::mcmc::base_mcmc& sampler) { std::vector<double> values; sample.get_sample_params(values); sampler.get_sampler_params(values); sampler.get_sampler_diagnostics(values); diagnostic_writer_(values); } /** * Internal method * * Prints timing information * * @param[in] warmDeltaT warmup time in seconds * @param[in] sampleDeltaT sample time in seconds * @param[in,out] writer output stream */ void write_timing(double warmDeltaT, double sampleDeltaT, callbacks::writer& writer) { std::string title(" Elapsed Time: "); writer(); std::stringstream ss1; ss1 << title << warmDeltaT << " seconds (Warm-up)"; writer(ss1.str()); std::stringstream ss2; ss2 << std::string(title.size(), ' ') << sampleDeltaT << " seconds (Sampling)"; writer(ss2.str()); std::stringstream ss3; ss3 << std::string(title.size(), ' ') << warmDeltaT + sampleDeltaT << " seconds (Total)"; writer(ss3.str()); writer(); } /** * Print timing information to all streams * * @param[in] warmDeltaT warmup time (sec) * @param[in] sampleDeltaT sample time (sec) */ void write_timing(double warmDeltaT, double sampleDeltaT) { write_timing(warmDeltaT, sampleDeltaT, sample_writer_); write_timing(warmDeltaT, sampleDeltaT, diagnostic_writer_); write_timing(warmDeltaT, sampleDeltaT, message_writer_); } }; } } } #endif <commit_msg>cpplint fix<commit_after>#ifndef STAN_SERVICES_UTIL_MCMC_WRITER_HPP #define STAN_SERVICES_UTIL_MCMC_WRITER_HPP #include <stan/mcmc/base_mcmc.hpp> #include <stan/mcmc/sample.hpp> #include <stan/model/prob_grad.hpp> #include <sstream> #include <iomanip> #include <string> #include <vector> namespace stan { namespace services { namespace util { /** * mcmc_writer writes out headers and samples * * @tparam Model Model class */ class mcmc_writer { private: callbacks::writer& sample_writer_; callbacks::writer& diagnostic_writer_; callbacks::writer& message_writer_; public: /** * Constructor. * * @param[in,out] sample_writer samples are "written" to this stream * @param[in,out] diagnostic_writer diagnostic info is "written" to this * stream * @param[in,out] message_writer messages are written to this stream */ mcmc_writer(callbacks::writer& sample_writer, callbacks::writer& diagnostic_writer, callbacks::writer& message_writer) : sample_writer_(sample_writer), diagnostic_writer_(diagnostic_writer), message_writer_(message_writer) { } /** * Outputs parameter string names. First outputs the names stored in * the sample object (stan::mcmc::sample), then uses the sampler * provided to output sampler specific names, then adds the model * constrained parameter names. * * The names are written to the sample_stream as comma separated values * with a newline at the end. * * @param[in] sample a sample (unconstrained) that works with the model * @param[in] sampler a stan::mcmc::base_mcmc object * @param[in] model the model */ template <class Model> void write_sample_names(stan::mcmc::sample& sample, stan::mcmc::base_mcmc& sampler, Model& model) { std::vector<std::string> names; sample.get_sample_param_names(names); sampler.get_sampler_param_names(names); model.constrained_param_names(names, true, true); sample_writer_(names); } /** * Outputs samples. First outputs the values of the sample params * from a stan::mcmc::sample, then outputs the values of the sampler * params from a stan::mcmc::base_mcmc, then finally outputs the values * of the model. * * The samples are written to the sample_stream as comma separated * values with a newline at the end. * * @param[in,out] rng random number generator (used by * model.write_array()) * @param[in] sample the sample in constrained space * @param[in] sampler the sampler * @param[in] model the model */ template <class Model, class RNG> void write_sample_params(RNG& rng, stan::mcmc::sample& sample, stan::mcmc::base_mcmc& sampler, Model& model) { std::vector<double> values; sample.get_sample_params(values); sampler.get_sampler_params(values); Eigen::VectorXd model_values; std::stringstream ss; try { model.write_array(rng, const_cast<Eigen::VectorXd&>(sample.cont_params()), model_values, true, true, &ss); } catch (const std::exception& e) { if (ss.str().length() > 0) message_writer_(ss.str()); message_writer_(e.what()); return; } if (ss.str().length() > 0) message_writer_(ss.str()); for (int i = 0; i < model_values.size(); ++i) values.push_back(model_values(i)); sample_writer_(values); } /** * Prints additional info to the streams * * Prints to the sample stream * * @param[in] sampler sampler */ void write_adapt_finish(stan::mcmc::base_mcmc& sampler) { sample_writer_("Adaptation terminated"); sampler.write_sampler_state(sample_writer_); } /** * Print diagnostic names * * @param[in] sample unconstrained sample * @param[in] sampler sampler * @param[in] model model */ template <class Model> void write_diagnostic_names(stan::mcmc::sample sample, stan::mcmc::base_mcmc& sampler, Model& model) { std::vector<std::string> names; sample.get_sample_param_names(names); sampler.get_sampler_param_names(names); std::vector<std::string> model_names; model.unconstrained_param_names(model_names, false, false); sampler.get_sampler_diagnostic_names(model_names, names); diagnostic_writer_(names); } /** * Print diagnostic params to the diagnostic stream. * * @param[in] sample unconstrained sample * @param[in] sampler sampler */ void write_diagnostic_params(stan::mcmc::sample& sample, stan::mcmc::base_mcmc& sampler) { std::vector<double> values; sample.get_sample_params(values); sampler.get_sampler_params(values); sampler.get_sampler_diagnostics(values); diagnostic_writer_(values); } /** * Internal method * * Prints timing information * * @param[in] warmDeltaT warmup time in seconds * @param[in] sampleDeltaT sample time in seconds * @param[in,out] writer output stream */ void write_timing(double warmDeltaT, double sampleDeltaT, callbacks::writer& writer) { std::string title(" Elapsed Time: "); writer(); std::stringstream ss1; ss1 << title << warmDeltaT << " seconds (Warm-up)"; writer(ss1.str()); std::stringstream ss2; ss2 << std::string(title.size(), ' ') << sampleDeltaT << " seconds (Sampling)"; writer(ss2.str()); std::stringstream ss3; ss3 << std::string(title.size(), ' ') << warmDeltaT + sampleDeltaT << " seconds (Total)"; writer(ss3.str()); writer(); } /** * Print timing information to all streams * * @param[in] warmDeltaT warmup time (sec) * @param[in] sampleDeltaT sample time (sec) */ void write_timing(double warmDeltaT, double sampleDeltaT) { write_timing(warmDeltaT, sampleDeltaT, sample_writer_); write_timing(warmDeltaT, sampleDeltaT, diagnostic_writer_); write_timing(warmDeltaT, sampleDeltaT, message_writer_); } }; } } } #endif <|endoftext|>
<commit_before>// (C) Copyright Ben Bear, Herve Bronnimann 2007. // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) /* Revision history: Nov 13, 2007: Incorporation of boost-devel comments (Jens Seidel, Ben Bear and myself) Nov 11, 2007: Rewrite of Ben Bear's Gacap */ #ifndef BOOST_ALGORITHM_COMBINATION_HPP #define BOOST_ALGORITHM_COMBINATION_HPP #include <algorithm> namespace boost { namespace detail { template<class BidirectionalIterator> bool next_combination(BidirectionalIterator first1, BidirectionalIterator last1, BidirectionalIterator first2, BidirectionalIterator last2) { if ((first1 == last1) || (first2 == last2)) { return false; } BidirectionalIterator m1 = last1; BidirectionalIterator m2 = last2; --m2; // Find first m1 not less than *m2 (i.e., lower_bound(first1, last1, *m2)). // Actually, this loop stops at one position before that, except perhaps // if m1 == first1 (in which case one must compare *first1 with *m2). while (--m1 != first1 && !(*m1 < *m2)) { } // Test if all elements in [first1, last1) not less than *m2. bool result = (m1 == first1) && !(*first1 < *m2); if (!result) { // Find first first2 greater than *m1 (since *m1 < *m2, we know it // can't pass m2 and there's no need to test m2). while (first2 != m2 && !(*m1 < *first2)) { ++first2; } first1 = m1; std::iter_swap (first1, first2); ++first1; ++first2; } // Merge [first1, last1) with [first2, last2), given that the rest of the // original ranges are sorted and compare appropriately. if ((first1 != last1) && (first2 != last2)) { for (m1 = last1, m2 = first2; (m1 != first1) && (m2 != last2); ++m2) { std::iter_swap (--m1, m2); } std::reverse (first1, m1); std::reverse (first1, last1); std::reverse (m2, last2); std::reverse (first2, last2); } return !result; } template<class BidirectionalIterator, class Compare> bool next_combination(BidirectionalIterator first1, BidirectionalIterator last1, BidirectionalIterator first2, BidirectionalIterator last2, Compare comp) { if ((first1 == last1) || (first2 == last2)) { return false; } BidirectionalIterator m1 = last1; BidirectionalIterator m2 = last2; --m2; while (--m1 != first1 && !comp(*m1, *m2)) { } bool result = (m1 == first1) && !comp(*first1, *m2); if (!result) { while (first2 != m2 && !comp(*m1, *first2)) { ++first2; } first1 = m1; std::iter_swap (first1, first2); ++first1; ++first2; } if ((first1 != last1) && (first2 != last2)) { for (m1 = last1, m2 = first2; (m1 != first1) && (m2 != last2); ++m2) { std::iter_swap (--m1, m2); } std::reverse (first1, m1); std::reverse (first1, last1); std::reverse (m2, last2); std::reverse (first2, last2); } return !result; } } // namespace detail /* PROPOSED STANDARD EXTENSIONS: * * template<class BidirectionalIterator> * bool next_partial_permutation(BidirectionalIterator first, * BidirectionalIterator middle, * BidirectionalIterator last); * * template<class BidirectionalIterator, class Compare> * bool next_partial_permutation(BidirectionalIterator first, * BidirectionalIterator middle, * BidirectionalIterator last, Compare comp); */ template <class BidirectionalIterator> bool next_partial_permutation(BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last) { reverse (middle, last); return next_permutation(first, last); } template<class BidirectionalIterator, class Compare> bool next_partial_permutation(BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last, Compare comp) { reverse (middle, last); return next_permutation(first, last, comp); } /* PROPOSED STANDARD EXTENSIONS: * * template<class BidirectionalIterator> * bool prev_partial_permutation(BidirectionalIterator first, * BidirectionalIterator middle, * BidirectionalIterator last); * * template<class BidirectionalIterator, class Compare> * bool prev_partial_permutation(BidirectionalIterator first, * BidirectionalIterator middle, * BidirectionalIterator last, Compare comp); */ template<class BidirectionalIterator> bool prev_partial_permutation(BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last) { bool result = prev_permutation(first, last); reverse (middle, last); return result; } template<class BidirectionalIterator, class Compare> bool prev_partial_permutation(BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last, Compare comp) { bool result = prev_permutation(first, last); reverse (middle, last); return result; } /* PROPOSED STANDARD EXTENSIONS: * * template<class BidirectionalIterator> * bool next_combination(BidirectionalIterator first, * BidirectionalIterator middle, * BidirectionalIterator last); * * template<class BidirectionalIterator, class Compare> * bool next_combination(BidirectionalIterator first, * BidirectionalIterator middle, * BidirectionalIterator last, Compare comp); */ template<class BidirectionalIterator> bool next_combination(BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last) { return detail::next_combination(first, middle, middle, last); } template<class BidirectionalIterator, class Compare> bool next_combination(BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last, Compare comp) { return detail::next_combination(first, middle, middle, last, comp); } /* PROPOSED STANDARD EXTENSIONS: * * template<class BidirectionalIterator> * bool prev_combination(BidirectionalIterator first, * BidirectionalIterator middle, * BidirectionalIterator last); * * template<class BidirectionalIterator, class Compare> * bool prev_combination(BidirectionalIterator first, * BidirectionalIterator middle, * BidirectionalIterator last, Compare comp); */ template<class BidirectionalIterator> inline bool prev_combination(BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last) { return detail::next_combination(middle, last, first, middle); } template<class BidirectionalIterator, class Compare> inline bool prev_combination(BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last, Compare comp) { return detail::next_combination(middle, last, first, middle, comp); } /* PROPOSED STANDARD EXTENSION: * * template<class BidirectionalIterator, class T> * bool next_mapping(BidirectionalIterator first, * BidirectionalIterator last, * T first_value, T last_value); * * template<class BidirectionalIterator, class T, class Incrementor> * bool next_mapping(BidirectionalIterator first, * BidirectionalIterator last, * T first_value, T last_value, Incrementor increment); */ template <class BidirectionalIterator, class T> bool next_mapping(BidirectionalIterator first, BidirectionalIterator last, T first_value, T last_value) { if (last == first ) { return false; } do { if (++(*(--last)) != last_value) { return true; } *last = first_value; } while (last != first); return false; } template <class BidirectionalIterator, class T, class Incrementer> bool next_mapping(BidirectionalIterator first, BidirectionalIterator last, T first_value, T last_value, Incrementer increment) { if (last == first ) { return false; } do { if (incrementer(*(--last)) != last_value) { return true; } *last = first_value; } while (last != first); return false; } /* PROPOSED STANDARD EXTENSION: * * template<class BidirectionalIterator, class T> * bool prev_mapping(BidirectionalIterator first, * BidirectionalIterator last, * T first_value, T last_value); * * template<class BidirectionalIterator, class T, class Decrementor> * bool prev_mapping(BidirectionalIterator first, * BidirectionalIterator last, * T first_value, T last_value, Decrementor decrement); */ template <class BidirectionalIterator, class T> bool prev_mapping(BidirectionalIterator first, BidirectionalIterator last, T first_value, T last_value) { if (last == first) { return false; } --last_value; do { if (*(--last) != first_value) { --(*last); return true; } *last = last_value; } while (last != first); return true; } template <class BidirectionalIterator, class T, class Decrementer> bool prev_mapping(BidirectionalIterator first, BidirectionalIterator last, T first_value, T last_value, Decrementer decrement) { if (last == first) { return false; } decrement(last_value); do { if (*(--last) != first_value) { decrement(*last); return true; } *last = last_value; } while (last != first); return true; } /* PROPOSED STANDARD EXTENSION: * * template<class BidirectionalIterator, class T> * bool next_combination_counts(BidirectionalIterator first, * BidirectionalIterator last); */ template <class BidirectionalIterator> bool next_combination_counts(BidirectionalIterator first, BidirectionalIterator last) { BidirectionalIterator current = last; while (current != first && *(--current) == 0) { } if (current == first) { if (first != last && *first != 0) std::iter_swap(--last, first); return false; } --(*current); std::iter_swap(--last, current); ++(*(--current)); return true; } /* PROPOSED STANDARD EXTENSION: * * template<class BidirectionalIterator> * bool prev_combination_counts(BidirectionalIterator first, * BidirectionalIterator last); */ template <class BidirectionalIterator> bool prev_combination_counts(BidirectionalIterator first, BidirectionalIterator last) { if (first == last) return false; BidirectionalIterator current = --last; while (current != first && *(--current) == 0) { } if (current == last || current == first && *current == 0) { if (first != last) std::iter_swap(first, last); return false; } --(*current); ++current; if (0 != *last) { std::iter_swap(current, last); } ++(*current); return true; } } // namespace boost #endif // BOOST_ALGORITHM_COMBINATION_HPP <commit_msg>Minor edit for avoiding compiler warning<commit_after>// (C) Copyright Ben Bear, Herve Bronnimann 2007. // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) /* Revision history: Nov 13, 2007: Incorporation of boost-devel comments (Jens Seidel, Ben Bear and myself) Nov 11, 2007: Rewrite of Ben Bear's Gacap */ #ifndef BOOST_ALGORITHM_COMBINATION_HPP #define BOOST_ALGORITHM_COMBINATION_HPP #include <algorithm> namespace boost { namespace detail { template<class BidirectionalIterator> bool next_combination(BidirectionalIterator first1, BidirectionalIterator last1, BidirectionalIterator first2, BidirectionalIterator last2) { if ((first1 == last1) || (first2 == last2)) { return false; } BidirectionalIterator m1 = last1; BidirectionalIterator m2 = last2; --m2; // Find first m1 not less than *m2 (i.e., lower_bound(first1, last1, *m2)). // Actually, this loop stops at one position before that, except perhaps // if m1 == first1 (in which case one must compare *first1 with *m2). while (--m1 != first1 && !(*m1 < *m2)) { } // Test if all elements in [first1, last1) not less than *m2. bool result = (m1 == first1) && !(*first1 < *m2); if (!result) { // Find first first2 greater than *m1 (since *m1 < *m2, we know it // can't pass m2 and there's no need to test m2). while (first2 != m2 && !(*m1 < *first2)) { ++first2; } first1 = m1; std::iter_swap (first1, first2); ++first1; ++first2; } // Merge [first1, last1) with [first2, last2), given that the rest of the // original ranges are sorted and compare appropriately. if ((first1 != last1) && (first2 != last2)) { for (m1 = last1, m2 = first2; (m1 != first1) && (m2 != last2); ++m2) { std::iter_swap (--m1, m2); } std::reverse (first1, m1); std::reverse (first1, last1); std::reverse (m2, last2); std::reverse (first2, last2); } return !result; } template<class BidirectionalIterator, class Compare> bool next_combination(BidirectionalIterator first1, BidirectionalIterator last1, BidirectionalIterator first2, BidirectionalIterator last2, Compare comp) { if ((first1 == last1) || (first2 == last2)) { return false; } BidirectionalIterator m1 = last1; BidirectionalIterator m2 = last2; --m2; while (--m1 != first1 && !comp(*m1, *m2)) { } bool result = (m1 == first1) && !comp(*first1, *m2); if (!result) { while (first2 != m2 && !comp(*m1, *first2)) { ++first2; } first1 = m1; std::iter_swap (first1, first2); ++first1; ++first2; } if ((first1 != last1) && (first2 != last2)) { for (m1 = last1, m2 = first2; (m1 != first1) && (m2 != last2); ++m2) { std::iter_swap (--m1, m2); } std::reverse (first1, m1); std::reverse (first1, last1); std::reverse (m2, last2); std::reverse (first2, last2); } return !result; } } // namespace detail /* PROPOSED STANDARD EXTENSIONS: * * template<class BidirectionalIterator> * bool next_partial_permutation(BidirectionalIterator first, * BidirectionalIterator middle, * BidirectionalIterator last); * * template<class BidirectionalIterator, class Compare> * bool next_partial_permutation(BidirectionalIterator first, * BidirectionalIterator middle, * BidirectionalIterator last, Compare comp); */ template <class BidirectionalIterator> bool next_partial_permutation(BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last) { reverse (middle, last); return next_permutation(first, last); } template<class BidirectionalIterator, class Compare> bool next_partial_permutation(BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last, Compare comp) { reverse (middle, last); return next_permutation(first, last, comp); } /* PROPOSED STANDARD EXTENSIONS: * * template<class BidirectionalIterator> * bool prev_partial_permutation(BidirectionalIterator first, * BidirectionalIterator middle, * BidirectionalIterator last); * * template<class BidirectionalIterator, class Compare> * bool prev_partial_permutation(BidirectionalIterator first, * BidirectionalIterator middle, * BidirectionalIterator last, Compare comp); */ template<class BidirectionalIterator> bool prev_partial_permutation(BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last) { bool result = prev_permutation(first, last); reverse (middle, last); return result; } template<class BidirectionalIterator, class Compare> bool prev_partial_permutation(BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last, Compare comp) { bool result = prev_permutation(first, last); reverse (middle, last); return result; } /* PROPOSED STANDARD EXTENSIONS: * * template<class BidirectionalIterator> * bool next_combination(BidirectionalIterator first, * BidirectionalIterator middle, * BidirectionalIterator last); * * template<class BidirectionalIterator, class Compare> * bool next_combination(BidirectionalIterator first, * BidirectionalIterator middle, * BidirectionalIterator last, Compare comp); */ template<class BidirectionalIterator> bool next_combination(BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last) { return detail::next_combination(first, middle, middle, last); } template<class BidirectionalIterator, class Compare> bool next_combination(BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last, Compare comp) { return detail::next_combination(first, middle, middle, last, comp); } /* PROPOSED STANDARD EXTENSIONS: * * template<class BidirectionalIterator> * bool prev_combination(BidirectionalIterator first, * BidirectionalIterator middle, * BidirectionalIterator last); * * template<class BidirectionalIterator, class Compare> * bool prev_combination(BidirectionalIterator first, * BidirectionalIterator middle, * BidirectionalIterator last, Compare comp); */ template<class BidirectionalIterator> inline bool prev_combination(BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last) { return detail::next_combination(middle, last, first, middle); } template<class BidirectionalIterator, class Compare> inline bool prev_combination(BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last, Compare comp) { return detail::next_combination(middle, last, first, middle, comp); } /* PROPOSED STANDARD EXTENSION: * * template<class BidirectionalIterator, class T> * bool next_mapping(BidirectionalIterator first, * BidirectionalIterator last, * T first_value, T last_value); * * template<class BidirectionalIterator, class T, class Incrementor> * bool next_mapping(BidirectionalIterator first, * BidirectionalIterator last, * T first_value, T last_value, Incrementor increment); */ template <class BidirectionalIterator, class T> bool next_mapping(BidirectionalIterator first, BidirectionalIterator last, T first_value, T last_value) { if (last == first ) { return false; } do { if (++(*(--last)) != last_value) { return true; } *last = first_value; } while (last != first); return false; } template <class BidirectionalIterator, class T, class Incrementer> bool next_mapping(BidirectionalIterator first, BidirectionalIterator last, T first_value, T last_value, Incrementer increment) { if (last == first ) { return false; } do { if (incrementer(*(--last)) != last_value) { return true; } *last = first_value; } while (last != first); return false; } /* PROPOSED STANDARD EXTENSION: * * template<class BidirectionalIterator, class T> * bool prev_mapping(BidirectionalIterator first, * BidirectionalIterator last, * T first_value, T last_value); * * template<class BidirectionalIterator, class T, class Decrementor> * bool prev_mapping(BidirectionalIterator first, * BidirectionalIterator last, * T first_value, T last_value, Decrementor decrement); */ template <class BidirectionalIterator, class T> bool prev_mapping(BidirectionalIterator first, BidirectionalIterator last, T first_value, T last_value) { if (last == first) { return false; } --last_value; do { if (*(--last) != first_value) { --(*last); return true; } *last = last_value; } while (last != first); return true; } template <class BidirectionalIterator, class T, class Decrementer> bool prev_mapping(BidirectionalIterator first, BidirectionalIterator last, T first_value, T last_value, Decrementer decrement) { if (last == first) { return false; } decrement(last_value); do { if (*(--last) != first_value) { decrement(*last); return true; } *last = last_value; } while (last != first); return true; } /* PROPOSED STANDARD EXTENSION: * * template<class BidirectionalIterator, class T> * bool next_combination_counts(BidirectionalIterator first, * BidirectionalIterator last); */ template <class BidirectionalIterator> bool next_combination_counts(BidirectionalIterator first, BidirectionalIterator last) { BidirectionalIterator current = last; while (current != first && *(--current) == 0) { } if (current == first) { if (first != last && *first != 0) std::iter_swap(--last, first); return false; } --(*current); std::iter_swap(--last, current); ++(*(--current)); return true; } /* PROPOSED STANDARD EXTENSION: * * template<class BidirectionalIterator> * bool prev_combination_counts(BidirectionalIterator first, * BidirectionalIterator last); */ template <class BidirectionalIterator> bool prev_combination_counts(BidirectionalIterator first, BidirectionalIterator last) { if (first == last) return false; BidirectionalIterator current = --last; while (current != first && *(--current) == 0) { } if (current == last || (current == first && *current == 0)) { if (first != last) std::iter_swap(first, last); return false; } --(*current); ++current; if (0 != *last) { std::iter_swap(current, last); } ++(*current); return true; } } // namespace boost #endif // BOOST_ALGORITHM_COMBINATION_HPP <|endoftext|>
<commit_before>#include <x0/StackTrace.h> #include <boost/lexical_cast.hpp> #include <execinfo.h> #include <cxxabi.h> #include <dlfcn.h> #include <strings.h> namespace x0 { StackTrace::StackTrace(int numSkipFrames, int numMaxFrames) { skip_ = 1 + numSkipFrames; //buffer_.resize(numSkipFrames + numMaxFrames); addresses_ = new void *[skip_ + numMaxFrames]; count_ = backtrace(addresses_, skip_ + numMaxFrames); } StackTrace::~StackTrace() { delete[] addresses_; } void StackTrace::generate(bool verbose) { if (!symbols_.empty()) return; auto stripLeftOf = [](const char *value, char ch) -> const char * { const char *p = value; for (auto i = value; *i; ++i) if (*i == ch) p = i; return p != value ? p + 1 : p; }; auto demangleSymbol = [](const char *symbolName, Buffer& result) { if (!symbolName || !*symbolName) result.push_back("<invalid symbol>"); else { char *rv = 0; int status = 0; std::size_t len = 1024; try { rv = abi::__cxa_demangle(symbolName, result.end(), &len, &status); } catch (...) {} if (status < 0) result.push_back(symbolName); else result.resize(result.size() + strlen(rv)); } }; for (int i = 0; i < count_; ++i) { void *address = addresses_[skip_ + i]; buffer_.push_back('['); buffer_.push_back(i); buffer_.push_back("] "); std::size_t begin = buffer_.size(); buffer_.reserve(buffer_.size() + 512); Dl_info info; if (!dladdr(address, &info)) buffer_.push_back("<unresolved symbol>"); else { demangleSymbol(info.dli_sname, buffer_); if (verbose) { buffer_.push_back(" in "); buffer_.push_back(stripLeftOf(info.dli_fname, '/')); } } std::size_t count = buffer_.size() - begin; symbols_.push_back(buffer_.ref(begin, count)); buffer_.push_back("\n"); } } /** retrieves the number of frames captured. */ int StackTrace::length() const { return count_; } /** retrieves the frame information of a frame at given index. */ const BufferRef& StackTrace::at(int index) const { return symbols_[index]; } /** retrieves full stack trace information (of all captured frames). */ const char *StackTrace::c_str() const { const_cast<StackTrace *>(this)->generate(true); return const_cast<StackTrace *>(this)->buffer_.c_str(); } } // namespace x0 <commit_msg>[core] StackTrace: let it be compilable on compilers not supporting lambdas yet.<commit_after>#include <x0/StackTrace.h> #include <boost/lexical_cast.hpp> #include <execinfo.h> #include <cxxabi.h> #include <dlfcn.h> #include <strings.h> namespace x0 { StackTrace::StackTrace(int numSkipFrames, int numMaxFrames) { skip_ = 1 + numSkipFrames; //buffer_.resize(numSkipFrames + numMaxFrames); addresses_ = new void *[skip_ + numMaxFrames]; count_ = backtrace(addresses_, skip_ + numMaxFrames); } StackTrace::~StackTrace() { delete[] addresses_; } inline auto stripLeftOf(const char *value, char ch) -> const char * { const char *p = value; for (auto i = value; *i; ++i) if (*i == ch) p = i; return p != value ? p + 1 : p; } inline auto demangleSymbol(const char *symbolName, Buffer& result) -> void { if (!symbolName || !*symbolName) result.push_back("<invalid symbol>"); else { char *rv = 0; int status = 0; std::size_t len = 1024; try { rv = abi::__cxa_demangle(symbolName, result.end(), &len, &status); } catch (...) {} if (status < 0) result.push_back(symbolName); else result.resize(result.size() + strlen(rv)); } } void StackTrace::generate(bool verbose) { if (!symbols_.empty()) return; for (int i = 0; i < count_; ++i) { void *address = addresses_[skip_ + i]; buffer_.push_back('['); buffer_.push_back(i); buffer_.push_back("] "); std::size_t begin = buffer_.size(); buffer_.reserve(buffer_.size() + 512); Dl_info info; if (!dladdr(address, &info)) buffer_.push_back("<unresolved symbol>"); else { demangleSymbol(info.dli_sname, buffer_); if (verbose) { buffer_.push_back(" in "); buffer_.push_back(stripLeftOf(info.dli_fname, '/')); } } std::size_t count = buffer_.size() - begin; symbols_.push_back(buffer_.ref(begin, count)); buffer_.push_back("\n"); } } /** retrieves the number of frames captured. */ int StackTrace::length() const { return count_; } /** retrieves the frame information of a frame at given index. */ const BufferRef& StackTrace::at(int index) const { return symbols_[index]; } /** retrieves full stack trace information (of all captured frames). */ const char *StackTrace::c_str() const { const_cast<StackTrace *>(this)->generate(true); return const_cast<StackTrace *>(this)->buffer_.c_str(); } } // namespace x0 <|endoftext|>
<commit_before>#include "gpu_optimizer.h" #include <iostream> #include <thread> #include <atomic> #include <chrono> #include <system_error> #include "gpu_problem.h" #include "gpu_analysis.h" #include "gpu_optdata.h" #include "gpu_optimize.h" //#define FIXED_BATCH_SIZE 48*1024 struct worker { std::thread thread; std::atomic<bool> cancel; std::atomic<uint32_t> iteration; worker() : cancel(false) { } }; gpu_optimizer::gpu_optimizer() { w = new worker(); } gpu_optimizer::~gpu_optimizer() { delete w; } bool gpu_optimizer::is_available() const { return gpu_check_requirements(); } uint32_t gpu_optimizer::get_iteration() const { return w->iteration; } void gpu_optimizer::optimize(const full_model & fm) { // set threshold const float delta_threshold = 1e-4f; // get information const problem & p = fm.get_problem(); // allocate and initialize gpu memory gpu_problem_allocator gp; gpu_analysis_allocator ga; gpu_optdata_allocator go; if (!gp.init(p)) { throw std::runtime_error("Failure when trying to allocate and initialize gpu_problem"); } if (!ga.init(p, fm)) { throw std::runtime_error("Failure when trying to allocate and initialize gpu_analysis"); } #if defined FIXED_BATCH_SIZE uint64_t state_batch_size = FIXED_BATCH_SIZE; std::cout << "Using fixed batch size: " << state_batch_size << std::endl; #else uint64_t state_batch_size = fm.get_system_states(); size_t free_byte, total_byte; cudaError_t err = cudaMemGetInfo( &free_byte, &total_byte ); if (err == cudaSuccess) { uint64_t required_byte = go.estimate_memory(p, fm, state_batch_size); // take into account a 10% overhead while ((required_byte * 11 / 10) > free_byte) { std::cout << "Batch size of " << state_batch_size << " requires "; std::cout << (required_byte / (1024*1024)) << " MB, "; std::cout << "but only " << (free_byte / (1024*1024)) << " MB are available" << std::endl; state_batch_size /= 2; required_byte = go.estimate_memory(p, fm, state_batch_size); } if (state_batch_size < fm.get_system_states()) { std::cout << "Using batched algorithm with batch size " << state_batch_size; } else { std::cout << "Using non-batched algorithm"; } std::cout << " (" << (required_byte / (1024*1024)) << " MB required)" << std::endl; } else { throw std::runtime_error("Unable to query available GPU memory"); } #endif if (!go.init(p, fm, state_batch_size)) { throw std::runtime_error("Failure when trying to allocate and initialize gpu_optdata"); } // start timing std::chrono::high_resolution_clock::time_point start, end; start = std::chrono::high_resolution_clock::now(); // initialize optimization gpu_optimize_init(*gp.get(), *ga.get(), *go.get()); w->iteration = 0; float delta = 1.0f; float cost = 0.0f; // iterations while (delta > delta_threshold && !w->cancel) { w->iteration += 1; gpu_optimize_iteration( ignore_revenue, always_allow_reject, check_strict_convergence, w->iteration, cost, delta); } // save solution objective = cost; gpu_get_policy(policy); // end timing end = std::chrono::high_resolution_clock::now(); long long ms = std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count(); // report information if (delta < delta_threshold) { std::cout << "Value Iteration Algorithm completed in " << w->iteration << " iterations" << std::endl; } else { std::cout << "Value Iteration Algorithm canceled after " << w->iteration << " iterations" << std::endl; } std::cout << "Value Iteration Algorithm run for " << ms << " ms" << std::endl; std::cout << "Value Iteration Algorithm: average cost: " << objective << std::endl; } void gpu_optimizer::start_optimize(const full_model & fm) { w->iteration = 0; w->cancel = false; w->thread = std::thread(&gpu_optimizer::optimize, this, std::cref(fm)); } void gpu_optimizer::cancel_optimize() { w->cancel = true; } void gpu_optimizer::join_optimize() { try { w->thread.join(); } catch (std::system_error & e) { std::cout << e.what() << std::endl; } } <commit_msg>Print used memory when using fixed batches<commit_after>#include "gpu_optimizer.h" #include <iostream> #include <thread> #include <atomic> #include <chrono> #include <system_error> #include "gpu_problem.h" #include "gpu_analysis.h" #include "gpu_optdata.h" #include "gpu_optimize.h" // #define FIXED_BATCH_SIZE 48*1024 struct worker { std::thread thread; std::atomic<bool> cancel; std::atomic<uint32_t> iteration; worker() : cancel(false) { } }; gpu_optimizer::gpu_optimizer() { w = new worker(); } gpu_optimizer::~gpu_optimizer() { delete w; } bool gpu_optimizer::is_available() const { return gpu_check_requirements(); } uint32_t gpu_optimizer::get_iteration() const { return w->iteration; } void gpu_optimizer::optimize(const full_model & fm) { // set threshold const float delta_threshold = 1e-4f; // get information const problem & p = fm.get_problem(); // allocate and initialize gpu memory gpu_problem_allocator gp; gpu_analysis_allocator ga; gpu_optdata_allocator go; if (!gp.init(p)) { throw std::runtime_error("Failure when trying to allocate and initialize gpu_problem"); } if (!ga.init(p, fm)) { throw std::runtime_error("Failure when trying to allocate and initialize gpu_analysis"); } #if defined FIXED_BATCH_SIZE uint64_t state_batch_size = FIXED_BATCH_SIZE; uint64_t required_byte = go.estimate_memory(p, fm, state_batch_size); std::cout << "Using fixed batch size: " << state_batch_size << " "; std::cout << "(" << (required_byte / (1024*1024)) << " MB required)" << std::endl; #else uint64_t state_batch_size = fm.get_system_states(); size_t free_byte, total_byte; cudaError_t err = cudaMemGetInfo( &free_byte, &total_byte ); if (err == cudaSuccess) { uint64_t required_byte = go.estimate_memory(p, fm, state_batch_size); // take into account a 10% overhead while ((required_byte * 11 / 10) > free_byte) { std::cout << "Batch size of " << state_batch_size << " requires "; std::cout << (required_byte / (1024*1024)) << " MB, "; std::cout << "but only " << (free_byte / (1024*1024)) << " MB are available" << std::endl; state_batch_size /= 2; required_byte = go.estimate_memory(p, fm, state_batch_size); } if (state_batch_size < fm.get_system_states()) { std::cout << "Using batched algorithm with batch size " << state_batch_size; } else { std::cout << "Using non-batched algorithm"; } std::cout << " (" << (required_byte / (1024*1024)) << " MB required)" << std::endl; } else { throw std::runtime_error("Unable to query available GPU memory"); } #endif if (!go.init(p, fm, state_batch_size)) { throw std::runtime_error("Failure when trying to allocate and initialize gpu_optdata"); } // start timing std::chrono::high_resolution_clock::time_point start, end; start = std::chrono::high_resolution_clock::now(); // initialize optimization gpu_optimize_init(*gp.get(), *ga.get(), *go.get()); w->iteration = 0; float delta = 1.0f; float cost = 0.0f; // iterations while (delta > delta_threshold && !w->cancel) { w->iteration += 1; gpu_optimize_iteration( ignore_revenue, always_allow_reject, check_strict_convergence, w->iteration, cost, delta); } // save solution objective = cost; gpu_get_policy(policy); // end timing end = std::chrono::high_resolution_clock::now(); long long ms = std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count(); // report information if (delta < delta_threshold) { std::cout << "Value Iteration Algorithm completed in " << w->iteration << " iterations" << std::endl; } else { std::cout << "Value Iteration Algorithm canceled after " << w->iteration << " iterations" << std::endl; } std::cout << "Value Iteration Algorithm run for " << ms << " ms" << std::endl; std::cout << "Value Iteration Algorithm: average cost: " << objective << std::endl; } void gpu_optimizer::start_optimize(const full_model & fm) { w->iteration = 0; w->cancel = false; w->thread = std::thread(&gpu_optimizer::optimize, this, std::cref(fm)); } void gpu_optimizer::cancel_optimize() { w->cancel = true; } void gpu_optimizer::join_optimize() { try { w->thread.join(); } catch (std::system_error & e) { std::cout << e.what() << std::endl; } } <|endoftext|>
<commit_before>#include "yugong.hpp" #include "yugong-debug.hpp" #include <cinttypes> #include <cstdint> #include <cstring> #define YG_CHECK_UNW(rv, pred) if (!(pred)) {\ yg_error("libunwind error %d: %s\n", rv, _yg_unw_strerror(rv));\ } namespace yg { const char *_yg_unw_strerror(int rv) { #if defined(__APPLE__) return "(unw_strerror not available on OSX)"; #else return unw_strerror(rv); #endif } void YGContext::from_ss_top(uintptr_t sp) { uintptr_t* s = reinterpret_cast<uintptr_t*>(sp); r15 = s[1]; r14 = s[2]; r13 = s[3]; r12 = s[4]; rbx = s[5]; rbp = s[6]; rip = s[7]; rsp = reinterpret_cast<uintptr_t>(&s[8]); } void YGCursor::_load_yg_ctx(YGContext &yg_ctx) { yg_debug("Reset libunwind context:\n"); yg_debug(" r15: %" PRIxPTR "\n", yg_ctx.r15); yg_debug(" r14: %" PRIxPTR "\n", yg_ctx.r14); yg_debug(" r13: %" PRIxPTR "\n", yg_ctx.r13); yg_debug(" r12: %" PRIxPTR "\n", yg_ctx.r12); yg_debug(" rbx: %" PRIxPTR "\n", yg_ctx.rbx); yg_debug(" rbp: %" PRIxPTR "\n", yg_ctx.rbp); yg_debug(" rip: %" PRIxPTR "\n", yg_ctx.rip); yg_debug(" rsp: %" PRIxPTR "\n", yg_ctx.rsp); memset(&unw_context, 0, sizeof(unw_context)); #if defined(__APPLE__) unw_context.data[15] = yg_ctx.r15; unw_context.data[14] = yg_ctx.r14; unw_context.data[13] = yg_ctx.r13; unw_context.data[12] = yg_ctx.r12; unw_context.data[ 1] = yg_ctx.rbx; unw_context.data[ 6] = yg_ctx.rbp; unw_context.data[16] = yg_ctx.rip; unw_context.data[ 7] = yg_ctx.rsp; #elif defined(__linux__) ucontext_t *uctx = static_cast<ucontext_t*>(&unw_context); mcontext_t *mctx = &uctx->uc_mcontext; // see ucontext_i.h in libunwind mctx->gregs[REG_R15] = yg_ctx.r15; mctx->gregs[REG_R14] = yg_ctx.r14; mctx->gregs[REG_R13] = yg_ctx.r13; mctx->gregs[REG_R12] = yg_ctx.r12; mctx->gregs[REG_RBX] = yg_ctx.rbx; mctx->gregs[REG_RBP] = yg_ctx.rbp; mctx->gregs[REG_RIP] = yg_ctx.rip; mctx->gregs[REG_RSP] = yg_ctx.rsp; #else #error "Expect __APPLE__ or __linux__" #endif int rv = unw_init_local(&unw_cursor, &unw_context); YG_CHECK_UNW(rv, rv == 0); } void YGCursor::_dump_yg_ctx(YGContext &yg_ctx) { int rv; rv = unw_get_reg(&unw_cursor, UNW_REG_SP , reinterpret_cast<unw_word_t*>(&yg_ctx.rsp)); YG_CHECK_UNW(rv, rv == 0); rv = unw_get_reg(&unw_cursor, UNW_REG_IP , reinterpret_cast<unw_word_t*>(&yg_ctx.rip)); YG_CHECK_UNW(rv, rv == 0); rv = unw_get_reg(&unw_cursor, UNW_X86_64_RBP, reinterpret_cast<unw_word_t*>(&yg_ctx.rbp)); YG_CHECK_UNW(rv, rv == 0); rv = unw_get_reg(&unw_cursor, UNW_X86_64_RBX, reinterpret_cast<unw_word_t*>(&yg_ctx.rbx)); YG_CHECK_UNW(rv, rv == 0); rv = unw_get_reg(&unw_cursor, UNW_X86_64_R12, reinterpret_cast<unw_word_t*>(&yg_ctx.r12)); YG_CHECK_UNW(rv, rv == 0); rv = unw_get_reg(&unw_cursor, UNW_X86_64_R13, reinterpret_cast<unw_word_t*>(&yg_ctx.r13)); YG_CHECK_UNW(rv, rv == 0); rv = unw_get_reg(&unw_cursor, UNW_X86_64_R14, reinterpret_cast<unw_word_t*>(&yg_ctx.r14)); YG_CHECK_UNW(rv, rv == 0); rv = unw_get_reg(&unw_cursor, UNW_X86_64_R15, reinterpret_cast<unw_word_t*>(&yg_ctx.r15)); YG_CHECK_UNW(rv, rv == 0); } YGCursor::YGCursor(YGStack &the_stack): stack(&the_stack) { _init_unw(); } void YGCursor::_init_unw() { YGContext yg_ctx; yg_ctx.from_ss_top(stack->sp); _load_yg_ctx(yg_ctx); } void YGCursor::step() { uintptr_t pc = cur_pc(); if (pc == reinterpret_cast<uintptr_t>(_yg_func_begin_resume)) { yg_debug("Function begin frame. Unwind it manually without libunwind.\n"); YGContext yg_ctx; _dump_yg_ctx(yg_ctx); uintptr_t sp = yg_ctx.rsp; uintptr_t retaddr = _load_word(sp + 8); uintptr_t new_sp = sp + 16; yg_debug("Cur ip = %" PRIxPTR ", cur sp = %" PRIxPTR "\n", pc, sp); yg_debug("New ip = %" PRIxPTR ", new sp = %" PRIxPTR "\n", retaddr, new_sp); yg_debug("Additional stack dump:\n"); uintptr_t i; for (i = sp; i < sp + 80; i+=8) { yg_debug(" [%" PRIxPTR "] = %" PRIxPTR "\n", i, _load_word(i)); } yg_ctx.rip = retaddr; yg_ctx.rsp = new_sp; _load_yg_ctx(yg_ctx); } else { int rv = unw_step(&unw_cursor); YG_CHECK_UNW(rv, rv > 0); } } uintptr_t YGCursor::cur_pc() { uintptr_t ip; int rv = unw_get_reg(&unw_cursor, UNW_REG_IP, reinterpret_cast<unw_word_t*>(&ip)); YG_CHECK_UNW(rv, rv == 0); return ip; } uintptr_t YGCursor::_cur_sp() { uintptr_t sp; int rv = unw_get_reg(&unw_cursor, UNW_REG_SP, reinterpret_cast<unw_word_t*>(&sp)); YG_CHECK_UNW(rv, rv == 0); return sp; } void YGCursor::pop_frames_to() { YGContext yg_ctx; _dump_yg_ctx(yg_ctx); // Set stack->sp to the current CFI. yg_debug("new sp = %" PRIxPTR ", new pc = %" PRIxPTR "\n", yg_ctx.rsp, yg_ctx.rip); stack->sp = yg_ctx.rsp; // Push the current return address stack->_push_return_address(yg_ctx.rip); // return address // Push an swap-stack top so that it still has the SS return protocol. _push_ss_top(yg_ctx); } void YGCursor::_push_ss_top(YGContext &yg_ctx) { stack->_push_word(yg_ctx.rbp); stack->_push_word(yg_ctx.rbx); stack->_push_word(yg_ctx.r12); stack->_push_word(yg_ctx.r13); stack->_push_word(yg_ctx.r14); stack->_push_word(yg_ctx.r15); yg_debug("Now rbp is %" PRIxPTR "\n", yg_ctx.rbp); stack->_push_word(reinterpret_cast<uintptr_t>(_yg_stack_swap_cont)); // rip = _yg_stack_swap_cont } void YGCursor::push_frame(uintptr_t func) { YGContext yg_ctx; _dump_yg_ctx(yg_ctx); // Remove the swap-stack top on the physical stack. stack->sp = yg_ctx.rsp; // Push the current return address stack->_push_return_address(yg_ctx.rip); // return address // Push the function starter frame stack->_push_function_starter(func); // Push an swap-stack top so that it still has the SS return protocol. _push_ss_top(yg_ctx); yg_ctx.rsp -= 16; // does not include the function starter's return address yg_ctx.rip = reinterpret_cast<uintptr_t>(_yg_func_begin_resume); // this is the "return address". _load_yg_ctx(yg_ctx); // The stack top changed. Re-initailize unw_*_t } } <commit_msg>unw_step returning 0 is not an error.<commit_after>#include "yugong.hpp" #include "yugong-debug.hpp" #include <cinttypes> #include <cstdint> #include <cstring> #define YG_CHECK_UNW(rv, pred) if (!(pred)) {\ yg_error("libunwind error %d: %s\n", rv, _yg_unw_strerror(rv));\ } namespace yg { const char *_yg_unw_strerror(int rv) { #if defined(__APPLE__) return "(unw_strerror not available on OSX)"; #else return unw_strerror(rv); #endif } void YGContext::from_ss_top(uintptr_t sp) { uintptr_t* s = reinterpret_cast<uintptr_t*>(sp); r15 = s[1]; r14 = s[2]; r13 = s[3]; r12 = s[4]; rbx = s[5]; rbp = s[6]; rip = s[7]; rsp = reinterpret_cast<uintptr_t>(&s[8]); } void YGCursor::_load_yg_ctx(YGContext &yg_ctx) { yg_debug("Reset libunwind context:\n"); yg_debug(" r15: %" PRIxPTR "\n", yg_ctx.r15); yg_debug(" r14: %" PRIxPTR "\n", yg_ctx.r14); yg_debug(" r13: %" PRIxPTR "\n", yg_ctx.r13); yg_debug(" r12: %" PRIxPTR "\n", yg_ctx.r12); yg_debug(" rbx: %" PRIxPTR "\n", yg_ctx.rbx); yg_debug(" rbp: %" PRIxPTR "\n", yg_ctx.rbp); yg_debug(" rip: %" PRIxPTR "\n", yg_ctx.rip); yg_debug(" rsp: %" PRIxPTR "\n", yg_ctx.rsp); memset(&unw_context, 0, sizeof(unw_context)); #if defined(__APPLE__) unw_context.data[15] = yg_ctx.r15; unw_context.data[14] = yg_ctx.r14; unw_context.data[13] = yg_ctx.r13; unw_context.data[12] = yg_ctx.r12; unw_context.data[ 1] = yg_ctx.rbx; unw_context.data[ 6] = yg_ctx.rbp; unw_context.data[16] = yg_ctx.rip; unw_context.data[ 7] = yg_ctx.rsp; #elif defined(__linux__) ucontext_t *uctx = static_cast<ucontext_t*>(&unw_context); mcontext_t *mctx = &uctx->uc_mcontext; // see ucontext_i.h in libunwind mctx->gregs[REG_R15] = yg_ctx.r15; mctx->gregs[REG_R14] = yg_ctx.r14; mctx->gregs[REG_R13] = yg_ctx.r13; mctx->gregs[REG_R12] = yg_ctx.r12; mctx->gregs[REG_RBX] = yg_ctx.rbx; mctx->gregs[REG_RBP] = yg_ctx.rbp; mctx->gregs[REG_RIP] = yg_ctx.rip; mctx->gregs[REG_RSP] = yg_ctx.rsp; #else #error "Expect __APPLE__ or __linux__" #endif int rv = unw_init_local(&unw_cursor, &unw_context); YG_CHECK_UNW(rv, rv == 0); } void YGCursor::_dump_yg_ctx(YGContext &yg_ctx) { int rv; rv = unw_get_reg(&unw_cursor, UNW_REG_SP , reinterpret_cast<unw_word_t*>(&yg_ctx.rsp)); YG_CHECK_UNW(rv, rv == 0); rv = unw_get_reg(&unw_cursor, UNW_REG_IP , reinterpret_cast<unw_word_t*>(&yg_ctx.rip)); YG_CHECK_UNW(rv, rv == 0); rv = unw_get_reg(&unw_cursor, UNW_X86_64_RBP, reinterpret_cast<unw_word_t*>(&yg_ctx.rbp)); YG_CHECK_UNW(rv, rv == 0); rv = unw_get_reg(&unw_cursor, UNW_X86_64_RBX, reinterpret_cast<unw_word_t*>(&yg_ctx.rbx)); YG_CHECK_UNW(rv, rv == 0); rv = unw_get_reg(&unw_cursor, UNW_X86_64_R12, reinterpret_cast<unw_word_t*>(&yg_ctx.r12)); YG_CHECK_UNW(rv, rv == 0); rv = unw_get_reg(&unw_cursor, UNW_X86_64_R13, reinterpret_cast<unw_word_t*>(&yg_ctx.r13)); YG_CHECK_UNW(rv, rv == 0); rv = unw_get_reg(&unw_cursor, UNW_X86_64_R14, reinterpret_cast<unw_word_t*>(&yg_ctx.r14)); YG_CHECK_UNW(rv, rv == 0); rv = unw_get_reg(&unw_cursor, UNW_X86_64_R15, reinterpret_cast<unw_word_t*>(&yg_ctx.r15)); YG_CHECK_UNW(rv, rv == 0); } YGCursor::YGCursor(YGStack &the_stack): stack(&the_stack) { _init_unw(); } void YGCursor::_init_unw() { YGContext yg_ctx; yg_ctx.from_ss_top(stack->sp); _load_yg_ctx(yg_ctx); } void YGCursor::step() { uintptr_t pc = cur_pc(); if (pc == reinterpret_cast<uintptr_t>(_yg_func_begin_resume)) { yg_debug("Function begin frame. Unwind it manually without libunwind.\n"); YGContext yg_ctx; _dump_yg_ctx(yg_ctx); uintptr_t sp = yg_ctx.rsp; uintptr_t retaddr = _load_word(sp + 8); uintptr_t new_sp = sp + 16; yg_debug("Cur ip = %" PRIxPTR ", cur sp = %" PRIxPTR "\n", pc, sp); yg_debug("New ip = %" PRIxPTR ", new sp = %" PRIxPTR "\n", retaddr, new_sp); yg_debug("Additional stack dump:\n"); uintptr_t i; for (i = sp; i < sp + 80; i+=8) { yg_debug(" [%" PRIxPTR "] = %" PRIxPTR "\n", i, _load_word(i)); } yg_ctx.rip = retaddr; yg_ctx.rsp = new_sp; _load_yg_ctx(yg_ctx); } else { int rv = unw_step(&unw_cursor); YG_CHECK_UNW(rv, rv >= 0); } } uintptr_t YGCursor::cur_pc() { uintptr_t ip; int rv = unw_get_reg(&unw_cursor, UNW_REG_IP, reinterpret_cast<unw_word_t*>(&ip)); YG_CHECK_UNW(rv, rv == 0); return ip; } uintptr_t YGCursor::_cur_sp() { uintptr_t sp; int rv = unw_get_reg(&unw_cursor, UNW_REG_SP, reinterpret_cast<unw_word_t*>(&sp)); YG_CHECK_UNW(rv, rv == 0); return sp; } void YGCursor::pop_frames_to() { YGContext yg_ctx; _dump_yg_ctx(yg_ctx); // Set stack->sp to the current CFI. yg_debug("new sp = %" PRIxPTR ", new pc = %" PRIxPTR "\n", yg_ctx.rsp, yg_ctx.rip); stack->sp = yg_ctx.rsp; // Push the current return address stack->_push_return_address(yg_ctx.rip); // return address // Push an swap-stack top so that it still has the SS return protocol. _push_ss_top(yg_ctx); } void YGCursor::_push_ss_top(YGContext &yg_ctx) { stack->_push_word(yg_ctx.rbp); stack->_push_word(yg_ctx.rbx); stack->_push_word(yg_ctx.r12); stack->_push_word(yg_ctx.r13); stack->_push_word(yg_ctx.r14); stack->_push_word(yg_ctx.r15); yg_debug("Now rbp is %" PRIxPTR "\n", yg_ctx.rbp); stack->_push_word(reinterpret_cast<uintptr_t>(_yg_stack_swap_cont)); // rip = _yg_stack_swap_cont } void YGCursor::push_frame(uintptr_t func) { YGContext yg_ctx; _dump_yg_ctx(yg_ctx); // Remove the swap-stack top on the physical stack. stack->sp = yg_ctx.rsp; // Push the current return address stack->_push_return_address(yg_ctx.rip); // return address // Push the function starter frame stack->_push_function_starter(func); // Push an swap-stack top so that it still has the SS return protocol. _push_ss_top(yg_ctx); yg_ctx.rsp -= 16; // does not include the function starter's return address yg_ctx.rip = reinterpret_cast<uintptr_t>(_yg_func_begin_resume); // this is the "return address". _load_yg_ctx(yg_ctx); // The stack top changed. Re-initailize unw_*_t } } <|endoftext|>
<commit_before>#include "AnimationComponent.h" #include "GameManager.h" #include "ResourceManager.h" bool Arthas::AnimationCompnent::init() { if (!Arthas::Component::init()) { return false; } m_Type = CT_ANIMATION; return true; } void Arthas::AnimationCompnent::update(float dTime) { } void Arthas::AnimationCompnent::enter() { auto animation = GET_RESOURCE_MANAGER()->createAnimation(m_AnimationType); auto animate = cocos2d::Animate::create(animation); auto repeat = cocos2d::RepeatForever::create(animate); m_Sprite->setVisible(true); m_Sprite->runAction(repeat); } void Arthas::AnimationCompnent::exit() { m_Sprite->setVisible(false); m_Sprite->stopAllActions(); } void Arthas::AnimationCompnent::setAnimation(ResourceType animationType, Component* renderTarget) { m_AnimationType = animationType; m_Sprite = cocos2d::Sprite::create(); renderTarget->addChild(m_Sprite); m_Sprite->setAnchorPoint(cocos2d::Point::ZERO); m_Sprite->setVisible(false); } <commit_msg>commit<commit_after>#include "AnimationComponent.h" #include "GameManager.h" #include "ResourceManager.h" bool Arthas::AnimationCompnent::init() { if (!Arthas::Component::init()) { return false; } m_Type = CT_ANIMATION; return true; } void Arthas::AnimationCompnent::update(float dTime) { } void Arthas::AnimationCompnent::enter() { auto animation = GET_RESOURCE_MANAGER()->createAnimation(m_AnimationType); auto animate = cocos2d::Animate::create(animation); auto repeat = cocos2d::RepeatForever::create(animate); m_Sprite->setVisible(true); m_Sprite->runAction(repeat); } void Arthas::AnimationCompnent::exit() { m_Sprite->setVisible(false); m_Sprite->stopAllActions(); } void Arthas::AnimationCompnent::setAnimation(ResourceType animationType, Component* renderTarget) { m_AnimationType = animationType; m_Sprite = cocos2d::Sprite::create(); renderTarget->addChild(m_Sprite); m_Sprite->setAnchorPoint(cocos2d::Point(0.5f,0.5f)); m_Sprite->setVisible(false); } <|endoftext|>
<commit_before>//===-- EmulateInstructionARM.cpp -------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "EmulateInstructionARM.h" #include "ARMUtils.h" using namespace lldb; using namespace lldb_private; // ARM constants used during decoding #define REG_RD 0 #define LDM_REGLIST 1 #define PC_REG 15 #define PC_REGLIST_BIT 0x8000 #define ARMv4 (1u << 0) #define ARMv4T (1u << 1) #define ARMv5T (1u << 2) #define ARMv5TE (1u << 3) #define ARMv5TEJ (1u << 4) #define ARMv6 (1u << 5) #define ARMv6K (1u << 6) #define ARMv6T2 (1u << 7) #define ARMv7 (1u << 8) #define ARMv8 (1u << 8) #define ARMvAll (0xffffffffu) typedef enum { eEncodingA1, eEncodingA2, eEncodingA3, eEncodingA4, eEncodingA5, eEncodingT1, eEncodingT2, eEncodingT3, eEncodingT4, eEncodingT5, } ARMEncoding; typedef enum { eSize16, eSize32 } ARMInstrSize; // Typedef for the callback function used during the emulation. // Pass along (ARMEncoding)encoding as the callback data. typedef bool (*EmulateCallback) (EmulateInstructionARM *emulator, ARMEncoding encoding); typedef struct { uint32_t mask; uint32_t value; uint32_t variants; ARMEncoding encoding; ARMInstrSize size; EmulateCallback callback; const char *name; } ARMOpcode; static bool emulate_push (EmulateInstructionARM *emulator, ARMEncoding encoding) { #if 0 // ARM pseudo code... if (ConditionPassed()) { EncodingSpecificOperations(); NullCheckIfThumbEE(13); address = SP - 4*BitCount(registers); for (i = 0 to 14) { if (registers<i> == ’1’) { if i == 13 && i != LowestSetBit(registers) // Only possible for encoding A1 MemA[address,4] = bits(32) UNKNOWN; else MemA[address,4] = R[i]; address = address + 4; } } if (registers<15> == ’1’) // Only possible for encoding A1 or A2 MemA[address,4] = PCStoreValue(); SP = SP - 4*BitCount(registers); } #endif bool success = false; const uint32_t opcode = emulator->OpcodeAsUnsigned (&success); if (!success) return false; if (emulator->ConditionPassed()) { const uint32_t addr_byte_size = emulator->GetAddressByteSize(); const addr_t sp = emulator->ReadRegisterUnsigned (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_SP, 0, &success); if (!success) return false; uint32_t registers = 0; uint32_t t; // t = UInt(Rt) switch (encoding) { case eEncodingT1: registers = EmulateInstruction::UnsignedBits (opcode, 7, 0); // The M bit represents LR. if (EmulateInstruction::UnsignedBits (opcode, 8, 8)) registers |= 0x000eu; // if BitCount(registers) < 1 then UNPREDICTABLE; if (BitCount(registers) < 1) return false; break; case eEncodingT2: // Ignore bits 15 & 13. registers = EmulateInstruction::UnsignedBits (opcode, 15, 0) & ~0xa000; // if BitCount(registers) < 2 then UNPREDICTABLE; if (BitCount(registers) < 2) return false; break; case eEncodingT3: t = EmulateInstruction::UnsignedBits (opcode, 15, 12); // if BadReg(t) then UNPREDICTABLE; if (BadReg(t)) return false; registers = (1u << t); break; case eEncodingA1: registers = EmulateInstruction::UnsignedBits (opcode, 15, 0); // Instead of return false, let's handle the following case as well, // which amounts to pushing one reg onto the full descending stacks. // if BitCount(register_list) < 2 then SEE STMDB / STMFD; break; case eEncodingA2: t = EmulateInstruction::UnsignedBits (opcode, 15, 12); // if t == 13 then UNPREDICTABLE; if (t == dwarf_sp) return false; registers = (1u << t); break; default: return false; } addr_t sp_offset = addr_byte_size * BitCount (registers); addr_t addr = sp - sp_offset; uint32_t i; EmulateInstruction::Context context = { EmulateInstruction::eContextPushRegisterOnStack, eRegisterKindDWARF, 0, 0 }; for (i=0; i<15; ++i) { if (EmulateInstruction::BitIsSet (registers, 1u << i)) { context.arg1 = dwarf_r0 + i; // arg1 in the context is the DWARF register number context.arg2 = addr - sp; // arg2 in the context is the stack pointer offset uint32_t reg_value = emulator->ReadRegisterUnsigned(eRegisterKindDWARF, context.arg1, 0, &success); if (!success) return false; if (!emulator->WriteMemoryUnsigned (context, addr, reg_value, addr_byte_size)) return false; addr += addr_byte_size; } } if (EmulateInstruction::BitIsSet (registers, 1u << 15)) { context.arg1 = dwarf_pc; // arg1 in the context is the DWARF register number context.arg2 = addr - sp; // arg2 in the context is the stack pointer offset const uint32_t pc = emulator->ReadRegisterUnsigned(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC, 0, &success); if (!success) return false; if (!emulator->WriteMemoryUnsigned (context, addr, pc + 8, addr_byte_size)) return false; } context.type = EmulateInstruction::eContextAdjustStackPointer; context.arg0 = eRegisterKindGeneric; context.arg1 = LLDB_REGNUM_GENERIC_SP; context.arg2 = sp_offset; if (!emulator->WriteRegisterUnsigned (context, eRegisterKindGeneric, LLDB_REGNUM_GENERIC_SP, sp - sp_offset)) return false; } return true; } // A store operation to the SP that also updates the SP. static bool emulate_str_rt_sp (EmulateInstructionARM *emulator, ARMEncoding encoding) { #if 0 // ARM pseudo code... if (ConditionPassed()) { EncodingSpecificOperations(); offset_addr = if add then (R[n] + imm32) else (R[n] - imm32); address = if index then offset_addr else R[n]; MemU[address,4] = if t == 15 then PCStoreValue() else R[t]; if wback then R[n] = offset_addr; } #endif bool success = false; const uint32_t opcode = emulator->OpcodeAsUnsigned (&success); if (!success) return false; if (emulator->ConditionPassed()) { const uint32_t addr_byte_size = emulator->GetAddressByteSize(); const addr_t sp = emulator->ReadRegisterUnsigned (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_SP, 0, &success); if (!success) return false; uint32_t t; // t = UInt(Rt) uint32_t imm12; switch (encoding) { case eEncodingA1: t = EmulateInstruction::UnsignedBits (opcode, 15, 12); imm12 = EmulateInstruction::UnsignedBits (opcode, 11, 0); break; default: return false; } addr_t sp_offset = imm12; addr_t addr = sp - sp_offset; EmulateInstruction::Context context = { EmulateInstruction::eContextPushRegisterOnStack, eRegisterKindDWARF, 0, 0 }; if (t != 15) { context.arg1 = dwarf_r0 + t; // arg1 in the context is the DWARF register number context.arg2 = addr - sp; // arg2 in the context is the stack pointer offset uint32_t reg_value = emulator->ReadRegisterUnsigned(eRegisterKindDWARF, context.arg1, 0, &success); if (!success) return false; if (!emulator->WriteMemoryUnsigned (context, addr, reg_value, addr_byte_size)) return false; } else { context.arg1 = dwarf_pc; // arg1 in the context is the DWARF register number context.arg2 = addr - sp; // arg2 in the context is the stack pointer offset const uint32_t pc = emulator->ReadRegisterUnsigned(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC, 0, &success); if (!success) return false; if (!emulator->WriteMemoryUnsigned (context, addr, pc + 8, addr_byte_size)) return false; } context.type = EmulateInstruction::eContextAdjustStackPointer; context.arg0 = eRegisterKindGeneric; context.arg1 = LLDB_REGNUM_GENERIC_SP; context.arg2 = sp_offset; if (!emulator->WriteRegisterUnsigned (context, eRegisterKindGeneric, LLDB_REGNUM_GENERIC_SP, sp - sp_offset)) return false; } return true; } static ARMOpcode g_arm_opcodes[] = { { 0x0fff0000, 0x092d0000, ARMvAll, eEncodingA1, eSize32, emulate_push, "push<c> <registers> ; <registers> contains more than one register" }, { 0x0fff0fff, 0x052d0004, ARMvAll, eEncodingA2, eSize32, emulate_push, "push<c> <registers> ; <registers> contains one register, <Rt>" }, // if Rn == '1101' && imm12 == '000000000100' then SEE PUSH; { 0x0fff0000, 0x052d0000, ARMvAll, eEncodingA1, eSize32, emulate_str_rt_sp, "str<c><q> Rt, [sp, #-n]!" } }; static ARMOpcode g_thumb_opcodes[] = { { 0x0000fe00, 0x0000b400, ARMvAll, eEncodingT1, eSize16, emulate_push, "push<c> <registers>" }, { 0xffff0000, 0xe92d0000, ARMv6T2|ARMv7, eEncodingT2, eSize32, emulate_push, "push<c>.w <registers> ; <registers> contains more than one register" }, { 0xffff0fff, 0xf84d0d04, ARMv6T2|ARMv7, eEncodingT3, eSize32, emulate_push, "push<c>.w <registers> ; <registers> contains one register, <Rt>" } }; static const size_t k_num_arm_opcodes = sizeof(g_arm_opcodes)/sizeof(ARMOpcode); static const size_t k_num_thumb_opcodes = sizeof(g_thumb_opcodes)/sizeof(ARMOpcode); bool EmulateInstructionARM::ReadInstruction () { bool success = false; m_inst_cpsr = ReadRegisterUnsigned (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS, 0, &success); if (success) { addr_t pc = ReadRegisterUnsigned (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC, LLDB_INVALID_ADDRESS, &success); if (success) { Context read_inst_context = {eContextReadOpcode, 0, 0}; if (m_inst_cpsr & MASK_CPSR_T) { m_inst_mode = eModeThumb; uint32_t thumb_opcode = ReadMemoryUnsigned(read_inst_context, pc, 2, 0, &success); if (success) { if ((m_inst.opcode.inst16 & 0xe000) != 0xe000 || ((m_inst.opcode.inst16 & 0x1800u) == 0)) { m_inst.opcode_type = eOpcode16; m_inst.opcode.inst16 = thumb_opcode; } else { m_inst.opcode_type = eOpcode32; m_inst.opcode.inst32 = (thumb_opcode << 16) | ReadMemoryUnsigned(read_inst_context, pc + 2, 2, 0, &success); } } } else { m_inst_mode = eModeARM; m_inst.opcode_type = eOpcode32; m_inst.opcode.inst32 = ReadMemoryUnsigned(read_inst_context, pc, 4, 0, &success); } } } if (!success) { m_inst_mode = eModeInvalid; m_inst_pc = LLDB_INVALID_ADDRESS; } return success; } uint32_t EmulateInstructionARM::CurrentCond () { switch (m_inst_mode) { default: case eModeInvalid: break; case eModeARM: return UnsignedBits(m_inst.opcode.inst32, 31, 28); case eModeThumb: return 0x0000000Eu; // Return always for now, we need to handl IT instructions later } return UINT32_MAX; // Return invalid value } bool EmulateInstructionARM::ConditionPassed () { if (m_inst_cpsr == 0) return false; const uint32_t cond = CurrentCond (); if (cond == UINT32_MAX) return false; bool result = false; switch (UnsignedBits(cond, 3, 1)) { case 0: result = (m_inst_cpsr & MASK_CPSR_Z) != 0; break; case 1: result = (m_inst_cpsr & MASK_CPSR_C) != 0; break; case 2: result = (m_inst_cpsr & MASK_CPSR_N) != 0; break; case 3: result = (m_inst_cpsr & MASK_CPSR_V) != 0; break; case 4: result = ((m_inst_cpsr & MASK_CPSR_C) != 0) && ((m_inst_cpsr & MASK_CPSR_Z) == 0); break; case 5: { bool n = (m_inst_cpsr & MASK_CPSR_N); bool v = (m_inst_cpsr & MASK_CPSR_V); result = n == v; } break; case 6: { bool n = (m_inst_cpsr & MASK_CPSR_N); bool v = (m_inst_cpsr & MASK_CPSR_V); result = n == v && ((m_inst_cpsr & MASK_CPSR_Z) == 0); } break; case 7: result = true; break; } if (cond & 1) result = !result; return result; } bool EmulateInstructionARM::EvaluateInstruction () { return false; } <commit_msg>Variable renaming for better readability.<commit_after>//===-- EmulateInstructionARM.cpp -------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "EmulateInstructionARM.h" #include "ARMUtils.h" using namespace lldb; using namespace lldb_private; // ARM constants used during decoding #define REG_RD 0 #define LDM_REGLIST 1 #define PC_REG 15 #define PC_REGLIST_BIT 0x8000 #define ARMv4 (1u << 0) #define ARMv4T (1u << 1) #define ARMv5T (1u << 2) #define ARMv5TE (1u << 3) #define ARMv5TEJ (1u << 4) #define ARMv6 (1u << 5) #define ARMv6K (1u << 6) #define ARMv6T2 (1u << 7) #define ARMv7 (1u << 8) #define ARMv8 (1u << 8) #define ARMvAll (0xffffffffu) typedef enum { eEncodingA1, eEncodingA2, eEncodingA3, eEncodingA4, eEncodingA5, eEncodingT1, eEncodingT2, eEncodingT3, eEncodingT4, eEncodingT5, } ARMEncoding; typedef enum { eSize16, eSize32 } ARMInstrSize; // Typedef for the callback function used during the emulation. // Pass along (ARMEncoding)encoding as the callback data. typedef bool (*EmulateCallback) (EmulateInstructionARM *emulator, ARMEncoding encoding); typedef struct { uint32_t mask; uint32_t value; uint32_t variants; ARMEncoding encoding; ARMInstrSize size; EmulateCallback callback; const char *name; } ARMOpcode; static bool emulate_push (EmulateInstructionARM *emulator, ARMEncoding encoding) { #if 0 // ARM pseudo code... if (ConditionPassed()) { EncodingSpecificOperations(); NullCheckIfThumbEE(13); address = SP - 4*BitCount(registers); for (i = 0 to 14) { if (registers<i> == ’1’) { if i == 13 && i != LowestSetBit(registers) // Only possible for encoding A1 MemA[address,4] = bits(32) UNKNOWN; else MemA[address,4] = R[i]; address = address + 4; } } if (registers<15> == ’1’) // Only possible for encoding A1 or A2 MemA[address,4] = PCStoreValue(); SP = SP - 4*BitCount(registers); } #endif bool success = false; const uint32_t opcode = emulator->OpcodeAsUnsigned (&success); if (!success) return false; if (emulator->ConditionPassed()) { const uint32_t addr_byte_size = emulator->GetAddressByteSize(); const addr_t sp = emulator->ReadRegisterUnsigned (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_SP, 0, &success); if (!success) return false; uint32_t registers = 0; uint32_t Rt; // the source register switch (encoding) { case eEncodingT1: registers = EmulateInstruction::UnsignedBits (opcode, 7, 0); // The M bit represents LR. if (EmulateInstruction::UnsignedBits (opcode, 8, 8)) registers |= 0x000eu; // if BitCount(registers) < 1 then UNPREDICTABLE; if (BitCount(registers) < 1) return false; break; case eEncodingT2: // Ignore bits 15 & 13. registers = EmulateInstruction::UnsignedBits (opcode, 15, 0) & ~0xa000; // if BitCount(registers) < 2 then UNPREDICTABLE; if (BitCount(registers) < 2) return false; break; case eEncodingT3: Rt = EmulateInstruction::UnsignedBits (opcode, 15, 12); // if BadReg(t) then UNPREDICTABLE; if (BadReg(Rt)) return false; registers = (1u << Rt); break; case eEncodingA1: registers = EmulateInstruction::UnsignedBits (opcode, 15, 0); // Instead of return false, let's handle the following case as well, // which amounts to pushing one reg onto the full descending stacks. // if BitCount(register_list) < 2 then SEE STMDB / STMFD; break; case eEncodingA2: Rt = EmulateInstruction::UnsignedBits (opcode, 15, 12); // if t == 13 then UNPREDICTABLE; if (Rt == dwarf_sp) return false; registers = (1u << Rt); break; default: return false; } addr_t sp_offset = addr_byte_size * BitCount (registers); addr_t addr = sp - sp_offset; uint32_t i; EmulateInstruction::Context context = { EmulateInstruction::eContextPushRegisterOnStack, eRegisterKindDWARF, 0, 0 }; for (i=0; i<15; ++i) { if (EmulateInstruction::BitIsSet (registers, 1u << i)) { context.arg1 = dwarf_r0 + i; // arg1 in the context is the DWARF register number context.arg2 = addr - sp; // arg2 in the context is the stack pointer offset uint32_t reg_value = emulator->ReadRegisterUnsigned(eRegisterKindDWARF, context.arg1, 0, &success); if (!success) return false; if (!emulator->WriteMemoryUnsigned (context, addr, reg_value, addr_byte_size)) return false; addr += addr_byte_size; } } if (EmulateInstruction::BitIsSet (registers, 1u << 15)) { context.arg1 = dwarf_pc; // arg1 in the context is the DWARF register number context.arg2 = addr - sp; // arg2 in the context is the stack pointer offset const uint32_t pc = emulator->ReadRegisterUnsigned(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC, 0, &success); if (!success) return false; if (!emulator->WriteMemoryUnsigned (context, addr, pc + 8, addr_byte_size)) return false; } context.type = EmulateInstruction::eContextAdjustStackPointer; context.arg0 = eRegisterKindGeneric; context.arg1 = LLDB_REGNUM_GENERIC_SP; context.arg2 = sp_offset; if (!emulator->WriteRegisterUnsigned (context, eRegisterKindGeneric, LLDB_REGNUM_GENERIC_SP, sp - sp_offset)) return false; } return true; } // A store operation to the SP that also updates the SP. static bool emulate_str_rt_sp (EmulateInstructionARM *emulator, ARMEncoding encoding) { #if 0 // ARM pseudo code... if (ConditionPassed()) { EncodingSpecificOperations(); offset_addr = if add then (R[n] + imm32) else (R[n] - imm32); address = if index then offset_addr else R[n]; MemU[address,4] = if t == 15 then PCStoreValue() else R[t]; if wback then R[n] = offset_addr; } #endif bool success = false; const uint32_t opcode = emulator->OpcodeAsUnsigned (&success); if (!success) return false; if (emulator->ConditionPassed()) { const uint32_t addr_byte_size = emulator->GetAddressByteSize(); const addr_t sp = emulator->ReadRegisterUnsigned (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_SP, 0, &success); if (!success) return false; uint32_t Rt; // the source register uint32_t imm12; switch (encoding) { case eEncodingA1: Rt = EmulateInstruction::UnsignedBits (opcode, 15, 12); imm12 = EmulateInstruction::UnsignedBits (opcode, 11, 0); break; default: return false; } addr_t sp_offset = imm12; addr_t addr = sp - sp_offset; EmulateInstruction::Context context = { EmulateInstruction::eContextPushRegisterOnStack, eRegisterKindDWARF, 0, 0 }; if (Rt != 15) { context.arg1 = dwarf_r0 + Rt; // arg1 in the context is the DWARF register number context.arg2 = addr - sp; // arg2 in the context is the stack pointer offset uint32_t reg_value = emulator->ReadRegisterUnsigned(eRegisterKindDWARF, context.arg1, 0, &success); if (!success) return false; if (!emulator->WriteMemoryUnsigned (context, addr, reg_value, addr_byte_size)) return false; } else { context.arg1 = dwarf_pc; // arg1 in the context is the DWARF register number context.arg2 = addr - sp; // arg2 in the context is the stack pointer offset const uint32_t pc = emulator->ReadRegisterUnsigned(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC, 0, &success); if (!success) return false; if (!emulator->WriteMemoryUnsigned (context, addr, pc + 8, addr_byte_size)) return false; } context.type = EmulateInstruction::eContextAdjustStackPointer; context.arg0 = eRegisterKindGeneric; context.arg1 = LLDB_REGNUM_GENERIC_SP; context.arg2 = sp_offset; if (!emulator->WriteRegisterUnsigned (context, eRegisterKindGeneric, LLDB_REGNUM_GENERIC_SP, sp - sp_offset)) return false; } return true; } static ARMOpcode g_arm_opcodes[] = { { 0x0fff0000, 0x092d0000, ARMvAll, eEncodingA1, eSize32, emulate_push, "push<c> <registers> ; <registers> contains more than one register" }, { 0x0fff0fff, 0x052d0004, ARMvAll, eEncodingA2, eSize32, emulate_push, "push<c> <registers> ; <registers> contains one register, <Rt>" }, // if Rn == '1101' && imm12 == '000000000100' then SEE PUSH; { 0x0fff0000, 0x052d0000, ARMvAll, eEncodingA1, eSize32, emulate_str_rt_sp, "str<c><q> Rt, [sp, #-n]!" } }; static ARMOpcode g_thumb_opcodes[] = { { 0x0000fe00, 0x0000b400, ARMvAll, eEncodingT1, eSize16, emulate_push, "push<c> <registers>" }, { 0xffff0000, 0xe92d0000, ARMv6T2|ARMv7, eEncodingT2, eSize32, emulate_push, "push<c>.w <registers> ; <registers> contains more than one register" }, { 0xffff0fff, 0xf84d0d04, ARMv6T2|ARMv7, eEncodingT3, eSize32, emulate_push, "push<c>.w <registers> ; <registers> contains one register, <Rt>" } }; static const size_t k_num_arm_opcodes = sizeof(g_arm_opcodes)/sizeof(ARMOpcode); static const size_t k_num_thumb_opcodes = sizeof(g_thumb_opcodes)/sizeof(ARMOpcode); bool EmulateInstructionARM::ReadInstruction () { bool success = false; m_inst_cpsr = ReadRegisterUnsigned (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS, 0, &success); if (success) { addr_t pc = ReadRegisterUnsigned (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC, LLDB_INVALID_ADDRESS, &success); if (success) { Context read_inst_context = {eContextReadOpcode, 0, 0}; if (m_inst_cpsr & MASK_CPSR_T) { m_inst_mode = eModeThumb; uint32_t thumb_opcode = ReadMemoryUnsigned(read_inst_context, pc, 2, 0, &success); if (success) { if ((m_inst.opcode.inst16 & 0xe000) != 0xe000 || ((m_inst.opcode.inst16 & 0x1800u) == 0)) { m_inst.opcode_type = eOpcode16; m_inst.opcode.inst16 = thumb_opcode; } else { m_inst.opcode_type = eOpcode32; m_inst.opcode.inst32 = (thumb_opcode << 16) | ReadMemoryUnsigned(read_inst_context, pc + 2, 2, 0, &success); } } } else { m_inst_mode = eModeARM; m_inst.opcode_type = eOpcode32; m_inst.opcode.inst32 = ReadMemoryUnsigned(read_inst_context, pc, 4, 0, &success); } } } if (!success) { m_inst_mode = eModeInvalid; m_inst_pc = LLDB_INVALID_ADDRESS; } return success; } uint32_t EmulateInstructionARM::CurrentCond () { switch (m_inst_mode) { default: case eModeInvalid: break; case eModeARM: return UnsignedBits(m_inst.opcode.inst32, 31, 28); case eModeThumb: return 0x0000000Eu; // Return always for now, we need to handl IT instructions later } return UINT32_MAX; // Return invalid value } bool EmulateInstructionARM::ConditionPassed () { if (m_inst_cpsr == 0) return false; const uint32_t cond = CurrentCond (); if (cond == UINT32_MAX) return false; bool result = false; switch (UnsignedBits(cond, 3, 1)) { case 0: result = (m_inst_cpsr & MASK_CPSR_Z) != 0; break; case 1: result = (m_inst_cpsr & MASK_CPSR_C) != 0; break; case 2: result = (m_inst_cpsr & MASK_CPSR_N) != 0; break; case 3: result = (m_inst_cpsr & MASK_CPSR_V) != 0; break; case 4: result = ((m_inst_cpsr & MASK_CPSR_C) != 0) && ((m_inst_cpsr & MASK_CPSR_Z) == 0); break; case 5: { bool n = (m_inst_cpsr & MASK_CPSR_N); bool v = (m_inst_cpsr & MASK_CPSR_V); result = n == v; } break; case 6: { bool n = (m_inst_cpsr & MASK_CPSR_N); bool v = (m_inst_cpsr & MASK_CPSR_V); result = n == v && ((m_inst_cpsr & MASK_CPSR_Z) == 0); } break; case 7: result = true; break; } if (cond & 1) result = !result; return result; } bool EmulateInstructionARM::EvaluateInstruction () { return false; } <|endoftext|>
<commit_before>#include "SearchManagerPreProcessor.h" #include "Sorter.h" #include "NumericPropertyTableBuilder.h" #include "RTypeStringPropTableBuilder.h" #include <common/RTypeStringPropTable.h> #include <common/PropSharedLockSet.h> #include "DocumentIterator.h" #include <ranking-manager/RankQueryProperty.h> #include <ranking-manager/PropertyRanker.h> #include <mining-manager/product-scorer/ProductScorerFactory.h> #include <mining-manager/product-scorer/ProductScoreParam.h> #include <mining-manager/faceted-submanager/ctr_manager.h> #include <common/SFLogger.h> #include <util/get.h> #include <util/ClockTimer.h> #include <fstream> #include <algorithm> // to_lower using namespace sf1r; const std::string RANK_PROPERTY("_rank"); const std::string DATE_PROPERTY("date"); const std::string CUSTOM_RANK_PROPERTY("custom_rank"); SearchManagerPreProcessor::SearchManagerPreProcessor(const IndexBundleSchema& indexSchema) : productScorerFactory_(NULL) , numericTableBuilder_(NULL) , rtypeStringPropTableBuilder_(NULL) { for (IndexBundleSchema::const_iterator iter = indexSchema.begin(); iter != indexSchema.end(); ++iter) { schemaMap_[iter->getName()] = *iter; } } void SearchManagerPreProcessor::prepareSorterCustomRanker( const SearchKeywordOperation& actionOperation, boost::shared_ptr<Sorter>& pSorter, CustomRankerPtr& customRanker) { std::vector<std::pair<std::string, bool> >& sortPropertyList = actionOperation.actionItem_.sortPriorityList_; if (!sortPropertyList.empty()) { std::vector<std::pair<std::string, bool> >::iterator iter = sortPropertyList.begin(); for (; iter != sortPropertyList.end(); ++iter) { std::string fieldNameL = iter->first; boost::to_lower(fieldNameL); // sort by custom ranking if (fieldNameL == CUSTOM_RANK_PROPERTY) { // prepare custom ranker data, custom score will be evaluated later as rank score customRanker = actionOperation.actionItem_.customRanker_; if (!customRanker) customRanker = buildCustomRanker_(actionOperation.actionItem_); if (!customRanker->setPropertyData(numericTableBuilder_)) { LOG(ERROR) << customRanker->getErrorInfo() ; continue; } //customRanker->printESTree(); if (!pSorter) pSorter.reset(new Sorter(numericTableBuilder_,rtypeStringPropTableBuilder_)); SortProperty* pSortProperty = new SortProperty( "CUSTOM_RANK", CUSTOM_RANKING_PROPERTY_TYPE, SortProperty::CUSTOM, iter->second); pSorter->addSortProperty(pSortProperty); continue; } // sort by rank if (fieldNameL == RANK_PROPERTY) { if (!pSorter) pSorter.reset(new Sorter(numericTableBuilder_,rtypeStringPropTableBuilder_)); SortProperty* pSortProperty = new SortProperty( "RANK", UNKNOWN_DATA_PROPERTY_TYPE, SortProperty::SCORE, iter->second); pSorter->addSortProperty(pSortProperty); continue; } // sort by date if (fieldNameL == DATE_PROPERTY) { if (!pSorter) pSorter.reset(new Sorter(numericTableBuilder_,rtypeStringPropTableBuilder_)); SortProperty* pSortProperty = new SortProperty( iter->first, INT64_PROPERTY_TYPE, iter->second); pSorter->addSortProperty(pSortProperty); continue; } // sort by ctr (click through rate) if (fieldNameL == faceted::CTRManager::kCtrPropName) { if (!pSorter) pSorter.reset(new Sorter(numericTableBuilder_,rtypeStringPropTableBuilder_)); SortProperty* pSortProperty = new SortProperty( iter->first, INT32_PROPERTY_TYPE, SortProperty::CTR, iter->second); pSorter->addSortProperty(pSortProperty); continue; } // sort by arbitrary property SchemaMap::const_iterator it = schemaMap_.find(iter->first); if (it == schemaMap_.end()) continue; const PropertyConfig& propertyConfig = it->second; if (!propertyConfig.isIndex() || propertyConfig.isAnalyzed()) continue; LOG(INFO) << "add sort property : " << iter->first; PropertyDataType propertyType = propertyConfig.getType(); switch (propertyType) { case STRING_PROPERTY_TYPE: case INT32_PROPERTY_TYPE: case FLOAT_PROPERTY_TYPE: case DATETIME_PROPERTY_TYPE: case INT8_PROPERTY_TYPE: case INT16_PROPERTY_TYPE: case INT64_PROPERTY_TYPE: case DOUBLE_PROPERTY_TYPE: case NOMINAL_PROPERTY_TYPE: { if (!pSorter) pSorter.reset(new Sorter(numericTableBuilder_,rtypeStringPropTableBuilder_)); SortProperty* pSortProperty = new SortProperty( iter->first, propertyType, iter->second); pSorter->addSortProperty(pSortProperty); break; } default: DLOG(ERROR) << "Sort by properties other than int, float, double type"; // TODO : Log break; } } } } bool SearchManagerPreProcessor::getPropertyTypeByName_( const std::string& name, PropertyDataType& type) const { SchemaMap::const_iterator it = schemaMap_.find(name); if (it != schemaMap_.end()) { type = it->second.getType(); return true; } return false; } CustomRankerPtr SearchManagerPreProcessor::buildCustomRanker_(KeywordSearchActionItem& actionItem) { CustomRankerPtr customRanker(new CustomRanker()); customRanker->getConstParamMap() = actionItem.paramConstValueMap_; customRanker->getPropertyParamMap() = actionItem.paramPropertyValueMap_; customRanker->parse(actionItem.strExp_); std::map<std::string, PropertyDataType>& propertyDataTypeMap = customRanker->getPropertyDataTypeMap(); std::map<std::string, PropertyDataType>::iterator iter = propertyDataTypeMap.begin(); for (; iter != propertyDataTypeMap.end(); iter++) { getPropertyTypeByName_(iter->first, iter->second); } return customRanker; } void SearchManagerPreProcessor::fillSearchInfoWithSortPropertyData( Sorter* pSorter, std::vector<unsigned int>& docIdList, DistKeywordSearchInfo& distSearchInfo, PropSharedLockSet& propSharedLockSet) { if (!pSorter) return; size_t docNum = docIdList.size(); std::list<SortProperty*>& sortProperties = pSorter->sortProperties_; std::list<SortProperty*>::iterator iter; SortProperty* pSortProperty; for (iter = sortProperties.begin(); iter != sortProperties.end(); ++iter) { pSortProperty = *iter; const std::string& sortPropertyName = pSortProperty->getProperty(); distSearchInfo.sortPropertyList_.push_back( std::make_pair(sortPropertyName, pSortProperty->isReverse())); LOG(INFO) << "adding sort property : " << sortPropertyName; if (sortPropertyName == "CUSTOM_RANK" || sortPropertyName == "RANK") continue; if (pSortProperty->getPropertyDataType() == STRING_PROPERTY_TYPE) { if (!rtypeStringPropTableBuilder_) continue; boost::shared_ptr<RTypeStringPropTable>& strPropertyTable = rtypeStringPropTableBuilder_->createPropertyTable(sortPropertyName); if (!strPropertyTable) continue; propSharedLockSet.insertSharedLock(strPropertyTable.get()); distSearchInfo.sortPropertyStrDataList_.push_back(std::make_pair(sortPropertyName, std::vector<std::string>())); std::vector<std::string>& dataList = distSearchInfo.sortPropertyStrDataList_.back().second; dataList.resize(docNum); for (size_t i = 0; i < docNum; ++i) { strPropertyTable->getRTypeString(docIdList[i], dataList[i]); } continue; } if (!numericTableBuilder_) continue; boost::shared_ptr<NumericPropertyTableBase>& numericPropertyTable = numericTableBuilder_->createPropertyTable(sortPropertyName); if (!numericPropertyTable) continue; propSharedLockSet.insertSharedLock(numericPropertyTable.get()); switch (numericPropertyTable->getType()) { case INT32_PROPERTY_TYPE: case INT8_PROPERTY_TYPE: case INT16_PROPERTY_TYPE: { distSearchInfo.sortPropertyInt32DataList_.push_back(std::make_pair(sortPropertyName, std::vector<int32_t>())); std::vector<int32_t>& dataList = distSearchInfo.sortPropertyInt32DataList_.back().second; dataList.resize(docNum); for (size_t i = 0; i < docNum; i++) { numericPropertyTable->getInt32Value(docIdList[i], dataList[i], false); } } break; case INT64_PROPERTY_TYPE: case DATETIME_PROPERTY_TYPE: { distSearchInfo.sortPropertyInt64DataList_.push_back(std::make_pair(sortPropertyName, std::vector<int64_t>())); std::vector<int64_t>& dataList = distSearchInfo.sortPropertyInt64DataList_.back().second; dataList.resize(docNum); for (size_t i = 0; i < docNum; i++) { numericPropertyTable->getInt64Value(docIdList[i], dataList[i], false); } } break; case FLOAT_PROPERTY_TYPE: { distSearchInfo.sortPropertyFloatDataList_.push_back(std::make_pair(sortPropertyName, std::vector<float>())); std::vector<float>& dataList = distSearchInfo.sortPropertyFloatDataList_.back().second; dataList.resize(docNum); for (size_t i = 0; i < docNum; i++) { numericPropertyTable->getFloatValue(docIdList[i], dataList[i], false); } } break; case DOUBLE_PROPERTY_TYPE: { distSearchInfo.sortPropertyFloatDataList_.push_back(std::make_pair(sortPropertyName, std::vector<float>())); std::vector<float>& dataList = distSearchInfo.sortPropertyFloatDataList_.back().second; dataList.resize(docNum); for (size_t i = 0; i < docNum; i++) { numericPropertyTable->getFloatValue(docIdList[i], dataList[i], false); } } break; default: break; } } } void SearchManagerPreProcessor::preparePropertyTermIndex( const std::map<std::string, PropertyTermInfo>& propertyTermInfoMap, const std::vector<std::string>& indexPropertyList, std::vector<std::map<termid_t, unsigned> >& termIndexMaps) { // use empty object for not found property const PropertyTermInfo emptyPropertyTermInfo; // build term index maps typedef std::vector<std::string>::const_iterator property_list_iterator; for (uint32_t i = 0; i < indexPropertyList.size(); ++i) { const PropertyTermInfo::id_uint_list_map_t& termPositionsMap = izenelib::util::getOr( propertyTermInfoMap, indexPropertyList[i], emptyPropertyTermInfo ).getTermIdPositionMap(); unsigned index = 0; typedef PropertyTermInfo::id_uint_list_map_t::const_iterator term_id_position_iterator; for (term_id_position_iterator termIt = termPositionsMap.begin(); termIt != termPositionsMap.end(); ++termIt) { termIndexMaps[i][termIt->first] = index++; } } } ProductScorer* SearchManagerPreProcessor::createProductScorer( const KeywordSearchActionItem& actionItem, PropSharedLockSet& propSharedLockSet, ProductScorer* relevanceScorer) { std::auto_ptr<ProductScorer> relevanceScorerPtr(relevanceScorer); SearchingMode::SearchingModeType searchMode = actionItem.searchingMode_.mode_; if (searchMode != SearchingMode::SUFFIX_MATCH && !hasSortByRankProp(actionItem.sortPriorityList_)) return NULL; if (!isProductRanking_(actionItem)) return relevanceScorerPtr.release(); ProductScoreParam scoreParam(actionItem.env_.normalizedQueryString_, actionItem.env_.queryString_, actionItem.env_.querySource_, actionItem.groupParam_, propSharedLockSet, relevanceScorerPtr.release(), actionItem.searchingMode_.mode_, actionItem.queryScore_); return productScorerFactory_->createScorer(scoreParam); } bool SearchManagerPreProcessor::isProductRanking_( const KeywordSearchActionItem& actionItem) const { if (productScorerFactory_ == NULL) return false; SearchingMode::SearchingModeType searchMode = actionItem.searchingMode_.mode_; if (searchMode == SearchingMode::KNN) return false; return true; } bool SearchManagerPreProcessor::isNeedCustomDocIterator( const KeywordSearchActionItem& actionItem) const { return hasSortByRankProp(actionItem.sortPriorityList_) && isProductRanking_(actionItem); } bool SearchManagerPreProcessor::isNeedRerank( const KeywordSearchActionItem& actionItem) const { return isSortByRankProp(actionItem.sortPriorityList_) && isProductRanking_(actionItem); } bool SearchManagerPreProcessor::hasSortByRankProp( const KeywordSearchActionItem::SortPriorityList& sortPriorityList) { for (KeywordSearchActionItem::SortPriorityList::const_iterator it = sortPriorityList.begin(); it != sortPriorityList.end(); ++it) { std::string propName = it->first; boost::to_lower(propName); if (propName == RANK_PROPERTY) return true; } return false; } bool SearchManagerPreProcessor::isSortByRankProp( const KeywordSearchActionItem::SortPriorityList& sortPriorityList) { return sortPriorityList.size() == 1 && hasSortByRankProp(sortPriorityList); } <commit_msg>Disable rerank for Zambezi search.<commit_after>#include "SearchManagerPreProcessor.h" #include "Sorter.h" #include "NumericPropertyTableBuilder.h" #include "RTypeStringPropTableBuilder.h" #include <common/RTypeStringPropTable.h> #include <common/PropSharedLockSet.h> #include "DocumentIterator.h" #include <ranking-manager/RankQueryProperty.h> #include <ranking-manager/PropertyRanker.h> #include <mining-manager/product-scorer/ProductScorerFactory.h> #include <mining-manager/product-scorer/ProductScoreParam.h> #include <mining-manager/faceted-submanager/ctr_manager.h> #include <common/SFLogger.h> #include <util/get.h> #include <util/ClockTimer.h> #include <fstream> #include <algorithm> // to_lower using namespace sf1r; const std::string RANK_PROPERTY("_rank"); const std::string DATE_PROPERTY("date"); const std::string CUSTOM_RANK_PROPERTY("custom_rank"); SearchManagerPreProcessor::SearchManagerPreProcessor(const IndexBundleSchema& indexSchema) : productScorerFactory_(NULL) , numericTableBuilder_(NULL) , rtypeStringPropTableBuilder_(NULL) { for (IndexBundleSchema::const_iterator iter = indexSchema.begin(); iter != indexSchema.end(); ++iter) { schemaMap_[iter->getName()] = *iter; } } void SearchManagerPreProcessor::prepareSorterCustomRanker( const SearchKeywordOperation& actionOperation, boost::shared_ptr<Sorter>& pSorter, CustomRankerPtr& customRanker) { std::vector<std::pair<std::string, bool> >& sortPropertyList = actionOperation.actionItem_.sortPriorityList_; if (!sortPropertyList.empty()) { std::vector<std::pair<std::string, bool> >::iterator iter = sortPropertyList.begin(); for (; iter != sortPropertyList.end(); ++iter) { std::string fieldNameL = iter->first; boost::to_lower(fieldNameL); // sort by custom ranking if (fieldNameL == CUSTOM_RANK_PROPERTY) { // prepare custom ranker data, custom score will be evaluated later as rank score customRanker = actionOperation.actionItem_.customRanker_; if (!customRanker) customRanker = buildCustomRanker_(actionOperation.actionItem_); if (!customRanker->setPropertyData(numericTableBuilder_)) { LOG(ERROR) << customRanker->getErrorInfo() ; continue; } //customRanker->printESTree(); if (!pSorter) pSorter.reset(new Sorter(numericTableBuilder_,rtypeStringPropTableBuilder_)); SortProperty* pSortProperty = new SortProperty( "CUSTOM_RANK", CUSTOM_RANKING_PROPERTY_TYPE, SortProperty::CUSTOM, iter->second); pSorter->addSortProperty(pSortProperty); continue; } // sort by rank if (fieldNameL == RANK_PROPERTY) { if (!pSorter) pSorter.reset(new Sorter(numericTableBuilder_,rtypeStringPropTableBuilder_)); SortProperty* pSortProperty = new SortProperty( "RANK", UNKNOWN_DATA_PROPERTY_TYPE, SortProperty::SCORE, iter->second); pSorter->addSortProperty(pSortProperty); continue; } // sort by date if (fieldNameL == DATE_PROPERTY) { if (!pSorter) pSorter.reset(new Sorter(numericTableBuilder_,rtypeStringPropTableBuilder_)); SortProperty* pSortProperty = new SortProperty( iter->first, INT64_PROPERTY_TYPE, iter->second); pSorter->addSortProperty(pSortProperty); continue; } // sort by ctr (click through rate) if (fieldNameL == faceted::CTRManager::kCtrPropName) { if (!pSorter) pSorter.reset(new Sorter(numericTableBuilder_,rtypeStringPropTableBuilder_)); SortProperty* pSortProperty = new SortProperty( iter->first, INT32_PROPERTY_TYPE, SortProperty::CTR, iter->second); pSorter->addSortProperty(pSortProperty); continue; } // sort by arbitrary property SchemaMap::const_iterator it = schemaMap_.find(iter->first); if (it == schemaMap_.end()) continue; const PropertyConfig& propertyConfig = it->second; if (!propertyConfig.isIndex() || propertyConfig.isAnalyzed()) continue; LOG(INFO) << "add sort property : " << iter->first; PropertyDataType propertyType = propertyConfig.getType(); switch (propertyType) { case STRING_PROPERTY_TYPE: case INT32_PROPERTY_TYPE: case FLOAT_PROPERTY_TYPE: case DATETIME_PROPERTY_TYPE: case INT8_PROPERTY_TYPE: case INT16_PROPERTY_TYPE: case INT64_PROPERTY_TYPE: case DOUBLE_PROPERTY_TYPE: case NOMINAL_PROPERTY_TYPE: { if (!pSorter) pSorter.reset(new Sorter(numericTableBuilder_,rtypeStringPropTableBuilder_)); SortProperty* pSortProperty = new SortProperty( iter->first, propertyType, iter->second); pSorter->addSortProperty(pSortProperty); break; } default: DLOG(ERROR) << "Sort by properties other than int, float, double type"; // TODO : Log break; } } } } bool SearchManagerPreProcessor::getPropertyTypeByName_( const std::string& name, PropertyDataType& type) const { SchemaMap::const_iterator it = schemaMap_.find(name); if (it != schemaMap_.end()) { type = it->second.getType(); return true; } return false; } CustomRankerPtr SearchManagerPreProcessor::buildCustomRanker_(KeywordSearchActionItem& actionItem) { CustomRankerPtr customRanker(new CustomRanker()); customRanker->getConstParamMap() = actionItem.paramConstValueMap_; customRanker->getPropertyParamMap() = actionItem.paramPropertyValueMap_; customRanker->parse(actionItem.strExp_); std::map<std::string, PropertyDataType>& propertyDataTypeMap = customRanker->getPropertyDataTypeMap(); std::map<std::string, PropertyDataType>::iterator iter = propertyDataTypeMap.begin(); for (; iter != propertyDataTypeMap.end(); iter++) { getPropertyTypeByName_(iter->first, iter->second); } return customRanker; } void SearchManagerPreProcessor::fillSearchInfoWithSortPropertyData( Sorter* pSorter, std::vector<unsigned int>& docIdList, DistKeywordSearchInfo& distSearchInfo, PropSharedLockSet& propSharedLockSet) { if (!pSorter) return; size_t docNum = docIdList.size(); std::list<SortProperty*>& sortProperties = pSorter->sortProperties_; std::list<SortProperty*>::iterator iter; SortProperty* pSortProperty; for (iter = sortProperties.begin(); iter != sortProperties.end(); ++iter) { pSortProperty = *iter; const std::string& sortPropertyName = pSortProperty->getProperty(); distSearchInfo.sortPropertyList_.push_back( std::make_pair(sortPropertyName, pSortProperty->isReverse())); LOG(INFO) << "adding sort property : " << sortPropertyName; if (sortPropertyName == "CUSTOM_RANK" || sortPropertyName == "RANK") continue; if (pSortProperty->getPropertyDataType() == STRING_PROPERTY_TYPE) { if (!rtypeStringPropTableBuilder_) continue; boost::shared_ptr<RTypeStringPropTable>& strPropertyTable = rtypeStringPropTableBuilder_->createPropertyTable(sortPropertyName); if (!strPropertyTable) continue; propSharedLockSet.insertSharedLock(strPropertyTable.get()); distSearchInfo.sortPropertyStrDataList_.push_back(std::make_pair(sortPropertyName, std::vector<std::string>())); std::vector<std::string>& dataList = distSearchInfo.sortPropertyStrDataList_.back().second; dataList.resize(docNum); for (size_t i = 0; i < docNum; ++i) { strPropertyTable->getRTypeString(docIdList[i], dataList[i]); } continue; } if (!numericTableBuilder_) continue; boost::shared_ptr<NumericPropertyTableBase>& numericPropertyTable = numericTableBuilder_->createPropertyTable(sortPropertyName); if (!numericPropertyTable) continue; propSharedLockSet.insertSharedLock(numericPropertyTable.get()); switch (numericPropertyTable->getType()) { case INT32_PROPERTY_TYPE: case INT8_PROPERTY_TYPE: case INT16_PROPERTY_TYPE: { distSearchInfo.sortPropertyInt32DataList_.push_back(std::make_pair(sortPropertyName, std::vector<int32_t>())); std::vector<int32_t>& dataList = distSearchInfo.sortPropertyInt32DataList_.back().second; dataList.resize(docNum); for (size_t i = 0; i < docNum; i++) { numericPropertyTable->getInt32Value(docIdList[i], dataList[i], false); } } break; case INT64_PROPERTY_TYPE: case DATETIME_PROPERTY_TYPE: { distSearchInfo.sortPropertyInt64DataList_.push_back(std::make_pair(sortPropertyName, std::vector<int64_t>())); std::vector<int64_t>& dataList = distSearchInfo.sortPropertyInt64DataList_.back().second; dataList.resize(docNum); for (size_t i = 0; i < docNum; i++) { numericPropertyTable->getInt64Value(docIdList[i], dataList[i], false); } } break; case FLOAT_PROPERTY_TYPE: { distSearchInfo.sortPropertyFloatDataList_.push_back(std::make_pair(sortPropertyName, std::vector<float>())); std::vector<float>& dataList = distSearchInfo.sortPropertyFloatDataList_.back().second; dataList.resize(docNum); for (size_t i = 0; i < docNum; i++) { numericPropertyTable->getFloatValue(docIdList[i], dataList[i], false); } } break; case DOUBLE_PROPERTY_TYPE: { distSearchInfo.sortPropertyFloatDataList_.push_back(std::make_pair(sortPropertyName, std::vector<float>())); std::vector<float>& dataList = distSearchInfo.sortPropertyFloatDataList_.back().second; dataList.resize(docNum); for (size_t i = 0; i < docNum; i++) { numericPropertyTable->getFloatValue(docIdList[i], dataList[i], false); } } break; default: break; } } } void SearchManagerPreProcessor::preparePropertyTermIndex( const std::map<std::string, PropertyTermInfo>& propertyTermInfoMap, const std::vector<std::string>& indexPropertyList, std::vector<std::map<termid_t, unsigned> >& termIndexMaps) { // use empty object for not found property const PropertyTermInfo emptyPropertyTermInfo; // build term index maps typedef std::vector<std::string>::const_iterator property_list_iterator; for (uint32_t i = 0; i < indexPropertyList.size(); ++i) { const PropertyTermInfo::id_uint_list_map_t& termPositionsMap = izenelib::util::getOr( propertyTermInfoMap, indexPropertyList[i], emptyPropertyTermInfo ).getTermIdPositionMap(); unsigned index = 0; typedef PropertyTermInfo::id_uint_list_map_t::const_iterator term_id_position_iterator; for (term_id_position_iterator termIt = termPositionsMap.begin(); termIt != termPositionsMap.end(); ++termIt) { termIndexMaps[i][termIt->first] = index++; } } } ProductScorer* SearchManagerPreProcessor::createProductScorer( const KeywordSearchActionItem& actionItem, PropSharedLockSet& propSharedLockSet, ProductScorer* relevanceScorer) { std::auto_ptr<ProductScorer> relevanceScorerPtr(relevanceScorer); SearchingMode::SearchingModeType searchMode = actionItem.searchingMode_.mode_; if (searchMode != SearchingMode::SUFFIX_MATCH && !hasSortByRankProp(actionItem.sortPriorityList_)) return NULL; if (!isProductRanking_(actionItem)) return relevanceScorerPtr.release(); ProductScoreParam scoreParam(actionItem.env_.normalizedQueryString_, actionItem.env_.queryString_, actionItem.env_.querySource_, actionItem.groupParam_, propSharedLockSet, relevanceScorerPtr.release(), actionItem.searchingMode_.mode_, actionItem.queryScore_); return productScorerFactory_->createScorer(scoreParam); } bool SearchManagerPreProcessor::isProductRanking_( const KeywordSearchActionItem& actionItem) const { if (productScorerFactory_ == NULL) return false; SearchingMode::SearchingModeType searchMode = actionItem.searchingMode_.mode_; if (searchMode == SearchingMode::KNN) return false; return true; } bool SearchManagerPreProcessor::isNeedCustomDocIterator( const KeywordSearchActionItem& actionItem) const { return hasSortByRankProp(actionItem.sortPriorityList_) && isProductRanking_(actionItem); } bool SearchManagerPreProcessor::isNeedRerank( const KeywordSearchActionItem& actionItem) const { SearchingMode::SearchingModeType searchMode = actionItem.searchingMode_.mode_; return isSortByRankProp(actionItem.sortPriorityList_) && isProductRanking_(actionItem) && searchMode != SearchingMode::ZAMBEZI; } bool SearchManagerPreProcessor::hasSortByRankProp( const KeywordSearchActionItem::SortPriorityList& sortPriorityList) { for (KeywordSearchActionItem::SortPriorityList::const_iterator it = sortPriorityList.begin(); it != sortPriorityList.end(); ++it) { std::string propName = it->first; boost::to_lower(propName); if (propName == RANK_PROPERTY) return true; } return false; } bool SearchManagerPreProcessor::isSortByRankProp( const KeywordSearchActionItem::SortPriorityList& sortPriorityList) { return sortPriorityList.size() == 1 && hasSortByRankProp(sortPriorityList); } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. * * This file incorporates work covered by the following license notice: * * 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 . */ #ifndef INCLUDED_EMBEDDEDOBJ_SOURCE_COMMONEMBEDDING_XFACTORY_HXX #define INCLUDED_EMBEDDEDOBJ_SOURCE_COMMONEMBEDDING_XFACTORY_HXX #include <com/sun/star/embed/XEmbeddedObjectCreator.hpp> #include <com/sun/star/embed/XLinkFactory.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> #include <osl/diagnose.h> #include <cppuhelper/implbase.hxx> #include <comphelper/mimeconfighelper.hxx> class OOoEmbeddedObjectFactory : public ::cppu::WeakImplHelper< ::com::sun::star::embed::XEmbeddedObjectCreator, css::embed::XLinkFactory, ::com::sun::star::lang::XServiceInfo > { ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > m_xContext; ::comphelper::MimeConfigurationHelper m_aConfigHelper; public: OOoEmbeddedObjectFactory( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& rxContext ) : m_xContext( rxContext ) , m_aConfigHelper( rxContext ) { OSL_ENSURE( rxContext.is(), "No service manager is provided!\n" ); } static ::com::sun::star::uno::Sequence< OUString > SAL_CALL impl_staticGetSupportedServiceNames(); static OUString SAL_CALL impl_staticGetImplementationName(); static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL impl_staticCreateSelfInstance( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager ); // XEmbedObjectCreator virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceInitNew( const ::com::sun::star::uno::Sequence< sal_Int8 >& aClassID, const OUString& aClassName, const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage, const OUString& sEntName, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lObjArgs ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::io::IOException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE; virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceInitFromEntry( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage, const OUString& sEntName, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aMediaDescr, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lObjArgs ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::NoSuchElementException, ::com::sun::star::io::IOException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE; virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceInitFromMediaDescriptor( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage, const OUString& sEntName, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aMediaDescr, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lObjArgs ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::io::IOException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE; // XEmbedObjectFactory virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceUserInit( const ::com::sun::star::uno::Sequence< sal_Int8 >& aClassID, const OUString& aClassName, const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage, const OUString& sEntName, sal_Int32 nEntryConnectionMode, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lArguments, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lObjArgs ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::io::IOException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE; // XLinkCreator virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceLink( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage, const OUString& sEntName, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aMediaDescr, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lObjArgs ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::io::IOException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE; // XLinkFactory ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceLinkUserInit( const ::com::sun::star::uno::Sequence< sal_Int8 >& aClassID, const OUString& aClassName, const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage, const OUString& sEntName, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lArguments, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lObjArgs ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::io::IOException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException) SAL_OVERRIDE; // XServiceInfo virtual OUString SAL_CALL getImplementationName() throw (::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE; virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE; virtual ::com::sun::star::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames() throw (::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE; }; class OOoSpecialEmbeddedObjectFactory : public ::cppu::WeakImplHelper< ::com::sun::star::embed::XEmbedObjectFactory, ::com::sun::star::lang::XServiceInfo > { ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > m_xContext; ::comphelper::MimeConfigurationHelper m_aConfigHelper; public: OOoSpecialEmbeddedObjectFactory( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& rxContext ) : m_xContext( rxContext ) , m_aConfigHelper( rxContext ) { OSL_ENSURE( rxContext.is(), "No service manager is provided!\n" ); } static ::com::sun::star::uno::Sequence< OUString > SAL_CALL impl_staticGetSupportedServiceNames(); static OUString SAL_CALL impl_staticGetImplementationName(); static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL impl_staticCreateSelfInstance( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager ); // XEmbedObjectFactory virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceUserInit( const ::com::sun::star::uno::Sequence< sal_Int8 >& aClassID, const OUString& aClassName, const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage, const OUString& sEntName, sal_Int32 nEntryConnectionMode, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lArguments, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lObjArgs ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::io::IOException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE; // XServiceInfo virtual OUString SAL_CALL getImplementationName() throw (::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE; virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE; virtual ::com::sun::star::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames() throw (::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE; }; #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>add an explicit virtual keyword here, like the other ones<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. * * This file incorporates work covered by the following license notice: * * 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 . */ #ifndef INCLUDED_EMBEDDEDOBJ_SOURCE_COMMONEMBEDDING_XFACTORY_HXX #define INCLUDED_EMBEDDEDOBJ_SOURCE_COMMONEMBEDDING_XFACTORY_HXX #include <com/sun/star/embed/XEmbeddedObjectCreator.hpp> #include <com/sun/star/embed/XLinkFactory.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> #include <osl/diagnose.h> #include <cppuhelper/implbase.hxx> #include <comphelper/mimeconfighelper.hxx> class OOoEmbeddedObjectFactory : public ::cppu::WeakImplHelper< ::com::sun::star::embed::XEmbeddedObjectCreator, css::embed::XLinkFactory, ::com::sun::star::lang::XServiceInfo > { ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > m_xContext; ::comphelper::MimeConfigurationHelper m_aConfigHelper; public: OOoEmbeddedObjectFactory( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& rxContext ) : m_xContext( rxContext ) , m_aConfigHelper( rxContext ) { OSL_ENSURE( rxContext.is(), "No service manager is provided!\n" ); } static ::com::sun::star::uno::Sequence< OUString > SAL_CALL impl_staticGetSupportedServiceNames(); static OUString SAL_CALL impl_staticGetImplementationName(); static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL impl_staticCreateSelfInstance( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager ); // XEmbedObjectCreator virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceInitNew( const ::com::sun::star::uno::Sequence< sal_Int8 >& aClassID, const OUString& aClassName, const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage, const OUString& sEntName, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lObjArgs ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::io::IOException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE; virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceInitFromEntry( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage, const OUString& sEntName, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aMediaDescr, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lObjArgs ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::NoSuchElementException, ::com::sun::star::io::IOException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE; virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceInitFromMediaDescriptor( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage, const OUString& sEntName, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aMediaDescr, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lObjArgs ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::io::IOException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE; // XEmbedObjectFactory virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceUserInit( const ::com::sun::star::uno::Sequence< sal_Int8 >& aClassID, const OUString& aClassName, const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage, const OUString& sEntName, sal_Int32 nEntryConnectionMode, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lArguments, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lObjArgs ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::io::IOException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE; // XLinkCreator virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceLink( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage, const OUString& sEntName, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aMediaDescr, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lObjArgs ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::io::IOException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE; // XLinkFactory virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceLinkUserInit( const ::com::sun::star::uno::Sequence< sal_Int8 >& aClassID, const OUString& aClassName, const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage, const OUString& sEntName, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lArguments, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lObjArgs ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::io::IOException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException) SAL_OVERRIDE; // XServiceInfo virtual OUString SAL_CALL getImplementationName() throw (::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE; virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE; virtual ::com::sun::star::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames() throw (::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE; }; class OOoSpecialEmbeddedObjectFactory : public ::cppu::WeakImplHelper< ::com::sun::star::embed::XEmbedObjectFactory, ::com::sun::star::lang::XServiceInfo > { ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > m_xContext; ::comphelper::MimeConfigurationHelper m_aConfigHelper; public: OOoSpecialEmbeddedObjectFactory( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& rxContext ) : m_xContext( rxContext ) , m_aConfigHelper( rxContext ) { OSL_ENSURE( rxContext.is(), "No service manager is provided!\n" ); } static ::com::sun::star::uno::Sequence< OUString > SAL_CALL impl_staticGetSupportedServiceNames(); static OUString SAL_CALL impl_staticGetImplementationName(); static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL impl_staticCreateSelfInstance( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager ); // XEmbedObjectFactory virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceUserInit( const ::com::sun::star::uno::Sequence< sal_Int8 >& aClassID, const OUString& aClassName, const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage, const OUString& sEntName, sal_Int32 nEntryConnectionMode, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lArguments, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lObjArgs ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::io::IOException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE; // XServiceInfo virtual OUString SAL_CALL getImplementationName() throw (::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE; virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE; virtual ::com::sun::star::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames() throw (::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE; }; #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/*! \file Texture.cpp * \author Jared Hoberock * \brief Implementation of Texture class. */ #include "Texture.h" #ifdef WIN32 #define OPENEXR_DLL #endif // WIN32 #include <halfLimits.h> #include <ImfRgbaFile.h> #include <ImfRgba.h> #include <ImfStringAttribute.h> #include <ImfHeader.h> #include <ImfArray.h> #undef BOOST_NO_EXCEPTIONS #include <boost/gil/image.hpp> #include <boost/gil/typedefs.hpp> #include <boost/gil/extension/io/jpeg_io.hpp> #include <boost/gil/extension/io/jpeg_dynamic_io.hpp> #include <boost/gil/extension/io/png_io.hpp> #include <boost/gil/extension/io/png_dynamic_io.hpp> #include <boost/mpl/vector.hpp> Texture ::Texture(void) :Parent(1,1) { Parent::raster(0,0) = Spectrum::white(); } // end Texture::Texture() Texture ::Texture(const size_t w, const size_t h, const Spectrum *pixels) :Parent(w,h) { const Spectrum *src = pixels; for(iterator p = begin(); p != end(); ++p, ++src) { *p = *src; } // end for i } // end Texture::Texture() // create a gamma-inversion lookup table for // gamma = 2.2 and unsigned chars template<typename T> inline static float gammaInversion(const T x) { //static float lut[256]; //static float lut[std::numeric_limits<T>::max() + 1]; static std::vector<float> lut(std::numeric_limits<T>::max() + 1); static bool firstTime = true; if(firstTime) { for(size_t i = 0; i != std::numeric_limits<T>::max() + 1; ++i) { // convert uchar to [0,1] float f = static_cast<float>(i) / (std::numeric_limits<T>::max() - std::numeric_limits<T>::min()); // gamma correction: // gammaCorrect = rgb^(1.0/gamma) // inversion: // rgb = gammaCorrect^(gamma) // assume gamma = 2.2 // invert x lut[i] = powf(f, 2.2f); } // end for i firstTime = false; } // end if return lut[x]; } // end gammaInversion() template<typename View> static void readGrayImg(const View &v, Array2<Spectrum> &tex) { using namespace boost::gil; // now resize ourself tex.resize(v.width(),v.height()); float factor = 1.0f / channel_traits<typename channel_type<View>::type>::max_value(); // convert unsigned characters to gamma-corrected float in [0,1] Spectrum *dst = &tex.raster(0,0); for(size_t y = 0; y < v.height(); ++y) { // flip the image because gil images are stored ass-backwards size_t x = 0; for(typename View::x_iterator src = v.row_begin(v.height()-1-y); x < v.width(); ++src, ++x, ++dst) { //(*dst).x = factor * static_cast<float>(*src); //(*dst).y = factor * static_cast<float>(*src); //(*dst).z = factor * static_cast<float>(*src); (*dst).x = gammaInversion(*src); (*dst).y = gammaInversion(*src); (*dst).z = gammaInversion(*src); } // end for src, x } // end for y } // end readImg() template<typename View> static void readRgbImg(const View &v, Array2<Spectrum> &tex) { using namespace boost::gil; // now resize ourself tex.resize(v.width(),v.height()); Spectrum *dst = &tex.raster(0,0); for(size_t y = 0; y < v.height(); ++y) { // flip the image because gil images are stored ass-backwards typename View::x_iterator src = v.row_begin(v.height()-1-y); size_t x = 0; for(typename View::x_iterator src = v.row_begin(v.height()-1-y); x < v.width(); ++src, ++x, ++dst) { (*dst).x = gammaInversion((*src)[0]); (*dst).y = gammaInversion((*src)[1]); (*dst).z = gammaInversion((*src)[2]); } // end for src, x } // end for y } // end readImg() static void readJPG(const char *filename, Array2<Spectrum> &tex) { // try different pixel formats //std::cerr << "readJPG(): reading file." << std::endl; try { boost::gil::rgb8_image_t img; boost::gil::jpeg_read_image(filename, img); //std::cerr << "readJPG(): done." << std::endl; readRgbImg(const_view(img), tex); } // end try catch(...) { boost::gil::gray8_image_t img; boost::gil::jpeg_read_image(filename, img); //std::cerr << "readJPG(): done." << std::endl; readGrayImg(const_view(img), tex); } // end catch } // end readJPG() static void readPNG(const char *filename, Array2<Spectrum> &tex) { boost::gil::rgba8_image_t img; boost::gil::png_read_image(filename, img); readRgbImg(const_view(img), tex); } // end readJPG() static void readEXR(const char *filename, Array2<Spectrum> &image) { Imf::RgbaInputFile file(filename); Imath::Box2i dw = file.dataWindow(); unsigned int w = dw.max.x - dw.min.x + 1; unsigned int h = dw.max.y - dw.min.y + 1; Imf::Array2D<Imf::Rgba> pixels; pixels.resizeErase(h, w); file.setFrameBuffer(&pixels[0][0] - dw.min.x - dw.min.y * w, 1, w); file.readPixels(dw.min.y, dw.max.y); // now resize ourself image.resize(w,h); for(size_t y = 0; y < w; ++y) { for(size_t x = 0; x < h; ++x) { // flip the image because EXR is stored ass-backwards image.raster(x,y).x = pixels[h-1-y][x].r; image.raster(x,y).y = pixels[h-1-y][x].g; image.raster(x,y).z = pixels[h-1-y][x].b; } // end for } // end for } // end readEXR() void Texture ::load(const char *filename) { try { readEXR(filename, *this); } // end try catch(...) { try { readPNG(filename, *this); } // end try catch(std::ios_base::failure e) { // XXX for some reason, this isn't throwing an exception // it just exit()s readJPG(filename, *this); } // end catch } // end catch } // end Texture::load() Texture ::Texture(const char *filename) { load(filename); } // end Texture::Texture() const Spectrum &Texture ::texRect(const size_t x, const size_t y) const { return Parent::raster(x,y); } // end Texture::texRect() const Spectrum &Texture ::tex2D(const float u, const float v) const { return texRect(static_cast<size_t>(u * getDimensions()[0]), static_cast<size_t>(v * getDimensions()[1])); } // end Texture::tex2D() <commit_msg>Clamp texture coordinates before access<commit_after>/*! \file Texture.cpp * \author Jared Hoberock * \brief Implementation of Texture class. */ #include "Texture.h" #ifdef WIN32 #define OPENEXR_DLL #endif // WIN32 #include <halfLimits.h> #include <ImfRgbaFile.h> #include <ImfRgba.h> #include <ImfStringAttribute.h> #include <ImfHeader.h> #include <ImfArray.h> #undef BOOST_NO_EXCEPTIONS #include <boost/gil/image.hpp> #include <boost/gil/typedefs.hpp> #include <boost/gil/extension/io/jpeg_io.hpp> #include <boost/gil/extension/io/jpeg_dynamic_io.hpp> #include <boost/gil/extension/io/png_io.hpp> #include <boost/gil/extension/io/png_dynamic_io.hpp> #include <boost/mpl/vector.hpp> Texture ::Texture(void) :Parent(1,1) { Parent::raster(0,0) = Spectrum::white(); } // end Texture::Texture() Texture ::Texture(const size_t w, const size_t h, const Spectrum *pixels) :Parent(w,h) { const Spectrum *src = pixels; for(iterator p = begin(); p != end(); ++p, ++src) { *p = *src; } // end for i } // end Texture::Texture() // create a gamma-inversion lookup table for // gamma = 2.2 and unsigned chars template<typename T> inline static float gammaInversion(const T x) { //static float lut[256]; //static float lut[std::numeric_limits<T>::max() + 1]; static std::vector<float> lut(std::numeric_limits<T>::max() + 1); static bool firstTime = true; if(firstTime) { for(size_t i = 0; i != std::numeric_limits<T>::max() + 1; ++i) { // convert uchar to [0,1] float f = static_cast<float>(i) / (std::numeric_limits<T>::max() - std::numeric_limits<T>::min()); // gamma correction: // gammaCorrect = rgb^(1.0/gamma) // inversion: // rgb = gammaCorrect^(gamma) // assume gamma = 2.2 // invert x lut[i] = powf(f, 2.2f); } // end for i firstTime = false; } // end if return lut[x]; } // end gammaInversion() template<typename View> static void readGrayImg(const View &v, Array2<Spectrum> &tex) { using namespace boost::gil; // now resize ourself tex.resize(v.width(),v.height()); float factor = 1.0f / channel_traits<typename channel_type<View>::type>::max_value(); // convert unsigned characters to gamma-corrected float in [0,1] Spectrum *dst = &tex.raster(0,0); for(size_t y = 0; y < v.height(); ++y) { // flip the image because gil images are stored ass-backwards size_t x = 0; for(typename View::x_iterator src = v.row_begin(v.height()-1-y); x < v.width(); ++src, ++x, ++dst) { //(*dst).x = factor * static_cast<float>(*src); //(*dst).y = factor * static_cast<float>(*src); //(*dst).z = factor * static_cast<float>(*src); (*dst).x = gammaInversion(*src); (*dst).y = gammaInversion(*src); (*dst).z = gammaInversion(*src); } // end for src, x } // end for y } // end readImg() template<typename View> static void readRgbImg(const View &v, Array2<Spectrum> &tex) { using namespace boost::gil; // now resize ourself tex.resize(v.width(),v.height()); Spectrum *dst = &tex.raster(0,0); for(size_t y = 0; y < v.height(); ++y) { // flip the image because gil images are stored ass-backwards typename View::x_iterator src = v.row_begin(v.height()-1-y); size_t x = 0; for(typename View::x_iterator src = v.row_begin(v.height()-1-y); x < v.width(); ++src, ++x, ++dst) { (*dst).x = gammaInversion((*src)[0]); (*dst).y = gammaInversion((*src)[1]); (*dst).z = gammaInversion((*src)[2]); } // end for src, x } // end for y } // end readImg() static void readJPG(const char *filename, Array2<Spectrum> &tex) { // try different pixel formats //std::cerr << "readJPG(): reading file." << std::endl; try { boost::gil::rgb8_image_t img; boost::gil::jpeg_read_image(filename, img); //std::cerr << "readJPG(): done." << std::endl; readRgbImg(const_view(img), tex); } // end try catch(...) { boost::gil::gray8_image_t img; boost::gil::jpeg_read_image(filename, img); //std::cerr << "readJPG(): done." << std::endl; readGrayImg(const_view(img), tex); } // end catch } // end readJPG() static void readPNG(const char *filename, Array2<Spectrum> &tex) { boost::gil::rgba8_image_t img; boost::gil::png_read_image(filename, img); readRgbImg(const_view(img), tex); } // end readJPG() static void readEXR(const char *filename, Array2<Spectrum> &image) { Imf::RgbaInputFile file(filename); Imath::Box2i dw = file.dataWindow(); unsigned int w = dw.max.x - dw.min.x + 1; unsigned int h = dw.max.y - dw.min.y + 1; Imf::Array2D<Imf::Rgba> pixels; pixels.resizeErase(h, w); file.setFrameBuffer(&pixels[0][0] - dw.min.x - dw.min.y * w, 1, w); file.readPixels(dw.min.y, dw.max.y); // now resize ourself image.resize(w,h); for(size_t y = 0; y < w; ++y) { for(size_t x = 0; x < h; ++x) { // flip the image because EXR is stored ass-backwards image.raster(x,y).x = pixels[h-1-y][x].r; image.raster(x,y).y = pixels[h-1-y][x].g; image.raster(x,y).z = pixels[h-1-y][x].b; } // end for } // end for } // end readEXR() void Texture ::load(const char *filename) { try { readEXR(filename, *this); } // end try catch(...) { try { readPNG(filename, *this); } // end try catch(std::ios_base::failure e) { // XXX for some reason, this isn't throwing an exception // it just exit()s readJPG(filename, *this); } // end catch } // end catch } // end Texture::load() Texture ::Texture(const char *filename) { load(filename); } // end Texture::Texture() const Spectrum &Texture ::texRect(const size_t x, const size_t y) const { // clamp to dim - 1 return Parent::raster(std::min<size_t>(x, mDimensions[0]-1), std::min<size_t>(y, mDimensions[1]-1)); } // end Texture::texRect() const Spectrum &Texture ::tex2D(const float u, const float v) const { int x = static_cast<int>(u * getDimensions()[0]); int y = static_cast<int>(v * getDimensions()[1]); // clamp to 0 return texRect(std::max<int>(0,x), std::max<int>(0,y)); } // end Texture::tex2D() <|endoftext|>
<commit_before>// Copyright (c) 2009 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 "media/base/media.h" #include <string> #include <dlfcn.h> #include "base/file_path.h" #include "base/logging.h" #include "base/path_service.h" #include "third_party/ffmpeg/ffmpeg_stubs.h" namespace tp_ffmpeg = third_party_ffmpeg; namespace media { namespace { // Retrieves the DSOName for the given key. std::string GetDSOName(tp_ffmpeg::StubModules stub_key) { // TODO(ajwong): Do we want to lock to a specific ffmpeg version? // TODO(port): These library names are incorrect for mac. We need .dynlib // suffixes. switch (stub_key) { case tp_ffmpeg::kModuleAvcodec52: return FILE_PATH_LITERAL("libavcodec.so.52"); case tp_ffmpeg::kModuleAvformat52: return FILE_PATH_LITERAL("libavformat.so.52"); case tp_ffmpeg::kModuleAvutil50: return FILE_PATH_LITERAL("libavutil.so.50"); default: LOG(DFATAL) << "Invalid stub module requested: " << stub_key; return FILE_PATH_LITERAL(""); } } } // namespace // Attempts to initialize the media library (loading DSOs, etc.). // Returns true if everything was successfully initialized, false otherwise. bool InitializeMediaLibrary(const FilePath& module_dir) { // TODO(ajwong): We need error resolution. tp_ffmpeg::StubPathMap paths; for (int i = 0; i < static_cast<int>(tp_ffmpeg::kNumStubModules); ++i) { tp_ffmpeg::StubModules module = static_cast<tp_ffmpeg::StubModules>(i); FilePath path = module_dir.Append(GetDSOName(module)); paths[module].push_back(path.value()); } return tp_ffmpeg::InitializeStubs(paths); } } // namespace media <commit_msg>Add in macro to abstract the differences in library naming conventions between mac and linux.<commit_after>// Copyright (c) 2009 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 "media/base/media.h" #include <string> #include <dlfcn.h> #include "base/file_path.h" #include "base/logging.h" #include "base/path_service.h" #include "third_party/ffmpeg/ffmpeg_stubs.h" namespace tp_ffmpeg = third_party_ffmpeg; namespace media { namespace { #if defined(OS_MACOSX) #define DSO_NAME(MODULE, VERSION) ("lib" MODULE "." #VERSION ".dylib") #elif defined(OS_LINUX) #define DSO_NAME(MODULE, VERSION) ("lib" MODULE ".so." #VERSION) #else #error "Do not know how to construct DSO name for this OS." #endif // Retrieves the DSOName for the given key. std::string GetDSOName(tp_ffmpeg::StubModules stub_key) { switch (stub_key) { case tp_ffmpeg::kModuleAvcodec52: return FILE_PATH_LITERAL(DSO_NAME("avcodec", 52)); case tp_ffmpeg::kModuleAvformat52: return FILE_PATH_LITERAL(DSO_NAME("avformat", 52)); case tp_ffmpeg::kModuleAvutil50: return FILE_PATH_LITERAL(DSO_NAME("avutil", 50)); default: LOG(DFATAL) << "Invalid stub module requested: " << stub_key; return FILE_PATH_LITERAL(""); } } } // namespace // Attempts to initialize the media library (loading DSOs, etc.). // Returns true if everything was successfully initialized, false otherwise. bool InitializeMediaLibrary(const FilePath& module_dir) { // TODO(ajwong): We need error resolution. tp_ffmpeg::StubPathMap paths; for (int i = 0; i < static_cast<int>(tp_ffmpeg::kNumStubModules); ++i) { tp_ffmpeg::StubModules module = static_cast<tp_ffmpeg::StubModules>(i); FilePath path = module_dir.Append(GetDSOName(module)); paths[module].push_back(path.value()); } return tp_ffmpeg::InitializeStubs(paths); } } // namespace media <|endoftext|>
<commit_before>/* Qt4xHb - Bindings libraries for Harbour/xHarbour and Qt Framework 4 Copyright (C) 2018 Marcos Antonio Gambeta <marcosgambeta AT outlook DOT com> */ /* DO NOT EDIT THIS FILE - the content was created using a source code generator */ #include "QSvgRendererSlots.h" static QSvgRendererSlots * s = NULL; QSvgRendererSlots::QSvgRendererSlots(QObject *parent) : QObject(parent) { } QSvgRendererSlots::~QSvgRendererSlots() { } void QSvgRendererSlots::repaintNeeded() { QObject *object = qobject_cast<QObject *>(sender()); PHB_ITEM cb = Signals_return_codeblock( object, "repaintNeeded()" ); if( cb ) { PHB_ITEM psender = hb_itemPutPtr( NULL, (QObject *) object ); hb_vmEvalBlockV( (PHB_ITEM) cb, 1, psender ); hb_itemRelease( psender ); } } void QSvgRendererSlots_connect_signal ( const QString & signal, const QString & slot ) { if( s == NULL ) { s = new QSvgRendererSlots( QCoreApplication::instance() ); } hb_retl( Signals_connection_disconnection( s, signal, slot ) ); } <commit_msg>QtSvg: module updated<commit_after>/* Qt4xHb - Bindings libraries for Harbour/xHarbour and Qt Framework 4 Copyright (C) 2018 Marcos Antonio Gambeta <marcosgambeta AT outlook DOT com> */ /* DO NOT EDIT THIS FILE - the content was created using a source code generator */ #include "QSvgRendererSlots.h" static QSvgRendererSlots * s = NULL; QSvgRendererSlots::QSvgRendererSlots(QObject *parent) : QObject(parent) { } QSvgRendererSlots::~QSvgRendererSlots() { } void QSvgRendererSlots::repaintNeeded() { QObject *object = qobject_cast<QObject *>(sender()); PHB_ITEM cb = Signals_return_codeblock( object, "repaintNeeded()" ); if( cb ) { PHB_ITEM psender = Signals_return_qobject ( object, "QOBJECT" ); hb_vmEvalBlockV( (PHB_ITEM) cb, 1, psender ); hb_itemRelease( psender ); } } void QSvgRendererSlots_connect_signal ( const QString & signal, const QString & slot ) { if( s == NULL ) { s = new QSvgRendererSlots( QCoreApplication::instance() ); } hb_retl( Signals_connection_disconnection( s, signal, slot ) ); } <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Vassil Vassilev <vvasielv@cern.ch> //------------------------------------------------------------------------------ #include "cling/Interpreter/Transaction.h" #include "cling/Utils/AST.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclBase.h" #include "clang/AST/PrettyPrinter.h" #include "llvm/Support/raw_ostream.h" using namespace clang; namespace cling { Transaction::Transaction(const ASTContext& C) : m_ASTContext(C) { Initialize(C); } Transaction::Transaction(const CompilationOptions& Opts, const ASTContext& C) : m_ASTContext(C) { Initialize(C); m_Opts = Opts; // intentional copy. } void Transaction::Initialize(const ASTContext& C) { m_NestedTransactions.reset(0); m_Parent = 0; m_State = kCollecting; m_IssuedDiags = kNone; m_Opts = CompilationOptions(); m_Module = 0; m_WrapperFD = 0; m_CFWrapperFD = 0; m_Next = 0; //m_ASTContext = C; } Transaction::~Transaction() { if (hasNestedTransactions()) for (size_t i = 0; i < m_NestedTransactions->size(); ++i) { assert((*m_NestedTransactions)[i]->getState() == kCommitted && "All nested transactions must be committed!"); delete (*m_NestedTransactions)[i]; } } void Transaction::addNestedTransaction(Transaction* nested) { // Create lazily the list if (!m_NestedTransactions) m_NestedTransactions.reset(new NestedTransactions()); nested->setParent(this); // Leave a marker in the parent transaction, where the nested transaction // started. DelayCallInfo marker(clang::DeclGroupRef(), Transaction::kCCINone); m_DeclQueue.push_back(marker); m_NestedTransactions->push_back(nested); } void Transaction::removeNestedTransaction(Transaction* nested) { assert(hasNestedTransactions() && "Does not contain nested transactions"); int nestedPos = -1; for (size_t i = 0; i < m_NestedTransactions->size(); ++i) if ((*m_NestedTransactions)[i] == nested) { nestedPos = i; break; } assert(nestedPos > -1 && "Not found!?"); m_NestedTransactions->erase(m_NestedTransactions->begin() + nestedPos); // We need to remove the marker too. int markerPos = -1; for (size_t i = 0; i < size(); ++i) { if ((*this)[i].m_DGR.isNull() && (*this)[i].m_Call == kCCINone) { ++markerPos; if (nestedPos == markerPos) { erase(i); break; } } } if (!m_NestedTransactions->size()) m_NestedTransactions.reset(0); } void Transaction::reset() { assert(empty() && "The transaction must be empty."); if (Transaction* parent = getParent()) parent->removeNestedTransaction(this); m_Parent = 0; m_State = kCollecting; m_IssuedDiags = kNone; m_Opts = CompilationOptions(); m_NestedTransactions.reset(0); // FIXME: leaks the nested transactions. m_Module = 0; m_WrapperFD = 0; m_CFWrapperFD = 0; m_Next = 0; } void Transaction::append(DelayCallInfo DCI) { assert(!DCI.m_DGR.isNull() && "Appending null DGR?!"); assert(getState() == kCollecting && "Cannot append declarations in current state."); forceAppend(DCI); } void Transaction::forceAppend(DelayCallInfo DCI) { assert(!DCI.m_DGR.isNull() && "Appending null DGR?!"); assert((getState() == kCollecting || getState() == kCompleted) && "Must not be"); #ifndef NDEBUG // Check for duplicates for (size_t i = 0, e = m_DeclQueue.size(); i < e; ++i) { DelayCallInfo &oldDCI (m_DeclQueue[i]); // FIXME: This is possible bug in clang, which will instantiate one and // the same CXXStaticMemberVar several times. This happens when there are // two dependent expressions and the first uses another declaration from // the redeclaration chain. This will force Sema in to instantiate the // definition (usually the most recent decl in the chain) and then the // second expression might referece the definition (which was already) // instantiated, but Sema seems not to keep track of these kinds of // instantiations, even though the points of instantiation are the same! // // This should be investigated further when we merge with newest clang. // This is triggered by running the roottest: ./root/io/newstl if (oldDCI.m_Call == kCCIHandleCXXStaticMemberVarInstantiation) continue; // It is possible to have duplicate calls to HandleVTable with the same // declaration, because each time Sema believes a vtable is used it emits // that callback. // For reference (clang::CodeGen::CodeGenModule::EmitVTable). if (oldDCI.m_Call != kCCIHandleVTable) assert(oldDCI != DCI && "Duplicates?!"); } #endif bool checkForWrapper = !m_WrapperFD; bool checkForCFWrapper = !m_CFWrapperFD; // FIXME: Assignment in assert!!!! assert(checkForWrapper = true && "Check for wrappers with asserts"); // register the wrapper if any. if ((checkForWrapper || checkForCFWrapper) && !DCI.m_DGR.isNull() && DCI.m_DGR.isSingleDecl()) { if (FunctionDecl* FD = dyn_cast<FunctionDecl>(DCI.m_DGR.getSingleDecl())) { if (checkForWrapper && utils::Analyze::IsWrapper(FD)) { assert(!m_WrapperFD && "Two wrappers in one transaction?"); m_WrapperFD = FD; } if (checkForCFWrapper && utils::Analyze::IsCFWrapper(FD)) { m_CFWrapperFD = FD; } } } if (comesFromASTReader(DCI.m_DGR)) m_DeserializedDeclQueue.push_back(DCI); else m_DeclQueue.push_back(DCI); } void Transaction::append(clang::DeclGroupRef DGR) { append(DelayCallInfo(DGR, kCCIHandleTopLevelDecl)); } void Transaction::append(Decl* D) { append(DeclGroupRef(D)); } void Transaction::forceAppend(Decl* D) { forceAppend(DelayCallInfo(DeclGroupRef(D), kCCIHandleTopLevelDecl)); } void Transaction::erase(size_t pos) { assert(!empty() && "Erasing from an empty transaction."); m_DeclQueue.erase(decls_begin() + pos); } void Transaction::dump() const { if (!size()) return; const ASTContext& C = getASTContext(); PrintingPolicy Policy = C.getPrintingPolicy(); print(llvm::errs(), Policy, /*Indent*/0, /*PrintInstantiation*/true); } void Transaction::dumpPretty() const { if (!size()) return; const ASTContext& C = getASTContext(); PrintingPolicy Policy(C->getLangOpts()); print(llvm::errs(), Policy, /*Indent*/0, /*PrintInstantiation*/true); } void Transaction::print(llvm::raw_ostream& Out, const PrintingPolicy& Policy, unsigned Indent, bool PrintInstantiation) const { int nestedT = 0; for (const_iterator I = decls_begin(), E = decls_end(); I != E; ++I) { if (I->m_DGR.isNull()) { assert(hasNestedTransactions() && "DGR is null even if no nesting?"); // print the nested decl Out<< "\n"; Out<<"+====================================================+\n"; Out<<" Nested Transaction" << nestedT << " \n"; Out<<"+====================================================+\n"; (*m_NestedTransactions)[nestedT++]->print(Out, Policy, Indent, PrintInstantiation); Out<< "\n"; Out<<"+====================================================+\n"; Out<<" End Transaction" << nestedT << " \n"; Out<<"+====================================================+\n"; } for (DeclGroupRef::const_iterator J = I->m_DGR.begin(), L = I->m_DGR.end(); J != L; ++J) if (*J) (*J)->print(Out, Policy, Indent, PrintInstantiation); else Out << "<<NULL DECL>>"; } } void Transaction::printStructure(size_t nindent) const { static const char* const stateNames[kNumStates] = { "Collecting", "kCompleted", "RolledBack", "RolledBackWithErrors", "Committed" }; std::string indent(nindent, ' '); llvm::errs() << indent << "Transaction @" << this << ": \n"; for (const_nested_iterator I = nested_begin(), E = nested_end(); I != E; ++I) { (*I)->printStructure(nindent + 3); } llvm::errs() << indent << " state: " << stateNames[getState()] << ", " << size() << " decl groups, "; if (hasNestedTransactions()) llvm::errs() << m_NestedTransactions->size(); else llvm::errs() << "0"; llvm::errs() << " nested transactions\n" << indent << " wrapper: " << m_WrapperFD << ", parent: " << m_Parent << ", next: " << m_Next << "\n"; } void Transaction::printStructureBrief(size_t nindent /*=0*/) const { std::string indent(nindent, ' '); llvm::errs() << indent << "<cling::Transaction* " << this << " isEmpty=" << empty(); llvm::errs() << " isCommitted=" << (getState() == kCommitted); llvm::errs() <<"> \n"; for (const_nested_iterator I = nested_begin(), E = nested_end(); I != E; ++I) { llvm::errs() << indent << "`"; (*I)->printStructureBrief(nindent + 3); } } bool Transaction::comesFromASTReader(DeclGroupRef DGR) const { assert(!DGR.isNull() && "DeclGroupRef is Null!"); if (getCompilationOpts().CodeGenerationForModule) return true; // Take the first/only decl in the group. Decl* D = *DGR.begin(); return D->isFromASTFile(); } } // end namespace cling <commit_msg>The ASTContext is a ref.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Vassil Vassilev <vvasielv@cern.ch> //------------------------------------------------------------------------------ #include "cling/Interpreter/Transaction.h" #include "cling/Utils/AST.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclBase.h" #include "clang/AST/PrettyPrinter.h" #include "llvm/Support/raw_ostream.h" using namespace clang; namespace cling { Transaction::Transaction(const ASTContext& C) : m_ASTContext(C) { Initialize(C); } Transaction::Transaction(const CompilationOptions& Opts, const ASTContext& C) : m_ASTContext(C) { Initialize(C); m_Opts = Opts; // intentional copy. } void Transaction::Initialize(const ASTContext& C) { m_NestedTransactions.reset(0); m_Parent = 0; m_State = kCollecting; m_IssuedDiags = kNone; m_Opts = CompilationOptions(); m_Module = 0; m_WrapperFD = 0; m_CFWrapperFD = 0; m_Next = 0; //m_ASTContext = C; } Transaction::~Transaction() { if (hasNestedTransactions()) for (size_t i = 0; i < m_NestedTransactions->size(); ++i) { assert((*m_NestedTransactions)[i]->getState() == kCommitted && "All nested transactions must be committed!"); delete (*m_NestedTransactions)[i]; } } void Transaction::addNestedTransaction(Transaction* nested) { // Create lazily the list if (!m_NestedTransactions) m_NestedTransactions.reset(new NestedTransactions()); nested->setParent(this); // Leave a marker in the parent transaction, where the nested transaction // started. DelayCallInfo marker(clang::DeclGroupRef(), Transaction::kCCINone); m_DeclQueue.push_back(marker); m_NestedTransactions->push_back(nested); } void Transaction::removeNestedTransaction(Transaction* nested) { assert(hasNestedTransactions() && "Does not contain nested transactions"); int nestedPos = -1; for (size_t i = 0; i < m_NestedTransactions->size(); ++i) if ((*m_NestedTransactions)[i] == nested) { nestedPos = i; break; } assert(nestedPos > -1 && "Not found!?"); m_NestedTransactions->erase(m_NestedTransactions->begin() + nestedPos); // We need to remove the marker too. int markerPos = -1; for (size_t i = 0; i < size(); ++i) { if ((*this)[i].m_DGR.isNull() && (*this)[i].m_Call == kCCINone) { ++markerPos; if (nestedPos == markerPos) { erase(i); break; } } } if (!m_NestedTransactions->size()) m_NestedTransactions.reset(0); } void Transaction::reset() { assert(empty() && "The transaction must be empty."); if (Transaction* parent = getParent()) parent->removeNestedTransaction(this); m_Parent = 0; m_State = kCollecting; m_IssuedDiags = kNone; m_Opts = CompilationOptions(); m_NestedTransactions.reset(0); // FIXME: leaks the nested transactions. m_Module = 0; m_WrapperFD = 0; m_CFWrapperFD = 0; m_Next = 0; } void Transaction::append(DelayCallInfo DCI) { assert(!DCI.m_DGR.isNull() && "Appending null DGR?!"); assert(getState() == kCollecting && "Cannot append declarations in current state."); forceAppend(DCI); } void Transaction::forceAppend(DelayCallInfo DCI) { assert(!DCI.m_DGR.isNull() && "Appending null DGR?!"); assert((getState() == kCollecting || getState() == kCompleted) && "Must not be"); #ifndef NDEBUG // Check for duplicates for (size_t i = 0, e = m_DeclQueue.size(); i < e; ++i) { DelayCallInfo &oldDCI (m_DeclQueue[i]); // FIXME: This is possible bug in clang, which will instantiate one and // the same CXXStaticMemberVar several times. This happens when there are // two dependent expressions and the first uses another declaration from // the redeclaration chain. This will force Sema in to instantiate the // definition (usually the most recent decl in the chain) and then the // second expression might referece the definition (which was already) // instantiated, but Sema seems not to keep track of these kinds of // instantiations, even though the points of instantiation are the same! // // This should be investigated further when we merge with newest clang. // This is triggered by running the roottest: ./root/io/newstl if (oldDCI.m_Call == kCCIHandleCXXStaticMemberVarInstantiation) continue; // It is possible to have duplicate calls to HandleVTable with the same // declaration, because each time Sema believes a vtable is used it emits // that callback. // For reference (clang::CodeGen::CodeGenModule::EmitVTable). if (oldDCI.m_Call != kCCIHandleVTable) assert(oldDCI != DCI && "Duplicates?!"); } #endif bool checkForWrapper = !m_WrapperFD; bool checkForCFWrapper = !m_CFWrapperFD; // FIXME: Assignment in assert!!!! assert(checkForWrapper = true && "Check for wrappers with asserts"); // register the wrapper if any. if ((checkForWrapper || checkForCFWrapper) && !DCI.m_DGR.isNull() && DCI.m_DGR.isSingleDecl()) { if (FunctionDecl* FD = dyn_cast<FunctionDecl>(DCI.m_DGR.getSingleDecl())) { if (checkForWrapper && utils::Analyze::IsWrapper(FD)) { assert(!m_WrapperFD && "Two wrappers in one transaction?"); m_WrapperFD = FD; } if (checkForCFWrapper && utils::Analyze::IsCFWrapper(FD)) { m_CFWrapperFD = FD; } } } if (comesFromASTReader(DCI.m_DGR)) m_DeserializedDeclQueue.push_back(DCI); else m_DeclQueue.push_back(DCI); } void Transaction::append(clang::DeclGroupRef DGR) { append(DelayCallInfo(DGR, kCCIHandleTopLevelDecl)); } void Transaction::append(Decl* D) { append(DeclGroupRef(D)); } void Transaction::forceAppend(Decl* D) { forceAppend(DelayCallInfo(DeclGroupRef(D), kCCIHandleTopLevelDecl)); } void Transaction::erase(size_t pos) { assert(!empty() && "Erasing from an empty transaction."); m_DeclQueue.erase(decls_begin() + pos); } void Transaction::dump() const { if (!size()) return; const ASTContext& C = getASTContext(); PrintingPolicy Policy = C.getPrintingPolicy(); print(llvm::errs(), Policy, /*Indent*/0, /*PrintInstantiation*/true); } void Transaction::dumpPretty() const { if (!size()) return; const ASTContext& C = getASTContext(); PrintingPolicy Policy(C.getLangOpts()); print(llvm::errs(), Policy, /*Indent*/0, /*PrintInstantiation*/true); } void Transaction::print(llvm::raw_ostream& Out, const PrintingPolicy& Policy, unsigned Indent, bool PrintInstantiation) const { int nestedT = 0; for (const_iterator I = decls_begin(), E = decls_end(); I != E; ++I) { if (I->m_DGR.isNull()) { assert(hasNestedTransactions() && "DGR is null even if no nesting?"); // print the nested decl Out<< "\n"; Out<<"+====================================================+\n"; Out<<" Nested Transaction" << nestedT << " \n"; Out<<"+====================================================+\n"; (*m_NestedTransactions)[nestedT++]->print(Out, Policy, Indent, PrintInstantiation); Out<< "\n"; Out<<"+====================================================+\n"; Out<<" End Transaction" << nestedT << " \n"; Out<<"+====================================================+\n"; } for (DeclGroupRef::const_iterator J = I->m_DGR.begin(), L = I->m_DGR.end(); J != L; ++J) if (*J) (*J)->print(Out, Policy, Indent, PrintInstantiation); else Out << "<<NULL DECL>>"; } } void Transaction::printStructure(size_t nindent) const { static const char* const stateNames[kNumStates] = { "Collecting", "kCompleted", "RolledBack", "RolledBackWithErrors", "Committed" }; std::string indent(nindent, ' '); llvm::errs() << indent << "Transaction @" << this << ": \n"; for (const_nested_iterator I = nested_begin(), E = nested_end(); I != E; ++I) { (*I)->printStructure(nindent + 3); } llvm::errs() << indent << " state: " << stateNames[getState()] << ", " << size() << " decl groups, "; if (hasNestedTransactions()) llvm::errs() << m_NestedTransactions->size(); else llvm::errs() << "0"; llvm::errs() << " nested transactions\n" << indent << " wrapper: " << m_WrapperFD << ", parent: " << m_Parent << ", next: " << m_Next << "\n"; } void Transaction::printStructureBrief(size_t nindent /*=0*/) const { std::string indent(nindent, ' '); llvm::errs() << indent << "<cling::Transaction* " << this << " isEmpty=" << empty(); llvm::errs() << " isCommitted=" << (getState() == kCommitted); llvm::errs() <<"> \n"; for (const_nested_iterator I = nested_begin(), E = nested_end(); I != E; ++I) { llvm::errs() << indent << "`"; (*I)->printStructureBrief(nindent + 3); } } bool Transaction::comesFromASTReader(DeclGroupRef DGR) const { assert(!DGR.isNull() && "DeclGroupRef is Null!"); if (getCompilationOpts().CodeGenerationForModule) return true; // Take the first/only decl in the group. Decl* D = *DGR.begin(); return D->isFromASTFile(); } } // end namespace cling <|endoftext|>
<commit_before>#include "buzz_controller_spiri.h" /****************************************/ /****************************************/ static int BuzzTakeOff(buzzvm_t vm) { /* Get pointer to the controller */ buzzvm_pushs(vm, buzzvm_string_register(vm, "controller")); buzzvm_gload(vm); /* Call function */ int cont = reinterpret_cast<CBuzzControllerSpiri*>(buzzvm_stack_at(vm, 1)->u.value)->TakeOff(); buzzvm_pushi(vm, cont); return buzzvm_ret1(vm); } static int BuzzLand(buzzvm_t vm) { /* Get pointer to the controller */ buzzvm_pushs(vm, buzzvm_string_register(vm, "controller")); buzzvm_gload(vm); /* Call function */ int cont = reinterpret_cast<CBuzzControllerSpiri*>(buzzvm_stack_at(vm, 1)->u.value)->Land(); buzzvm_pushi(vm, cont); return buzzvm_ret1(vm); } static int BuzzGoTo(buzzvm_t vm) { /* Push the vector components */ buzzvm_lload(vm, 1); buzzvm_lload(vm, 2); /* Create a new vector with that */ CVector3 cDir(buzzvm_stack_at(vm, 2)->f.value, buzzvm_stack_at(vm, 1)->f.value, 0.0f); /* Get pointer to the controller */ buzzvm_pushs(vm, buzzvm_string_register(vm, "controller")); buzzvm_gload(vm); /* Call function */ reinterpret_cast<CBuzzControllerSpiri*>(buzzvm_stack_at(vm, 1)->u.value)->SetDirection(cDir); return buzzvm_ret0(vm); } /****************************************/ /****************************************/ CBuzzControllerSpiri::CBuzzControllerSpiri() : m_pcPropellers(NULL) { } /****************************************/ /****************************************/ CBuzzControllerSpiri::~CBuzzControllerSpiri() { } /****************************************/ /****************************************/ void CBuzzControllerSpiri::Init(TConfigurationNode& t_node) { try { /* Get pointers to devices */ m_pcPropellers = GetActuator<CCI_QuadRotorPositionActuator>("quadrotor_position"); m_pcPosition = GetSensor <CCI_PositioningSensor> ("positioning"); /* Initialize the rest */ CBuzzController::Init(t_node); } catch(CARGoSException& ex) { THROW_ARGOSEXCEPTION_NESTED("Error initializing the Buzz controller for the spiri", ex); } } /****************************************/ /****************************************/ void CBuzzControllerSpiri::SetDirection(const CVector3& c_heading) { CVector3 cDir = c_heading; if(cDir.SquareLength() > 0.01f) { cDir.Normalize(); cDir *= 0.1; } m_pcPropellers->SetRelativePosition(cDir); } /****************************************/ /****************************************/ bool CBuzzControllerSpiri::TakeOff() { CVector3 cPos = m_pcPosition->GetReading().Position; if(Abs(cPos.GetZ() - 2.0f) < 0.01f) return false; cPos.SetZ(2.0f); m_pcPropellers->SetAbsolutePosition(cPos); return true; } /****************************************/ /****************************************/ bool CBuzzControllerSpiri::Land() { CVector3 cPos = m_pcPosition->GetReading().Position; if(Abs(cPos.GetZ()) < 0.01f) return false; cPos.SetZ(0.0f); m_pcPropellers->SetAbsolutePosition(cPos); return true; } /****************************************/ /****************************************/ int CBuzzControllerSpiri::RegisterFunctions() { /* Register base functions */ CBuzzController::RegisterFunctions(); /* BuzzTakeOff */ buzzvm_pushs(m_tBuzzVM, buzzvm_string_register(m_tBuzzVM, "takeoff")); buzzvm_pushcc(m_tBuzzVM, buzzvm_function_register(m_tBuzzVM, BuzzTakeOff)); buzzvm_gstore(m_tBuzzVM); /* BuzzLand */ buzzvm_pushs(m_tBuzzVM, buzzvm_string_register(m_tBuzzVM, "land")); buzzvm_pushcc(m_tBuzzVM, buzzvm_function_register(m_tBuzzVM, BuzzLand)); buzzvm_gstore(m_tBuzzVM); /* BuzzGoTo */ buzzvm_pushs(m_tBuzzVM, buzzvm_string_register(m_tBuzzVM, "goto")); buzzvm_pushcc(m_tBuzzVM, buzzvm_function_register(m_tBuzzVM, BuzzGoTo)); buzzvm_gstore(m_tBuzzVM); return m_tBuzzVM->state; } /****************************************/ /****************************************/ REGISTER_CONTROLLER(CBuzzControllerSpiri, "buzz_controller_spiri"); <commit_msg>Fixed speed factor in Spiri controller.<commit_after>#include "buzz_controller_spiri.h" /****************************************/ /****************************************/ static int BuzzTakeOff(buzzvm_t vm) { /* Get pointer to the controller */ buzzvm_pushs(vm, buzzvm_string_register(vm, "controller")); buzzvm_gload(vm); /* Call function */ int cont = reinterpret_cast<CBuzzControllerSpiri*>(buzzvm_stack_at(vm, 1)->u.value)->TakeOff(); buzzvm_pushi(vm, cont); return buzzvm_ret1(vm); } static int BuzzLand(buzzvm_t vm) { /* Get pointer to the controller */ buzzvm_pushs(vm, buzzvm_string_register(vm, "controller")); buzzvm_gload(vm); /* Call function */ int cont = reinterpret_cast<CBuzzControllerSpiri*>(buzzvm_stack_at(vm, 1)->u.value)->Land(); buzzvm_pushi(vm, cont); return buzzvm_ret1(vm); } static int BuzzGoTo(buzzvm_t vm) { /* Push the vector components */ buzzvm_lload(vm, 1); buzzvm_lload(vm, 2); /* Create a new vector with that */ CVector3 cDir(buzzvm_stack_at(vm, 2)->f.value, buzzvm_stack_at(vm, 1)->f.value, 0.0f); /* Get pointer to the controller */ buzzvm_pushs(vm, buzzvm_string_register(vm, "controller")); buzzvm_gload(vm); /* Call function */ reinterpret_cast<CBuzzControllerSpiri*>(buzzvm_stack_at(vm, 1)->u.value)->SetDirection(cDir); return buzzvm_ret0(vm); } /****************************************/ /****************************************/ CBuzzControllerSpiri::CBuzzControllerSpiri() : m_pcPropellers(NULL) { } /****************************************/ /****************************************/ CBuzzControllerSpiri::~CBuzzControllerSpiri() { } /****************************************/ /****************************************/ void CBuzzControllerSpiri::Init(TConfigurationNode& t_node) { try { /* Get pointers to devices */ m_pcPropellers = GetActuator<CCI_QuadRotorPositionActuator>("quadrotor_position"); m_pcPosition = GetSensor <CCI_PositioningSensor> ("positioning"); /* Initialize the rest */ CBuzzController::Init(t_node); } catch(CARGoSException& ex) { THROW_ARGOSEXCEPTION_NESTED("Error initializing the Buzz controller for the spiri", ex); } } /****************************************/ /****************************************/ void CBuzzControllerSpiri::SetDirection(const CVector3& c_heading) { CVector3 cDir = c_heading; if(cDir.SquareLength() > 0.01f) { cDir.Normalize(); cDir *= 0.01; } m_pcPropellers->SetRelativePosition(cDir); } /****************************************/ /****************************************/ bool CBuzzControllerSpiri::TakeOff() { CVector3 cPos = m_pcPosition->GetReading().Position; if(Abs(cPos.GetZ() - 2.0f) < 0.01f) return false; cPos.SetZ(2.0f); m_pcPropellers->SetAbsolutePosition(cPos); return true; } /****************************************/ /****************************************/ bool CBuzzControllerSpiri::Land() { CVector3 cPos = m_pcPosition->GetReading().Position; if(Abs(cPos.GetZ()) < 0.01f) return false; cPos.SetZ(0.0f); m_pcPropellers->SetAbsolutePosition(cPos); return true; } /****************************************/ /****************************************/ int CBuzzControllerSpiri::RegisterFunctions() { /* Register base functions */ CBuzzController::RegisterFunctions(); /* BuzzTakeOff */ buzzvm_pushs(m_tBuzzVM, buzzvm_string_register(m_tBuzzVM, "takeoff")); buzzvm_pushcc(m_tBuzzVM, buzzvm_function_register(m_tBuzzVM, BuzzTakeOff)); buzzvm_gstore(m_tBuzzVM); /* BuzzLand */ buzzvm_pushs(m_tBuzzVM, buzzvm_string_register(m_tBuzzVM, "land")); buzzvm_pushcc(m_tBuzzVM, buzzvm_function_register(m_tBuzzVM, BuzzLand)); buzzvm_gstore(m_tBuzzVM); /* BuzzGoTo */ buzzvm_pushs(m_tBuzzVM, buzzvm_string_register(m_tBuzzVM, "goto")); buzzvm_pushcc(m_tBuzzVM, buzzvm_function_register(m_tBuzzVM, BuzzGoTo)); buzzvm_gstore(m_tBuzzVM); return m_tBuzzVM->state; } /****************************************/ /****************************************/ REGISTER_CONTROLLER(CBuzzControllerSpiri, "buzz_controller_spiri"); <|endoftext|>
<commit_before> /* tests/test-givaropoly.C * Copyright (C) 2014 Gavin Harrison, * * Written by Gavin Harrison <gmh33@drexel.edu>, * * ========LICENCE======== * This file is part of the library LinBox. * * LinBox 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 * ========LICENCE======== *. */ /*! @file tests/test-gf2.C * @ingroup tests * @brief no doc * @test NO DOC */ #include "linbox/linbox-config.h" #include <iostream> #include "linbox/ring/polynomial-ring.h" #include "linbox/ring/modular.h" #include "test-field.h" using namespace LinBox; int main (int argc, char **argv) { static int p = 13; static int e = 1; // currently not used static Argument args[] = { { 'p', "-p P", "Set the base field prime.", TYPE_INT, &p }, { 'e', "-e E", "Set the base field exponent.", TYPE_INT, &e }, END_OF_ARGUMENTS }; parseArguments (argc, argv, args); commentator().start("PolynomialRing test suite", "PolynomialRing"); bool pass = true; typedef Givaro::Modular<float> BaseDom; typedef PolynomialRing<BaseDom> PolyDom; BaseDom Fp(p); PolyDom Poly(Fp); // Make sure some more detailed messages get printed commentator().getMessageClass (INTERNAL_DESCRIPTION).setMaxDepth (4); commentator().getMessageClass (INTERNAL_DESCRIPTION).setMaxDetailLevel (Commentator::LEVEL_UNIMPORTANT); commentator().start ("Testing GivaroPoly", "main", 10); if ( not testRing (Fp, "PolynomialRing<Modular<float>>")) pass = false; commentator().progress (); commentator().stop("PolynomialRing test suite"); return pass ? 0 : -1; } // vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,:0,t0,+0,=s // Local Variables: // mode: C++ // tab-width: 8 // indent-tabs-mode: nil // c-basic-offset: 8 // End: <commit_msg>Fix test poly ring to use polynomial ring class<commit_after> /* tests/test-givaropoly.C * Copyright (C) 2014 Gavin Harrison, * * Written by Gavin Harrison <gmh33@drexel.edu>, * * ========LICENCE======== * This file is part of the library LinBox. * * LinBox 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 * ========LICENCE======== *. */ /*! @file tests/test-gf2.C * @ingroup tests * @brief no doc * @test NO DOC */ #include "linbox/linbox-config.h" #include <iostream> #include "linbox/ring/polynomial-ring.h" #include "linbox/ring/modular.h" #include "test-field.h" using namespace LinBox; int main (int argc, char **argv) { static int p = 13; static int e = 1; // currently not used static Argument args[] = { { 'p', "-p P", "Set the base field prime.", TYPE_INT, &p }, { 'e', "-e E", "Set the base field exponent.", TYPE_INT, &e }, END_OF_ARGUMENTS }; parseArguments (argc, argv, args); commentator().start("PolynomialRing test suite", "PolynomialRing"); bool pass = true; typedef Givaro::Modular<float> BaseDom; typedef PolynomialRing<BaseDom> PolyDom; BaseDom Fp(p); PolyDom Poly(Fp); // Make sure some more detailed messages get printed commentator().getMessageClass (INTERNAL_DESCRIPTION).setMaxDepth (4); commentator().getMessageClass (INTERNAL_DESCRIPTION).setMaxDetailLevel (Commentator::LEVEL_UNIMPORTANT); commentator().start ("Testing GivaroPoly", "main", 10); if ( not testRing (Poly, "PolynomialRing<Modular<float>>")) pass = false; commentator().progress (); commentator().stop("PolynomialRing test suite"); return pass ? 0 : -1; } // vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,:0,t0,+0,=s // Local Variables: // mode: C++ // tab-width: 8 // indent-tabs-mode: nil // c-basic-offset: 8 // End: <|endoftext|>
<commit_before>#include "d3d_common.h" namespace D3D { void GenerateQuad(Geom::RectFloat position, Geom::RectFloat texCoords, Geom::SizeFloat adjustment, Geom::SizeInt targetSize, Filter::RotationAngle angle, D3D::Vertex2D& a, D3D::Vertex2D& b, D3D::Vertex2D& c, D3D::Vertex2D& d) { switch (angle) { case Filter::RotationAngle::RotateDefault: a.Position = position.TopLeft(); a.TexCoord = texCoords.TopLeft(); b.Position = position.TopRight(); b.TexCoord = texCoords.TopRight(); c.Position = position.BottomLeft(); c.TexCoord = texCoords.BottomLeft(); d.Position = position.BottomRight(); d.TexCoord = texCoords.BottomRight(); break; case Filter::RotationAngle::FlipX: a.Position = { targetSize.Width - position.Left() - position.Width(), position.Top() }; a.TexCoord = texCoords.TopRight(); b.Position = { targetSize.Width - position.Left(), position.Top() }; b.TexCoord = texCoords.TopLeft(); c.Position = { targetSize.Width - position.Left() - position.Width(), position.Bottom() }; c.TexCoord = texCoords.BottomRight(); d.Position = { targetSize.Width - position.Left(), position.Bottom() }; d.TexCoord = texCoords.BottomLeft(); break; case Filter::RotationAngle::FlipY: a.Position = { position.Left(), targetSize.Height - position.Top() - position.Height() }; a.TexCoord = texCoords.BottomLeft(); b.Position = { position.Right(), targetSize.Height - position.Top() - position.Height() }; b.TexCoord = texCoords.BottomRight(); c.Position = { position.Left(), targetSize.Height - position.Top() }; c.TexCoord = texCoords.TopLeft(); d.Position = { position.Right(), targetSize.Height - position.Top() }; d.TexCoord = texCoords.TopRight(); break; case Filter::RotationAngle::Rotate90: a.Position = { targetSize.Width - position.Top() - position.Height(), position.Left() }; a.TexCoord = texCoords.BottomLeft(); b.Position = { targetSize.Width - position.Top(), position.Left() }; b.TexCoord = texCoords.TopLeft(); c.Position = { targetSize.Width - position.Top() - position.Height(), position.Right() }; c.TexCoord = texCoords.BottomRight(); d.Position = { targetSize.Width - position.Top(), position.Right() }; d.TexCoord = texCoords.TopRight(); break; case Filter::RotationAngle::Rotate90FlipY: // SCREENSPACE: // TopLeft vert (x, y) a.Position = { targetSize.Width - position.Top() - position.Height(), targetSize.Height - position.Left() - position.Width() }; a.TexCoord = texCoords.BottomRight(); // TopRight vert (x, y) b.Position = { targetSize.Width - position.Top(), targetSize.Height - position.Left() - position.Width() }; b.TexCoord = texCoords.TopRight(); c.Position = { targetSize.Width - position.Top() - position.Height(), targetSize.Height - position.Left() }; c.TexCoord = texCoords.BottomLeft(); d.Position = { targetSize.Width - position.Top(), targetSize.Height - position.Left() }; d.TexCoord = texCoords.TopLeft(); break; case Filter::RotationAngle::Rotate180: a.Position = { targetSize.Width - position.Left() - position.Width(), targetSize.Height - position.Top() - position.Height() }; a.TexCoord = texCoords.BottomRight(); b.Position = { targetSize.Width - position.Left(), targetSize.Height - position.Top() - position.Height() }; b.TexCoord = texCoords.BottomLeft(); c.Position = { targetSize.Width - position.Left() - position.Width(), targetSize.Height - position.Top() }; c.TexCoord = texCoords.TopRight(); d.Position = { targetSize.Width - position.Left(), targetSize.Height - position.Top() }; d.TexCoord = texCoords.TopLeft(); break; case Filter::RotationAngle::Rotate270: a.Position = { position.Top(), targetSize.Height - position.Left() - position.Width() }; a.TexCoord = texCoords.TopRight(); b.Position = { position.Bottom(), targetSize.Height - position.Left() - position.Width() }; b.TexCoord = texCoords.BottomRight(); c.Position = { position.Top(), targetSize.Height - position.Left() }; c.TexCoord = texCoords.TopLeft(); d.Position = { position.Bottom(), targetSize.Height - position.Left() }; d.TexCoord = texCoords.BottomLeft(); break; case Filter::RotationAngle::Rotate270FlipY: // SCREENSPACE: // TopLeft vert (x, y) a.Position = { position.Top(), position.Left() }; a.TexCoord = texCoords.TopLeft(); // TopRight vert (x, y) b.Position = { position.Bottom(), position.Left() }; b.TexCoord = texCoords.BottomLeft(); // Bottom Left (x, y) c.Position = { position.Top(), position.Right() }; c.TexCoord = texCoords.TopRight(); // Bottom Right (x, y) d.Position = { position.Bottom(), position.Right() }; d.TexCoord = texCoords.BottomRight(); break; default: DO_THROW(Err::InvalidParam, "Angle not supported"); break; } a.Position += adjustment; b.Position += adjustment; c.Position += adjustment; d.Position += adjustment; } } <commit_msg>Sloppy hack to avoid varying image position depending on rotation.<commit_after>#include "d3d_common.h" namespace D3D { void GenerateQuad(Geom::RectFloat position, Geom::RectFloat texCoords, Geom::SizeFloat adjustment, Geom::SizeInt targetSize, Filter::RotationAngle angle, D3D::Vertex2D& a, D3D::Vertex2D& b, D3D::Vertex2D& c, D3D::Vertex2D& d) { switch (angle) { case Filter::RotationAngle::RotateDefault: a.Position = position.TopLeft(); a.TexCoord = texCoords.TopLeft(); b.Position = position.TopRight(); b.TexCoord = texCoords.TopRight(); c.Position = position.BottomLeft(); c.TexCoord = texCoords.BottomLeft(); d.Position = position.BottomRight(); d.TexCoord = texCoords.BottomRight(); break; case Filter::RotationAngle::FlipX: adjustment += Geom::SizeFloat{ static_cast<float>(targetSize.Width & 1), 0 }; a.Position = { targetSize.Width - position.Left() - position.Width(), position.Top() }; a.TexCoord = texCoords.TopRight(); b.Position = { targetSize.Width - position.Left(), position.Top() }; b.TexCoord = texCoords.TopLeft(); c.Position = { targetSize.Width - position.Left() - position.Width(), position.Bottom() }; c.TexCoord = texCoords.BottomRight(); d.Position = { targetSize.Width - position.Left(), position.Bottom() }; d.TexCoord = texCoords.BottomLeft(); break; case Filter::RotationAngle::FlipY: adjustment += Geom::SizeFloat{ 0, static_cast<float>(targetSize.Height & 1) }; a.Position = { position.Left(), targetSize.Height - position.Top() - position.Height() }; a.TexCoord = texCoords.BottomLeft(); b.Position = { position.Right(), targetSize.Height - position.Top() - position.Height() }; b.TexCoord = texCoords.BottomRight(); c.Position = { position.Left(), targetSize.Height - position.Top() }; c.TexCoord = texCoords.TopLeft(); d.Position = { position.Right(), targetSize.Height - position.Top() }; d.TexCoord = texCoords.TopRight(); break; case Filter::RotationAngle::Rotate90: adjustment += Geom::SizeFloat{ static_cast<float>(targetSize.Width & 1), 0 }; a.Position = { targetSize.Width - position.Top() - position.Height(), position.Left() }; a.TexCoord = texCoords.BottomLeft(); b.Position = { targetSize.Width - position.Top(), position.Left() }; b.TexCoord = texCoords.TopLeft(); c.Position = { targetSize.Width - position.Top() - position.Height(), position.Right() }; c.TexCoord = texCoords.BottomRight(); d.Position = { targetSize.Width - position.Top(), position.Right() }; d.TexCoord = texCoords.TopRight(); break; case Filter::RotationAngle::Rotate90FlipY: adjustment += Geom::SizeFloat{ static_cast<float>(targetSize.Width & 1), static_cast<float>(targetSize.Height & 1) }; // SCREENSPACE: // TopLeft vert (x, y) a.Position = { targetSize.Width - position.Top() - position.Height(), targetSize.Height - position.Left() - position.Width() }; a.TexCoord = texCoords.BottomRight(); // TopRight vert (x, y) b.Position = { targetSize.Width - position.Top(), targetSize.Height - position.Left() - position.Width() }; b.TexCoord = texCoords.TopRight(); c.Position = { targetSize.Width - position.Top() - position.Height(), targetSize.Height - position.Left() }; c.TexCoord = texCoords.BottomLeft(); d.Position = { targetSize.Width - position.Top(), targetSize.Height - position.Left() }; d.TexCoord = texCoords.TopLeft(); break; case Filter::RotationAngle::Rotate180: adjustment += Geom::SizeFloat{ static_cast<float>(targetSize.Width & 1), static_cast<float>(targetSize.Height & 1) }; a.Position = { targetSize.Width - position.Left() - position.Width(), targetSize.Height - position.Top() - position.Height() }; a.TexCoord = texCoords.BottomRight(); b.Position = { targetSize.Width - position.Left(), targetSize.Height - position.Top() - position.Height() }; b.TexCoord = texCoords.BottomLeft(); c.Position = { targetSize.Width - position.Left() - position.Width(), targetSize.Height - position.Top() }; c.TexCoord = texCoords.TopRight(); d.Position = { targetSize.Width - position.Left(), targetSize.Height - position.Top() }; d.TexCoord = texCoords.TopLeft(); break; case Filter::RotationAngle::Rotate270: adjustment += Geom::SizeFloat{ 0, static_cast<float>(targetSize.Height & 1) }; a.Position = { position.Top(), targetSize.Height - position.Left() - position.Width() }; a.TexCoord = texCoords.TopRight(); b.Position = { position.Bottom(), targetSize.Height - position.Left() - position.Width() }; b.TexCoord = texCoords.BottomRight(); c.Position = { position.Top(), targetSize.Height - position.Left() }; c.TexCoord = texCoords.TopLeft(); d.Position = { position.Bottom(), targetSize.Height - position.Left() }; d.TexCoord = texCoords.BottomLeft(); break; case Filter::RotationAngle::Rotate270FlipY: // SCREENSPACE: // TopLeft vert (x, y) a.Position = { position.Top(), position.Left() }; a.TexCoord = texCoords.TopLeft(); // TopRight vert (x, y) b.Position = { position.Bottom(), position.Left() }; b.TexCoord = texCoords.BottomLeft(); // Bottom Left (x, y) c.Position = { position.Top(), position.Right() }; c.TexCoord = texCoords.TopRight(); // Bottom Right (x, y) d.Position = { position.Bottom(), position.Right() }; d.TexCoord = texCoords.BottomRight(); break; default: DO_THROW(Err::InvalidParam, "Angle not supported"); break; } a.Position += adjustment; b.Position += adjustment; c.Position += adjustment; d.Position += adjustment; } } <|endoftext|>
<commit_before>#include "tiling_render_policy_mt.hpp" #include "../platform/platform.hpp" #include "../yg/internal/opengl.hpp" #include "window_handle.hpp" #include "tile_renderer.hpp" #include "coverage_generator.hpp" TilingRenderPolicyMT::TilingRenderPolicyMT(VideoTimer * videoTimer, bool useDefaultFB, yg::ResourceManager::Params const & rmParams, shared_ptr<yg::gl::RenderContext> const & primaryRC) : BasicTilingRenderPolicy(primaryRC, false, GetPlatform().CpuCores()) { yg::ResourceManager::Params rmp = rmParams; rmp.selectTexRTFormat(); rmp.m_primaryTexturesParams = yg::ResourceManager::TexturePoolParams(512, 256, 10, rmp.m_texFormat, true, true, true, 1, "primaryTexture", false, false); rmp.m_primaryStoragesParams = yg::ResourceManager::StoragePoolParams(50000 * sizeof(yg::gl::Vertex), sizeof(yg::gl::Vertex), 100000 * sizeof(unsigned short), sizeof(unsigned short), 15, false, true, 1, "primaryStorage", false, false); rmp.m_multiBlitStoragesParams = yg::ResourceManager::StoragePoolParams(500 * sizeof(yg::gl::Vertex), sizeof(yg::gl::Vertex), 500 * sizeof(unsigned short), sizeof(unsigned short), 10, true, true, 1, "multiBlitStorage", false, false); rmp.m_renderTargetTexturesParams = yg::ResourceManager::TexturePoolParams(GetPlatform().TileSize(), GetPlatform().TileSize(), GetPlatform().MaxTilesCount(), rmp.m_texRtFormat, true, true, false, 5, "renderTargetTexture", false, false); rmp.m_styleCacheTexturesParams = yg::ResourceManager::TexturePoolParams(512, 1024, 2, rmp.m_texFormat, true, true, true, 1, "styleCacheTexture", false, false); rmp.m_guiThreadStoragesParams = yg::ResourceManager::StoragePoolParams(5000 * sizeof(yg::gl::Vertex), sizeof(yg::gl::Vertex), 10000 * sizeof(unsigned short), sizeof(unsigned short), 10, true, true, 1, "guiThreadStorage", false, false); rmp.m_guiThreadTexturesParams = yg::ResourceManager::TexturePoolParams(256, 128, 4, rmp.m_texFormat, true, true, true, 1, "guiThreadTexture", false, false); rmp.m_glyphCacheParams = yg::ResourceManager::GlyphCacheParams("unicode_blocks.txt", "fonts_whitelist.txt", "fonts_blacklist.txt", 2 * 1024 * 1024, GetPlatform().CpuCores() + 2, GetPlatform().CpuCores(), 0); rmp.m_useSingleThreadedOGL = false; rmp.m_useVA = !yg::gl::g_isBufferObjectsSupported; m_resourceManager.reset(new yg::ResourceManager(rmp)); Platform::FilesList fonts; GetPlatform().GetFontNames(fonts); m_resourceManager->addFonts(fonts); DrawerYG::params_t p; p.m_frameBuffer = make_shared_ptr(new yg::gl::FrameBuffer(useDefaultFB)); p.m_resourceManager = m_resourceManager; p.m_dynamicPagesCount = 2; p.m_textPagesCount = 2; p.m_glyphCacheID = m_resourceManager->guiThreadGlyphCacheID(); p.m_skinName = GetPlatform().SkinName(); p.m_visualScale = GetPlatform().VisualScale(); p.m_useGuiResources = true; p.m_isSynchronized = false; m_drawer.reset(new DrawerYG(p)); m_windowHandle.reset(new WindowHandle()); m_windowHandle->setUpdatesEnabled(false); m_windowHandle->setRenderPolicy(this); m_windowHandle->setVideoTimer(videoTimer); m_windowHandle->setRenderContext(primaryRC); } TilingRenderPolicyMT::~TilingRenderPolicyMT() { LOG(LINFO, ("cancelling ResourceManager")); m_resourceManager->cancel(); m_CoverageGenerator.reset(); m_TileRenderer->ClearCommands(); m_TileRenderer->SetSequenceID(numeric_limits<int>::max()); m_TileRenderer->CancelCommands(); m_TileRenderer->WaitForEmptyAndFinished(); m_TileRenderer.reset(); } void TilingRenderPolicyMT::SetRenderFn(TRenderFn renderFn) { m_TileRenderer.reset(new TileRenderer(GetPlatform().SkinName(), GetPlatform().MaxTilesCount(), GetPlatform().CpuCores(), m_bgColor, renderFn, m_primaryRC, m_resourceManager, GetPlatform().VisualScale(), 0)); m_CoverageGenerator.reset(new CoverageGenerator(m_TileRenderer.get(), m_windowHandle, m_primaryRC, m_resourceManager, 0)); } <commit_msg>refined OpenGL resource allocation strategies.<commit_after>#include "tiling_render_policy_mt.hpp" #include "../platform/platform.hpp" #include "../yg/internal/opengl.hpp" #include "window_handle.hpp" #include "tile_renderer.hpp" #include "coverage_generator.hpp" TilingRenderPolicyMT::TilingRenderPolicyMT(VideoTimer * videoTimer, bool useDefaultFB, yg::ResourceManager::Params const & rmParams, shared_ptr<yg::gl::RenderContext> const & primaryRC) : BasicTilingRenderPolicy(primaryRC, false, GetPlatform().CpuCores()) { yg::ResourceManager::Params rmp = rmParams; rmp.selectTexRTFormat(); rmp.m_primaryTexturesParams = yg::ResourceManager::TexturePoolParams(512, 256, 1, rmp.m_texFormat, true, true, true, 1, "primaryTexture", false, true); rmp.m_primaryStoragesParams = yg::ResourceManager::StoragePoolParams(50000 * sizeof(yg::gl::Vertex), sizeof(yg::gl::Vertex), 100000 * sizeof(unsigned short), sizeof(unsigned short), 5, true, true, 1, "primaryStorage", false, true); rmp.m_multiBlitStoragesParams = yg::ResourceManager::StoragePoolParams(500 * sizeof(yg::gl::Vertex), sizeof(yg::gl::Vertex), 500 * sizeof(unsigned short), sizeof(unsigned short), 10, true, true, 1, "multiBlitStorage", false, false); rmp.m_renderTargetTexturesParams = yg::ResourceManager::TexturePoolParams(GetPlatform().TileSize(), GetPlatform().TileSize(), GetPlatform().MaxTilesCount(), rmp.m_texRtFormat, true, true, true, 5, "renderTargetTexture", false, false); rmp.m_styleCacheTexturesParams = yg::ResourceManager::TexturePoolParams(512, 1024, 2, rmp.m_texFormat, true, true, true, 1, "styleCacheTexture", false, false); rmp.m_guiThreadStoragesParams = yg::ResourceManager::StoragePoolParams(5000 * sizeof(yg::gl::Vertex), sizeof(yg::gl::Vertex), 10000 * sizeof(unsigned short), sizeof(unsigned short), 10, true, true, 1, "guiThreadStorage", false, false); rmp.m_guiThreadTexturesParams = yg::ResourceManager::TexturePoolParams(256, 128, 4, rmp.m_texFormat, true, true, true, 1, "guiThreadTexture", false, false); rmp.m_glyphCacheParams = yg::ResourceManager::GlyphCacheParams("unicode_blocks.txt", "fonts_whitelist.txt", "fonts_blacklist.txt", 2 * 1024 * 1024, GetPlatform().CpuCores() + 2, GetPlatform().CpuCores(), 0); rmp.m_useSingleThreadedOGL = false; rmp.m_useVA = !yg::gl::g_isBufferObjectsSupported; m_resourceManager.reset(new yg::ResourceManager(rmp)); Platform::FilesList fonts; GetPlatform().GetFontNames(fonts); m_resourceManager->addFonts(fonts); DrawerYG::params_t p; p.m_frameBuffer = make_shared_ptr(new yg::gl::FrameBuffer(useDefaultFB)); p.m_resourceManager = m_resourceManager; p.m_dynamicPagesCount = 2; p.m_textPagesCount = 2; p.m_glyphCacheID = m_resourceManager->guiThreadGlyphCacheID(); p.m_skinName = GetPlatform().SkinName(); p.m_visualScale = GetPlatform().VisualScale(); p.m_useGuiResources = true; p.m_isSynchronized = false; m_drawer.reset(new DrawerYG(p)); m_windowHandle.reset(new WindowHandle()); m_windowHandle->setUpdatesEnabled(false); m_windowHandle->setRenderPolicy(this); m_windowHandle->setVideoTimer(videoTimer); m_windowHandle->setRenderContext(primaryRC); } TilingRenderPolicyMT::~TilingRenderPolicyMT() { LOG(LINFO, ("cancelling ResourceManager")); m_resourceManager->cancel(); m_CoverageGenerator.reset(); m_TileRenderer->ClearCommands(); m_TileRenderer->SetSequenceID(numeric_limits<int>::max()); m_TileRenderer->CancelCommands(); m_TileRenderer->WaitForEmptyAndFinished(); m_TileRenderer.reset(); } void TilingRenderPolicyMT::SetRenderFn(TRenderFn renderFn) { m_TileRenderer.reset(new TileRenderer(GetPlatform().SkinName(), GetPlatform().MaxTilesCount(), GetPlatform().CpuCores(), m_bgColor, renderFn, m_primaryRC, m_resourceManager, GetPlatform().VisualScale(), 0)); m_CoverageGenerator.reset(new CoverageGenerator(m_TileRenderer.get(), m_windowHandle, m_primaryRC, m_resourceManager, 0)); } <|endoftext|>
<commit_before>/* * Score a grammar in striped format * ./score_grammar <alignment> < filtered.grammar > scored.grammar */ #include <iostream> #include <string> #include <map> #include <vector> #include <utility> #include <cstdlib> #include <fstream> #include <tr1/unordered_map> #include "sentence_pair.h" #include "extract.h" #include "fdict.h" #include "tdict.h" #include "lex_trans_tbl.h" #include "filelib.h" #include <boost/functional/hash.hpp> #include <boost/program_options.hpp> #include <boost/program_options/variables_map.hpp> using namespace std; using namespace std::tr1; static const size_t MAX_LINE_LENGTH = 64000000; typedef unordered_map<vector<WordID>, RuleStatistics, boost::hash<vector<WordID> > > ID2RuleStatistics; namespace { inline bool IsWhitespace(char c) { return c == ' ' || c == '\t'; } inline bool IsBracket(char c){return c == '[' || c == ']';} inline void SkipWhitespace(const char* buf, int* ptr) { while (buf[*ptr] && IsWhitespace(buf[*ptr])) { ++(*ptr); } } } int ReadPhraseUntilDividerOrEnd(const char* buf, const int sstart, const int end, vector<WordID>* p) { static const WordID kDIV = TD::Convert("|||"); int ptr = sstart; while(ptr < end) { while(ptr < end && IsWhitespace(buf[ptr])) { ++ptr; } int start = ptr; while(ptr < end && !IsWhitespace(buf[ptr])) { ++ptr; } if (ptr == start) {cerr << "Warning! empty token.\n"; return ptr; } const WordID w = TD::Convert(string(buf, start, ptr - start)); if((IsBracket(buf[start]) and IsBracket(buf[ptr-1])) or( w == kDIV)) p->push_back(1 * w); else { if (w == kDIV) return ptr; p->push_back(w); } } return ptr; } void ParseLine(const char* buf, vector<WordID>* cur_key, ID2RuleStatistics* counts) { static const WordID kDIV = TD::Convert("|||"); counts->clear(); int ptr = 0; while(buf[ptr] != 0 && buf[ptr] != '\t') { ++ptr; } if (buf[ptr] != '\t') { cerr << "Missing tab separator between key and value!\n INPUT=" << buf << endl; exit(1); } cur_key->clear(); // key is: "[X] ||| word word word" int tmpp = ReadPhraseUntilDividerOrEnd(buf, 0, ptr, cur_key); cur_key->push_back(kDIV); ReadPhraseUntilDividerOrEnd(buf, tmpp, ptr, cur_key); ++ptr; int start = ptr; int end = ptr; int state = 0; // 0=reading label, 1=reading count vector<WordID> name; while(buf[ptr] != 0) { while(buf[ptr] != 0 && buf[ptr] != '|') { ++ptr; } if (buf[ptr] == '|') { ++ptr; if (buf[ptr] == '|') { ++ptr; if (buf[ptr] == '|') { ++ptr; end = ptr - 3; while (end > start && IsWhitespace(buf[end-1])) { --end; } if (start == end) { cerr << "Got empty token!\n LINE=" << buf << endl; exit(1); } switch (state) { case 0: ++state; name.clear(); ReadPhraseUntilDividerOrEnd(buf, start, end, &name); break; case 1: --state; (*counts)[name].ParseRuleStatistics(buf, start, end); break; default: cerr << "Can't happen\n"; abort(); } SkipWhitespace(buf, &ptr); start = ptr; } } } } end=ptr; while (end > start && IsWhitespace(buf[end-1])) { --end; } if (end > start) { switch (state) { case 0: ++state; name.clear(); ReadPhraseUntilDividerOrEnd(buf, start, end, &name); break; case 1: --state; (*counts)[name].ParseRuleStatistics(buf, start, end); break; default: cerr << "Can't happen\n"; abort(); } } } void LexTranslationTable::createTTable(const char* buf){ bool DEBUG = false; AnnotatedParallelSentence sent; sent.ParseInputLine(buf); //iterate over the alignment to compute aligned words for(int i =0;i<sent.aligned.width();i++) { for (int j=0;j<sent.aligned.height();j++) { if (DEBUG) cerr << sent.aligned(i,j) << " "; if( sent.aligned(i,j)) { if (DEBUG) cerr << TD::Convert(sent.f[i]) << " aligned to " << TD::Convert(sent.e[j]); ++word_translation[pair<WordID,WordID> (sent.f[i], sent.e[j])]; ++total_foreign[sent.f[i]]; ++total_english[sent.e[j]]; } } if (DEBUG) cerr << endl; } if (DEBUG) cerr << endl; static const WordID NULL_ = TD::Convert("NULL"); //handle unaligned words - align them to null for (int j =0; j < sent.e_len; j++) { if (sent.e_aligned[j]) continue; ++word_translation[pair<WordID,WordID> (NULL_, sent.e[j])]; ++total_foreign[NULL_]; ++total_english[sent.e[j]]; } for (int i =0; i < sent.f_len; i++) { if (sent.f_aligned[i]) continue; ++word_translation[pair<WordID,WordID> (sent.f[i], NULL_)]; ++total_english[NULL_]; ++total_foreign[sent.f[i]]; } } inline float safenlog(float v) { if (v == 1.0f) return 0.0f; float res = -log(v); if (res > 100.0f) res = 100.0f; return res; } int main(int argc, char** argv){ bool DEBUG= false; if (argc != 2) { cerr << "Usage: " << argv[0] << " corpus.al < filtered.grammar\n"; return 1; } ifstream alignment (argv[1]); istream& unscored_grammar = cin; ostream& scored_grammar = cout; //create lexical translation table cerr << "Creating table..." << endl; char* buf = new char[MAX_LINE_LENGTH]; LexTranslationTable table; while(!alignment.eof()) { alignment.getline(buf, MAX_LINE_LENGTH); if (buf[0] == 0) continue; table.createTTable(buf); } bool PRINT_TABLE=false; if (PRINT_TABLE) { ofstream trans_table; trans_table.open("lex_trans_table.out"); for(map < pair<WordID,WordID>,int >::iterator it = table.word_translation.begin(); it != table.word_translation.end(); ++it) { trans_table << TD::Convert(it->first.first) << "|||" << TD::Convert(it->first.second) << "==" << it->second << "//" << table.total_foreign[it->first.first] << "//" << table.total_english[it->first.second] << endl; } trans_table.close(); } //score unscored grammar cerr <<"Scoring grammar..." << endl; ID2RuleStatistics acc, cur_counts; vector<WordID> key, cur_key,temp_key; vector< pair<short,short> > al; vector< pair<short,short> >::iterator ita; int line = 0; static const int kCF = FD::Convert("CF"); static const int kCE = FD::Convert("CE"); static const int kCFE = FD::Convert("CFE"); while(!unscored_grammar.eof()) { ++line; unscored_grammar.getline(buf, MAX_LINE_LENGTH); if (buf[0] == 0) continue; ParseLine(buf, &cur_key, &cur_counts); //loop over all the Target side phrases that this source aligns to for (ID2RuleStatistics::const_iterator it = cur_counts.begin(); it != cur_counts.end(); ++it) { /*Compute phrase translation prob. Print out scores in this format: Phrase trnaslation prob P(F|E) Phrase translation prob P(E|F) Lexical weighting prob lex(F|E) Lexical weighting prob lex(E|F) */ float pEF_ = it->second.counts.value(kCFE) / it->second.counts.value(kCF); float pFE_ = it->second.counts.value(kCFE) / it->second.counts.value(kCE); map <WordID, pair<int, float> > foreign_aligned; map <WordID, pair<int, float> > english_aligned; //Loop over all the alignment points to compute lexical translation probability al = it->second.aligns; for(ita = al.begin(); ita != al.end(); ++ita) { if (DEBUG) { cerr << "\nA:" << ita->first << "," << ita->second << "::"; cerr << TD::Convert(cur_key[ita->first + 2]) << "-" << TD::Convert(it->first[ita->second]); } //Lookup this alignment probability in the table int temp = table.word_translation[pair<WordID,WordID> (cur_key[ita->first+2],it->first[ita->second])]; float f2e=0, e2f=0; if ( table.total_foreign[cur_key[ita->first+2]] != 0) f2e = (float) temp / table.total_foreign[cur_key[ita->first+2]]; if ( table.total_english[it->first[ita->second]] !=0 ) e2f = (float) temp / table.total_english[it->first[ita->second]]; if (DEBUG) printf (" %d %E %E\n", temp, f2e, e2f); //local counts to keep track of which things haven't been aligned, to later compute their null alignment if (foreign_aligned.count(cur_key[ita->first+2])) { foreign_aligned[ cur_key[ita->first+2] ].first++; foreign_aligned[ cur_key[ita->first+2] ].second += e2f; } else foreign_aligned [ cur_key[ita->first+2] ] = pair<int,float> (1,e2f); if (english_aligned.count( it->first[ ita->second] )) { english_aligned[ it->first[ ita->second ]].first++; english_aligned[ it->first[ ita->second] ].second += f2e; } else english_aligned [ it->first[ ita->second] ] = pair<int,float> (1,f2e); } float final_lex_f2e=1, final_lex_e2f=1; static const WordID NULL_ = TD::Convert("NULL"); //compute lexical weight P(F|E) and include unaligned foreign words for(int i=0;i<cur_key.size(); i++) { if (!table.total_foreign.count(cur_key[i])) continue; //if we dont have it in the translation table, we won't know its lexical weight if (foreign_aligned.count(cur_key[i])) { pair<int, float> temp_lex_prob = foreign_aligned[cur_key[i]]; final_lex_e2f *= temp_lex_prob.second / temp_lex_prob.first; } else //dealing with null alignment { int temp_count = table.word_translation[pair<WordID,WordID> (cur_key[i],NULL_)]; float temp_e2f = (float) temp_count / table.total_english[NULL_]; final_lex_e2f *= temp_e2f; } } //compute P(E|F) unaligned english words for(int j=0; j< it->first.size(); j++) { if (!table.total_english.count(it->first[j])) continue; if (english_aligned.count(it->first[j])) { pair<int, float> temp_lex_prob = english_aligned[it->first[j]]; final_lex_f2e *= temp_lex_prob.second / temp_lex_prob.first; } else //dealing with null { int temp_count = table.word_translation[pair<WordID,WordID> (NULL_,it->first[j])]; float temp_f2e = (float) temp_count / table.total_foreign[NULL_]; final_lex_f2e *= temp_f2e; } } scored_grammar << TD::GetString(cur_key); scored_grammar << " " << TD::GetString(it->first) << " |||"; scored_grammar << " " << safenlog(pFE_) << " " << safenlog(pEF_); scored_grammar << " " << safenlog(final_lex_e2f) << " " << safenlog(final_lex_f2e) << endl; } } } <commit_msg>use named features<commit_after>/* * Score a grammar in striped format * ./score_grammar <alignment> < filtered.grammar > scored.grammar */ #include <iostream> #include <string> #include <map> #include <vector> #include <utility> #include <cstdlib> #include <fstream> #include <tr1/unordered_map> #include "sentence_pair.h" #include "extract.h" #include "fdict.h" #include "tdict.h" #include "lex_trans_tbl.h" #include "filelib.h" #include <boost/functional/hash.hpp> #include <boost/program_options.hpp> #include <boost/program_options/variables_map.hpp> using namespace std; using namespace std::tr1; static const size_t MAX_LINE_LENGTH = 64000000; typedef unordered_map<vector<WordID>, RuleStatistics, boost::hash<vector<WordID> > > ID2RuleStatistics; namespace { inline bool IsWhitespace(char c) { return c == ' ' || c == '\t'; } inline bool IsBracket(char c){return c == '[' || c == ']';} inline void SkipWhitespace(const char* buf, int* ptr) { while (buf[*ptr] && IsWhitespace(buf[*ptr])) { ++(*ptr); } } } int ReadPhraseUntilDividerOrEnd(const char* buf, const int sstart, const int end, vector<WordID>* p) { static const WordID kDIV = TD::Convert("|||"); int ptr = sstart; while(ptr < end) { while(ptr < end && IsWhitespace(buf[ptr])) { ++ptr; } int start = ptr; while(ptr < end && !IsWhitespace(buf[ptr])) { ++ptr; } if (ptr == start) {cerr << "Warning! empty token.\n"; return ptr; } const WordID w = TD::Convert(string(buf, start, ptr - start)); if((IsBracket(buf[start]) and IsBracket(buf[ptr-1])) or( w == kDIV)) p->push_back(1 * w); else { if (w == kDIV) return ptr; p->push_back(w); } } return ptr; } void ParseLine(const char* buf, vector<WordID>* cur_key, ID2RuleStatistics* counts) { static const WordID kDIV = TD::Convert("|||"); counts->clear(); int ptr = 0; while(buf[ptr] != 0 && buf[ptr] != '\t') { ++ptr; } if (buf[ptr] != '\t') { cerr << "Missing tab separator between key and value!\n INPUT=" << buf << endl; exit(1); } cur_key->clear(); // key is: "[X] ||| word word word" int tmpp = ReadPhraseUntilDividerOrEnd(buf, 0, ptr, cur_key); cur_key->push_back(kDIV); ReadPhraseUntilDividerOrEnd(buf, tmpp, ptr, cur_key); ++ptr; int start = ptr; int end = ptr; int state = 0; // 0=reading label, 1=reading count vector<WordID> name; while(buf[ptr] != 0) { while(buf[ptr] != 0 && buf[ptr] != '|') { ++ptr; } if (buf[ptr] == '|') { ++ptr; if (buf[ptr] == '|') { ++ptr; if (buf[ptr] == '|') { ++ptr; end = ptr - 3; while (end > start && IsWhitespace(buf[end-1])) { --end; } if (start == end) { cerr << "Got empty token!\n LINE=" << buf << endl; exit(1); } switch (state) { case 0: ++state; name.clear(); ReadPhraseUntilDividerOrEnd(buf, start, end, &name); break; case 1: --state; (*counts)[name].ParseRuleStatistics(buf, start, end); break; default: cerr << "Can't happen\n"; abort(); } SkipWhitespace(buf, &ptr); start = ptr; } } } } end=ptr; while (end > start && IsWhitespace(buf[end-1])) { --end; } if (end > start) { switch (state) { case 0: ++state; name.clear(); ReadPhraseUntilDividerOrEnd(buf, start, end, &name); break; case 1: --state; (*counts)[name].ParseRuleStatistics(buf, start, end); break; default: cerr << "Can't happen\n"; abort(); } } } void LexTranslationTable::createTTable(const char* buf){ bool DEBUG = false; AnnotatedParallelSentence sent; sent.ParseInputLine(buf); //iterate over the alignment to compute aligned words for(int i =0;i<sent.aligned.width();i++) { for (int j=0;j<sent.aligned.height();j++) { if (DEBUG) cerr << sent.aligned(i,j) << " "; if( sent.aligned(i,j)) { if (DEBUG) cerr << TD::Convert(sent.f[i]) << " aligned to " << TD::Convert(sent.e[j]); ++word_translation[pair<WordID,WordID> (sent.f[i], sent.e[j])]; ++total_foreign[sent.f[i]]; ++total_english[sent.e[j]]; } } if (DEBUG) cerr << endl; } if (DEBUG) cerr << endl; static const WordID NULL_ = TD::Convert("NULL"); //handle unaligned words - align them to null for (int j =0; j < sent.e_len; j++) { if (sent.e_aligned[j]) continue; ++word_translation[pair<WordID,WordID> (NULL_, sent.e[j])]; ++total_foreign[NULL_]; ++total_english[sent.e[j]]; } for (int i =0; i < sent.f_len; i++) { if (sent.f_aligned[i]) continue; ++word_translation[pair<WordID,WordID> (sent.f[i], NULL_)]; ++total_english[NULL_]; ++total_foreign[sent.f[i]]; } } inline float safenlog(float v) { if (v == 1.0f) return 0.0f; float res = -log(v); if (res > 100.0f) res = 100.0f; return res; } int main(int argc, char** argv){ bool DEBUG= false; if (argc != 2) { cerr << "Usage: " << argv[0] << " corpus.al < filtered.grammar\n"; return 1; } ifstream alignment (argv[1]); istream& unscored_grammar = cin; ostream& scored_grammar = cout; //create lexical translation table cerr << "Creating table..." << endl; char* buf = new char[MAX_LINE_LENGTH]; LexTranslationTable table; while(!alignment.eof()) { alignment.getline(buf, MAX_LINE_LENGTH); if (buf[0] == 0) continue; table.createTTable(buf); } bool PRINT_TABLE=false; if (PRINT_TABLE) { ofstream trans_table; trans_table.open("lex_trans_table.out"); for(map < pair<WordID,WordID>,int >::iterator it = table.word_translation.begin(); it != table.word_translation.end(); ++it) { trans_table << TD::Convert(it->first.first) << "|||" << TD::Convert(it->first.second) << "==" << it->second << "//" << table.total_foreign[it->first.first] << "//" << table.total_english[it->first.second] << endl; } trans_table.close(); } //score unscored grammar cerr <<"Scoring grammar..." << endl; ID2RuleStatistics acc, cur_counts; vector<WordID> key, cur_key,temp_key; vector< pair<short,short> > al; vector< pair<short,short> >::iterator ita; int line = 0; static const int kCF = FD::Convert("CF"); static const int kCE = FD::Convert("CE"); static const int kCFE = FD::Convert("CFE"); while(!unscored_grammar.eof()) { ++line; unscored_grammar.getline(buf, MAX_LINE_LENGTH); if (buf[0] == 0) continue; ParseLine(buf, &cur_key, &cur_counts); //loop over all the Target side phrases that this source aligns to for (ID2RuleStatistics::const_iterator it = cur_counts.begin(); it != cur_counts.end(); ++it) { /*Compute phrase translation prob. Print out scores in this format: Phrase trnaslation prob P(F|E) Phrase translation prob P(E|F) Lexical weighting prob lex(F|E) Lexical weighting prob lex(E|F) */ float pEF_ = it->second.counts.value(kCFE) / it->second.counts.value(kCF); float pFE_ = it->second.counts.value(kCFE) / it->second.counts.value(kCE); map <WordID, pair<int, float> > foreign_aligned; map <WordID, pair<int, float> > english_aligned; //Loop over all the alignment points to compute lexical translation probability al = it->second.aligns; for(ita = al.begin(); ita != al.end(); ++ita) { if (DEBUG) { cerr << "\nA:" << ita->first << "," << ita->second << "::"; cerr << TD::Convert(cur_key[ita->first + 2]) << "-" << TD::Convert(it->first[ita->second]); } //Lookup this alignment probability in the table int temp = table.word_translation[pair<WordID,WordID> (cur_key[ita->first+2],it->first[ita->second])]; float f2e=0, e2f=0; if ( table.total_foreign[cur_key[ita->first+2]] != 0) f2e = (float) temp / table.total_foreign[cur_key[ita->first+2]]; if ( table.total_english[it->first[ita->second]] !=0 ) e2f = (float) temp / table.total_english[it->first[ita->second]]; if (DEBUG) printf (" %d %E %E\n", temp, f2e, e2f); //local counts to keep track of which things haven't been aligned, to later compute their null alignment if (foreign_aligned.count(cur_key[ita->first+2])) { foreign_aligned[ cur_key[ita->first+2] ].first++; foreign_aligned[ cur_key[ita->first+2] ].second += e2f; } else foreign_aligned [ cur_key[ita->first+2] ] = pair<int,float> (1,e2f); if (english_aligned.count( it->first[ ita->second] )) { english_aligned[ it->first[ ita->second ]].first++; english_aligned[ it->first[ ita->second] ].second += f2e; } else english_aligned [ it->first[ ita->second] ] = pair<int,float> (1,f2e); } float final_lex_f2e=1, final_lex_e2f=1; static const WordID NULL_ = TD::Convert("NULL"); //compute lexical weight P(F|E) and include unaligned foreign words for(int i=0;i<cur_key.size(); i++) { if (!table.total_foreign.count(cur_key[i])) continue; //if we dont have it in the translation table, we won't know its lexical weight if (foreign_aligned.count(cur_key[i])) { pair<int, float> temp_lex_prob = foreign_aligned[cur_key[i]]; final_lex_e2f *= temp_lex_prob.second / temp_lex_prob.first; } else //dealing with null alignment { int temp_count = table.word_translation[pair<WordID,WordID> (cur_key[i],NULL_)]; float temp_e2f = (float) temp_count / table.total_english[NULL_]; final_lex_e2f *= temp_e2f; } } //compute P(E|F) unaligned english words for(int j=0; j< it->first.size(); j++) { if (!table.total_english.count(it->first[j])) continue; if (english_aligned.count(it->first[j])) { pair<int, float> temp_lex_prob = english_aligned[it->first[j]]; final_lex_f2e *= temp_lex_prob.second / temp_lex_prob.first; } else //dealing with null { int temp_count = table.word_translation[pair<WordID,WordID> (NULL_,it->first[j])]; float temp_f2e = (float) temp_count / table.total_foreign[NULL_]; final_lex_f2e *= temp_f2e; } } scored_grammar << TD::GetString(cur_key); scored_grammar << " " << TD::GetString(it->first) << " |||"; scored_grammar << " FGivenE=" << safenlog(pFE_) << " EGivenF=" << safenlog(pEF_); scored_grammar << " LexE2F=" << safenlog(final_lex_e2f) << " LexF2E=" << safenlog(final_lex_f2e) << endl; } } } <|endoftext|>
<commit_before>#include "array.h" #include "test.h" namespace array { TEST(array_1d) { auto A = make_dense_array<int>(10); for_all_indices(A.shape(), [&](int x) { A(x) = x; }); auto B = make_dense_array<int>(10); B = A; for_all_indices(B.shape(), [&](int x) { ASSERT_EQ(B(x), x); }); } TEST(array_2d) { auto A = make_dense_array<int>(10, 5); for_all_indices(A.shape(), [&](int x, int y) { A(x, y) = y * 100 + x; }); auto B = make_dense_array<int>(10, 5); B = A; for_all_indices(B.shape(), [&](int x, int y) { ASSERT_EQ(B(x, y), y * 100 + x); }); } } // namespace array <commit_msg>Add more tests of array.<commit_after>#include "array.h" #include "test.h" namespace array { shape<dim<>, dim<>> make_2d_shape(const dim<>& x, const dim<>& y) { return {x, y}; } typedef array<int, shape<dense_dim<>>> array_1d; typedef array<int, shape<dense_dim<>, dim<>>> array_2d; typedef array<int, shape<dense_dim<>, dim<>, dim<>>> array_3d; TEST(array_default_constructor) { array_1d a(make_dense_shape(10)); for (int x = 0; x < 10; x++) { ASSERT_EQ(a(x), 0); } array_2d b(make_dense_shape(7, 3)); for (int y = 0; y < 3; y++) { for (int x = 0; x < 7; x++) { ASSERT_EQ(b(x, y), 0); } } array_3d c(make_dense_shape(5, 9, 3)); for (int z = 0; z < 3; z++) { for (int y = 0; y < 9; y++) { for (int x = 0; x < 5; x++) { ASSERT_EQ(c(x, y, z), 0); } } } auto sparse_shape = make_shape(dim<>(-2, 5, 2), dim<>(4, 10, 20)); array<int, shape<dim<>, dim<>>> sparse(sparse_shape); for (int y = 4; y < 14; y++) { for (int x = -2; x < 3; x++) { ASSERT_EQ(sparse(x, y), 0); } } } TEST(array_fill_constructor) { array_1d a(make_dense_shape(10), 3); for (int x = 0; x < 10; x++) { ASSERT_EQ(a(x), 3); } array_2d b(make_dense_shape(7, 3), 5); for (int y = 0; y < 3; y++) { for (int x = 0; x < 7; x++) { ASSERT_EQ(b(x, y), 5); } } array_3d c(make_dense_shape(5, 9, 3), 7); for (int z = 0; z < 3; z++) { for (int y = 0; y < 9; y++) { for (int x = 0; x < 5; x++) { ASSERT_EQ(c(x, y, z), 7); } } } auto sparse_shape = make_shape(dim<>(-2, 5, 2), dim<>(4, 10, 20)); array<int, shape<dim<>, dim<>>> sparse(sparse_shape, 13); for (int y = 4; y < 14; y++) { for (int x = -2; x < 3; x++) { ASSERT_EQ(sparse(x, y), 13); } } } TEST(array_fill_assign) { array_1d a; a.assign(make_dense_shape(10), 3); for (int x = 0; x < 10; x++) { ASSERT_EQ(a(x), 3); } array_2d b; b.assign(make_dense_shape(7, 3), 5); for (int y = 0; y < 3; y++) { for (int x = 0; x < 7; x++) { ASSERT_EQ(b(x, y), 5); } } array_3d c; c.assign(make_dense_shape(5, 9, 3), 7); for (int z = 0; z < 3; z++) { for (int y = 0; y < 9; y++) { for (int x = 0; x < 5; x++) { ASSERT_EQ(c(x, y, z), 7); } } } array<int, shape<dim<>, dim<>>> sparse; auto sparse_shape = make_shape(dim<>(-2, 5, 2), dim<>(4, 10, 20)); sparse.assign(sparse_shape, 13); for (int y = 4; y < 14; y++) { for (int x = -2; x < 3; x++) { ASSERT_EQ(sparse(x, y), 13); } } } TEST(sparse_array) { auto sparse_shape = make_shape(dim<>(-2, 5, 2), dim<>(4, 10, 20)); array<int, shape<dim<>, dim<>>> sparse(sparse_shape); // Fill the storage with a constant. for (int i = 0; i < sparse_shape.flat_extent(); i++) { sparse.data()[i] = 7; } // Assign a different constant. sparse.assign(sparse_shape, 3); // Check that we assigned all of the elements of the array. for (int y = 4; y < 14; y++) { for (int x = -2; x < 3; x++) { ASSERT_EQ(sparse(x, y), 3); } } // Check that only the elements of the array were assigned. int threes = 0; for (int i = 0; i < sparse_shape.flat_extent(); i++) { if (sparse.data()[i] == 3) { threes++; } } ASSERT_EQ(threes, sparse.size()); } } // namespace array <|endoftext|>
<commit_before>/* vim: set sw=4 sts=4 et foldmethod=syntax : */ #include <max_clique/dbmcsa_max_clique.hh> #include <max_clique/colourise.hh> #include <max_clique/print_incumbent.hh> #include <graph/degree_sort.hh> #include <graph/min_width_sort.hh> #include <algorithm> using namespace parasols; namespace { template <unsigned size_> auto expand( const FixedBitGraph<size_> & graph, const std::vector<int> & o, // vertex ordering const std::array<unsigned, size_ * bits_per_word> & p_order, const std::array<unsigned, size_ * bits_per_word> & colours, FixedBitSet<size_> & c, // current candidate clique FixedBitSet<size_> & p, // potential additions MaxCliqueResult & result, const MaxCliqueParams & params, std::vector<int> & position ) -> void { auto c_popcount = c.popcount(); int n = p.popcount() - 1; // bound, timeout or early exit? if (c_popcount + colours[n] <= result.size || result.size >= params.stop_after_finding || params.abort.load()) return; auto v = p_order[n]; // consider taking v c.set(v); ++c_popcount; ++position.back(); // filter p to contain vertices adjacent to v FixedBitSet<size_> new_p = p; graph.intersect_with_row(v, new_p); if (new_p.empty()) { // potential new best if (c_popcount > result.size) { result.size = c_popcount; result.members.clear(); for (int i = 0 ; i < graph.size() ; ++i) if (c.test(i)) result.members.insert(o[i]); print_incumbent(params, c_popcount, position); } } else { // get our coloured vertices ++result.nodes; std::array<unsigned, size_ * bits_per_word> new_p_order, new_colours; colourise<size_>(graph, new_p, new_p_order, new_colours); position.push_back(0); expand<size_>(graph, o, new_p_order, new_colours, c, new_p, result, params, position); position.pop_back(); } // now consider not taking v c.unset(v); p.unset(v); --c_popcount; if (n > 0) { expand<size_>(graph, o, p_order, colours, c, p, result, params, position); } } template <MaxCliqueOrder order_, unsigned size_> auto dbmcsa(const Graph & graph, const MaxCliqueParams & params) -> MaxCliqueResult { MaxCliqueResult result; result.size = params.initial_bound; std::vector<int> o(graph.size()); // vertex ordering FixedBitSet<size_> c; // current candidate clique c.resize(graph.size()); FixedBitSet<size_> p; // potential additions p.resize(graph.size()); p.set_all(); // populate our order with every vertex initially std::iota(o.begin(), o.end(), 0); switch (order_) { case MaxCliqueOrder::Degree: degree_sort(graph, o, false); break; case MaxCliqueOrder::MinWidth: min_width_sort(graph, o, false); break; case MaxCliqueOrder::ExDegree: exdegree_sort(graph, o, false); break; case MaxCliqueOrder::DynExDegree: dynexdegree_sort(graph, o, false); break; } // re-encode graph as a bit graph FixedBitGraph<size_> bit_graph; bit_graph.resize(graph.size()); for (int i = 0 ; i < graph.size() ; ++i) for (int j = 0 ; j < graph.size() ; ++j) if (graph.adjacent(o[i], o[j])) bit_graph.add_edge(i, j); std::vector<int> positions; positions.reserve(graph.size()); positions.push_back(0); // initial ordering ++result.nodes; std::array<unsigned, size_ * bits_per_word> new_p_order, new_colours; colourise<size_>(bit_graph, p, new_p_order, new_colours); // go! expand<size_>(bit_graph, o, new_p_order, new_colours, c, p, result, params, positions); return result; } } template <MaxCliqueOrder order_> auto parasols::dbmcsa_max_clique(const Graph & graph, const MaxCliqueParams & params) -> MaxCliqueResult { /* This is pretty horrible: in order to avoid dynamic allocation, select * the appropriate specialisation for our graph's size. */ static_assert(max_graph_words == 1024, "Need to update here if max_graph_size is changed."); if (graph.size() < bits_per_word) return dbmcsa<order_, 1>(graph, params); else if (graph.size() < 2 * bits_per_word) return dbmcsa<order_, 2>(graph, params); else if (graph.size() < 4 * bits_per_word) return dbmcsa<order_, 4>(graph, params); else if (graph.size() < 8 * bits_per_word) return dbmcsa<order_, 8>(graph, params); else if (graph.size() < 16 * bits_per_word) return dbmcsa<order_, 16>(graph, params); else if (graph.size() < 32 * bits_per_word) return dbmcsa<order_, 32>(graph, params); else if (graph.size() < 64 * bits_per_word) return dbmcsa<order_, 64>(graph, params); else if (graph.size() < 128 * bits_per_word) return dbmcsa<order_, 128>(graph, params); else if (graph.size() < 256 * bits_per_word) return dbmcsa<order_, 256>(graph, params); else if (graph.size() < 512 * bits_per_word) return dbmcsa<order_, 512>(graph, params); else if (graph.size() < 1024 * bits_per_word) return dbmcsa<order_, 1024>(graph, params); else throw GraphTooBig(); } template auto parasols::dbmcsa_max_clique<MaxCliqueOrder::Degree>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult; template auto parasols::dbmcsa_max_clique<MaxCliqueOrder::MinWidth>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult; template auto parasols::dbmcsa_max_clique<MaxCliqueOrder::ExDegree>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult; template auto parasols::dbmcsa_max_clique<MaxCliqueOrder::DynExDegree>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult; <commit_msg>Implement defers<commit_after>/* vim: set sw=4 sts=4 et foldmethod=syntax : */ #include <max_clique/dbmcsa_max_clique.hh> #include <max_clique/colourise.hh> #include <max_clique/print_incumbent.hh> #include <graph/degree_sort.hh> #include <graph/min_width_sort.hh> #include <algorithm> using namespace parasols; namespace { template <unsigned size_> struct Defer { std::array<unsigned, size_ * bits_per_word> p_order; std::array<unsigned, size_ * bits_per_word> colours; FixedBitSet<size_> c; FixedBitSet<size_> p; std::vector<int> positions; }; template <unsigned size_> auto expand( const FixedBitGraph<size_> & graph, const std::vector<int> & o, // vertex ordering const std::array<unsigned, size_ * bits_per_word> & p_order, const std::array<unsigned, size_ * bits_per_word> & colours, FixedBitSet<size_> & c, // current candidate clique FixedBitSet<size_> & p, // potential additions MaxCliqueResult & result, const MaxCliqueParams & params, std::vector<int> & positions, bool already_split ) -> void { auto c_popcount = c.popcount(); int n = p.popcount() - 1; // bound, timeout or early exit? if (c_popcount + colours[n] <= result.size || result.size >= params.stop_after_finding || params.abort.load()) return; auto v = p_order[n]; ++positions.back(); // consider taking v c.set(v); ++c_popcount; // filter p to contain vertices adjacent to v FixedBitSet<size_> new_p = p; graph.intersect_with_row(v, new_p); if (new_p.empty()) { // potential new best if (c_popcount > result.size) { result.size = c_popcount; result.members.clear(); for (int i = 0 ; i < graph.size() ; ++i) if (c.test(i)) result.members.insert(o[i]); print_incumbent(params, c_popcount, positions); } } else { // get our coloured vertices ++result.nodes; std::array<unsigned, size_ * bits_per_word> new_p_order, new_colours; colourise<size_>(graph, new_p, new_p_order, new_colours); positions.push_back(0); expand<size_>(graph, o, new_p_order, new_colours, c, new_p, result, params, positions, false); positions.pop_back(); } if (! already_split) { // now consider not taking v c.unset(v); p.unset(v); --c_popcount; if (n > 0) { expand<size_>(graph, o, p_order, colours, c, p, result, params, positions, false); } } } template <MaxCliqueOrder order_, unsigned size_> auto dbmcsa(const Graph & graph, const MaxCliqueParams & params) -> MaxCliqueResult { MaxCliqueResult result; result.size = params.initial_bound; std::vector<int> o(graph.size()); // vertex ordering FixedBitSet<size_> c; // current candidate clique c.resize(graph.size()); FixedBitSet<size_> p; // potential additions p.resize(graph.size()); p.set_all(); // populate our order with every vertex initially std::iota(o.begin(), o.end(), 0); switch (order_) { case MaxCliqueOrder::Degree: degree_sort(graph, o, false); break; case MaxCliqueOrder::MinWidth: min_width_sort(graph, o, false); break; case MaxCliqueOrder::ExDegree: exdegree_sort(graph, o, false); break; case MaxCliqueOrder::DynExDegree: dynexdegree_sort(graph, o, false); break; } // re-encode graph as a bit graph FixedBitGraph<size_> bit_graph; bit_graph.resize(graph.size()); for (int i = 0 ; i < graph.size() ; ++i) for (int j = 0 ; j < graph.size() ; ++j) if (graph.adjacent(o[i], o[j])) bit_graph.add_edge(i, j); std::vector<int> positions; positions.reserve(graph.size()); positions.push_back(0); // initial ordering ++result.nodes; std::array<unsigned, size_ * bits_per_word> new_p_order, new_colours; colourise<size_>(bit_graph, p, new_p_order, new_colours); // first job Defer<size_> next_job{ new_p_order, new_colours, c, p, positions }; // go! while (! next_job.p.empty()) { // split Defer<size_> job = next_job; ++next_job.positions.back(); auto v = next_job.p_order[next_job.p.popcount() - 1]; next_job.c.unset(v); next_job.p.unset(v); expand<size_>(bit_graph, o, job.p_order, job.colours, job.c, job.p, result, params, job.positions, true); } return result; } } template <MaxCliqueOrder order_> auto parasols::dbmcsa_max_clique(const Graph & graph, const MaxCliqueParams & params) -> MaxCliqueResult { /* This is pretty horrible: in order to avoid dynamic allocation, select * the appropriate specialisation for our graph's size. */ static_assert(max_graph_words == 1024, "Need to update here if max_graph_size is changed."); if (graph.size() < bits_per_word) return dbmcsa<order_, 1>(graph, params); else if (graph.size() < 2 * bits_per_word) return dbmcsa<order_, 2>(graph, params); else if (graph.size() < 4 * bits_per_word) return dbmcsa<order_, 4>(graph, params); else if (graph.size() < 8 * bits_per_word) return dbmcsa<order_, 8>(graph, params); else if (graph.size() < 16 * bits_per_word) return dbmcsa<order_, 16>(graph, params); else if (graph.size() < 32 * bits_per_word) return dbmcsa<order_, 32>(graph, params); else if (graph.size() < 64 * bits_per_word) return dbmcsa<order_, 64>(graph, params); else if (graph.size() < 128 * bits_per_word) return dbmcsa<order_, 128>(graph, params); else if (graph.size() < 256 * bits_per_word) return dbmcsa<order_, 256>(graph, params); else if (graph.size() < 512 * bits_per_word) return dbmcsa<order_, 512>(graph, params); else if (graph.size() < 1024 * bits_per_word) return dbmcsa<order_, 1024>(graph, params); else throw GraphTooBig(); } template auto parasols::dbmcsa_max_clique<MaxCliqueOrder::Degree>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult; template auto parasols::dbmcsa_max_clique<MaxCliqueOrder::MinWidth>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult; template auto parasols::dbmcsa_max_clique<MaxCliqueOrder::ExDegree>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult; template auto parasols::dbmcsa_max_clique<MaxCliqueOrder::DynExDegree>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult; <|endoftext|>
<commit_before>#include "scriptcompilerwidget.h" #include "ui_scriptcompilerwidget.h" #include <qfilesystemmodel.h> #include "scriptcompiler.h" ScriptCompilerWidget::ScriptCompilerWidget(QWidget* parent) : QDockWidget(parent), m_ui(new Ui::ScriptCompilerWidget) { m_ui->setupUi(this); m_model = new QFileSystemModel; m_model->setRootPath(QDir::currentPath() + "/scripts/"); m_base_path = QDir::currentPath().toLatin1().data(); QStringList filters; filters << "*.cpp"; m_model->setNameFilterDisables(false); m_model->setNameFilters(filters); m_ui->scriptListView->setModel(m_model); m_ui->scriptListView->setRootIndex(m_model->index(QDir::currentPath() + "/scripts/")); m_compiler = new ScriptCompiler; connect(m_compiler, SIGNAL(messageLogged(const QString&)), this, SLOT(logMessage(const QString&))); m_compiler->setBasePath(m_base_path.c_str()); m_compiler->compileAll(); } ScriptCompilerWidget::~ScriptCompilerWidget() { delete m_ui; delete m_model; } void ScriptCompilerWidget::logMessage(const QString& message) { m_ui->logView->addItem(message); } void ScriptCompilerWidget::on_scriptListView_clicked(const QModelIndex &index) { QString path = m_model->filePath(index); const char* c = m_compiler->getLog(path.toLatin1().data()); m_ui->compilerOutputView->setText(c); } void ScriptCompilerWidget::on_compileAllButton_clicked() { m_compiler->compileAll(); } <commit_msg>memory leaks fixed<commit_after>#include "scriptcompilerwidget.h" #include "ui_scriptcompilerwidget.h" #include <qfilesystemmodel.h> #include "scriptcompiler.h" ScriptCompilerWidget::ScriptCompilerWidget(QWidget* parent) : QDockWidget(parent), m_ui(new Ui::ScriptCompilerWidget) { m_ui->setupUi(this); m_model = new QFileSystemModel; m_model->setRootPath(QDir::currentPath() + "/scripts/"); m_base_path = QDir::currentPath().toLatin1().data(); QStringList filters; filters << "*.cpp"; m_model->setNameFilterDisables(false); m_model->setNameFilters(filters); m_ui->scriptListView->setModel(m_model); m_ui->scriptListView->setRootIndex(m_model->index(QDir::currentPath() + "/scripts/")); m_compiler = new ScriptCompiler; connect(m_compiler, SIGNAL(messageLogged(const QString&)), this, SLOT(logMessage(const QString&))); m_compiler->setBasePath(m_base_path.c_str()); m_compiler->compileAll(); } ScriptCompilerWidget::~ScriptCompilerWidget() { delete m_compiler; delete m_ui; delete m_model; } void ScriptCompilerWidget::logMessage(const QString& message) { m_ui->logView->addItem(message); } void ScriptCompilerWidget::on_scriptListView_clicked(const QModelIndex &index) { QString path = m_model->filePath(index); const char* c = m_compiler->getLog(path.toLatin1().data()); m_ui->compilerOutputView->setText(c); } void ScriptCompilerWidget::on_compileAllButton_clicked() { m_compiler->compileAll(); } <|endoftext|>
<commit_before> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010 Francois Beaune // // 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. // // Interface header. #include "assemblyitem.h" // appleseed.studio headers. #include "mainwindow/project/colorcollectionitem.h" #include "mainwindow/project/lightcollectionitem.h" #include "mainwindow/project/multimodelcollectionitem.h" #include "mainwindow/project/objectcollectionitem.h" #include "mainwindow/project/objectinstancecollectionitem.h" #include "mainwindow/project/projectbuilder.h" #include "mainwindow/project/projecttree.h" #include "mainwindow/project/singlemodelcollectionitem.h" #include "mainwindow/project/texturecollectionitem.h" #include "mainwindow/project/textureinstancecollectionitem.h" #include "mainwindow/project/tools.h" // appleseed.renderer headers. #include "renderer/api/bsdf.h" #include "renderer/api/color.h" #include "renderer/api/edf.h" #include "renderer/api/entity.h" #include "renderer/api/light.h" #include "renderer/api/material.h" #include "renderer/api/object.h" #include "renderer/api/scene.h" #include "renderer/api/surfaceshader.h" #include "renderer/api/texture.h" // appleseed.foundation headers. #include "foundation/utility/uid.h" // Qt headers. #include <QFileDialog> #include <QMenu> #include <QString> #include <QStringList> // Standard headers. #include <string> using namespace foundation; using namespace renderer; using namespace std; namespace appleseed { namespace studio { AssemblyItem::AssemblyItem( Scene& scene, Assembly& assembly, ProjectBuilder& project_builder) : ItemBase(assembly.get_class_uid(), assembly.get_name()) , m_scene(scene) , m_assembly(assembly) , m_project_builder(project_builder) { m_color_collection_item = add_collection_item(assembly.colors()); m_texture_collection_item = add_collection_item(assembly.textures()); m_texture_instance_collection_item = add_collection_item(assembly.texture_instances()); m_bsdf_collection_item = add_multi_model_collection_item<BSDF>(assembly.bsdfs()); m_edf_collection_item = add_multi_model_collection_item<EDF>(assembly.edfs()); m_surface_shader_collection_item = add_multi_model_collection_item<SurfaceShader>(assembly.surface_shaders()); m_material_collection_item = add_single_model_collection_item<Material>(assembly.materials()); m_light_collection_item = add_collection_item(assembly.lights()); m_object_collection_item = add_collection_item(assembly.objects()); m_object_instance_collection_item = add_collection_item(assembly.object_instances()); } QMenu* AssemblyItem::get_single_item_context_menu() const { QMenu* menu = ItemBase::get_single_item_context_menu(); menu->addSeparator(); menu->addAction("Instantiate...", this, SLOT(slot_instantiate())); menu->addSeparator(); menu->addAction("Import Objects...", m_object_collection_item, SLOT(slot_import_objects())); menu->addAction("Import Textures...", m_texture_collection_item, SLOT(slot_import_textures())); menu->addSeparator(); menu->addAction("Create BSDF...", m_bsdf_collection_item, SLOT(slot_create())); menu->addAction("Create EDF...", m_edf_collection_item, SLOT(slot_create())); menu->addAction("Create Surface Shader...", m_surface_shader_collection_item, SLOT(slot_create())); menu->addAction("Create Material...", m_material_collection_item, SLOT(slot_create_material())); return menu; } void AssemblyItem::add_item(ColorEntity* color) { m_color_collection_item->add_item(color); } void AssemblyItem::add_item(Texture* texture) { m_texture_collection_item->add_item(texture); } void AssemblyItem::add_item(TextureInstance* texture_instance) { m_texture_instance_collection_item->add_item(texture_instance); } void AssemblyItem::add_item(BSDF* bsdf) { m_bsdf_collection_item->add_item(bsdf); } void AssemblyItem::add_item(EDF* edf) { m_edf_collection_item->add_item(edf); } void AssemblyItem::add_item(SurfaceShader* surface_shader) { m_surface_shader_collection_item->add_item(surface_shader); } void AssemblyItem::add_item(Material* material) { m_material_collection_item->add_item(material); } void AssemblyItem::add_item(Light* light) { m_light_collection_item->add_item(light); } void AssemblyItem::add_item(Object* object) { m_object_collection_item->add_item(object); } void AssemblyItem::add_item(ObjectInstance* object_instance) { m_object_instance_collection_item->add_item(object_instance); } template <typename EntityContainer> typename ItemTypeMap<EntityContainer>::T* AssemblyItem::add_collection_item(EntityContainer& entities) { typedef ItemTypeMap<EntityContainer>::T ItemType; ItemType* item = new ItemType( m_assembly, entities, m_project_builder); addChild(item); return item; } template <typename Entity, typename EntityContainer> CollectionItem<Entity, Assembly>* AssemblyItem::add_single_model_collection_item(EntityContainer& entities) { CollectionItem<Entity, Assembly>* item = new SingleModelCollectionItem<Entity, Assembly>( new_guid(), EntityTraits<Entity>::get_human_readable_collection_type_name(), m_assembly, m_project_builder); item->add_items(entities); addChild(item); return item; } template <typename Entity, typename EntityContainer> CollectionItem<Entity, Assembly>* AssemblyItem::add_multi_model_collection_item(EntityContainer& entities) { CollectionItem<Entity, Assembly>* item = new MultiModelCollectionItem<Entity, Assembly>( new_guid(), EntityTraits<Entity>::get_human_readable_collection_type_name(), m_assembly, m_project_builder); item->add_items(entities); addChild(item); return item; } void AssemblyItem::slot_instantiate() { const string instance_name_suggestion = get_name_suggestion( string(m_assembly.get_name()) + "_inst", m_scene.assembly_instances()); const string instance_name = get_entity_name_dialog( treeWidget(), "Instantiate Assembly", "Assembly Instance Name:", instance_name_suggestion); if (!instance_name.empty()) m_project_builder.insert_assembly_instance(instance_name, m_assembly); } } // namespace studio } // namespace appleseed <commit_msg>fixed creation of materials via the context menu of an assembly.<commit_after> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010 Francois Beaune // // 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. // // Interface header. #include "assemblyitem.h" // appleseed.studio headers. #include "mainwindow/project/colorcollectionitem.h" #include "mainwindow/project/lightcollectionitem.h" #include "mainwindow/project/multimodelcollectionitem.h" #include "mainwindow/project/objectcollectionitem.h" #include "mainwindow/project/objectinstancecollectionitem.h" #include "mainwindow/project/projectbuilder.h" #include "mainwindow/project/projecttree.h" #include "mainwindow/project/singlemodelcollectionitem.h" #include "mainwindow/project/texturecollectionitem.h" #include "mainwindow/project/textureinstancecollectionitem.h" #include "mainwindow/project/tools.h" // appleseed.renderer headers. #include "renderer/api/bsdf.h" #include "renderer/api/color.h" #include "renderer/api/edf.h" #include "renderer/api/entity.h" #include "renderer/api/light.h" #include "renderer/api/material.h" #include "renderer/api/object.h" #include "renderer/api/scene.h" #include "renderer/api/surfaceshader.h" #include "renderer/api/texture.h" // appleseed.foundation headers. #include "foundation/utility/uid.h" // Qt headers. #include <QFileDialog> #include <QMenu> #include <QString> #include <QStringList> // Standard headers. #include <string> using namespace foundation; using namespace renderer; using namespace std; namespace appleseed { namespace studio { AssemblyItem::AssemblyItem( Scene& scene, Assembly& assembly, ProjectBuilder& project_builder) : ItemBase(assembly.get_class_uid(), assembly.get_name()) , m_scene(scene) , m_assembly(assembly) , m_project_builder(project_builder) { m_color_collection_item = add_collection_item(assembly.colors()); m_texture_collection_item = add_collection_item(assembly.textures()); m_texture_instance_collection_item = add_collection_item(assembly.texture_instances()); m_bsdf_collection_item = add_multi_model_collection_item<BSDF>(assembly.bsdfs()); m_edf_collection_item = add_multi_model_collection_item<EDF>(assembly.edfs()); m_surface_shader_collection_item = add_multi_model_collection_item<SurfaceShader>(assembly.surface_shaders()); m_material_collection_item = add_single_model_collection_item<Material>(assembly.materials()); m_light_collection_item = add_collection_item(assembly.lights()); m_object_collection_item = add_collection_item(assembly.objects()); m_object_instance_collection_item = add_collection_item(assembly.object_instances()); } QMenu* AssemblyItem::get_single_item_context_menu() const { QMenu* menu = ItemBase::get_single_item_context_menu(); menu->addSeparator(); menu->addAction("Instantiate...", this, SLOT(slot_instantiate())); menu->addSeparator(); menu->addAction("Import Objects...", m_object_collection_item, SLOT(slot_import_objects())); menu->addAction("Import Textures...", m_texture_collection_item, SLOT(slot_import_textures())); menu->addSeparator(); menu->addAction("Create BSDF...", m_bsdf_collection_item, SLOT(slot_create())); menu->addAction("Create EDF...", m_edf_collection_item, SLOT(slot_create())); menu->addAction("Create Surface Shader...", m_surface_shader_collection_item, SLOT(slot_create())); menu->addAction("Create Material...", m_material_collection_item, SLOT(slot_create())); return menu; } void AssemblyItem::add_item(ColorEntity* color) { m_color_collection_item->add_item(color); } void AssemblyItem::add_item(Texture* texture) { m_texture_collection_item->add_item(texture); } void AssemblyItem::add_item(TextureInstance* texture_instance) { m_texture_instance_collection_item->add_item(texture_instance); } void AssemblyItem::add_item(BSDF* bsdf) { m_bsdf_collection_item->add_item(bsdf); } void AssemblyItem::add_item(EDF* edf) { m_edf_collection_item->add_item(edf); } void AssemblyItem::add_item(SurfaceShader* surface_shader) { m_surface_shader_collection_item->add_item(surface_shader); } void AssemblyItem::add_item(Material* material) { m_material_collection_item->add_item(material); } void AssemblyItem::add_item(Light* light) { m_light_collection_item->add_item(light); } void AssemblyItem::add_item(Object* object) { m_object_collection_item->add_item(object); } void AssemblyItem::add_item(ObjectInstance* object_instance) { m_object_instance_collection_item->add_item(object_instance); } template <typename EntityContainer> typename ItemTypeMap<EntityContainer>::T* AssemblyItem::add_collection_item(EntityContainer& entities) { typedef ItemTypeMap<EntityContainer>::T ItemType; ItemType* item = new ItemType( m_assembly, entities, m_project_builder); addChild(item); return item; } template <typename Entity, typename EntityContainer> CollectionItem<Entity, Assembly>* AssemblyItem::add_single_model_collection_item(EntityContainer& entities) { CollectionItem<Entity, Assembly>* item = new SingleModelCollectionItem<Entity, Assembly>( new_guid(), EntityTraits<Entity>::get_human_readable_collection_type_name(), m_assembly, m_project_builder); item->add_items(entities); addChild(item); return item; } template <typename Entity, typename EntityContainer> CollectionItem<Entity, Assembly>* AssemblyItem::add_multi_model_collection_item(EntityContainer& entities) { CollectionItem<Entity, Assembly>* item = new MultiModelCollectionItem<Entity, Assembly>( new_guid(), EntityTraits<Entity>::get_human_readable_collection_type_name(), m_assembly, m_project_builder); item->add_items(entities); addChild(item); return item; } void AssemblyItem::slot_instantiate() { const string instance_name_suggestion = get_name_suggestion( string(m_assembly.get_name()) + "_inst", m_scene.assembly_instances()); const string instance_name = get_entity_name_dialog( treeWidget(), "Instantiate Assembly", "Assembly Instance Name:", instance_name_suggestion); if (!instance_name.empty()) m_project_builder.insert_assembly_instance(instance_name, m_assembly); } } // namespace studio } // namespace appleseed <|endoftext|>
<commit_before>/*! \copyright (c) RDO-Team, 2011 \file main.cpp \authors Урусов Андрей (rdo@rk9.bmstu.ru) \authors Клеванец Игорь (impus@hotbox.ru) \date 2.10.2011 \brief Тест законов распределения \indent 4T */ // ---------------------------------------------------------------------------- PCH // ----------------------------------------------------------------------- INCLUDES #define BOOST_TEST_MODULE RDOSequencesTest #include <iostream> #include <fstream> #include <vector> #include <math.h> #include <boost/test/included/unit_test.hpp> #include <boost/bind.hpp> #include <boost/function.hpp> // ----------------------------------------------------------------------- SYNOPSIS #include "utils/rdofile.h" #include "utils/platform.h" #include "simulator/runtime/rdo_random_distribution.h" // -------------------------------------------------------------------------------- #ifdef COMPILER_VISUAL_STUDIO #define __SCANF sscanf_s #else // not COMPILER_VISUAL_STUDIO #define __SCANF sscanf #endif // COMPILER_VISUAL_STUDIO typedef std::vector<double> Container; typedef std::vector<ruint> ContainerInt; typedef const tstring contstr; const long int g_seed = 123456789; //!< база генератора contstr g_filePath = "../../test/sequences/";//!< путь к файлам относительно проекта contstr g_fileNormalName = "data_normal.txt"; //!< файл данных contstr g_fileUniformName = "data_uniform.txt"; //!< файл данных contstr g_fileExponentialName = "data_exponential.txt"; //!< файл данных contstr g_fileTriangularName = "data_trinagular.txt"; //!< файл данных const ruint g_count = 100000; //!< количество генерируемых данных const double g_main = 10.0; //!< параметр закона экспоненциального и нормального const double g_var = 1.0; //!< параметр закона нормального const double g_from = 1.0; //!< параметр закона равномерного и треугольного const double g_to = 7.0; //!< параметр закона равномерного и треугольного const double g_top = 5.0; //!< параметр закона треугольного #if defined(ARCHITECTURE_X86) const ruint g_precision = 20; //!< точность вещественного числа при выводе в поток #elif defined(ARCHITECTURE_AMD64) || defined(ARCHITECTURE_ARM) const ruint g_precision = 14; //!< точность вещественного числа при выводе в поток #endif const ruint g_countOfExamples = 2000; //!< количество чисел в выборке const ruint g_countOfR = 39; //!< число разрядов const double pi = 3.141592653; //!< фундаментальная константа const double g_ksiEtalon = 50.9985; //!< табличное значение. 95% вероятность того, что это действительно тот самый закон распределения // -------------------------------------------------------------------------------- // -------Templates // -------------------------------------------------------------------------------- template <class T, class F, class contstr> void onGenerateData(F binder, contstr g_fileName) { if (rdo::File::exist(g_fileName.c_str())) return; T sequence(g_seed); Container test; test.reserve(g_count); for (ruint i = 0; i < g_count; ++i) { test.push_back(binder.operator()(&sequence)); } std::ofstream stream(g_fileName.c_str()); stream.precision(g_precision); STL_FOR_ALL(test, it) { stream << *it << std::endl; } } template <class T, class F, class contstr> void onCheckData(F binder, contstr g_fileName) { std::ifstream stream(g_fileName.c_str()); BOOST_CHECK(stream.good()); Container orig; while (stream.good()) { double value; stream >> value; std::stringstream s; s.precision(g_precision); s << value; s >> value; orig.push_back(value); } Container test; test.reserve(g_count); T sequence(g_seed); for (ruint i = 0; i < g_count; ++i) { std::stringstream s; s.precision(g_precision); s << binder.operator()(&sequence); double value; s >> value; test.push_back(value); } Container::const_iterator origIt = orig.begin(); stream.precision(g_precision); STL_FOR_ALL(test, it) { BOOST_CHECK(origIt != orig.end()); rbool check = *it == *origIt; BOOST_CHECK(check); if (!check) { std::cout.precision(g_precision); std::cout << *it << std::endl; std::cout << *origIt << std::endl; } ++origIt; } } template <class T,class F> double area (F binder, double n, double m) { double k = 1; double S1 = 1; double S2 = 0; ruint t = 10; while (fabs(S1-S2)/S1 > 0.01) { S2 = S1; S1 = 0; for (ruint g = 0; g < t + 1; ++g) { if ((g == 0) || (g == t - 1)) k = 0.5; S1 += k*(binder.operator()(n + g*(m-n)/t)); k = 1; } S1 *= (m-n)/t; t *= 10; } return S1; } template <class T, class G, class F, class S> void onCheckKsi(F binder, S binderSeq, double left, double right) { Container x; x.reserve(g_countOfR + 1); double elem = (right-left)/(g_countOfR*1.0); //расстояние между точками на прямой for (ruint i = 0; i < g_countOfR + 1; ++i) { x.push_back(left + elem*i); } Container vb; //контейнер для хранения выборки vb.reserve(g_countOfExamples); G sequence(g_seed); //выборка for (ruint i = 0; i < g_countOfExamples; ++i) { vb.push_back(binderSeq.operator()(&sequence)); } Container f_vb; //контейнер для храниения количества попаданий на интервал f_vb.reserve(g_countOfR); for(ruint i = 0; i < g_countOfR; ++i) //нахождение количества попаданий на интервал { ruint freq = 0; for(ruint k = 0; k < g_countOfExamples; ++k) { if((vb[k] > x[i]) & (vb[k] <= x[i+1])) { ++freq; } } f_vb.push_back(freq); } Container F_etalon; F_etalon.reserve(g_countOfR); for (ruint i = 0; i < g_countOfR; ++i) { F_etalon.push_back(area<T>(binder, x[i], x[i+1])); } double ksi = 0; for(ruint i = 0; i < g_countOfR; ++i) { double ksiTemp = F_etalon[i]*g_countOfExamples; ksi += (f_vb[i] - ksiTemp)*(f_vb[i] - ksiTemp)/ksiTemp; } BOOST_CHECK(ksi <= g_ksiEtalon); if (ksi > g_ksiEtalon) { std::cout << ksi << std::endl; } } // -------------------------------------------------------------------------------- class SequenceNormal { public: SequenceNormal(double main, double var) : m_main(main) , m_var (var ) {} double get(double x) const { return 1/(sqrt(2*pi)*m_var*exp((x - m_main)*(x - m_main)/(2*m_var*m_var))); } private: double m_main; double m_var; }; class SequenceExponential { public: SequenceExponential(double main) : m_main(main) {} double get(double x) const { return 1/(m_main*exp(x/m_main)); } private: double m_main; }; class SequenceUniform { public: SequenceUniform(double min, double max) : m_min(min) , m_max(max) {} double get(double x) const { UNUSED(x); return 1/(m_max-m_min); } private: double m_min; double m_max; }; class SequenceTriangular { public: SequenceTriangular(double min, double top, double max) : m_min(min-top) , m_top(top) , m_max(max-top) {} double get(double x) const { x -= m_top; double temp; if (x < 0) { temp = -2*x/((m_max - m_min)*m_min) + 2/(m_max - m_min); } else { temp = -2*x/((m_max - m_min)*m_max) + 2/(m_max - m_min); } return temp; } private: double m_min; double m_top; double m_max; }; BOOST_AUTO_TEST_SUITE(RDOSequencesTest) // -------------------------------------------------------------------------------- // -------Normal sequence // -------------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(RDONormalTestCreate) { onGenerateData<rdo::runtime::RandGeneratorNormal> (boost::bind(&rdo::runtime::RandGeneratorNormal::next, _1, g_main, g_var), g_filePath + g_fileNormalName); } BOOST_AUTO_TEST_CASE(RDONormalTestCheck) { onCheckData<rdo::runtime::RandGeneratorNormal> (boost::bind(&rdo::runtime::RandGeneratorNormal::next, _1, g_main, g_var), g_filePath + g_fileNormalName); SequenceNormal normal(g_main, g_var); onCheckKsi<SequenceNormal, rdo::runtime::RandGeneratorNormal> (boost::bind(&SequenceNormal::get, normal, _1), boost::bind(&rdo::runtime::RandGeneratorNormal::next, _1, g_main, g_var), g_main-4*g_var, g_main+4*g_var); } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // -------Uniform sequence // -------------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(RDOUniformTestCreate) { onGenerateData<rdo::runtime::RandGeneratorUniform> (boost::bind(&rdo::runtime::RandGeneratorUniform::next, _1, g_from, g_to), g_filePath + g_fileUniformName); } BOOST_AUTO_TEST_CASE(RDOUniformTestCheck) { onCheckData<rdo::runtime::RandGeneratorUniform> (boost::bind(&rdo::runtime::RandGeneratorUniform::next, _1, g_from, g_to), g_filePath + g_fileUniformName); SequenceUniform uniform(g_from, g_to); onCheckKsi<SequenceUniform, rdo::runtime::RandGeneratorUniform> (boost::bind(&SequenceUniform::get, uniform, _1), boost::bind(&rdo::runtime::RandGeneratorUniform::next, _1, g_from, g_to), g_from, g_to); } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // -------Exponential sequence // -------------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(RDOExponentialTestCreate) { onGenerateData<rdo::runtime::RandGeneratorExponential> (boost::bind(&rdo::runtime::RandGeneratorExponential::next, _1, g_main), g_filePath + g_fileExponentialName); } BOOST_AUTO_TEST_CASE(RDOExponentialTestCheck) { onCheckData<rdo::runtime::RandGeneratorExponential> (boost::bind(&rdo::runtime::RandGeneratorExponential::next, _1, g_main), g_filePath + g_fileExponentialName); SequenceExponential exponential(g_main); onCheckKsi<SequenceExponential, rdo::runtime::RandGeneratorExponential> (boost::bind(&SequenceExponential::get, exponential, _1), boost::bind(&rdo::runtime::RandGeneratorExponential::next, _1, g_main), 0, 7*g_main); } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // -------Triangular sequence // -------------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(RDOTriangularTestCreate) { onGenerateData<rdo::runtime::RandGeneratorTriangular> (boost::bind(&rdo::runtime::RandGeneratorTriangular::next, _1, g_from, g_top, g_to), g_filePath + g_fileTriangularName); } BOOST_AUTO_TEST_CASE(RDOTriangularTestCheck) { onCheckData<rdo::runtime::RandGeneratorTriangular> (boost::bind(&rdo::runtime::RandGeneratorTriangular::next, _1, g_from, g_top, g_to), g_filePath + g_fileTriangularName); SequenceTriangular triangular(g_from, g_top, g_to); onCheckKsi<SequenceTriangular, rdo::runtime::RandGeneratorTriangular> (boost::bind(&SequenceTriangular::get, triangular, _1), boost::bind(&rdo::runtime::RandGeneratorTriangular::next, _1, g_from, g_top, g_to), g_from, g_to); } // -------------------------------------------------------------------------------- BOOST_AUTO_TEST_SUITE_END() <commit_msg> - настроена локаль<commit_after>/*! \copyright (c) RDO-Team, 2011 \file main.cpp \authors Урусов Андрей (rdo@rk9.bmstu.ru) \authors Клеванец Игорь (impus@hotbox.ru) \date 2.10.2011 \brief Тест законов распределения \indent 4T */ // ----------------------------------------------------------------------- PLATFORM #include "utils/platform.h" // ---------------------------------------------------------------------------- PCH // ----------------------------------------------------------------------- INCLUDES #define BOOST_TEST_MODULE RDOSequencesTest #include <iostream> #include <fstream> #include <vector> #include <math.h> #include <boost/test/included/unit_test.hpp> #include <boost/bind.hpp> #include <boost/function.hpp> // ----------------------------------------------------------------------- SYNOPSIS #include "utils/rdofile.h" #include "utils/rdolocale.h" #include "simulator/runtime/rdo_random_distribution.h" // -------------------------------------------------------------------------------- #ifdef COMPILER_VISUAL_STUDIO #define __SCANF sscanf_s #else // not COMPILER_VISUAL_STUDIO #define __SCANF sscanf #endif // COMPILER_VISUAL_STUDIO typedef std::vector<double> Container; typedef std::vector<ruint> ContainerInt; typedef const tstring contstr; const long int g_seed = 123456789; //!< база генератора contstr g_filePath = "../../test/sequences/";//!< путь к файлам относительно проекта contstr g_fileNormalName = "data_normal.txt"; //!< файл данных contstr g_fileUniformName = "data_uniform.txt"; //!< файл данных contstr g_fileExponentialName = "data_exponential.txt"; //!< файл данных contstr g_fileTriangularName = "data_trinagular.txt"; //!< файл данных const ruint g_count = 100000; //!< количество генерируемых данных const double g_main = 10.0; //!< параметр закона экспоненциального и нормального const double g_var = 1.0; //!< параметр закона нормального const double g_from = 1.0; //!< параметр закона равномерного и треугольного const double g_to = 7.0; //!< параметр закона равномерного и треугольного const double g_top = 5.0; //!< параметр закона треугольного #if defined(ARCHITECTURE_X86) const ruint g_precision = 20; //!< точность вещественного числа при выводе в поток #elif defined(ARCHITECTURE_AMD64) || defined(ARCHITECTURE_ARM) const ruint g_precision = 14; //!< точность вещественного числа при выводе в поток #endif const ruint g_countOfExamples = 2000; //!< количество чисел в выборке const ruint g_countOfR = 39; //!< число разрядов const double pi = 3.141592653; //!< фундаментальная константа const double g_ksiEtalon = 50.9985; //!< табличное значение. 95% вероятность того, что это действительно тот самый закон распределения // -------------------------------------------------------------------------------- // -------Templates // -------------------------------------------------------------------------------- template <class T, class F, class contstr> void onGenerateData(F binder, contstr g_fileName) { if (rdo::File::exist(g_fileName.c_str())) return; T sequence(g_seed); Container test; test.reserve(g_count); for (ruint i = 0; i < g_count; ++i) { test.push_back(binder.operator()(&sequence)); } std::ofstream stream(g_fileName.c_str()); stream.precision(g_precision); STL_FOR_ALL(test, it) { stream << *it << std::endl; } } template <class T, class F, class contstr> void onCheckData(F binder, contstr g_fileName) { std::ifstream stream(g_fileName.c_str()); BOOST_CHECK(stream.good()); Container orig; while (stream.good()) { double value; stream >> value; std::stringstream s; s.precision(g_precision); s << value; s >> value; orig.push_back(value); } Container test; test.reserve(g_count); T sequence(g_seed); for (ruint i = 0; i < g_count; ++i) { std::stringstream s; s.precision(g_precision); s << binder.operator()(&sequence); double value; s >> value; test.push_back(value); } Container::const_iterator origIt = orig.begin(); stream.precision(g_precision); STL_FOR_ALL(test, it) { BOOST_CHECK(origIt != orig.end()); rbool check = *it == *origIt; BOOST_CHECK(check); if (!check) { std::cout.precision(g_precision); std::cout << *it << std::endl; std::cout << *origIt << std::endl; } ++origIt; } } template <class T,class F> double area (F binder, double n, double m) { double k = 1; double S1 = 1; double S2 = 0; ruint t = 10; while (fabs(S1-S2)/S1 > 0.01) { S2 = S1; S1 = 0; for (ruint g = 0; g < t + 1; ++g) { if ((g == 0) || (g == t - 1)) k = 0.5; S1 += k*(binder.operator()(n + g*(m-n)/t)); k = 1; } S1 *= (m-n)/t; t *= 10; } return S1; } template <class T, class G, class F, class S> void onCheckKsi(F binder, S binderSeq, double left, double right) { Container x; x.reserve(g_countOfR + 1); double elem = (right-left)/(g_countOfR*1.0); //расстояние между точками на прямой for (ruint i = 0; i < g_countOfR + 1; ++i) { x.push_back(left + elem*i); } Container vb; //контейнер для хранения выборки vb.reserve(g_countOfExamples); G sequence(g_seed); //выборка for (ruint i = 0; i < g_countOfExamples; ++i) { vb.push_back(binderSeq.operator()(&sequence)); } Container f_vb; //контейнер для храниения количества попаданий на интервал f_vb.reserve(g_countOfR); for(ruint i = 0; i < g_countOfR; ++i) //нахождение количества попаданий на интервал { ruint freq = 0; for(ruint k = 0; k < g_countOfExamples; ++k) { if((vb[k] > x[i]) & (vb[k] <= x[i+1])) { ++freq; } } f_vb.push_back(freq); } Container F_etalon; F_etalon.reserve(g_countOfR); for (ruint i = 0; i < g_countOfR; ++i) { F_etalon.push_back(area<T>(binder, x[i], x[i+1])); } double ksi = 0; for(ruint i = 0; i < g_countOfR; ++i) { double ksiTemp = F_etalon[i]*g_countOfExamples; ksi += (f_vb[i] - ksiTemp)*(f_vb[i] - ksiTemp)/ksiTemp; } BOOST_CHECK(ksi <= g_ksiEtalon); if (ksi > g_ksiEtalon) { std::cout << ksi << std::endl; } } // -------------------------------------------------------------------------------- class SequenceNormal { public: SequenceNormal(double main, double var) : m_main(main) , m_var (var ) {} double get(double x) const { return 1/(sqrt(2*pi)*m_var*exp((x - m_main)*(x - m_main)/(2*m_var*m_var))); } private: double m_main; double m_var; }; class SequenceExponential { public: SequenceExponential(double main) : m_main(main) {} double get(double x) const { return 1/(m_main*exp(x/m_main)); } private: double m_main; }; class SequenceUniform { public: SequenceUniform(double min, double max) : m_min(min) , m_max(max) {} double get(double x) const { UNUSED(x); return 1/(m_max-m_min); } private: double m_min; double m_max; }; class SequenceTriangular { public: SequenceTriangular(double min, double top, double max) : m_min(min-top) , m_top(top) , m_max(max-top) {} double get(double x) const { x -= m_top; double temp; if (x < 0) { temp = -2*x/((m_max - m_min)*m_min) + 2/(m_max - m_min); } else { temp = -2*x/((m_max - m_min)*m_max) + 2/(m_max - m_min); } return temp; } private: double m_min; double m_top; double m_max; }; BOOST_AUTO_TEST_SUITE(RDOSequencesTest) // -------------------------------------------------------------------------------- // -------Normal sequence // -------------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(RDONormalTestCreate) { rdo::locale::init(); onGenerateData<rdo::runtime::RandGeneratorNormal> (boost::bind(&rdo::runtime::RandGeneratorNormal::next, _1, g_main, g_var), g_filePath + g_fileNormalName); } BOOST_AUTO_TEST_CASE(RDONormalTestCheck) { onCheckData<rdo::runtime::RandGeneratorNormal> (boost::bind(&rdo::runtime::RandGeneratorNormal::next, _1, g_main, g_var), g_filePath + g_fileNormalName); SequenceNormal normal(g_main, g_var); onCheckKsi<SequenceNormal, rdo::runtime::RandGeneratorNormal> (boost::bind(&SequenceNormal::get, normal, _1), boost::bind(&rdo::runtime::RandGeneratorNormal::next, _1, g_main, g_var), g_main-4*g_var, g_main+4*g_var); } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // -------Uniform sequence // -------------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(RDOUniformTestCreate) { onGenerateData<rdo::runtime::RandGeneratorUniform> (boost::bind(&rdo::runtime::RandGeneratorUniform::next, _1, g_from, g_to), g_filePath + g_fileUniformName); } BOOST_AUTO_TEST_CASE(RDOUniformTestCheck) { onCheckData<rdo::runtime::RandGeneratorUniform> (boost::bind(&rdo::runtime::RandGeneratorUniform::next, _1, g_from, g_to), g_filePath + g_fileUniformName); SequenceUniform uniform(g_from, g_to); onCheckKsi<SequenceUniform, rdo::runtime::RandGeneratorUniform> (boost::bind(&SequenceUniform::get, uniform, _1), boost::bind(&rdo::runtime::RandGeneratorUniform::next, _1, g_from, g_to), g_from, g_to); } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // -------Exponential sequence // -------------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(RDOExponentialTestCreate) { onGenerateData<rdo::runtime::RandGeneratorExponential> (boost::bind(&rdo::runtime::RandGeneratorExponential::next, _1, g_main), g_filePath + g_fileExponentialName); } BOOST_AUTO_TEST_CASE(RDOExponentialTestCheck) { onCheckData<rdo::runtime::RandGeneratorExponential> (boost::bind(&rdo::runtime::RandGeneratorExponential::next, _1, g_main), g_filePath + g_fileExponentialName); SequenceExponential exponential(g_main); onCheckKsi<SequenceExponential, rdo::runtime::RandGeneratorExponential> (boost::bind(&SequenceExponential::get, exponential, _1), boost::bind(&rdo::runtime::RandGeneratorExponential::next, _1, g_main), 0, 7*g_main); } // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // -------Triangular sequence // -------------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(RDOTriangularTestCreate) { onGenerateData<rdo::runtime::RandGeneratorTriangular> (boost::bind(&rdo::runtime::RandGeneratorTriangular::next, _1, g_from, g_top, g_to), g_filePath + g_fileTriangularName); } BOOST_AUTO_TEST_CASE(RDOTriangularTestCheck) { onCheckData<rdo::runtime::RandGeneratorTriangular> (boost::bind(&rdo::runtime::RandGeneratorTriangular::next, _1, g_from, g_top, g_to), g_filePath + g_fileTriangularName); SequenceTriangular triangular(g_from, g_top, g_to); onCheckKsi<SequenceTriangular, rdo::runtime::RandGeneratorTriangular> (boost::bind(&SequenceTriangular::get, triangular, _1), boost::bind(&rdo::runtime::RandGeneratorTriangular::next, _1, g_from, g_top, g_to), g_from, g_to); } // -------------------------------------------------------------------------------- BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>#include "nodes/node.hh" #include "nodes/node_system.hh" #include <vector> #include <tuple> namespace doanimate { class Manager { nodes::NodeSystem* system; std::vector<size_t> inputs; std::vector<size_t> outputs; public: float frames_per_second; size_t width; size_t height; size_t audio_chunk_length; float audio_chunks_per_second; size_t frames; Manager(nodes::NodeSystem*); }; struct Image { std::vector<std::tuple<unsigned char, unsigned char, unsigned char>> data; size_t width; size_t height; }; using AudioChunk = std::vector<float>; void add_time_input(Manager&); void audio_time_input(Manager&); void add_info_input(Manager&); void image_output(Manager&); void audio_output(Manager&); Image render_image(Manager&); std::vector<Image> render_animation(Manager&); AudioChunk render_audio_chunk(Manager&); std::vector<AudioChunk> render_audio(Manager&); std::pair<std::vector<Image>, std::vector<AudioChunk>> render_video(Manager&); } <commit_msg>Made doanimate::Manager::system public.<commit_after>#include "nodes/node.hh" #include "nodes/node_system.hh" #include <vector> #include <tuple> namespace doanimate { class Manager { std::vector<size_t> inputs; std::vector<size_t> outputs; public: nodes::NodeSystem* system; float frames_per_second; size_t width; size_t height; size_t audio_chunk_length; float audio_chunks_per_second; size_t frames; Manager(nodes::NodeSystem*); }; struct Image { std::vector<std::tuple<unsigned char, unsigned char, unsigned char>> data; size_t width; size_t height; }; using AudioChunk = std::vector<float>; void add_time_input(Manager&); void audio_time_input(Manager&); void add_info_input(Manager&); void image_output(Manager&); void audio_output(Manager&); Image render_image(Manager&); std::vector<Image> render_animation(Manager&); AudioChunk render_audio_chunk(Manager&); std::vector<AudioChunk> render_audio(Manager&); std::pair<std::vector<Image>, std::vector<AudioChunk>> render_video(Manager&); } <|endoftext|>
<commit_before>/// HEADER #include "pointcloud_to_pointmatrix.h" /// PROJECT #include <csapex/model/connector_in.h> #include <csapex/model/connector_out.h> #include <utils_param/parameter_factory.h> #include <csapex_vision/cv_mat_message.h> /// SYSTEM #include <csapex/utility/register_apex_plugin.h> #include <pcl/point_types.h> #include <pcl/conversions.h> CSAPEX_REGISTER_CLASS(csapex::PointCloudToPointMatrix, csapex::Node) using namespace csapex; using namespace csapex::connection_types; PointCloudToPointMatrix::PointCloudToPointMatrix() { } void PointCloudToPointMatrix::process() { PointCloudMessage::Ptr msg(input_->getMessage<PointCloudMessage>()); boost::apply_visitor (PointCloudMessage::Dispatch<PointCloudToPointMatrix>(this), msg->value); } void PointCloudToPointMatrix::setup() { setSynchronizedInputs(true); input_ = addInput<PointCloudMessage>("PointCloud"); output_ = addOutput<CvMatMessage>("Point Matrix"); } namespace implementation { template<class PointT> struct Impl { static void convert(const typename pcl::PointCloud<PointT>::Ptr cloud, cv::Mat &matrix) { int height = cloud->height; int width = cloud->width; matrix = cv::Mat(height, width, CV_32FC3); for(int i = 0 ; i < height ; ++i) { for(int j = 0 ; j < width ; ++j) { PointT pos = cloud->at(i * width + j); matrix.at<float>(i, (j * 3 + 0)) = pos.x; matrix.at<float>(i, (j * 3 + 1)) = pos.y; matrix.at<float>(i, (j * 3 + 2)) = pos.z; } } } }; template <> struct Impl<pcl::PointXY> { static void convert(cv::Mat &matrix, typename pcl::PointCloud<pcl::PointXY>::Ptr cloud) { std::runtime_error("Conversion is not supported for pcl::PointXY!"); } }; } template <class PointT> void PointCloudToPointMatrix::inputCloud(typename pcl::PointCloud<PointT>::Ptr cloud) { CvMatMessage::Ptr out(new CvMatMessage(enc::unknown)); implementation::Impl<PointT>::convert(cloud, out->value); /// TODO : ENCODING NOT YET IMPLEMENTED FOR MULTICHANNEL FLOAT MATRICES output_->publish(out); } <commit_msg>warning for insufficient encoding<commit_after>/// HEADER #include "pointcloud_to_pointmatrix.h" /// PROJECT #include <csapex/model/connector_in.h> #include <csapex/model/connector_out.h> #include <utils_param/parameter_factory.h> #include <csapex_vision/cv_mat_message.h> /// SYSTEM #include <csapex/utility/register_apex_plugin.h> #include <pcl/point_types.h> #include <pcl/conversions.h> CSAPEX_REGISTER_CLASS(csapex::PointCloudToPointMatrix, csapex::Node) using namespace csapex; using namespace csapex::connection_types; PointCloudToPointMatrix::PointCloudToPointMatrix() { } void PointCloudToPointMatrix::process() { PointCloudMessage::Ptr msg(input_->getMessage<PointCloudMessage>()); boost::apply_visitor (PointCloudMessage::Dispatch<PointCloudToPointMatrix>(this), msg->value); } void PointCloudToPointMatrix::setup() { setSynchronizedInputs(true); input_ = addInput<PointCloudMessage>("PointCloud"); output_ = addOutput<CvMatMessage>("Point Matrix"); } namespace implementation { template<class PointT> struct Impl { static void convert(const typename pcl::PointCloud<PointT>::Ptr cloud, cv::Mat &matrix) { int height = cloud->height; int width = cloud->width; matrix = cv::Mat(height, width, CV_32FC3); for(int i = 0 ; i < height ; ++i) { for(int j = 0 ; j < width ; ++j) { PointT pos = cloud->at(i * width + j); matrix.at<float>(i, (j * 3 + 0)) = pos.x; matrix.at<float>(i, (j * 3 + 1)) = pos.y; matrix.at<float>(i, (j * 3 + 2)) = pos.z; } } } }; template <> struct Impl<pcl::PointXY> { static void convert(cv::Mat &matrix, typename pcl::PointCloud<pcl::PointXY>::Ptr cloud) { std::runtime_error("Conversion is not supported for pcl::PointXY!"); } }; } template <class PointT> void PointCloudToPointMatrix::inputCloud(typename pcl::PointCloud<PointT>::Ptr cloud) { #warning "Fix unsupported type encoding!" CvMatMessage::Ptr out(new CvMatMessage(enc::unknown)); implementation::Impl<PointT>::convert(cloud, out->value); output_->publish(out); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: XMLTableShapeImportHelper.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: sab $ $Date: 2002-05-28 06:55:01 $ * * 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 _SC_XMLTABLESHAPEIMPORTHELPER_HXX #define _SC_XMLTABLESHAPEIMPORTHELPER_HXX #ifndef _XMLOFF_SHAPEIMPORT_HXX_ #include <xmloff/shapeimport.hxx> #endif #ifndef _COM_SUN_STAR_TABLE_CELLADDRESS_HPP_ #include <com/sun/star/table/CellAddress.hpp> #endif class ScXMLImport; class XMLTableShapeImportHelper : public XMLShapeImportHelper { ::com::sun::star::table::CellAddress aStartCell; sal_Bool bOnTable : 1; public: XMLTableShapeImportHelper( ScXMLImport& rImp, SvXMLImportPropertyMapper *pImpMapper=0 ); ~XMLTableShapeImportHelper(); void SetLayer(com::sun::star::uno::Reference<com::sun::star::drawing::XShape>& rShape, sal_Int16 nLayerID, const rtl::OUString& sType) const; virtual void finishShape(com::sun::star::uno::Reference< com::sun::star::drawing::XShape >& rShape, const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList, com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes); void SetCell (const ::com::sun::star::table::CellAddress& rAddress) { aStartCell = rAddress; } void SetOnTable (const sal_Bool bTempOnTable) { bOnTable = bTempOnTable; } }; #endif <commit_msg>INTEGRATION: CWS dr12 (1.8.280); FILE MERGED 2004/07/23 20:58:25 sab 1.8.280.1: #i21253#; add formatted notes<commit_after>/************************************************************************* * * $RCSfile: XMLTableShapeImportHelper.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: hr $ $Date: 2004-09-08 13:50:04 $ * * 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 _SC_XMLTABLESHAPEIMPORTHELPER_HXX #define _SC_XMLTABLESHAPEIMPORTHELPER_HXX #ifndef _XMLOFF_SHAPEIMPORT_HXX_ #include <xmloff/shapeimport.hxx> #endif #ifndef _COM_SUN_STAR_TABLE_CELLADDRESS_HPP_ #include <com/sun/star/table/CellAddress.hpp> #endif class ScXMLImport; class ScXMLAnnotationContext; class XMLTableShapeImportHelper : public XMLShapeImportHelper { ::com::sun::star::table::CellAddress aStartCell; ScXMLAnnotationContext* pAnnotationContext; sal_Bool bOnTable; public: XMLTableShapeImportHelper( ScXMLImport& rImp, SvXMLImportPropertyMapper *pImpMapper=0 ); ~XMLTableShapeImportHelper(); void SetLayer(com::sun::star::uno::Reference<com::sun::star::drawing::XShape>& rShape, sal_Int16 nLayerID, const rtl::OUString& sType) const; virtual void finishShape(com::sun::star::uno::Reference< com::sun::star::drawing::XShape >& rShape, const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList, com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes); void SetCell (const ::com::sun::star::table::CellAddress& rAddress) { aStartCell = rAddress; } void SetOnTable (const sal_Bool bTempOnTable) { bOnTable = bTempOnTable; } void SetAnnotation(ScXMLAnnotationContext* pAnnotation) { pAnnotationContext = pAnnotation; } }; #endif <|endoftext|>
<commit_before>#include <SDL2/Sdl2Backend.h> #include <SDL2/Sdl2Window.h> #include <iostream> #include <cmath> #include <direct.h> #include "../Include/Boost.h" #include "Application.h" #include "IBackend.h" #include "Modeler3D.h" #include "Types.h" #include "Math/ModelerMath.h" using namespace Core; using namespace std; int main(int argc, char** argv) { cout << "Starting Modeler3D" << endl; IBackend* backend = new Sdl2Backend(); Modeler3D app(backend); app.Start(); delete backend; cout << "Exiting Modeler3D" << endl; return 0; } <commit_msg>removed direct.h<commit_after>#include <SDL2/Sdl2Backend.h> #include <SDL2/Sdl2Window.h> #include <iostream> #include <cmath> #include "../Include/Boost.h" #include "Application.h" #include "IBackend.h" #include "Modeler3D.h" #include "Types.h" #include "Math/ModelerMath.h" using namespace Core; using namespace std; int main(int argc, char** argv) { cout << "Starting Modeler3D" << endl; IBackend* backend = new Sdl2Backend(); Modeler3D app(backend); app.Start(); delete backend; cout << "Exiting Modeler3D" << endl; return 0; } <|endoftext|>
<commit_before>// // Created by Evan Almonte on 10/29/2015. // #include <iostream> #include <cstdlib> #include <ctime> #include "Deck.hpp" using std::cout; int main ( ) { srand (static_cast<unsigned int>(time (NULL))); Deck original; cout << "---------Before Shuffle---------\n"; cout << original; original.shuffle ( ); cout << "\n---------After Shuffle---------\n"; cout << original; return 0; }<commit_msg>Adds main to test GoFishGame<commit_after>// // Created by Evan Almonte on 10/29/2015. // #include "GoFishGame.hpp" #include <cstdlib> #include <ctime> int main ( ) { srand (static_cast<unsigned int>(time (nullptr))); GoFishGame* aGame = new GoFishGame(2); aGame->play ( ); return 0; }<|endoftext|>
<commit_before>// ------------------------------------------------------------------------ // Pion is a development platform for building Reactors that process Events // ------------------------------------------------------------------------ // Copyright (C) 2007-2008 Atomic Labs, Inc. (http://www.atomiclabs.com) // // Pion is free software: you can redistribute it and/or modify it under the // terms of the GNU Affero General Public License as published by the Free // Software Foundation, either version 3 of the License, or (at your option) // any later version. // // Pion 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 Affero General Public License for // more details. // // You should have received a copy of the GNU Affero General Public License // along with Pion. If not, see <http://www.gnu.org/licenses/>. // #include "QueryService.hpp" #include <boost/bind.hpp> #include <pion/net/HTTPResponseWriter.hpp> #include <pion/net/PionUser.hpp> #include "PlatformConfig.hpp" using namespace pion; using namespace pion::net; namespace pion { // begin namespace pion namespace plugins { // begin namespace plugins // QueryService member functions /// handles requests for QueryService void QueryService::operator()(HTTPRequestPtr& request, TCPConnectionPtr& tcp_conn) { // split out the path branches from the HTTP request PathBranches branches; splitPathBranches(branches, request->getResource()); std::string xml; /* for (int i = 0; i < branches.size() ; i++ ) xml += branches[i] + "::"; xml += "\r\n"; */ if (branches.empty()) { xml += "No branch (/reactors) defined"; } else if (branches.front() == "reactors") { xml = getConfig().getReactionEngine().query( branches.at(1), branches, request->getQueryParams()); } else { xml += "Only /reactors supported"; } // Set Content-type to "text/plain" (plain ascii text) HTTPResponseWriterPtr writer(HTTPResponseWriter::create(tcp_conn, *request, boost::bind(&TCPConnection::finish, tcp_conn))); writer->getResponse().setContentType(HTTPTypes::CONTENT_TYPE_XML); writer->write(xml); // send the writer writer->send(); } } // end namespace plugins } // end namespace pion /// creates new QueryService objects extern "C" PION_SERVICE_API pion::server::PlatformService *pion_create_QueryService(void) { return new pion::plugins::QueryService(); } /// destroys QueryService objects extern "C" PION_SERVICE_API void pion_destroy_QueryService(pion::plugins::QueryService *service_ptr) { delete service_ptr; } <commit_msg>QueryService<commit_after>// ------------------------------------------------------------------------ // Pion is a development platform for building Reactors that process Events // ------------------------------------------------------------------------ // Copyright (C) 2007-2008 Atomic Labs, Inc. (http://www.atomiclabs.com) // // Pion is free software: you can redistribute it and/or modify it under the // terms of the GNU Affero General Public License as published by the Free // Software Foundation, either version 3 of the License, or (at your option) // any later version. // // Pion 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 Affero General Public License for // more details. // // You should have received a copy of the GNU Affero General Public License // along with Pion. If not, see <http://www.gnu.org/licenses/>. // #include "QueryService.hpp" #include <boost/bind.hpp> #include <pion/net/HTTPResponseWriter.hpp> #include <pion/net/PionUser.hpp> #include "PlatformConfig.hpp" using namespace pion; using namespace pion::net; namespace pion { // begin namespace pion namespace plugins { // begin namespace plugins // QueryService member functions /// handles requests for QueryService void QueryService::operator()(HTTPRequestPtr& request, TCPConnectionPtr& tcp_conn) { // split out the path branches from the HTTP request PathBranches branches; splitPathBranches(branches, request->getResource()); std::string xml; /* for (int i = 0; i < branches.size() ; i++ ) xml += branches[i] + "::"; xml += "\r\n"; */ /* * branches[0] == reactors * branches[1] == UUID * branches[2] == aggregate/example/info */ if (branches.empty()) { xml += "No branch (/reactors) defined"; } else if (branches.front() == "reactors") { xml = getConfig().getReactionEngine().query( branches.at(1), branches, request->getQueryParams()); } else { xml += "Only /reactors supported"; } // Set Content-type to "text/plain" (plain ascii text) HTTPResponseWriterPtr writer(HTTPResponseWriter::create(tcp_conn, *request, boost::bind(&TCPConnection::finish, tcp_conn))); writer->getResponse().setContentType(HTTPTypes::CONTENT_TYPE_XML); writer->write(xml); // send the writer writer->send(); } } // end namespace plugins } // end namespace pion /// creates new QueryService objects extern "C" PION_SERVICE_API pion::server::PlatformService *pion_create_QueryService(void) { return new pion::plugins::QueryService(); } /// destroys QueryService objects extern "C" PION_SERVICE_API void pion_destroy_QueryService(pion::plugins::QueryService *service_ptr) { delete service_ptr; } <|endoftext|>
<commit_before>/*------------------------------------------------------------------------ * (The MIT License) * * Copyright (c) 2008-2011 Rhomobile, Inc. * * 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. * * http://rhomobile.com *------------------------------------------------------------------------*/ #include <string> #include "common/RhoPort.h" #include "ruby/ext/rho/rhoruby.h" #include "logging/RhoLog.h" #include "common/RhoConf.h" #include "common/RhodesApp.h" #include "common/rhoparams.h" #include "common/StringConverter.h" #include "sync/RhoconnectClientManager.h" #include "common/RhoFilePath.h" #undef null #include <qglobal.h> #if QT_VERSION >= 0x050000 #include <QApplication> #else #include <QtGui/QApplication> #endif #include <QMessageBox> #include "impl/MainWindowImpl.h" using namespace rho; using namespace rho::common; using namespace std; static String g_strCmdLine; static bool m_isJSApplication; static String m_strRootPath, m_strRhodesPath, m_logPort; static String m_strHttpProxy; extern "C" { void parseHttpProxyURI(const String &http_proxy); void rho_ringtone_manager_stop(); const char* rho_native_rhopath() { return m_strRootPath.c_str(); } const char* rho_sys_get_http_proxy_url() { return m_strHttpProxy.c_str(); } } char* parseToken(const char* start) { int len = strlen(start); int nNameLen = 0; while (*start==' ') { start++; len--; } int i = 0; for (i = 0; i < len; i++) { if (start[i] == '=') { if (i > 0) { int s = i-1; for (; s >= 0 && start[s]==' '; s--); nNameLen = s+1; break; } else break; } } if ( nNameLen == 0 ) return NULL; const char* szValue = start + i+1; int nValueLen = 0; while (*szValue==' ' || *szValue=='\'' || *szValue=='"' && nValueLen >= 0) { szValue++; } while (szValue[nValueLen] && szValue[nValueLen] !='\'' && szValue[nValueLen] != '"') { nValueLen++; } //while (nValueLen > 0 && (szValue[nValueLen-1]==' ' || szValue[nValueLen-1]=='\'' || szValue[nValueLen-1]=='"')) nValueLen--; char* value = (char*) malloc(nValueLen+2); strncpy(value, szValue, nValueLen); value[nValueLen] = '\0'; return value; } #include <QDir> int main(int argc, char *argv[]) { CMainWindow* m_appWindow = CMainWindow::getInstance(); m_logPort = String("11000"); for (int i=1; i<argc; ++i) { g_strCmdLine += String(argv[i]) + " "; if (strncasecmp("-log",argv[i],4)==0) { char* port = parseToken(argv[i]); if (port) { String strLogPort = port; m_logPort = strLogPort; free(port); } } else if (strncasecmp("-http_proxy_url",argv[i],15)==0) { char *proxy = parseToken(argv[i]); if (proxy) { m_strHttpProxy = proxy; free(proxy); } else RAWLOGC_INFO("Main", "invalid value for \"http_proxy_url\" cmd parameter"); } else if (strncasecmp("-approot",argv[i],8)==0) { char* path = parseToken(argv[i]); if (path) { int len = strlen(path); if (!(path[len-1]=='\\' || path[len-1]=='/')) { path[len] = '/'; path[len+1] = 0; } m_strRootPath = path; free(path); } } else if (strncasecmp("-jsapproot",argv[i],10)==0) { char* path = parseToken(argv[i]); if (path) { int len = strlen(path); if (!(path[len-1]=='\\' || path[len-1]=='/')) { path[len] = '/'; path[len+1] = 0; } m_strRootPath = path; free(path); } m_isJSApplication = true; } else if (strncasecmp("-rhodespath",argv[i],11)==0) { char* path = parseToken(argv[i]); if (path) { m_strRhodesPath = path; free(path); } } else { RAWLOGC_INFO1("Main", "wrong cmd parameter: %s", argv[i]); } } #if defined(RHO_SYMBIAN) m_strRootPath = (QDir::currentPath()+"/").toUtf8().data(); #endif // PreMessageLoop: rho_logconf_Init(m_strRootPath.c_str(), m_strRootPath.c_str(), m_logPort.c_str()); #ifdef RHODES_EMULATOR RHOSIMCONF().setAppConfFilePath(CFilePath::join(m_strRootPath, RHO_EMULATOR_DIR"/rhosimconfig.txt").c_str()); RHOSIMCONF().loadFromFile(); if ( m_strRhodesPath.length() > 0 ) RHOSIMCONF().setString("rhodes_path", m_strRhodesPath, false ); RHOCONF().setString( "rhosim_platform", RHOSIMCONF().getString( "platform"), false); RHOCONF().setString( "app_version", RHOSIMCONF().getString( "app_version"), false); String start_path = RHOSIMCONF().getString("start_path"); if ( start_path.length() > 0 ) RHOCONF().setString("start_path", start_path, false); RHOSIMCONF().setString( "ext_path", RHOSIMCONF().getString( "ext_path") + CFilePath::join( m_strRhodesPath, "/lib/extensions/debugger;"), false); RHOSIMCONF().setString( "ext_path", RHOSIMCONF().getString( "ext_path") + CFilePath::join( m_strRhodesPath, "/lib/extensions/uri;"), false); RHOSIMCONF().setString( "ext_path", RHOSIMCONF().getString( "ext_path") + CFilePath::join( m_strRhodesPath, "/lib/extensions/timeout;"), false); RHOSIMCONF().setString( "ext_path", RHOSIMCONF().getString( "ext_path") + CFilePath::join( m_strRhodesPath, "/lib/extensions/digest;"), false); RHOSIMCONF().setString( "ext_path", RHOSIMCONF().getString( "ext_path") + CFilePath::join( m_strRhodesPath, "/lib/extensions/openssl;"), false); #endif if ( !rho_rhodesapp_canstartapp(g_strCmdLine.c_str(), " /-,") ) { QMessageBox::critical(0,QString("This is hidden app and can be started only with security key."), QString("Security Token Verification Failed")); RAWLOGC_INFO("Main", "This is hidden app and can be started only with security key."); if (RHOCONF().getString("invalid_security_token_start_path").length() <= 0) return 1; } RAWLOGC_INFO("Main", "Rhodes started"); if (m_strHttpProxy.length() > 0) { parseHttpProxyURI(m_strHttpProxy); } else { if (RHOCONF().isExist("http_proxy_url")) { parseHttpProxyURI(RHOCONF().getString("http_proxy_url")); } } #ifdef RHODES_EMULATOR if (RHOSIMCONF().getString("debug_host").length() > 0) #ifdef OS_WINDOWS_DESKTOP SetEnvironmentVariableA("RHOHOST", RHOSIMCONF().getString("debug_host").c_str() ); #else // !OS_WINDOWS_DESKTOP setenv("RHOHOST", RHOSIMCONF().getString("debug_host").c_str(), 1 ); #endif // OS_WINDOWS_DESKTOP if (RHOSIMCONF().getString("debug_port").length() > 0) #ifdef OS_WINDOWS_DESKTOP SetEnvironmentVariableA("rho_debug_port", RHOSIMCONF().getString("debug_port").c_str() ); #else // RHODES_EMULATOR setenv("rho_debug_port", RHOSIMCONF().getString("debug_port").c_str(), 1 ); #endif // OS_WINDOWS_DESKTOP #endif // RHODES_EMULATOR rho::common::CRhodesApp::Create(m_strRootPath, m_strRootPath, m_strRootPath); RHODESAPP().setJSApplication(m_isJSApplication); // Create the main application window #ifdef RHODES_EMULATOR m_appWindow->Initialize(convertToStringW(RHOSIMCONF().getString("app_name")).c_str()); #else m_appWindow->Initialize(L"Rhodes"); #endif RHODESAPP().startApp(); // Navigate to the "loading..." page m_appWindow->navigate(L"about:blank", -1); if (RHOCONF().getString("test_push_client").length() > 0 ) rho_clientregister_create(RHOCONF().getString("test_push_client").c_str());//"qt_client"); // RunMessageLoop: m_appWindow->messageLoop(); // stopping Rhodes application rho_ringtone_manager_stop(); m_appWindow->DestroyUi(); rho::common::CRhodesApp::Destroy(); return 0; } #ifdef OS_SYMBIAN extern "C" { void rho_sys_replace_current_bundle(const char* path) { } int rho_sys_delete_folder(const char* path) { return 0; } } #endif <commit_msg>rhosimulator: cmd line params path separators fixed<commit_after>/*------------------------------------------------------------------------ * (The MIT License) * * Copyright (c) 2008-2011 Rhomobile, Inc. * * 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. * * http://rhomobile.com *------------------------------------------------------------------------*/ #include <string> #include "common/RhoPort.h" #include "ruby/ext/rho/rhoruby.h" #include "logging/RhoLog.h" #include "common/RhoConf.h" #include "common/RhodesApp.h" #include "common/rhoparams.h" #include "common/StringConverter.h" #include "sync/RhoconnectClientManager.h" #include "common/RhoFilePath.h" #undef null #include <qglobal.h> #if QT_VERSION >= 0x050000 #include <QApplication> #else #include <QtGui/QApplication> #endif #include <QMessageBox> #include <QDir> #include "impl/MainWindowImpl.h" using namespace rho; using namespace rho::common; using namespace std; static String g_strCmdLine; static bool m_isJSApplication; static String m_strRootPath, m_strRhodesPath, m_logPort; static String m_strHttpProxy; extern "C" { void parseHttpProxyURI(const String &http_proxy); void rho_ringtone_manager_stop(); const char* rho_native_rhopath() { return m_strRootPath.c_str(); } const char* rho_sys_get_http_proxy_url() { return m_strHttpProxy.c_str(); } } char* parseToken(const char* start) { int len = strlen(start); int nNameLen = 0; while (*start==' ') { start++; len--; } int i = 0; for (i = 0; i < len; i++) { if (start[i] == '=') { if (i > 0) { int s = i-1; for (; s >= 0 && start[s]==' '; s--); nNameLen = s+1; break; } else break; } } if ( nNameLen == 0 ) return NULL; const char* szValue = start + i+1; int nValueLen = 0; while (*szValue==' ' || *szValue=='\'' || *szValue=='"' && nValueLen >= 0) { szValue++; } while (szValue[nValueLen] && szValue[nValueLen] !='\'' && szValue[nValueLen] != '"') { nValueLen++; } //while (nValueLen > 0 && (szValue[nValueLen-1]==' ' || szValue[nValueLen-1]=='\'' || szValue[nValueLen-1]=='"')) nValueLen--; char* value = (char*) malloc(nValueLen+2); strncpy(value, szValue, nValueLen); value[nValueLen] = '\0'; return value; } int main(int argc, char *argv[]) { bool isJSApp; CMainWindow* m_appWindow = CMainWindow::getInstance(); m_logPort = String("11000"); for (int i=1; i<argc; ++i) { g_strCmdLine += String(argv[i]) + " "; if (strncasecmp("-log",argv[i],4)==0) { char* port = parseToken(argv[i]); if (port) { String strLogPort = port; m_logPort = strLogPort; free(port); } } else if (strncasecmp("-http_proxy_url",argv[i],15)==0) { char *proxy = parseToken(argv[i]); if (proxy) { m_strHttpProxy = proxy; free(proxy); } else RAWLOGC_INFO("Main", "invalid value for \"http_proxy_url\" cmd parameter"); } else if ((strncasecmp("-approot",argv[i],8)==0) || (isJSApp = (strncasecmp("-jsapproot",argv[i],10)==0))) { char* path = parseToken(argv[i]); if (path) { int len = strlen(path); if (!(path[len-1]=='\\' || path[len-1]=='/')) { path[len] = '/'; path[len+1] = 0; } m_strRootPath = path; free(path); if (m_strRootPath.substr(0,7).compare("file://")==0) m_strRootPath.erase(0,7); String_replace(m_strRootPath, '\\', '/'); } m_isJSApplication = isJSApp; } else if (strncasecmp("-rhodespath",argv[i],11)==0) { char* path = parseToken(argv[i]); if (path) { m_strRhodesPath = path; free(path); if (m_strRhodesPath.substr(0,7).compare("file://")==0) m_strRhodesPath.erase(0,7); String_replace(m_strRhodesPath, '\\', '/'); } } else { RAWLOGC_INFO1("Main", "wrong cmd parameter: %s", argv[i]); } } #if defined(RHO_SYMBIAN) m_strRootPath = (QDir::currentPath()+"/").toUtf8().data(); #endif // PreMessageLoop: rho_logconf_Init(m_strRootPath.c_str(), m_strRootPath.c_str(), m_logPort.c_str()); #ifdef RHODES_EMULATOR RHOSIMCONF().setAppConfFilePath(CFilePath::join(m_strRootPath, RHO_EMULATOR_DIR"/rhosimconfig.txt").c_str()); RHOSIMCONF().loadFromFile(); if ( m_strRhodesPath.length() > 0 ) RHOSIMCONF().setString("rhodes_path", m_strRhodesPath, false ); RHOCONF().setString( "rhosim_platform", RHOSIMCONF().getString( "platform"), false); RHOCONF().setString( "app_version", RHOSIMCONF().getString( "app_version"), false); String start_path = RHOSIMCONF().getString("start_path"); if ( start_path.length() > 0 ) RHOCONF().setString("start_path", start_path, false); RHOSIMCONF().setString( "ext_path", RHOSIMCONF().getString( "ext_path") + CFilePath::join( m_strRhodesPath, "/lib/extensions/debugger;"), false); RHOSIMCONF().setString( "ext_path", RHOSIMCONF().getString( "ext_path") + CFilePath::join( m_strRhodesPath, "/lib/extensions/uri;"), false); RHOSIMCONF().setString( "ext_path", RHOSIMCONF().getString( "ext_path") + CFilePath::join( m_strRhodesPath, "/lib/extensions/timeout;"), false); RHOSIMCONF().setString( "ext_path", RHOSIMCONF().getString( "ext_path") + CFilePath::join( m_strRhodesPath, "/lib/extensions/digest;"), false); RHOSIMCONF().setString( "ext_path", RHOSIMCONF().getString( "ext_path") + CFilePath::join( m_strRhodesPath, "/lib/extensions/openssl;"), false); #endif if ( !rho_rhodesapp_canstartapp(g_strCmdLine.c_str(), " /-,") ) { QMessageBox::critical(0,QString("This is hidden app and can be started only with security key."), QString("Security Token Verification Failed")); RAWLOGC_INFO("Main", "This is hidden app and can be started only with security key."); if (RHOCONF().getString("invalid_security_token_start_path").length() <= 0) return 1; } RAWLOGC_INFO("Main", "Rhodes started"); if (m_strHttpProxy.length() > 0) { parseHttpProxyURI(m_strHttpProxy); } else { if (RHOCONF().isExist("http_proxy_url")) { parseHttpProxyURI(RHOCONF().getString("http_proxy_url")); } } #ifdef RHODES_EMULATOR if (RHOSIMCONF().getString("debug_host").length() > 0) #ifdef OS_WINDOWS_DESKTOP SetEnvironmentVariableA("RHOHOST", RHOSIMCONF().getString("debug_host").c_str() ); #else // !OS_WINDOWS_DESKTOP setenv("RHOHOST", RHOSIMCONF().getString("debug_host").c_str(), 1 ); #endif // OS_WINDOWS_DESKTOP if (RHOSIMCONF().getString("debug_port").length() > 0) #ifdef OS_WINDOWS_DESKTOP SetEnvironmentVariableA("rho_debug_port", RHOSIMCONF().getString("debug_port").c_str() ); #else // RHODES_EMULATOR setenv("rho_debug_port", RHOSIMCONF().getString("debug_port").c_str(), 1 ); #endif // OS_WINDOWS_DESKTOP #endif // RHODES_EMULATOR rho::common::CRhodesApp::Create(m_strRootPath, m_strRootPath, m_strRootPath); RHODESAPP().setJSApplication(m_isJSApplication); // Create the main application window #ifdef RHODES_EMULATOR m_appWindow->Initialize(convertToStringW(RHOSIMCONF().getString("app_name")).c_str()); #else m_appWindow->Initialize(L"Rhodes"); #endif RHODESAPP().startApp(); // Navigate to the "loading..." page m_appWindow->navigate(L"about:blank", -1); if (RHOCONF().getString("test_push_client").length() > 0 ) rho_clientregister_create(RHOCONF().getString("test_push_client").c_str());//"qt_client"); // RunMessageLoop: m_appWindow->messageLoop(); // stopping Rhodes application rho_ringtone_manager_stop(); m_appWindow->DestroyUi(); rho::common::CRhodesApp::Destroy(); return 0; } #ifdef OS_SYMBIAN extern "C" { void rho_sys_replace_current_bundle(const char* path) { } int rho_sys_delete_folder(const char* path) { return 0; } } #endif <|endoftext|>
<commit_before>/***************************************************************************** * This file is part of the Gluon Development Platform * Copyright (c) 2011 Laszlo Papp <djszapi@archlinux.us> * * 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 2 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, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *****************************************************************************/ #include "gamewindowmanager.h" #include "input/inputmanager.h" #include "engine/scene.h" # include <QtCore/QTimer> using namespace GluonQMLPlayer; class GameWindowManager::GameWindowManagerPrivate { public: GameWindowManagerPrivate() {} GluonGraphics::RenderWidget* widget; QString title; QString fileName; int msecElapsed; int frameCount; }; GameWindowManager::GameWindowManager(const QString& /* filename */) : QObject() , d( new GameWindowManagerPrivate ) , m_project( new GluonEngine::GameProject ) { } GameWindowManager::GameWindowManager(GluonGraphics::RenderWidget* renderWidget, QGraphicsView* view, GluonPlayer::GameItemsModel* gameItemsModel, const QString& /* filename */ ) : QObject() , d( new GameWindowManagerPrivate ) , m_project( new GluonEngine::GameProject ) , m_view(view) , m_gameItemsModel(gameItemsModel) { d->widget = renderWidget; } GameWindowManager::~GameWindowManager ( ) { } bool GameWindowManager::isViewportGLWidget( ) { return qobject_cast<QGLWidget*>(m_view); } void GameWindowManager::startGame( ) { GluonCore::GluonObjectFactory::instance()->loadPlugins(); m_project->loadFromFile( m_gameFileName ); GluonEngine::Game::instance()->setGameProject( m_project ); GluonEngine::Game::instance()->setCurrentScene( m_project->entryPoint() ); GluonEngine::Game::instance()->runGame(); // QApplication::instance()->exit(); } void GameWindowManager::pauseGame() { GluonEngine::Game::instance()->setPause( true ); // stateChanged( "paused" ); } void GameWindowManager::stopGame() { GluonEngine::Game::instance()->stopGame(); } void GameWindowManager::setProject( int index ) { m_gameFileName = m_gameItemsModel->index(index).data(GluonPlayer::GameItemsModel::ProjectFileNameRole).toString(); openProject(); } int GameWindowManager::availableGamesCount( ) const { return m_gameItemsModel->rowCount(); } void GameWindowManager::buildCommentsModel( int index ) { QString gameID = m_gameItemsModel->index(index).data(GluonPlayer::GameItemsModel::IDRole).toString(); if( gameID.isEmpty() ) { return; } m_commentsModel = new GluonPlayer::CommentItemsModel( gameID ); } void GameWindowManager::setProject( const QModelIndex& index ) { m_gameFileName = index.data(GluonPlayer::GameItemsModel::ProjectFileNameRole).toString(); openProject(); } void GameWindowManager::openProject() { if( m_gameFileName.isEmpty() ) { return; } connect( GluonEngine::Game::instance(), SIGNAL( painted( int ) ), d->widget, SLOT( updateGL() ) ); connect( GluonEngine::Game::instance(), SIGNAL( painted( int ) ), SLOT( countFrames( int ) ) ); connect( GluonEngine::Game::instance(), SIGNAL( updated( int ) ), SLOT( updateTitle( int ) ) ); GluonInput::InputManager::instance()->setFilteredObject(d->widget); QTimer::singleShot( 1000, this, SLOT( startGame() ) ); } void GameWindowManager::activated( QModelIndex index ) { if( index.isValid() ) { } } void GameWindowManager::updateTitle( int msec ) { d->msecElapsed += msec; static int fps = 0; if( d->msecElapsed > 1000 ) { fps = d->frameCount; d->frameCount = 0; d->msecElapsed = 0; } } void GameWindowManager::countFrames( int /* time */ ) { d->frameCount++; } #include "gamewindowmanager.moc" <commit_msg>QML Player: Fix the crash issue because of the MeeGo/N900 testing<commit_after>/***************************************************************************** * This file is part of the Gluon Development Platform * Copyright (c) 2011 Laszlo Papp <djszapi@archlinux.us> * * 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 2 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, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *****************************************************************************/ #include "gamewindowmanager.h" #include "input/inputmanager.h" #include "engine/scene.h" #include <QtCore/QTimer> #include <QtCore/QDebug> #include <QtGui/QApplication> using namespace GluonQMLPlayer; class GameWindowManager::GameWindowManagerPrivate { public: GameWindowManagerPrivate() {} GluonGraphics::RenderWidget* widget; QString title; QString fileName; int msecElapsed; int frameCount; }; GameWindowManager::GameWindowManager(const QString& /* filename */) : QObject() , d( new GameWindowManagerPrivate ) , m_project( new GluonEngine::GameProject ) { } GameWindowManager::GameWindowManager(GluonGraphics::RenderWidget* renderWidget, QGraphicsView* view, GluonPlayer::GameItemsModel* gameItemsModel, const QString& /* filename */ ) : QObject() , d( new GameWindowManagerPrivate ) , m_project( new GluonEngine::GameProject ) , m_view(view) , m_gameItemsModel(gameItemsModel) { d->widget = renderWidget; } GameWindowManager::~GameWindowManager ( ) { } bool GameWindowManager::isViewportGLWidget( ) { return qobject_cast<QGLWidget*>(m_view); } void GameWindowManager::startGame( ) { GluonCore::GluonObjectFactory::instance()->loadPlugins(); m_project->loadFromFile( m_gameFileName ); GluonEngine::Game::instance()->setGameProject( m_project ); GluonEngine::Game::instance()->setCurrentScene( m_project->entryPoint() ); GluonEngine::Game::instance()->runGame(); QApplication::instance()->exit(); } void GameWindowManager::pauseGame() { GluonEngine::Game::instance()->setPause( true ); // stateChanged( "paused" ); } void GameWindowManager::stopGame() { GluonEngine::Game::instance()->stopGame(); } void GameWindowManager::setProject( int index ) { m_gameFileName = m_gameItemsModel->index(index).data(GluonPlayer::GameItemsModel::ProjectFileNameRole).toString(); openProject(); } int GameWindowManager::availableGamesCount( ) const { return m_gameItemsModel->rowCount(); } void GameWindowManager::buildCommentsModel( int index ) { QString gameID = m_gameItemsModel->index(index).data(GluonPlayer::GameItemsModel::IDRole).toString(); if( gameID.isEmpty() ) { return; } m_commentsModel = new GluonPlayer::CommentItemsModel( gameID ); } void GameWindowManager::setProject( const QModelIndex& index ) { m_gameFileName = index.data(GluonPlayer::GameItemsModel::ProjectFileNameRole).toString(); openProject(); } void GameWindowManager::openProject() { if( m_gameFileName.isEmpty() ) { return; } connect( GluonEngine::Game::instance(), SIGNAL( painted( int ) ), d->widget, SLOT( updateGL() ) ); connect( GluonEngine::Game::instance(), SIGNAL( painted( int ) ), SLOT( countFrames( int ) ) ); connect( GluonEngine::Game::instance(), SIGNAL( updated( int ) ), SLOT( updateTitle( int ) ) ); GluonInput::InputManager::instance()->setFilteredObject(d->widget); QTimer::singleShot( 1000, this, SLOT( startGame() ) ); } void GameWindowManager::activated( QModelIndex index ) { if( index.isValid() ) { } } void GameWindowManager::updateTitle( int msec ) { d->msecElapsed += msec; static int fps = 0; if( d->msecElapsed > 1000 ) { fps = d->frameCount; d->frameCount = 0; d->msecElapsed = 0; } } void GameWindowManager::countFrames( int /* time */ ) { d->frameCount++; } #include "gamewindowmanager.moc" <|endoftext|>
<commit_before>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0 #include <websocketpp/config/asio_no_tls.hpp> #include <websocketpp/server.hpp> typedef websocketpp::server<websocketpp::config::asio> server; #include <jsonipc/jsonipc.hh> #include <bse/platform.hh> #include <bse/regex.hh> #include "bse/jsonbindings.cc" #include <bse/bse.hh> // Bse::init_async #undef B0 // pollution from termios.h static Bse::ServerH bse_server; static Jsonipc::IpcDispatcher *dispatcher = NULL; static const bool verbose = false; // Configure websocket server struct CustomServerConfig : public websocketpp::config::asio { static const size_t connection_read_buffer_size = 16384; }; using ServerEndpoint = websocketpp::server<CustomServerConfig>; static ServerEndpoint websocket_server; static std::string handle_jsonipc (const std::string &message, const websocketpp::connection_hdl &hdl) { const ptrdiff_t conid = ptrdiff_t (websocket_server.get_con_from_hdl (hdl).get()); if (verbose) Bse::printerr ("%p: REQUEST: %s\n", conid, message); const std::string reply = dispatcher->dispatch_message (message); if (verbose) Bse::printerr ("%p: REPLY: %s\n", conid, reply); return reply; } static std::string user_agent_nick (const std::string &useragent) { using namespace Bse; std::string nick; if (Re::search (R"(\bFirefox/)", useragent)) nick += "Firefox"; else if (Re::search (R"(\bElectron/)", useragent)) nick += "Electron"; else if (Re::search (R"(\bChrome/)", useragent)) nick += "Chrome"; else if (Re::search (R"(\bSafari/)", useragent)) nick += "Safari"; else nick += "Unknown"; return nick; } static bool ws_validate_connection (websocketpp::connection_hdl hdl) { ServerEndpoint::connection_ptr con = websocket_server.get_con_from_hdl (hdl); // using subprotocol as auth string const std::vector<std::string> &subprotocols = con->get_requested_subprotocols(); if (subprotocols.size() == 1) { if (subprotocols[0] == "auth123") { con->select_subprotocol (subprotocols[0]); return true; } } return false; } static void ws_open_connection (websocketpp::connection_hdl hdl) { ServerEndpoint::connection_ptr con = websocket_server.get_con_from_hdl (hdl); // https://github.com/zaphoyd/websocketpp/issues/694#issuecomment-454623641 const auto &socket = con->get_raw_socket(); const auto &address = socket.remote_endpoint().address(); const int rport = socket.remote_endpoint().port(); const websocketpp::http::parser::request &rq = con->get_request(); const websocketpp::http::parser::header_list &headermap = rq.get_headers(); std::string useragent; for (auto it : headermap) // request headers if (it.first == "User-Agent") useragent = it.second; std::string nick = user_agent_nick (useragent); if (!nick.empty()) nick = "(" + nick + ")"; using namespace Bse::AnsiColors; auto B1 = color (BOLD); auto B0 = color (BOLD_OFF); Bse::printout ("%p: %sACCEPT:%s %s:%d/ %s\n", ptrdiff_t (con.get()), B1, B0, address.to_string().c_str(), rport, nick); // Bse::printout ("User-Agent: %s\n", useragent); } static void ws_message (websocketpp::connection_hdl con, server::message_ptr msg) { const std::string &message = msg->get_payload(); // send message to BSE thread and block until its been handled Aida::ScopedSemaphore sem; auto handle_wsmsg = [&message, &con, &sem] () { std::string reply = handle_jsonipc (message, con); if (!reply.empty()) websocket_server.send (con, reply, websocketpp::frame::opcode::text); sem.post(); }; bse_server.__iface_ptr__()->__execution_context_mt__().enqueue_mt (handle_wsmsg); sem.wait(); } static void print_usage (bool help) { if (!help) { Bse::printout ("beast-sound-engine version %s\n", Bse::version()); return; } Bse::printout ("Usage: beast-sound-engine [OPTIONS]\n"); Bse::printout (" --help Print command line help\n"); Bse::printout (" --version Print program version\n"); } int main (int argc, char *argv[]) { Bse::init_async (&argc, argv, argv[0]); // Bse::cstrings_to_vector (NULL) bse_server = Bse::init_server_instance(); // Register BSE bindings { Aida::ScopedSemaphore sem; auto handle_wsmsg = [&sem] () { Bse::register_json_bindings(); sem.post(); }; bse_server.__iface_ptr__()->__execution_context_mt__().enqueue_mt (handle_wsmsg); sem.wait(); } // Setup Jsonipc dispatcher dispatcher = new Jsonipc::IpcDispatcher(); dispatcher->add_method ("BeastSoundEngine/init_jsonipc", [] (Jsonipc::JsonCallbackInfo &cbi) -> std::string* { cbi.set_result (Jsonipc::to_json (Bse::ServerImpl::instance()).Move()); return NULL; }); // parse arguments bool seen_dashdash = false; std::vector<std::string> words; for (size_t i = 0; i < argc; i++) if (!argv[i]) continue; else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0) seen_dashdash = true; else if (!seen_dashdash && argv[i][0] == '-') { const char *arg = argv[i] + 1 + (argv[i][1] == '-'); const char *eq = strchr (arg, '='); const std::string arg_name = !eq ? arg : std::string (arg, eq - arg); if (arg_name == "version") { print_usage (false); return 0; } else if (arg_name == "h" || arg_name == "help") { print_usage (true); return 0; } else { Bse::printerr ("%s: invalid argument: %s\n", argv[0], argv[i]); print_usage (true); return 1; } } else words.push_back (argv[i]); const int BEAST_AUDIO_ENGINE_PORT = 27239; // 0x3ea67 % 32768 // setup websocket and run asio loop websocket_server.set_validate_handler (&ws_validate_connection); websocket_server.set_open_handler (&ws_open_connection); websocket_server.set_message_handler (&ws_message); websocket_server.init_asio(); websocket_server.clear_access_channels (websocketpp::log::alevel::all); websocket_server.set_reuse_addr (true); namespace IP = boost::asio::ip; IP::tcp::endpoint endpoint_local = IP::tcp::endpoint (IP::address::from_string ("127.0.0.1"), BEAST_AUDIO_ENGINE_PORT); websocket_server.listen (endpoint_local); websocket_server.start_accept(); using namespace Bse::AnsiColors; auto B1 = color (BOLD); auto B0 = color (BOLD_OFF); Bse::printout ("%sLISTEN:%s ws://localhost:%d/\n", B1, B0, BEAST_AUDIO_ENGINE_PORT); websocket_server.run(); return 0; } /* Dumb echo test: var WebSocket = require ('ws'), c = 0; ws = new WebSocket("ws://localhost:27239/", 'auth123'); ws.onopen=e=>ws.send("Hello!"); ws.onmessage=e=>{if(++c % 1000 == 0) console.log(e.data, c); ws.send("YO"); }; setTimeout(e=>{ws.close();console.log(c/10);},10000); */ <commit_msg>BSE: beast-sound-engine: support --verbose<commit_after>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0 #include <websocketpp/config/asio_no_tls.hpp> #include <websocketpp/server.hpp> typedef websocketpp::server<websocketpp::config::asio> server; #include <jsonipc/jsonipc.hh> #include <bse/platform.hh> #include <bse/regex.hh> #include "bse/jsonbindings.cc" #include <bse/bse.hh> // Bse::init_async #undef B0 // pollution from termios.h static Bse::ServerH bse_server; static Jsonipc::IpcDispatcher *dispatcher = NULL; static bool verbose = false; // Configure websocket server struct CustomServerConfig : public websocketpp::config::asio { static const size_t connection_read_buffer_size = 16384; }; using ServerEndpoint = websocketpp::server<CustomServerConfig>; static ServerEndpoint websocket_server; static std::string handle_jsonipc (const std::string &message, const websocketpp::connection_hdl &hdl) { const ptrdiff_t conid = ptrdiff_t (websocket_server.get_con_from_hdl (hdl).get()); if (verbose) Bse::printerr ("%p: REQUEST: %s\n", conid, message); const std::string reply = dispatcher->dispatch_message (message); if (verbose) Bse::printerr ("%p: REPLY: %s\n", conid, reply); return reply; } static std::string user_agent_nick (const std::string &useragent) { using namespace Bse; std::string nick; if (Re::search (R"(\bFirefox/)", useragent)) nick += "Firefox"; else if (Re::search (R"(\bElectron/)", useragent)) nick += "Electron"; else if (Re::search (R"(\bChrome/)", useragent)) nick += "Chrome"; else if (Re::search (R"(\bSafari/)", useragent)) nick += "Safari"; else nick += "Unknown"; return nick; } static bool ws_validate_connection (websocketpp::connection_hdl hdl) { ServerEndpoint::connection_ptr con = websocket_server.get_con_from_hdl (hdl); // using subprotocol as auth string const std::vector<std::string> &subprotocols = con->get_requested_subprotocols(); if (subprotocols.size() == 1) { if (subprotocols[0] == "auth123") { con->select_subprotocol (subprotocols[0]); return true; } } return false; } static void ws_open_connection (websocketpp::connection_hdl hdl) { ServerEndpoint::connection_ptr con = websocket_server.get_con_from_hdl (hdl); // https://github.com/zaphoyd/websocketpp/issues/694#issuecomment-454623641 const auto &socket = con->get_raw_socket(); const auto &address = socket.remote_endpoint().address(); const int rport = socket.remote_endpoint().port(); const websocketpp::http::parser::request &rq = con->get_request(); const websocketpp::http::parser::header_list &headermap = rq.get_headers(); std::string useragent; for (auto it : headermap) // request headers if (it.first == "User-Agent") useragent = it.second; std::string nick = user_agent_nick (useragent); if (!nick.empty()) nick = "(" + nick + ")"; using namespace Bse::AnsiColors; auto B1 = color (BOLD); auto B0 = color (BOLD_OFF); Bse::printout ("%p: %sACCEPT:%s %s:%d/ %s\n", ptrdiff_t (con.get()), B1, B0, address.to_string().c_str(), rport, nick); // Bse::printout ("User-Agent: %s\n", useragent); } static void ws_message (websocketpp::connection_hdl con, server::message_ptr msg) { const std::string &message = msg->get_payload(); // send message to BSE thread and block until its been handled Aida::ScopedSemaphore sem; auto handle_wsmsg = [&message, &con, &sem] () { std::string reply = handle_jsonipc (message, con); if (!reply.empty()) websocket_server.send (con, reply, websocketpp::frame::opcode::text); sem.post(); }; bse_server.__iface_ptr__()->__execution_context_mt__().enqueue_mt (handle_wsmsg); sem.wait(); } static void print_usage (bool help) { if (!help) { Bse::printout ("beast-sound-engine version %s\n", Bse::version()); return; } Bse::printout ("Usage: beast-sound-engine [OPTIONS]\n"); Bse::printout (" --help Print command line help\n"); Bse::printout (" --version Print program version\n"); Bse::printout (" --verbose Print requests and replies\n"); } int main (int argc, char *argv[]) { Bse::init_async (&argc, argv, argv[0]); // Bse::cstrings_to_vector (NULL) bse_server = Bse::init_server_instance(); // Register BSE bindings { Aida::ScopedSemaphore sem; auto handle_wsmsg = [&sem] () { Bse::register_json_bindings(); sem.post(); }; bse_server.__iface_ptr__()->__execution_context_mt__().enqueue_mt (handle_wsmsg); sem.wait(); } // Setup Jsonipc dispatcher dispatcher = new Jsonipc::IpcDispatcher(); dispatcher->add_method ("BeastSoundEngine/init_jsonipc", [] (Jsonipc::JsonCallbackInfo &cbi) -> std::string* { cbi.set_result (Jsonipc::to_json (Bse::ServerImpl::instance()).Move()); return NULL; }); // parse arguments bool seen_dashdash = false; std::vector<std::string> words; for (size_t i = 0; i < argc; i++) if (!argv[i]) continue; else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0) seen_dashdash = true; else if (!seen_dashdash && argv[i][0] == '-') { const char *arg = argv[i] + 1 + (argv[i][1] == '-'); const char *eq = strchr (arg, '='); const std::string arg_name = !eq ? arg : std::string (arg, eq - arg); if (arg_name == "version") { print_usage (false); return 0; } else if (arg_name == "h" || arg_name == "help") { print_usage (true); return 0; } else if (arg_name == "v" || arg_name == "verbose") { verbose = true; } else { Bse::printerr ("%s: invalid argument: %s\n", argv[0], argv[i]); print_usage (true); return 1; } } else words.push_back (argv[i]); const int BEAST_AUDIO_ENGINE_PORT = 27239; // 0x3ea67 % 32768 // setup websocket and run asio loop websocket_server.set_validate_handler (&ws_validate_connection); websocket_server.set_open_handler (&ws_open_connection); websocket_server.set_message_handler (&ws_message); websocket_server.init_asio(); websocket_server.clear_access_channels (websocketpp::log::alevel::all); websocket_server.set_reuse_addr (true); namespace IP = boost::asio::ip; IP::tcp::endpoint endpoint_local = IP::tcp::endpoint (IP::address::from_string ("127.0.0.1"), BEAST_AUDIO_ENGINE_PORT); websocket_server.listen (endpoint_local); websocket_server.start_accept(); using namespace Bse::AnsiColors; auto B1 = color (BOLD); auto B0 = color (BOLD_OFF); Bse::printout ("%sLISTEN:%s ws://localhost:%d/\n", B1, B0, BEAST_AUDIO_ENGINE_PORT); websocket_server.run(); return 0; } /* Dumb echo test: var WebSocket = require ('ws'), c = 0; ws = new WebSocket("ws://localhost:27239/", 'auth123'); ws.onopen=e=>ws.send("Hello!"); ws.onmessage=e=>{if(++c % 1000 == 0) console.log(e.data, c); ws.send("YO"); }; setTimeout(e=>{ws.close();console.log(c/10);},10000); */ <|endoftext|>
<commit_before>#include <string> #include "acmacs-base/argv.hh" #include "acmacs-base/enumerate.hh" #include "acmacs-chart-2/chart.hh" #include "acmacs-chart-2/factory-import.hh" #include "hidb-5/hidb.hh" // ---------------------------------------------------------------------- using namespace acmacs::argv; struct Options : public argv { Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); } argument<str> chart{*this, mandatory}; }; int main(int argc, const char* argv[]) { int exit_code = 0; try { Options opt(argc, argv); auto chart = acmacs::chart::import_from_file(opt.chart, acmacs::chart::Verify::None, report_time::no); const auto& hidb = hidb::get(chart->info()->virus_type(acmacs::chart::Info::Compute::Yes), report_time::no); auto sera = chart->sera(); const auto hidb_sera = hidb.sera()->find(*sera); auto hidb_tables = hidb.tables(); for (auto [sr_no, serum] : acmacs::enumerate(*sera)) { std::cout << std::setw(3) << std::right << sr_no << ' ' << serum->full_name_with_passage() << '\n'; if (auto hidb_serum = hidb_sera[sr_no]; hidb_serum) { const auto stat = hidb_tables->stat(hidb_serum->tables()); for (const auto& entry : stat) std::cout << " " << entry.title() << " tables:" << std::setw(3) << std::right << entry.number << " newest: " << std::setw(30) << std::left << entry.most_recent->name() << " oldest: " << entry.oldest->name() << '\n'; } else std::cerr << "WARNING: not in hidb: " << serum->full_name_with_fields() << '\n'; } } catch (std::exception& err) { std::cerr << err.what() << std::endl; exit_code = 1; } return exit_code; } // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <commit_msg>whocc-sera-of-chart<commit_after>#include <string> #include <regex> #include <optional> #include "acmacs-base/argv.hh" #include "acmacs-base/enumerate.hh" #include "acmacs-chart-2/chart.hh" #include "acmacs-chart-2/factory-import.hh" #include "hidb-5/hidb.hh" // ---------------------------------------------------------------------- using namespace acmacs::argv; struct Options : public argv { Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); } option<str> name{*this, "name", desc{"name (regex) to filter, matched against full_name"}}; argument<str> chart{*this, mandatory}; }; int main(int argc, const char* argv[]) { int exit_code = 0; try { Options opt(argc, argv); std::optional<std::regex> name_match; if (opt.name.has_value()) name_match = std::regex(opt.name->begin(), opt.name->end()); auto chart = acmacs::chart::import_from_file(opt.chart, acmacs::chart::Verify::None, report_time::no); const auto& hidb = hidb::get(chart->info()->virus_type(acmacs::chart::Info::Compute::Yes), report_time::no); auto sera = chart->sera(); const auto hidb_sera = hidb.sera()->find(*sera); auto hidb_tables = hidb.tables(); for (auto [sr_no, serum] : acmacs::enumerate(*sera)) { if (!name_match || std::regex_search(serum->full_name(), *name_match)) { std::cout << std::setw(3) << std::right << sr_no << ' ' << serum->full_name_with_passage() << '\n'; if (auto hidb_serum = hidb_sera[sr_no]; hidb_serum) { const auto stat = hidb_tables->stat(hidb_serum->tables()); for (const auto& entry : stat) std::cout << " " << entry.title() << " tables:" << std::setw(3) << std::right << entry.number << " newest: " << std::setw(30) << std::left << entry.most_recent->name() << " oldest: " << entry.oldest->name() << '\n'; } else std::cerr << "WARNING: not in hidb: " << serum->full_name_with_fields() << '\n'; } } } catch (std::exception& err) { std::cerr << err.what() << std::endl; exit_code = 1; } return exit_code; } // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <|endoftext|>
<commit_before>/* * database_impl.cpp * * Created on: Jul 13, 2015 * Author: zmij */ #include <tip/db/pg/detail/database_impl.hpp> #include <tip/db/pg/detail/connection_pool.hpp> #include <tip/db/pg/error.hpp> #include <stdexcept> #ifdef WITH_TIP_LOG #include <tip/version.hpp> #endif #include <tip/db/pg/log.hpp> namespace tip { namespace db { namespace pg { namespace detail { namespace { /** Local logging facility */ using namespace tip::log; const std::string LOG_CATEGORY = "PGDB"; logger::event_severity DEFAULT_SEVERITY = logger::OFF; local local_log(logger::event_severity s = DEFAULT_SEVERITY) { return local(LOG_CATEGORY, s); } } // namespace // For more convenient changing severity, eg local_log(logger::WARNING) using tip::log::logger; database_impl::database_impl(size_t pool_size, client_options_type const& defaults) : pool_size_(pool_size), defaults_(defaults) { local_log() << "Initializing postgre db service"; } database_impl::~database_impl() { stop(); local_log() << "* database_impl::~database_impl"; } void database_impl::set_defaults(size_t pool_size, client_options_type const& defaults) { pool_size_ = pool_size; defaults_ = defaults; } void database_impl::add_connection(std::string const& connection_string, db_service::optional_size pool_size, client_options_type const& params) { connection_options co = connection_options::parse(connection_string); add_connection(co, pool_size, params); } void database_impl::add_connection(connection_options co, db_service::optional_size pool_size, client_options_type const& params) { if (co.uri.empty()) throw error::connection_error("No URI in database connection string"); if (co.database.empty()) throw error::connection_error("No database name in database connection string"); if (co.user.empty()) throw error::connection_error("No user name in database connection string"); if (co.alias.empty()) { co.generate_alias(); } add_pool(co, pool_size, params); } database_impl::connection_pool_ptr database_impl::add_pool(connection_options const& co, db_service::optional_size pool_size, client_options_type const& params) { if (!connections_.count(co.alias)) { if (!pool_size.is_initialized()) { pool_size = pool_size_; } local_log(logger::INFO) << "Create a new connection pool " << co.alias; client_options_type parms(params); for (auto p : defaults_) { if (!parms.count(p.first)) { parms.insert(p); } } local_log(logger::INFO) << "Register new connection " << co.uri << "[" << co.database << "]" << " with alias " << co.alias; connections_.insert(std::make_pair(co.alias, connection_pool_ptr(connection_pool::create(service_, *pool_size, co, parms) ))); } return connections_[co.alias]; } void database_impl::get_connection(dbalias const& alias, transaction_callback const& cb, error_callback const& err) { if (!connections_.count(alias)) { throw error::connection_error("Database alias is not registered"); } connection_pool_ptr pool = connections_[alias]; pool->get_connection(cb, err); } void database_impl::run() { service_.run(); } void database_impl::stop() { for (auto c: connections_) { c.second->close(); } connections_.clear(); if (!service_.stopped()) { service_.stop(); service_.reset(); } } } /* namespace detail */ } /* namespace pg */ } /* namespace db */ } /* namespace tip */ <commit_msg>Refactor server configuration<commit_after>/* * database_impl.cpp * * Created on: Jul 13, 2015 * Author: zmij */ #include <tip/db/pg/detail/database_impl.hpp> #include <tip/db/pg/detail/connection_pool.hpp> #include <tip/db/pg/error.hpp> #include <stdexcept> #ifdef WITH_TIP_LOG #include <tip/version.hpp> #endif #include <tip/db/pg/log.hpp> namespace tip { namespace db { namespace pg { namespace detail { namespace { /** Local logging facility */ using namespace tip::log; const std::string LOG_CATEGORY = "PGDB"; logger::event_severity DEFAULT_SEVERITY = logger::OFF; local local_log(logger::event_severity s = DEFAULT_SEVERITY) { return local(LOG_CATEGORY, s); } } // namespace // For more convenient changing severity, eg local_log(logger::WARNING) using tip::log::logger; database_impl::database_impl(size_t pool_size, client_options_type const& defaults) : pool_size_(pool_size), defaults_(defaults) { local_log() << "Initializing postgre db service"; } database_impl::~database_impl() { stop(); local_log() << "* database_impl::~database_impl"; } void database_impl::set_defaults(size_t pool_size, client_options_type const& defaults) { pool_size_ = pool_size; defaults_ = defaults; } void database_impl::add_connection(std::string const& connection_string, db_service::optional_size pool_size, client_options_type const& params) { connection_options co = connection_options::parse(connection_string); add_connection(co, pool_size, params); } void database_impl::add_connection(connection_options co, db_service::optional_size pool_size, client_options_type const& params) { if (co.uri.empty()) throw error::connection_error("No URI in database connection string"); if (co.database.empty()) throw error::connection_error("No database name in database connection string"); if (co.user.empty()) throw error::connection_error("No user name in database connection string"); if (co.alias.empty()) { co.generate_alias(); } add_pool(co, pool_size, params); } database_impl::connection_pool_ptr database_impl::add_pool(connection_options const& co, db_service::optional_size pool_size, client_options_type const& params) { if (!connections_.count(co.alias)) { if (!pool_size.is_initialized()) { pool_size = pool_size_; } local_log(logger::INFO) << "Create a new connection pool " << co.alias; client_options_type parms(params); for (auto p : defaults_) { if (!parms.count(p.first)) { parms.insert(p); } } local_log(logger::INFO) << "Register new connection " << co.uri << "[" << co.database << "]" << " with alias " << co.alias; connections_.insert(std::make_pair(co.alias, connection_pool_ptr(connection_pool::create(service_, *pool_size, co, parms) ))); } return connections_[co.alias]; } void database_impl::get_connection(dbalias const& alias, transaction_callback const& cb, error_callback const& err) { if (!connections_.count(alias)) { throw error::connection_error("Database alias is not registered"); } connection_pool_ptr pool = connections_[alias]; pool->get_connection(cb, err); } void database_impl::run() { service_.run(); } void database_impl::stop() { local_log() << "Closing connections"; for (auto c: connections_) { c.second->close(); } connections_.clear(); service_.stop(); } } /* namespace detail */ } /* namespace pg */ } /* namespace db */ } /* namespace tip */ <|endoftext|>
<commit_before>/* * Copyright 2017 WebAssembly Community Group participants * * 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. */ // // wasm-emscripten-finalize console tool // Performs Emscripten-specific transforms on .wasm files // #include <exception> #include "abi/js.h" #include "ir/trapping.h" #include "support/colors.h" #include "support/file.h" #include "tool-options.h" #include "wasm-binary.h" #include "wasm-emscripten.h" #include "wasm-io.h" #include "wasm-printing.h" #include "wasm-validator.h" using namespace cashew; using namespace wasm; int main(int argc, const char* argv[]) { const uint64_t INVALID_BASE = -1; std::string infile; std::string outfile; std::string inputSourceMapFilename; std::string outputSourceMapFilename; std::string outputSourceMapUrl; std::string dataSegmentFile; bool emitBinary = true; bool debugInfo = false; bool isSideModule = false; bool legalizeJavaScriptFFI = true; bool checkStackOverflow = false; uint64_t globalBase = INVALID_BASE; bool standaloneWasm = false; ToolOptions options("wasm-emscripten-finalize", "Performs Emscripten-specific transforms on .wasm files"); options .add("--output", "-o", "Output file", Options::Arguments::One, [&outfile](Options*, const std::string& argument) { outfile = argument; Colors::setEnabled(false); }) .add("--debuginfo", "-g", "Emit names section in wasm binary (or full debuginfo in wast)", Options::Arguments::Zero, [&debugInfo](Options*, const std::string&) { debugInfo = true; }) .add("--emit-text", "-S", "Emit text instead of binary for the output file", Options::Arguments::Zero, [&emitBinary](Options*, const std::string&) { emitBinary = false; }) .add("--global-base", "", "The address at which static globals were placed", Options::Arguments::One, [&globalBase](Options*, const std::string& argument) { globalBase = std::stoull(argument); }) // TODO(sbc): Remove this one this argument is no longer passed by // emscripten. See https://github.com/emscripten-core/emscripten/issues/8905 .add("--initial-stack-pointer", "", "ignored - will be removed in a future release", Options::Arguments::One, [](Options*, const std::string& argument) {}) .add("--side-module", "", "Input is an emscripten side module", Options::Arguments::Zero, [&isSideModule](Options* o, const std::string& argument) { isSideModule = true; }) .add("--input-source-map", "-ism", "Consume source map from the specified file", Options::Arguments::One, [&inputSourceMapFilename](Options* o, const std::string& argument) { inputSourceMapFilename = argument; }) .add("--no-legalize-javascript-ffi", "-nj", "Do not fully legalize (i64->i32, " "f32->f64) the imports and exports for interfacing with JS", Options::Arguments::Zero, [&legalizeJavaScriptFFI](Options* o, const std::string&) { legalizeJavaScriptFFI = false; }) .add("--output-source-map", "-osm", "Emit source map to the specified file", Options::Arguments::One, [&outputSourceMapFilename](Options* o, const std::string& argument) { outputSourceMapFilename = argument; }) .add("--output-source-map-url", "-osu", "Emit specified string as source map URL", Options::Arguments::One, [&outputSourceMapUrl](Options* o, const std::string& argument) { outputSourceMapUrl = argument; }) .add("--separate-data-segments", "", "Separate data segments to a file", Options::Arguments::One, [&dataSegmentFile](Options* o, const std::string& argument) { dataSegmentFile = argument; }) .add("--check-stack-overflow", "", "Check for stack overflows every time the stack is extended", Options::Arguments::Zero, [&checkStackOverflow](Options* o, const std::string&) { checkStackOverflow = true; }) .add("--standalone-wasm", "", "Emit a wasm file that does not depend on JS, as much as possible," " using wasi and other standard conventions etc. where possible", Options::Arguments::Zero, [&standaloneWasm](Options* o, const std::string&) { standaloneWasm = true; }) .add_positional("INFILE", Options::Arguments::One, [&infile](Options* o, const std::string& argument) { infile = argument; }); options.parse(argc, argv); if (infile == "") { Fatal() << "Need to specify an infile\n"; } if (outfile == "" && emitBinary) { Fatal() << "Need to specify an outfile, or use text output\n"; } Module wasm; ModuleReader reader; try { reader.read(infile, wasm, inputSourceMapFilename); } catch (ParseException& p) { p.dump(std::cerr); std::cerr << '\n'; Fatal() << "error in parsing input"; } catch (MapParseException& p) { p.dump(std::cerr); std::cerr << '\n'; Fatal() << "error in parsing wasm source map"; } options.applyFeatures(wasm); if (options.debug) { std::cerr << "Module before:\n"; WasmPrinter::printModule(&wasm, std::cerr); } uint32_t dataSize = 0; if (!isSideModule) { if (globalBase == INVALID_BASE) { Fatal() << "globalBase must be set"; } Export* dataEndExport = wasm.getExport("__data_end"); if (dataEndExport == nullptr) { Fatal() << "__data_end export not found"; } Global* dataEnd = wasm.getGlobal(dataEndExport->value); if (dataEnd == nullptr) { Fatal() << "__data_end global not found"; } if (dataEnd->type != Type::i32) { Fatal() << "__data_end global has wrong type"; } if (dataEnd->imported()) { Fatal() << "__data_end must not be an imported global"; } Const* dataEndConst = dataEnd->init->cast<Const>(); dataSize = dataEndConst->value.geti32() - globalBase; } EmscriptenGlueGenerator generator(wasm); generator.fixInvokeFunctionNames(); std::vector<Name> initializerFunctions; if (wasm.table.imported()) { if (wasm.table.base != "table") { wasm.table.base = Name("table"); } } if (wasm.memory.imported()) { if (wasm.table.base != "memory") { wasm.memory.base = Name("memory"); } } wasm.updateMaps(); if (checkStackOverflow && !isSideModule) { generator.enforceStackLimit(); } if (isSideModule) { generator.replaceStackPointerGlobal(); generator.generatePostInstantiateFunction(); } else { generator.generateRuntimeFunctions(); generator.internalizeStackPointerGlobal(); generator.generateMemoryGrowthFunction(); // For side modules these gets called via __post_instantiate if (Function* F = generator.generateAssignGOTEntriesFunction()) { auto* ex = new Export(); ex->value = F->name; ex->name = F->name; ex->kind = ExternalKind::Function; wasm.addExport(ex); initializerFunctions.push_back(F->name); } if (auto* e = wasm.getExportOrNull(WASM_CALL_CTORS)) { initializerFunctions.push_back(e->name); } } if (standaloneWasm) { // Export a standard wasi "_start" method. generator.exportWasiStart(); } else { // If not standalone wasm then JS is relevant and we need dynCalls. generator.generateDynCallThunks(); } // Legalize the wasm. { PassRunner passRunner(&wasm); passRunner.setDebug(options.debug); passRunner.setDebugInfo(debugInfo); passRunner.add(ABI::getLegalizationPass( legalizeJavaScriptFFI ? ABI::LegalizationLevel::Full : ABI::LegalizationLevel::Minimal)); passRunner.run(); } // Substantial changes to the wasm are done, enough to create the metadata. std::string metadata = generator.generateEmscriptenMetadata(dataSize, initializerFunctions); // Finally, separate out data segments if relevant (they may have been needed // for metadata). if (!dataSegmentFile.empty()) { Output memInitFile(dataSegmentFile, Flags::Binary, Flags::Release); if (globalBase == INVALID_BASE) { Fatal() << "globalBase must be set"; } generator.separateDataSegments(&memInitFile, globalBase); } if (options.debug) { std::cerr << "Module after:\n"; WasmPrinter::printModule(&wasm, std::cerr); } // Strip target features section (its information is in the metadata) { PassRunner passRunner(&wasm); passRunner.add("strip-target-features"); passRunner.run(); } auto outputBinaryFlag = emitBinary ? Flags::Binary : Flags::Text; Output output(outfile, outputBinaryFlag, Flags::Release); ModuleWriter writer; writer.setDebug(options.debug); writer.setDebugInfo(debugInfo); // writer.setSymbolMap(symbolMap); writer.setBinary(emitBinary); if (outputSourceMapFilename.size()) { writer.setSourceMapFilename(outputSourceMapFilename); writer.setSourceMapUrl(outputSourceMapUrl); } writer.write(wasm, output); if (emitBinary) { std::cout << metadata; } else { output << "(;\n"; output << "--BEGIN METADATA --\n" << metadata << "-- END METADATA --\n"; output << ";)\n"; } return 0; } <commit_msg>Don't add __wasm_call_ctors to startup function list in wasm standalone mode (#2384)<commit_after>/* * Copyright 2017 WebAssembly Community Group participants * * 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. */ // // wasm-emscripten-finalize console tool // Performs Emscripten-specific transforms on .wasm files // #include <exception> #include "abi/js.h" #include "ir/trapping.h" #include "support/colors.h" #include "support/file.h" #include "tool-options.h" #include "wasm-binary.h" #include "wasm-emscripten.h" #include "wasm-io.h" #include "wasm-printing.h" #include "wasm-validator.h" using namespace cashew; using namespace wasm; int main(int argc, const char* argv[]) { const uint64_t INVALID_BASE = -1; std::string infile; std::string outfile; std::string inputSourceMapFilename; std::string outputSourceMapFilename; std::string outputSourceMapUrl; std::string dataSegmentFile; bool emitBinary = true; bool debugInfo = false; bool isSideModule = false; bool legalizeJavaScriptFFI = true; bool checkStackOverflow = false; uint64_t globalBase = INVALID_BASE; bool standaloneWasm = false; ToolOptions options("wasm-emscripten-finalize", "Performs Emscripten-specific transforms on .wasm files"); options .add("--output", "-o", "Output file", Options::Arguments::One, [&outfile](Options*, const std::string& argument) { outfile = argument; Colors::setEnabled(false); }) .add("--debuginfo", "-g", "Emit names section in wasm binary (or full debuginfo in wast)", Options::Arguments::Zero, [&debugInfo](Options*, const std::string&) { debugInfo = true; }) .add("--emit-text", "-S", "Emit text instead of binary for the output file", Options::Arguments::Zero, [&emitBinary](Options*, const std::string&) { emitBinary = false; }) .add("--global-base", "", "The address at which static globals were placed", Options::Arguments::One, [&globalBase](Options*, const std::string& argument) { globalBase = std::stoull(argument); }) // TODO(sbc): Remove this one this argument is no longer passed by // emscripten. See https://github.com/emscripten-core/emscripten/issues/8905 .add("--initial-stack-pointer", "", "ignored - will be removed in a future release", Options::Arguments::One, [](Options*, const std::string& argument) {}) .add("--side-module", "", "Input is an emscripten side module", Options::Arguments::Zero, [&isSideModule](Options* o, const std::string& argument) { isSideModule = true; }) .add("--input-source-map", "-ism", "Consume source map from the specified file", Options::Arguments::One, [&inputSourceMapFilename](Options* o, const std::string& argument) { inputSourceMapFilename = argument; }) .add("--no-legalize-javascript-ffi", "-nj", "Do not fully legalize (i64->i32, " "f32->f64) the imports and exports for interfacing with JS", Options::Arguments::Zero, [&legalizeJavaScriptFFI](Options* o, const std::string&) { legalizeJavaScriptFFI = false; }) .add("--output-source-map", "-osm", "Emit source map to the specified file", Options::Arguments::One, [&outputSourceMapFilename](Options* o, const std::string& argument) { outputSourceMapFilename = argument; }) .add("--output-source-map-url", "-osu", "Emit specified string as source map URL", Options::Arguments::One, [&outputSourceMapUrl](Options* o, const std::string& argument) { outputSourceMapUrl = argument; }) .add("--separate-data-segments", "", "Separate data segments to a file", Options::Arguments::One, [&dataSegmentFile](Options* o, const std::string& argument) { dataSegmentFile = argument; }) .add("--check-stack-overflow", "", "Check for stack overflows every time the stack is extended", Options::Arguments::Zero, [&checkStackOverflow](Options* o, const std::string&) { checkStackOverflow = true; }) .add("--standalone-wasm", "", "Emit a wasm file that does not depend on JS, as much as possible," " using wasi and other standard conventions etc. where possible", Options::Arguments::Zero, [&standaloneWasm](Options* o, const std::string&) { standaloneWasm = true; }) .add_positional("INFILE", Options::Arguments::One, [&infile](Options* o, const std::string& argument) { infile = argument; }); options.parse(argc, argv); if (infile == "") { Fatal() << "Need to specify an infile\n"; } if (outfile == "" && emitBinary) { Fatal() << "Need to specify an outfile, or use text output\n"; } Module wasm; ModuleReader reader; try { reader.read(infile, wasm, inputSourceMapFilename); } catch (ParseException& p) { p.dump(std::cerr); std::cerr << '\n'; Fatal() << "error in parsing input"; } catch (MapParseException& p) { p.dump(std::cerr); std::cerr << '\n'; Fatal() << "error in parsing wasm source map"; } options.applyFeatures(wasm); if (options.debug) { std::cerr << "Module before:\n"; WasmPrinter::printModule(&wasm, std::cerr); } uint32_t dataSize = 0; if (!isSideModule) { if (globalBase == INVALID_BASE) { Fatal() << "globalBase must be set"; } Export* dataEndExport = wasm.getExport("__data_end"); if (dataEndExport == nullptr) { Fatal() << "__data_end export not found"; } Global* dataEnd = wasm.getGlobal(dataEndExport->value); if (dataEnd == nullptr) { Fatal() << "__data_end global not found"; } if (dataEnd->type != Type::i32) { Fatal() << "__data_end global has wrong type"; } if (dataEnd->imported()) { Fatal() << "__data_end must not be an imported global"; } Const* dataEndConst = dataEnd->init->cast<Const>(); dataSize = dataEndConst->value.geti32() - globalBase; } EmscriptenGlueGenerator generator(wasm); generator.fixInvokeFunctionNames(); std::vector<Name> initializerFunctions; if (wasm.table.imported()) { if (wasm.table.base != "table") { wasm.table.base = Name("table"); } } if (wasm.memory.imported()) { if (wasm.table.base != "memory") { wasm.memory.base = Name("memory"); } } wasm.updateMaps(); if (checkStackOverflow && !isSideModule) { generator.enforceStackLimit(); } if (isSideModule) { generator.replaceStackPointerGlobal(); generator.generatePostInstantiateFunction(); } else { generator.generateRuntimeFunctions(); generator.internalizeStackPointerGlobal(); generator.generateMemoryGrowthFunction(); // For side modules these gets called via __post_instantiate if (Function* F = generator.generateAssignGOTEntriesFunction()) { auto* ex = new Export(); ex->value = F->name; ex->name = F->name; ex->kind = ExternalKind::Function; wasm.addExport(ex); initializerFunctions.push_back(F->name); } // Costructors get called from crt1 in wasm standalone mode. // Unless there is no entry point. if (!standaloneWasm || !wasm.getExportOrNull("_start")) { if (auto* e = wasm.getExportOrNull(WASM_CALL_CTORS)) { initializerFunctions.push_back(e->name); } } } if (standaloneWasm) { // Export a standard wasi "_start" method. generator.exportWasiStart(); } else { // If not standalone wasm then JS is relevant and we need dynCalls. generator.generateDynCallThunks(); } // Legalize the wasm. { PassRunner passRunner(&wasm); passRunner.setDebug(options.debug); passRunner.setDebugInfo(debugInfo); passRunner.add(ABI::getLegalizationPass( legalizeJavaScriptFFI ? ABI::LegalizationLevel::Full : ABI::LegalizationLevel::Minimal)); passRunner.run(); } // Substantial changes to the wasm are done, enough to create the metadata. std::string metadata = generator.generateEmscriptenMetadata(dataSize, initializerFunctions); // Finally, separate out data segments if relevant (they may have been needed // for metadata). if (!dataSegmentFile.empty()) { Output memInitFile(dataSegmentFile, Flags::Binary, Flags::Release); if (globalBase == INVALID_BASE) { Fatal() << "globalBase must be set"; } generator.separateDataSegments(&memInitFile, globalBase); } if (options.debug) { std::cerr << "Module after:\n"; WasmPrinter::printModule(&wasm, std::cerr); } // Strip target features section (its information is in the metadata) { PassRunner passRunner(&wasm); passRunner.add("strip-target-features"); passRunner.run(); } auto outputBinaryFlag = emitBinary ? Flags::Binary : Flags::Text; Output output(outfile, outputBinaryFlag, Flags::Release); ModuleWriter writer; writer.setDebug(options.debug); writer.setDebugInfo(debugInfo); // writer.setSymbolMap(symbolMap); writer.setBinary(emitBinary); if (outputSourceMapFilename.size()) { writer.setSourceMapFilename(outputSourceMapFilename); writer.setSourceMapUrl(outputSourceMapUrl); } writer.write(wasm, output); if (emitBinary) { std::cout << metadata; } else { output << "(;\n"; output << "--BEGIN METADATA --\n" << metadata << "-- END METADATA --\n"; output << ";)\n"; } return 0; } <|endoftext|>
<commit_before>// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2016 Intel Corporation. All Rights Reserved. #include "windows/v10/disk_read.h" #include "windows/v10/file_types.h" #include "windows/v10/conversions.h" #include "include/file.h" #include "rs/utils/log_utils.h" namespace { static rs_capabilities get_capability(rs_stream stream) { switch(stream) { case rs_stream::RS_STREAM_COLOR: return rs_capabilities::RS_CAPABILITIES_COLOR; case rs_stream::RS_STREAM_DEPTH: return rs_capabilities::RS_CAPABILITIES_DEPTH; case rs_stream::RS_STREAM_INFRARED: return rs_capabilities::RS_CAPABILITIES_INFRARED; case rs_stream::RS_STREAM_INFRARED2: return rs_capabilities::RS_CAPABILITIES_INFRARED2; case rs_stream::RS_STREAM_FISHEYE: return rs_capabilities::RS_CAPABILITIES_FISH_EYE; default: return rs_capabilities::RS_CAPABILITIES_COUNT; } } } using namespace rs::playback::windows::v10::file_types; namespace rs { namespace playback { namespace windows { namespace v10 { struct FrameInfo { int64_t offset; // file offset in bytes int64_t timeStamp; // the time stamp in 100ns. int32_t syncId; // syncId in the file }; disk_read::~disk_read(void) { LOG_FUNC_SCOPE(); pause(); } void disk_read::handle_ds_projection(std::vector<uint8_t> &projection_data) { LOG_INFO("handle ds projection") auto data = &(projection_data.data()[640]); // 640 is the size of PXCSerializableService::ProfileInfo ds_projection::ProjectionDataVersions projectionDataVersion = (ds_projection::ProjectionDataVersions)((unsigned int)(*data)); ds_projection::ProjectionData* projection = NULL; ds_projection::ProjectionData v0TmpProjection; switch (projectionDataVersion) { case ds_projection::ProjectionDataVersions::VERSION_0: { ds_projection::Version0_ProjectionData* version0ProjectionData = reinterpret_cast<ds_projection::Version0_ProjectionData*>(data); v0TmpProjection = *version0ProjectionData; projection = &v0TmpProjection; } break; case ds_projection::ProjectionDataVersions::VERSION_1: projection = reinterpret_cast<ds_projection::ProjectionData*>(data); break; } m_streams_infos[rs_stream::RS_STREAM_COLOR].profile.intrinsics = conversions::get_intrinsics(file_types::stream_type::stream_type_color, projection); m_streams_infos[rs_stream::RS_STREAM_DEPTH].profile.intrinsics = conversions::get_intrinsics(file_types::stream_type::stream_type_depth, projection); m_streams_infos[rs_stream::RS_STREAM_COLOR].profile.extrinsics = conversions::get_extrinsics(file_types::stream_type::stream_type_color, projection); } core::status disk_read::read_headers() { /* Get the file header */ m_file_data_read->set_position(0, core::move_method::begin); disk_format::header header; auto data_read_status = m_file_data_read->read_to_object(header); if(data_read_status == core::status_no_error) data_read_status = conversions::convert(header, m_file_header); if(data_read_status != core::status_no_error) return core::status_item_unavailable; if (header.version >= 8) data_read_status = conversions::convert(header.coordinate_system, m_file_header.coordinate_system); /* Get all chunks */ while (data_read_status == core::status_no_error) { disk_format::chunk chunk = {}; data_read_status = m_file_data_read->read_to_object(chunk); if (data_read_status != core::status_no_error || chunk.chunk_id == file_types::disk_format::chunk_frame_meta_data) break; switch (chunk.chunk_id) { case file_types::disk_format::chunk_deviceinfo: { file_types::disk_format::device_info_disk did; data_read_status = m_file_data_read->read_to_object(did, chunk.chunk_size); if(data_read_status == core::status_no_error) data_read_status = conversions::convert(did, m_camera_info); LOG_INFO("read device info chunk " << (data_read_status == core::status_no_error ? "succeeded" : "failed")); } break; case file_types::disk_format::chunk_profiles: { file_types::disk_format::stream_profile_set_disk spsd; data_read_status = m_file_data_read->read_to_object(spsd, chunk.chunk_size); if(data_read_status == core::status_no_error) data_read_status = conversions::convert(spsd, m_streams_infos); LOG_INFO("read profiles chunk " << (data_read_status == core::status_no_error ? "succeeded" : "failed")); } break; case file_types::disk_format::chunk_properties://TODO - create conversion table { uint32_t devcap_count = static_cast<uint32_t>(chunk.chunk_size / sizeof(file_types::device_cap)); std::vector<file_types::device_cap> devcaps(devcap_count); data_read_status = m_file_data_read->read_to_object_array(devcaps); LOG_INFO("read properties chunk " << (data_read_status == core::status_no_error ? "succeeded" : "failed")); } break; case file_types::disk_format::chunk_serializeable: { file_types::property label = static_cast<file_types::property>(0); data_read_status = m_file_data_read->read_to_object(label); if(data_read_status == core::status_no_error) { auto data_size = static_cast<uint32_t>(chunk.chunk_size - sizeof(label)); std::vector<uint8_t> data(data_size); data_read_status = m_file_data_read->read_to_object_array(data); if (label == file_types::property::property_projection_serializable) { auto str = m_camera_info.at(rs_camera_info::RS_CAMERA_INFO_DEVICE_NAME); std::size_t found = str.find("R200"); if (found != std::string::npos) { handle_ds_projection(data); } } } LOG_INFO("read serializeable chunk " << (data_read_status == core::status_no_error ? "succeeded" : "failed")); } break; case file_types::disk_format::chunk_streaminfo: { uint32_t stream_count = static_cast<uint32_t>(chunk.chunk_size / sizeof(disk_format::stream_info)); std::vector<disk_format::stream_info> stream_infos(stream_count); data_read_status = m_file_data_read->read_to_object_array(stream_infos); if(data_read_status == core::status_no_error) { for (auto &stream_info : stream_infos) { core::file_types::stream_info si; auto sts = conversions::convert(stream_info, si); if(sts == core::status_feature_unsupported) continue; //ignore unsupported streams if(sts != core::status_no_error) return core::status_item_unavailable; m_streams_infos[si.stream] = si; auto cap = get_capability(si.stream); if(cap != rs_capabilities::RS_CAPABILITIES_COUNT) m_capabilities.push_back(cap); } } LOG_INFO("read stream info chunk " << (data_read_status == core::status_no_error ? "succeeded" : "failed")); } break; default: { auto& data = m_unknowns[static_cast<core::file_types::chunk_id>(chunk.chunk_id)]; data.resize(chunk.chunk_size); data_read_status = m_file_data_read->read_to_object_array(data); LOG_INFO("read unknown chunk " << (data_read_status == core::status_no_error ? "succeeded" : "failed") << "chunk id - " << chunk.chunk_id); } break; } if (data_read_status != core::status_no_error) return core::status_item_unavailable; } return data_read_status; } int32_t disk_read::size_of_pitches(void) { return sizeof(int32_t) * NUM_OF_PLANES; } void disk_read::index_next_samples(uint32_t number_of_samples) { if (m_is_index_complete) return; std::lock_guard<std::mutex> guard(m_mutex); for (uint32_t index = 0; index < number_of_samples;) { disk_format::chunk chunk = {}; bool data_read_status = m_file_indexing->read_to_object(chunk); if (data_read_status != core::status_no_error || chunk.chunk_size <= 0 || chunk.chunk_size > 100000000 /*invalid chunk*/) { m_is_index_complete = true; LOG_INFO("samples indexing is done") break; } if (chunk.chunk_id == file_types::disk_format::chunk_frame_meta_data) { file_types::disk_format::frame_metadata mdata = {}; uint32_t so = static_cast<uint32_t>(m_file_header.version < 10 ? 24 : (unsigned long)sizeof(mdata)); data_read_status = m_file_indexing->read_to_object(mdata, so); core::file_types::sample_info sample_info; core::file_types::frame_info frame_info; if(conversions::convert(mdata, frame_info) != core::status_no_error) continue; auto ts = frame_info.time_stamp; auto st = frame_info.stream; auto fn = frame_info.number; frame_info = m_streams_infos[frame_info.stream].profile.info; frame_info.time_stamp = ts; frame_info.stream = st; frame_info.number = fn; if(m_time_stamp_base == 0) m_time_stamp_base = static_cast<uint64_t>(frame_info.time_stamp); frame_info.time_stamp -= static_cast<double>(m_time_stamp_base); sample_info.type = core::file_types::sample_type::st_image; sample_info.capture_time = static_cast<uint64_t>(frame_info.time_stamp); m_file_indexing->get_position(&sample_info.offset); frame_info.index_in_stream = static_cast<uint32_t>(m_image_indices[frame_info.stream].size()); m_image_indices[frame_info.stream].push_back(static_cast<uint32_t>(m_samples_desc.size())); m_samples_desc.push_back(std::make_shared<core::file_types::frame_sample>(frame_info, sample_info)); ++index; LOG_VERBOSE("frame sample indexed, sample time - " << sample_info.capture_time) } else { // skip any other sections m_file_indexing->set_position(chunk.chunk_size, core::move_method::current); } } } uint32_t disk_read::read_frame_metadata(const std::shared_ptr<core::file_types::frame_sample> & frame, unsigned long num_bytes_to_read) { //Does not do anything at the moment m_file_data_read->set_position(num_bytes_to_read, core::move_method::current); return 0; } } } } } <commit_msg>fix disk_read KW issue<commit_after>// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2016 Intel Corporation. All Rights Reserved. #include "windows/v10/disk_read.h" #include "windows/v10/file_types.h" #include "windows/v10/conversions.h" #include "include/file.h" #include "rs/utils/log_utils.h" namespace { static rs_capabilities get_capability(rs_stream stream) { switch(stream) { case rs_stream::RS_STREAM_COLOR: return rs_capabilities::RS_CAPABILITIES_COLOR; case rs_stream::RS_STREAM_DEPTH: return rs_capabilities::RS_CAPABILITIES_DEPTH; case rs_stream::RS_STREAM_INFRARED: return rs_capabilities::RS_CAPABILITIES_INFRARED; case rs_stream::RS_STREAM_INFRARED2: return rs_capabilities::RS_CAPABILITIES_INFRARED2; case rs_stream::RS_STREAM_FISHEYE: return rs_capabilities::RS_CAPABILITIES_FISH_EYE; default: return rs_capabilities::RS_CAPABILITIES_COUNT; } } } using namespace rs::playback::windows::v10::file_types; namespace rs { namespace playback { namespace windows { namespace v10 { struct FrameInfo { int64_t offset; // file offset in bytes int64_t timeStamp; // the time stamp in 100ns. int32_t syncId; // syncId in the file }; disk_read::~disk_read(void) { LOG_FUNC_SCOPE(); pause(); } void disk_read::handle_ds_projection(std::vector<uint8_t> &projection_data) { LOG_INFO("handle ds projection") auto data = &(projection_data.data()[640]); // 640 is the size of PXCSerializableService::ProfileInfo ds_projection::ProjectionDataVersions projectionDataVersion = (ds_projection::ProjectionDataVersions)((unsigned int)(*data)); ds_projection::ProjectionData* projection = NULL; ds_projection::ProjectionData v0TmpProjection; switch (projectionDataVersion) { case ds_projection::ProjectionDataVersions::VERSION_0: { ds_projection::Version0_ProjectionData* version0ProjectionData = reinterpret_cast<ds_projection::Version0_ProjectionData*>(data); v0TmpProjection = *version0ProjectionData; projection = &v0TmpProjection; } break; case ds_projection::ProjectionDataVersions::VERSION_1: projection = reinterpret_cast<ds_projection::ProjectionData*>(data); break; } m_streams_infos[rs_stream::RS_STREAM_COLOR].profile.intrinsics = conversions::get_intrinsics(file_types::stream_type::stream_type_color, projection); m_streams_infos[rs_stream::RS_STREAM_DEPTH].profile.intrinsics = conversions::get_intrinsics(file_types::stream_type::stream_type_depth, projection); m_streams_infos[rs_stream::RS_STREAM_COLOR].profile.extrinsics = conversions::get_extrinsics(file_types::stream_type::stream_type_color, projection); } core::status disk_read::read_headers() { /* Get the file header */ m_file_data_read->set_position(0, core::move_method::begin); disk_format::header header = {}; auto data_read_status = m_file_data_read->read_to_object(header); if(data_read_status == core::status_no_error) data_read_status = conversions::convert(header, m_file_header); if(data_read_status != core::status_no_error) return core::status_item_unavailable; if (header.version >= 8) data_read_status = conversions::convert(header.coordinate_system, m_file_header.coordinate_system); /* Get all chunks */ while (data_read_status == core::status_no_error) { disk_format::chunk chunk = {}; data_read_status = m_file_data_read->read_to_object(chunk); if (data_read_status != core::status_no_error || chunk.chunk_id == file_types::disk_format::chunk_frame_meta_data) break; switch (chunk.chunk_id) { case file_types::disk_format::chunk_deviceinfo: { file_types::disk_format::device_info_disk did; data_read_status = m_file_data_read->read_to_object(did, chunk.chunk_size); if(data_read_status == core::status_no_error) data_read_status = conversions::convert(did, m_camera_info); LOG_INFO("read device info chunk " << (data_read_status == core::status_no_error ? "succeeded" : "failed")); } break; case file_types::disk_format::chunk_profiles: { file_types::disk_format::stream_profile_set_disk spsd; data_read_status = m_file_data_read->read_to_object(spsd, chunk.chunk_size); if(data_read_status == core::status_no_error) data_read_status = conversions::convert(spsd, m_streams_infos); LOG_INFO("read profiles chunk " << (data_read_status == core::status_no_error ? "succeeded" : "failed")); } break; case file_types::disk_format::chunk_properties://TODO - create conversion table { uint32_t devcap_count = static_cast<uint32_t>(chunk.chunk_size / sizeof(file_types::device_cap)); std::vector<file_types::device_cap> devcaps(devcap_count); data_read_status = m_file_data_read->read_to_object_array(devcaps); LOG_INFO("read properties chunk " << (data_read_status == core::status_no_error ? "succeeded" : "failed")); } break; case file_types::disk_format::chunk_serializeable: { file_types::property label = static_cast<file_types::property>(0); data_read_status = m_file_data_read->read_to_object(label); if(data_read_status == core::status_no_error) { auto data_size = static_cast<uint32_t>(chunk.chunk_size - sizeof(label)); std::vector<uint8_t> data(data_size); data_read_status = m_file_data_read->read_to_object_array(data); if (label == file_types::property::property_projection_serializable) { auto str = m_camera_info.at(rs_camera_info::RS_CAMERA_INFO_DEVICE_NAME); std::size_t found = str.find("R200"); if (found != std::string::npos) { handle_ds_projection(data); } } } LOG_INFO("read serializeable chunk " << (data_read_status == core::status_no_error ? "succeeded" : "failed")); } break; case file_types::disk_format::chunk_streaminfo: { uint32_t stream_count = static_cast<uint32_t>(chunk.chunk_size / sizeof(disk_format::stream_info)); std::vector<disk_format::stream_info> stream_infos(stream_count); data_read_status = m_file_data_read->read_to_object_array(stream_infos); if(data_read_status == core::status_no_error) { for (auto &stream_info : stream_infos) { core::file_types::stream_info si; auto sts = conversions::convert(stream_info, si); if(sts == core::status_feature_unsupported) continue; //ignore unsupported streams if(sts != core::status_no_error) return core::status_item_unavailable; m_streams_infos[si.stream] = si; auto cap = get_capability(si.stream); if(cap != rs_capabilities::RS_CAPABILITIES_COUNT) m_capabilities.push_back(cap); } } LOG_INFO("read stream info chunk " << (data_read_status == core::status_no_error ? "succeeded" : "failed")); } break; default: { auto& data = m_unknowns[static_cast<core::file_types::chunk_id>(chunk.chunk_id)]; data.resize(chunk.chunk_size); data_read_status = m_file_data_read->read_to_object_array(data); LOG_INFO("read unknown chunk " << (data_read_status == core::status_no_error ? "succeeded" : "failed") << "chunk id - " << chunk.chunk_id); } break; } if (data_read_status != core::status_no_error) return core::status_item_unavailable; } return data_read_status; } int32_t disk_read::size_of_pitches(void) { return sizeof(int32_t) * NUM_OF_PLANES; } void disk_read::index_next_samples(uint32_t number_of_samples) { if (m_is_index_complete) return; std::lock_guard<std::mutex> guard(m_mutex); for (uint32_t index = 0; index < number_of_samples;) { disk_format::chunk chunk = {}; bool data_read_status = m_file_indexing->read_to_object(chunk); if (data_read_status != core::status_no_error || chunk.chunk_size <= 0 || chunk.chunk_size > 100000000 /*invalid chunk*/) { m_is_index_complete = true; LOG_INFO("samples indexing is done") break; } if (chunk.chunk_id == file_types::disk_format::chunk_frame_meta_data) { file_types::disk_format::frame_metadata mdata = {}; uint32_t so = static_cast<uint32_t>(m_file_header.version < 10 ? 24 : (unsigned long)sizeof(mdata)); data_read_status = m_file_indexing->read_to_object(mdata, so); core::file_types::sample_info sample_info; core::file_types::frame_info frame_info; if(conversions::convert(mdata, frame_info) != core::status_no_error) continue; auto ts = frame_info.time_stamp; auto st = frame_info.stream; auto fn = frame_info.number; frame_info = m_streams_infos[frame_info.stream].profile.info; frame_info.time_stamp = ts; frame_info.stream = st; frame_info.number = fn; if(m_time_stamp_base == 0) m_time_stamp_base = static_cast<uint64_t>(frame_info.time_stamp); frame_info.time_stamp -= static_cast<double>(m_time_stamp_base); sample_info.type = core::file_types::sample_type::st_image; sample_info.capture_time = static_cast<uint64_t>(frame_info.time_stamp); m_file_indexing->get_position(&sample_info.offset); frame_info.index_in_stream = static_cast<uint32_t>(m_image_indices[frame_info.stream].size()); m_image_indices[frame_info.stream].push_back(static_cast<uint32_t>(m_samples_desc.size())); m_samples_desc.push_back(std::make_shared<core::file_types::frame_sample>(frame_info, sample_info)); ++index; LOG_VERBOSE("frame sample indexed, sample time - " << sample_info.capture_time) } else { // skip any other sections m_file_indexing->set_position(chunk.chunk_size, core::move_method::current); } } } uint32_t disk_read::read_frame_metadata(const std::shared_ptr<core::file_types::frame_sample> & frame, unsigned long num_bytes_to_read) { //Does not do anything at the moment m_file_data_read->set_position(num_bytes_to_read, core::move_method::current); return 0; } } } } } <|endoftext|>
<commit_before>/*=================================================================== APM_PLANNER Open Source Ground Control Station (c) 2013 APM_PLANNER PROJECT <http://www.diydrones.com> This file is part of the APM_PLANNER project APM_PLANNER 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. APM_PLANNER 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 APM_PLANNER. If not, see <http://www.gnu.org/licenses/>. ======================================================================*/ #include "AirspeedConfig.h" #include <QMessageBox> AirspeedConfig::AirspeedConfig(QWidget *parent) : AP2ConfigWidget(parent) { ui.setupUi(this); connect(ui.enableCheckBox,SIGNAL(toggled(bool)),this,SLOT(enableCheckBoxClicked(bool))); connect(ui.useAirspeedCheckBox,SIGNAL(toggled(bool)),this,SLOT(useCheckBoxClicked(bool))); initConnections(); ui.sensorComboBox->setEnabled(false); ui.pinComboBox->setEnabled(false); connect(ui.hardwareComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(hardwareSelectComboBoxChanged(int))); connect(ui.pinSpinBox,SIGNAL(valueChanged(int)),this,SLOT(pinSpinBoxValueChanged(int))); } AirspeedConfig::~AirspeedConfig() { } void AirspeedConfig::parameterChanged(int uas, int component, QString parameterName, QVariant value) { Q_UNUSED(uas); Q_UNUSED(component); if (parameterName == "ARSPD_ENABLE") { if (value.toInt() == 0) { disconnect(ui.enableCheckBox,SIGNAL(toggled(bool)),this,SLOT(enableCheckBoxClicked(bool))); ui.enableCheckBox->setChecked(false); connect(ui.enableCheckBox,SIGNAL(toggled(bool)),this,SLOT(enableCheckBoxClicked(bool))); ui.useAirspeedCheckBox->setEnabled(false); } else { disconnect(ui.enableCheckBox,SIGNAL(toggled(bool)),this,SLOT(enableCheckBoxClicked(bool))); ui.enableCheckBox->setChecked(true); connect(ui.enableCheckBox,SIGNAL(toggled(bool)),this,SLOT(enableCheckBoxClicked(bool))); ui.useAirspeedCheckBox->setEnabled(true); } } else if (parameterName == "ARSPD_USE") { if (value.toInt() == 0) { disconnect(ui.useAirspeedCheckBox,SIGNAL(toggled(bool)),this,SLOT(useCheckBoxClicked(bool))); ui.useAirspeedCheckBox->setChecked(false); connect(ui.useAirspeedCheckBox,SIGNAL(toggled(bool)),this,SLOT(useCheckBoxClicked(bool))); } else { disconnect(ui.useAirspeedCheckBox,SIGNAL(toggled(bool)),this,SLOT(useCheckBoxClicked(bool))); ui.useAirspeedCheckBox->setChecked(true); connect(ui.useAirspeedCheckBox,SIGNAL(toggled(bool)),this,SLOT(useCheckBoxClicked(bool))); } } else if (parameterName == "ARSPD_PIN") { disconnect(ui.pinSpinBox,SIGNAL(valueChanged(int)),this,SLOT(pinSpinBoxValueChanged(int))); ui.pinSpinBox->setValue(value.toInt()); connect(ui.pinSpinBox,SIGNAL(valueChanged(int)),this,SLOT(pinSpinBoxValueChanged(int))); } } void AirspeedConfig::useCheckBoxClicked(bool checked) { if (!m_uas) { showNullMAVErrorMessageBox(); return; } if (checked) { m_uas->getParamManager()->setParameter(1,"ARSPD_USE",1); } else { m_uas->getParamManager()->setParameter(1,"ARSPD_USE",0); } } void AirspeedConfig::enableCheckBoxClicked(bool checked) { if (!m_uas) { showNullMAVErrorMessageBox(); return; } if (checked) { m_uas->getParamManager()->setParameter(1,"ARSPD_ENABLE",1); } else { m_uas->getParamManager()->setParameter(1,"ARSPD_ENABLE",0); } } void AirspeedConfig::hardwareSelectComboBoxChanged(int index) { if (index == 1) //APM1.X { disconnect(ui.sensorComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(sensorSelectComboBoxChanged(int))); ui.sensorComboBox->clear(); ui.sensorComboBox->addItem("Choose One"); ui.sensorComboBox->addItem("Analog Sensor"); ui.sensorComboBox->setEnabled(true); disconnect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); ui.pinComboBox->clear(); ui.pinComboBox->setEnabled(false); connect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); connect(ui.sensorComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(sensorSelectComboBoxChanged(int))); } else if (index == 2) //APM2.X { disconnect(ui.sensorComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(sensorSelectComboBoxChanged(int))); ui.sensorComboBox->clear(); ui.sensorComboBox->addItem("Choose One"); ui.sensorComboBox->addItem("Analog Sensor"); ui.sensorComboBox->addItem("EagleTree I2C"); ui.sensorComboBox->addItem("MEAS I2C"); ui.sensorComboBox->setEnabled(true); disconnect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); ui.pinComboBox->clear(); ui.pinComboBox->setEnabled(false); connect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); connect(ui.sensorComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(sensorSelectComboBoxChanged(int))); } else if (index == 3) //PX4 { disconnect(ui.sensorComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(sensorSelectComboBoxChanged(int))); ui.sensorComboBox->clear(); ui.sensorComboBox->addItem("Choose One"); ui.sensorComboBox->addItem("Analog Sensor"); ui.sensorComboBox->addItem("EagleTree I2C"); ui.sensorComboBox->addItem("MEAS I2C"); ui.sensorComboBox->setEnabled(true); disconnect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); ui.pinComboBox->clear(); ui.pinComboBox->setEnabled(false); connect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); connect(ui.sensorComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(sensorSelectComboBoxChanged(int))); } else if (index == 4) //Pixhawk { disconnect(ui.sensorComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(sensorSelectComboBoxChanged(int))); ui.sensorComboBox->clear(); ui.sensorComboBox->addItem("Choose One"); ui.sensorComboBox->addItem("Analog Sensor"); ui.sensorComboBox->addItem("EagleTree I2C"); ui.sensorComboBox->addItem("MEAS I2C"); ui.sensorComboBox->setEnabled(true); disconnect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); ui.pinComboBox->clear(); ui.pinComboBox->setEnabled(false); connect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); connect(ui.sensorComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(sensorSelectComboBoxChanged(int))); } else { disconnect(ui.sensorComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(sensorSelectComboBoxChanged(int))); ui.sensorComboBox->clear(); ui.sensorComboBox->setEnabled(false); disconnect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); ui.pinComboBox->clear(); ui.pinComboBox->setEnabled(false); connect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); connect(ui.sensorComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(sensorSelectComboBoxChanged(int))); } } void AirspeedConfig::sensorSelectComboBoxChanged(int index) { if (index == 1) //Analog Sensor { if (ui.hardwareComboBox->currentIndex() == 1) //APM1.X { disconnect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); ui.pinComboBox->clear(); ui.pinComboBox->addItem("Choose One"); ui.pinComboBox->addItem("64"); ui.pinComboBox->setEnabled(true); connect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); } else if (ui.hardwareComboBox->currentIndex() == 2) //APM2.X { disconnect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); ui.pinComboBox->clear(); ui.pinComboBox->addItem("Choose One"); ui.pinComboBox->addItem("0"); ui.pinComboBox->addItem("1"); ui.pinComboBox->addItem("2"); ui.pinComboBox->addItem("3"); ui.pinComboBox->addItem("4"); ui.pinComboBox->addItem("5"); ui.pinComboBox->addItem("6"); ui.pinComboBox->addItem("7"); ui.pinComboBox->addItem("8"); ui.pinComboBox->addItem("9"); ui.pinComboBox->setEnabled(true); connect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); } else if (ui.hardwareComboBox->currentIndex() == 3) //PX4 { disconnect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); ui.pinComboBox->clear(); ui.pinComboBox->addItem("Choose One"); ui.pinComboBox->addItem("11"); ui.pinComboBox->setEnabled(true); connect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); } else if (ui.hardwareComboBox->currentIndex() == 4) //Pixhawk { disconnect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); ui.pinComboBox->clear(); ui.pinComboBox->addItem("Choose One"); ui.pinComboBox->addItem("15"); ui.pinComboBox->setEnabled(true); connect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); } } else if (index == 2 || index == 3) //I2C Sensor { disconnect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); ui.pinComboBox->clear(); ui.pinComboBox->addItem("Choose One"); ui.pinComboBox->addItem("65"); ui.pinComboBox->setEnabled(true); connect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); } else { disconnect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); ui.pinComboBox->clear(); ui.pinComboBox->setEnabled(false); connect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); } } void AirspeedConfig::pinSelectComboBoxChanged(int index) { if (index < 0) { return; } if (ui.pinComboBox->itemText(index) != "Choose One") { bool ok = false; int pinnumber = ui.pinComboBox->itemText(index).toInt(&ok); if (!ok) { //For some reason, the conversion failed. An unexpected case //Don't want to set the pin to 0 for no reason, return on failure. return; } disconnect(ui.pinSpinBox,SIGNAL(valueChanged(int)),this,SLOT(pinSpinBoxValueChanged(int))); ui.pinSpinBox->setValue(pinnumber); connect(ui.pinSpinBox,SIGNAL(valueChanged(int)),this,SLOT(pinSpinBoxValueChanged(int))); m_uas->setParameter(1,"ARSPD_PIN",pinnumber); } } void AirspeedConfig::pinSpinBoxValueChanged(int value) { m_uas->setParameter(1,"ARSPD_PIN",value); } <commit_msg>Airspeed setup: adding Pixhawk I2C airspeed sensor<commit_after>/*=================================================================== APM_PLANNER Open Source Ground Control Station (c) 2013 APM_PLANNER PROJECT <http://www.diydrones.com> This file is part of the APM_PLANNER project APM_PLANNER 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. APM_PLANNER 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 APM_PLANNER. If not, see <http://www.gnu.org/licenses/>. ======================================================================*/ #include "AirspeedConfig.h" #include <QMessageBox> AirspeedConfig::AirspeedConfig(QWidget *parent) : AP2ConfigWidget(parent) { ui.setupUi(this); connect(ui.enableCheckBox,SIGNAL(toggled(bool)),this,SLOT(enableCheckBoxClicked(bool))); connect(ui.useAirspeedCheckBox,SIGNAL(toggled(bool)),this,SLOT(useCheckBoxClicked(bool))); initConnections(); ui.sensorComboBox->setEnabled(false); ui.pinComboBox->setEnabled(false); connect(ui.hardwareComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(hardwareSelectComboBoxChanged(int))); connect(ui.pinSpinBox,SIGNAL(valueChanged(int)),this,SLOT(pinSpinBoxValueChanged(int))); } AirspeedConfig::~AirspeedConfig() { } void AirspeedConfig::parameterChanged(int uas, int component, QString parameterName, QVariant value) { Q_UNUSED(uas); Q_UNUSED(component); if (parameterName == "ARSPD_ENABLE") { if (value.toInt() == 0) { disconnect(ui.enableCheckBox,SIGNAL(toggled(bool)),this,SLOT(enableCheckBoxClicked(bool))); ui.enableCheckBox->setChecked(false); connect(ui.enableCheckBox,SIGNAL(toggled(bool)),this,SLOT(enableCheckBoxClicked(bool))); ui.useAirspeedCheckBox->setEnabled(false); } else { disconnect(ui.enableCheckBox,SIGNAL(toggled(bool)),this,SLOT(enableCheckBoxClicked(bool))); ui.enableCheckBox->setChecked(true); connect(ui.enableCheckBox,SIGNAL(toggled(bool)),this,SLOT(enableCheckBoxClicked(bool))); ui.useAirspeedCheckBox->setEnabled(true); } } else if (parameterName == "ARSPD_USE") { if (value.toInt() == 0) { disconnect(ui.useAirspeedCheckBox,SIGNAL(toggled(bool)),this,SLOT(useCheckBoxClicked(bool))); ui.useAirspeedCheckBox->setChecked(false); connect(ui.useAirspeedCheckBox,SIGNAL(toggled(bool)),this,SLOT(useCheckBoxClicked(bool))); } else { disconnect(ui.useAirspeedCheckBox,SIGNAL(toggled(bool)),this,SLOT(useCheckBoxClicked(bool))); ui.useAirspeedCheckBox->setChecked(true); connect(ui.useAirspeedCheckBox,SIGNAL(toggled(bool)),this,SLOT(useCheckBoxClicked(bool))); } } else if (parameterName == "ARSPD_PIN") { disconnect(ui.pinSpinBox,SIGNAL(valueChanged(int)),this,SLOT(pinSpinBoxValueChanged(int))); ui.pinSpinBox->setValue(value.toInt()); connect(ui.pinSpinBox,SIGNAL(valueChanged(int)),this,SLOT(pinSpinBoxValueChanged(int))); } } void AirspeedConfig::useCheckBoxClicked(bool checked) { if (!m_uas) { showNullMAVErrorMessageBox(); return; } if (checked) { m_uas->getParamManager()->setParameter(1,"ARSPD_USE",1); } else { m_uas->getParamManager()->setParameter(1,"ARSPD_USE",0); } } void AirspeedConfig::enableCheckBoxClicked(bool checked) { if (!m_uas) { showNullMAVErrorMessageBox(); return; } if (checked) { m_uas->getParamManager()->setParameter(1,"ARSPD_ENABLE",1); } else { m_uas->getParamManager()->setParameter(1,"ARSPD_ENABLE",0); } } void AirspeedConfig::hardwareSelectComboBoxChanged(int index) { if (index == 1) //APM1.X { disconnect(ui.sensorComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(sensorSelectComboBoxChanged(int))); ui.sensorComboBox->clear(); ui.sensorComboBox->addItem("Choose One"); ui.sensorComboBox->addItem("Analog Sensor"); ui.sensorComboBox->setEnabled(true); disconnect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); ui.pinComboBox->clear(); ui.pinComboBox->setEnabled(false); connect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); connect(ui.sensorComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(sensorSelectComboBoxChanged(int))); } else if (index == 2) //APM2.X { disconnect(ui.sensorComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(sensorSelectComboBoxChanged(int))); ui.sensorComboBox->clear(); ui.sensorComboBox->addItem("Choose One"); ui.sensorComboBox->addItem("Analog Sensor"); ui.sensorComboBox->addItem("EagleTree I2C"); ui.sensorComboBox->addItem("MEAS I2C"); ui.sensorComboBox->addItem("Pixhawk I2C"); ui.sensorComboBox->setEnabled(true); disconnect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); ui.pinComboBox->clear(); ui.pinComboBox->setEnabled(false); connect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); connect(ui.sensorComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(sensorSelectComboBoxChanged(int))); } else if (index == 3) //PX4 { disconnect(ui.sensorComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(sensorSelectComboBoxChanged(int))); ui.sensorComboBox->clear(); ui.sensorComboBox->addItem("Choose One"); ui.sensorComboBox->addItem("Analog Sensor"); ui.sensorComboBox->addItem("EagleTree I2C"); ui.sensorComboBox->addItem("MEAS I2C"); ui.sensorComboBox->addItem("Pixhawk I2C"); ui.sensorComboBox->setEnabled(true); disconnect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); ui.pinComboBox->clear(); ui.pinComboBox->setEnabled(false); connect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); connect(ui.sensorComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(sensorSelectComboBoxChanged(int))); } else if (index == 4) //Pixhawk { disconnect(ui.sensorComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(sensorSelectComboBoxChanged(int))); ui.sensorComboBox->clear(); ui.sensorComboBox->addItem("Choose One"); ui.sensorComboBox->addItem("Analog Sensor"); ui.sensorComboBox->addItem("EagleTree I2C"); ui.sensorComboBox->addItem("MEAS I2C"); ui.sensorComboBox->addItem("Pixhawk I2C"); ui.sensorComboBox->setEnabled(true); disconnect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); ui.pinComboBox->clear(); ui.pinComboBox->setEnabled(false); connect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); connect(ui.sensorComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(sensorSelectComboBoxChanged(int))); } else { disconnect(ui.sensorComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(sensorSelectComboBoxChanged(int))); ui.sensorComboBox->clear(); ui.sensorComboBox->setEnabled(false); disconnect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); ui.pinComboBox->clear(); ui.pinComboBox->setEnabled(false); connect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); connect(ui.sensorComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(sensorSelectComboBoxChanged(int))); } } void AirspeedConfig::sensorSelectComboBoxChanged(int index) { if (index == 1) //Analog Sensor { if (ui.hardwareComboBox->currentIndex() == 1) //APM1.X { disconnect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); ui.pinComboBox->clear(); ui.pinComboBox->addItem("Choose One"); ui.pinComboBox->addItem("64"); ui.pinComboBox->setEnabled(true); connect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); } else if (ui.hardwareComboBox->currentIndex() == 2) //APM2.X { disconnect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); ui.pinComboBox->clear(); ui.pinComboBox->addItem("Choose One"); ui.pinComboBox->addItem("0"); ui.pinComboBox->addItem("1"); ui.pinComboBox->addItem("2"); ui.pinComboBox->addItem("3"); ui.pinComboBox->addItem("4"); ui.pinComboBox->addItem("5"); ui.pinComboBox->addItem("6"); ui.pinComboBox->addItem("7"); ui.pinComboBox->addItem("8"); ui.pinComboBox->addItem("9"); ui.pinComboBox->setEnabled(true); connect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); } else if (ui.hardwareComboBox->currentIndex() == 3) //PX4 { disconnect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); ui.pinComboBox->clear(); ui.pinComboBox->addItem("Choose One"); ui.pinComboBox->addItem("11"); ui.pinComboBox->setEnabled(true); connect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); } else if (ui.hardwareComboBox->currentIndex() == 4) //Pixhawk { disconnect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); ui.pinComboBox->clear(); ui.pinComboBox->addItem("Choose One"); ui.pinComboBox->addItem("15"); ui.pinComboBox->setEnabled(true); connect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); } } else if (index == 2 || index == 3 || index == 4) //I2C Sensor { disconnect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); ui.pinComboBox->clear(); ui.pinComboBox->addItem("Choose One"); ui.pinComboBox->addItem("65"); ui.pinComboBox->setEnabled(true); connect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); } else { disconnect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); ui.pinComboBox->clear(); ui.pinComboBox->setEnabled(false); connect(ui.pinComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(pinSelectComboBoxChanged(int))); } } void AirspeedConfig::pinSelectComboBoxChanged(int index) { if (index < 0) { return; } if (ui.pinComboBox->itemText(index) != "Choose One") { bool ok = false; int pinnumber = ui.pinComboBox->itemText(index).toInt(&ok); if (!ok) { //For some reason, the conversion failed. An unexpected case //Don't want to set the pin to 0 for no reason, return on failure. return; } disconnect(ui.pinSpinBox,SIGNAL(valueChanged(int)),this,SLOT(pinSpinBoxValueChanged(int))); ui.pinSpinBox->setValue(pinnumber); connect(ui.pinSpinBox,SIGNAL(valueChanged(int)),this,SLOT(pinSpinBoxValueChanged(int))); m_uas->setParameter(1,"ARSPD_PIN",pinnumber); } } void AirspeedConfig::pinSpinBoxValueChanged(int value) { m_uas->setParameter(1,"ARSPD_PIN",value); } <|endoftext|>
<commit_before> /* riscv_register.cpp - RISCV register info class * @author Alexandr Misevich * Copyright 2018 MIPT-MIPS */ #include "riscv_register.h" std::array<std::string_view, RISCVRegister::MAX_REG> RISCVRegister::regTable = {{ // NOLINTNEXTLINE(cppcoreguidelines-macro-usage) #define REGISTER(X) # X #include "riscv_register.def" #undef REGISTER // NOLINTNEXTLINE(cppcoreguidelines-macro-usage) #define DECLARE_CSR(X, Y) , # X #include <riscv.opcode.gen.h> #undef DECLARE_CSR }}; RISCVRegister::RegNum RISCVRegister::get_csr_regnum( uint16 val) { switch (val) { // NOLINTNEXTLINE(cppcoreguidelines-macro-usage) #define DECLARE_CSR(X, Y) case Y: return RegNum::RISCV_ ## Y; #include <riscv.opcode.gen.h> #undef DECLARE_CSR } return MAX_VAL_RegNum; } RISCVRegister::RegNum RISCVRegister::get_csr_regnum( std::string_view name) { // NOLINTNEXTLINE(cppcoreguidelines-macro-usage) #define DECLARE_CSR(X, Y) if ( name == # X) return RegNum::RISCV_ ## Y; #include <riscv.opcode.gen.h> #undef DECLARE_CSR return MAX_VAL_RegNum; } <commit_msg>Fix default case for get_csr_regnum (#987)<commit_after> /* riscv_register.cpp - RISCV register info class * @author Alexandr Misevich * Copyright 2018 MIPT-MIPS */ #include "riscv_register.h" std::array<std::string_view, RISCVRegister::MAX_REG> RISCVRegister::regTable = {{ #define REGISTER(X) # X #include "riscv_register.def" #undef REGISTER #define DECLARE_CSR(X, Y) , # X #include <riscv.opcode.gen.h> #undef DECLARE_CSR }}; RISCVRegister::RegNum RISCVRegister::get_csr_regnum( uint16 val) { switch (val) { #define DECLARE_CSR(X, Y) case Y: return RegNum::RISCV_ ## Y; #include <riscv.opcode.gen.h> #undef DECLARE_CSR default: return MAX_VAL_RegNum; } } RISCVRegister::RegNum RISCVRegister::get_csr_regnum( std::string_view name) { #define DECLARE_CSR(X, Y) if ( name == # X) return RegNum::RISCV_ ## Y; #include <riscv.opcode.gen.h> #undef DECLARE_CSR return MAX_VAL_RegNum; } <|endoftext|>
<commit_before>#include <common/buffer.h> #include <event/action.h> #include <event/callback.h> #include <event/event_callback.h> #include <event/event_main.h> #include <event/event_system.h> #include <http/http_server_pipe.h> #include <io/net/tcp_server.h> #include <io/pipe/pipe.h> #include <io/pipe/pipe_producer.h> #include <io/pipe/splice.h> #include <io/socket/simple_server.h> HTTPServerPipe::HTTPServerPipe(const LogHandle& log) : PipeProducer(log), state_(GetStart), buffer_(), message_(), last_header_(), action_(NULL), callback_(NULL) { } HTTPServerPipe::~HTTPServerPipe() { ASSERT(action_ == NULL); ASSERT(callback_ == NULL); } Action * HTTPServerPipe::message(HTTPMessageEventCallback *cb) { ASSERT(action_ == NULL); ASSERT(callback_ == NULL); if (state_ == GotMessage || state_ == Error) return (schedule_callback(cb)); callback_ = cb; return (cancellation(this, &HTTPServerPipe::cancel)); } void HTTPServerPipe::send_response(HTTPProtocol::Status status, Buffer *body, Buffer *headers) { if (state_ == GotMessage || state_ == Error) { ASSERT(buffer_.empty()); } else { if (!buffer_.empty()) { buffer_.clear(); } else { ASSERT(status == HTTPProtocol::BadRequest); DEBUG(log_) << "Premature end-of-stream."; } state_ = Error; /* Process no more input. */ /* * For state change to Error, we must schedule a * callback. */ ASSERT(action_ == NULL); if (callback_ != NULL) { action_ = schedule_callback(callback_); callback_ = NULL; } } /* * Format status line. */ Buffer response("HTTP/1.1 "); switch (status) { case HTTPProtocol::OK: response.append("200 OK"); break; case HTTPProtocol::BadRequest: response.append("400 Bad Request"); break; case HTTPProtocol::NotFound: response.append("404 Not Found"); break; case HTTPProtocol::NotImplemented: response.append("501 Not Implemented"); break; case HTTPProtocol::VersionNotSupported: response.append("505 Version Not Supported"); break; default: NOTREACHED(); } response.append("\r\n"); /* * Fill response headers. */ response.append("Server: " + (std::string)log_ + "\r\n"); response.append("Transfer-encoding: identity\r\n"); response.append("Connection: close\r\n"); if (headers != NULL) { response.append(headers); headers->clear(); } response.append("\r\n"); /* * Append body. No encodings supported yet. */ response.append(body); body->clear(); /* * Output response and EOS. * * XXX Really want produce_eos(&response); */ produce(&response); ASSERT(response.empty()); Buffer eos; produce(&eos); } void HTTPServerPipe::send_response(HTTPProtocol::Status status, const std::string& body, const std::string& content_type) { Buffer tmp(body); Buffer header("Content-type: " + content_type + "\r\n"); send_response(status, &tmp, &header); ASSERT(tmp.empty()); } void HTTPServerPipe::cancel(void) { if (action_ != NULL) { action_->cancel(); action_ = NULL; ASSERT(callback_ == NULL); } else { ASSERT(callback_ != NULL); delete callback_; callback_ = NULL; } } Action * HTTPServerPipe::schedule_callback(HTTPMessageEventCallback *cb) { switch (state_) { case GotMessage: cb->param(Event::Done, message_); break; case Error: cb->param(Event::Error, HTTPProtocol::Message()); break; default: NOTREACHED(); } return (cb->schedule()); } void HTTPServerPipe::consume(Buffer *in) { if (state_ == GotMessage || state_ == Error) { ASSERT(buffer_.empty()); if (in->empty()) { DEBUG(log_) << "Got end-of-stream."; return; } /* * XXX * Really want a way to shut down input. */ if (state_ == GotMessage) { ERROR(log_) << "Client sent unexpected additional data after request."; state_ = Error; /* * No need to schedule a callback for this state * change, the change to GotMessage already did. */ } else { ERROR(log_) << "Client continuing to send gibberish."; } in->clear(); return; } if (in->empty()) { send_response(HTTPProtocol::BadRequest, "Premature end of request."); return; } buffer_.append(in); in->clear(); for (;;) { ASSERT(!buffer_.empty()); Buffer line; unsigned pos; uint8_t found; if (!buffer_.find_any("\r\n", &pos, 0, &found)) { DEBUG(log_) << "Waiting for remainder of line."; return; } /* * XXX * We should pick line ending from the start line and require it to * be consistent for remaining lines, rather than using find_any over * and over, which is non-trivial. Handling of the start line can be * quite easily and cheaply before the loop. */ switch (found) { case '\r': /* CRLF line endings. */ ASSERT(buffer_.length() > pos); if (buffer_.length() == pos + 1) { DEBUG(log_) << "Carriage return at end of buffer, waiting for line feed."; return; } if (pos != 0) buffer_.moveout(&line, pos); buffer_.skip(1); if (buffer_.peek() != '\n') { ERROR(log_) << "Carriage return not followed by line feed."; send_response(HTTPProtocol::BadRequest, "Line includes embedded carriage return."); return; } buffer_.skip(1); break; case '\n': /* Unix line endings. */ if (pos != 0) buffer_.moveout(&line, pos); buffer_.skip(1); break; default: NOTREACHED(); } if (state_ == GetStart) { ASSERT(message_.start_line_.empty()); if (line.empty()) { ERROR(log_) << "Premature end of headers."; return; } message_.start_line_ = line; /* * There are two kinds of request line. The first has two * words, the second has three. Anything else is malformed. * * The first kind is HTTP/0.9. The second kind can be * anything, especially HTTP/1.0 and HTTP/1.1. */ std::vector<Buffer> words = line.split(' ', false); if (words.empty()) { send_response(HTTPProtocol::BadRequest, "Empty start line."); return; } if (words.size() == 3) { /* * HTTP/1.0 or HTTP/1.1. Get headers. */ state_ = GetHeaders; if (buffer_.empty()) break; continue; } if (words.size() != 2) { /* * Not HTTP/0.9. */ send_response(HTTPProtocol::BadRequest, "Too many request parameters."); return; } /* * HTTP/0.9. This is all we should get from the client. */ if (!buffer_.empty()) { send_response(HTTPProtocol::BadRequest, "Garbage after HTTP/0.9-style request."); return; } /* * We have received the full message. Process any * pending callback. */ state_ = GotMessage; ASSERT(action_ == NULL); if (callback_ != NULL) { action_ = schedule_callback(callback_); callback_ = NULL; } return; } ASSERT(state_ == GetHeaders); ASSERT(!message_.start_line_.empty()); /* * Process end of headers! */ if (line.empty()) { if (!buffer_.empty()) { ERROR(log_) << "Client sent garbage after message."; send_response(HTTPProtocol::BadRequest, "Garbage after message."); return; } /* * We have received the full message. Process any * pending callback. */ state_ = GotMessage; ASSERT(action_ == NULL); if (callback_ != NULL) { action_ = schedule_callback(callback_); callback_ = NULL; } return; } /* * Process header. */ if (line.peek() == ' ') { /* XXX isspace? */ /* * Fold headers per RFC822. * * XXX Always forget how to handle leading whitespace. */ if (last_header_ == "") { send_response(HTTPProtocol::BadRequest, "Folded header sent before any others."); return; } message_.headers_[last_header_].back().append(line); if (buffer_.empty()) break; continue; } if (!line.find(':', &pos)) { send_response(HTTPProtocol::BadRequest, "Empty header name."); return; } Buffer key; line.moveout(&key, pos); line.skip(1); Buffer value; while (!line.empty() && line.peek() == ' ') line.skip(1); value = line; std::string header; key.extract(header); message_.headers_[header].push_back(value); last_header_ = header; if (buffer_.empty()) break; } } <commit_msg>Fail in the presence of an empty start line.<commit_after>#include <common/buffer.h> #include <event/action.h> #include <event/callback.h> #include <event/event_callback.h> #include <event/event_main.h> #include <event/event_system.h> #include <http/http_server_pipe.h> #include <io/net/tcp_server.h> #include <io/pipe/pipe.h> #include <io/pipe/pipe_producer.h> #include <io/pipe/splice.h> #include <io/socket/simple_server.h> HTTPServerPipe::HTTPServerPipe(const LogHandle& log) : PipeProducer(log), state_(GetStart), buffer_(), message_(), last_header_(), action_(NULL), callback_(NULL) { } HTTPServerPipe::~HTTPServerPipe() { ASSERT(action_ == NULL); ASSERT(callback_ == NULL); } Action * HTTPServerPipe::message(HTTPMessageEventCallback *cb) { ASSERT(action_ == NULL); ASSERT(callback_ == NULL); if (state_ == GotMessage || state_ == Error) return (schedule_callback(cb)); callback_ = cb; return (cancellation(this, &HTTPServerPipe::cancel)); } void HTTPServerPipe::send_response(HTTPProtocol::Status status, Buffer *body, Buffer *headers) { if (state_ == GotMessage || state_ == Error) { ASSERT(buffer_.empty()); } else { if (!buffer_.empty()) { buffer_.clear(); } else { ASSERT(status == HTTPProtocol::BadRequest); DEBUG(log_) << "Premature end-of-stream."; } state_ = Error; /* Process no more input. */ /* * For state change to Error, we must schedule a * callback. */ ASSERT(action_ == NULL); if (callback_ != NULL) { action_ = schedule_callback(callback_); callback_ = NULL; } } /* * Format status line. */ Buffer response("HTTP/1.1 "); switch (status) { case HTTPProtocol::OK: response.append("200 OK"); break; case HTTPProtocol::BadRequest: response.append("400 Bad Request"); break; case HTTPProtocol::NotFound: response.append("404 Not Found"); break; case HTTPProtocol::NotImplemented: response.append("501 Not Implemented"); break; case HTTPProtocol::VersionNotSupported: response.append("505 Version Not Supported"); break; default: NOTREACHED(); } response.append("\r\n"); /* * Fill response headers. */ response.append("Server: " + (std::string)log_ + "\r\n"); response.append("Transfer-encoding: identity\r\n"); response.append("Connection: close\r\n"); if (headers != NULL) { response.append(headers); headers->clear(); } response.append("\r\n"); /* * Append body. No encodings supported yet. */ response.append(body); body->clear(); /* * Output response and EOS. * * XXX Really want produce_eos(&response); */ produce(&response); ASSERT(response.empty()); Buffer eos; produce(&eos); } void HTTPServerPipe::send_response(HTTPProtocol::Status status, const std::string& body, const std::string& content_type) { Buffer tmp(body); Buffer header("Content-type: " + content_type + "\r\n"); send_response(status, &tmp, &header); ASSERT(tmp.empty()); } void HTTPServerPipe::cancel(void) { if (action_ != NULL) { action_->cancel(); action_ = NULL; ASSERT(callback_ == NULL); } else { ASSERT(callback_ != NULL); delete callback_; callback_ = NULL; } } Action * HTTPServerPipe::schedule_callback(HTTPMessageEventCallback *cb) { switch (state_) { case GotMessage: cb->param(Event::Done, message_); break; case Error: cb->param(Event::Error, HTTPProtocol::Message()); break; default: NOTREACHED(); } return (cb->schedule()); } void HTTPServerPipe::consume(Buffer *in) { if (state_ == GotMessage || state_ == Error) { ASSERT(buffer_.empty()); if (in->empty()) { DEBUG(log_) << "Got end-of-stream."; return; } /* * XXX * Really want a way to shut down input. */ if (state_ == GotMessage) { ERROR(log_) << "Client sent unexpected additional data after request."; state_ = Error; /* * No need to schedule a callback for this state * change, the change to GotMessage already did. */ } else { ERROR(log_) << "Client continuing to send gibberish."; } in->clear(); return; } if (in->empty()) { send_response(HTTPProtocol::BadRequest, "Premature end of request."); return; } buffer_.append(in); in->clear(); for (;;) { ASSERT(!buffer_.empty()); Buffer line; unsigned pos; uint8_t found; if (!buffer_.find_any("\r\n", &pos, 0, &found)) { DEBUG(log_) << "Waiting for remainder of line."; return; } /* * XXX * We should pick line ending from the start line and require it to * be consistent for remaining lines, rather than using find_any over * and over, which is non-trivial. Handling of the start line can be * quite easily and cheaply before the loop. */ switch (found) { case '\r': /* CRLF line endings. */ ASSERT(buffer_.length() > pos); if (buffer_.length() == pos + 1) { DEBUG(log_) << "Carriage return at end of buffer, waiting for line feed."; return; } if (pos != 0) buffer_.moveout(&line, pos); buffer_.skip(1); if (buffer_.peek() != '\n') { ERROR(log_) << "Carriage return not followed by line feed."; send_response(HTTPProtocol::BadRequest, "Line includes embedded carriage return."); return; } buffer_.skip(1); break; case '\n': /* Unix line endings. */ if (pos != 0) buffer_.moveout(&line, pos); buffer_.skip(1); break; default: NOTREACHED(); } if (state_ == GetStart) { ASSERT(message_.start_line_.empty()); if (line.empty()) { ERROR(log_) << "Premature end of headers."; send_response(HTTPProtocol::BadRequest, "Empty start line."); return; } message_.start_line_ = line; /* * There are two kinds of request line. The first has two * words, the second has three. Anything else is malformed. * * The first kind is HTTP/0.9. The second kind can be * anything, especially HTTP/1.0 and HTTP/1.1. */ std::vector<Buffer> words = line.split(' ', false); if (words.empty()) { send_response(HTTPProtocol::BadRequest, "Empty start line."); return; } if (words.size() == 3) { /* * HTTP/1.0 or HTTP/1.1. Get headers. */ state_ = GetHeaders; if (buffer_.empty()) break; continue; } if (words.size() != 2) { /* * Not HTTP/0.9. */ send_response(HTTPProtocol::BadRequest, "Too many request parameters."); return; } /* * HTTP/0.9. This is all we should get from the client. */ if (!buffer_.empty()) { send_response(HTTPProtocol::BadRequest, "Garbage after HTTP/0.9-style request."); return; } /* * We have received the full message. Process any * pending callback. */ state_ = GotMessage; ASSERT(action_ == NULL); if (callback_ != NULL) { action_ = schedule_callback(callback_); callback_ = NULL; } return; } ASSERT(state_ == GetHeaders); ASSERT(!message_.start_line_.empty()); /* * Process end of headers! */ if (line.empty()) { if (!buffer_.empty()) { ERROR(log_) << "Client sent garbage after message."; send_response(HTTPProtocol::BadRequest, "Garbage after message."); return; } /* * We have received the full message. Process any * pending callback. */ state_ = GotMessage; ASSERT(action_ == NULL); if (callback_ != NULL) { action_ = schedule_callback(callback_); callback_ = NULL; } return; } /* * Process header. */ if (line.peek() == ' ') { /* XXX isspace? */ /* * Fold headers per RFC822. * * XXX Always forget how to handle leading whitespace. */ if (last_header_ == "") { send_response(HTTPProtocol::BadRequest, "Folded header sent before any others."); return; } message_.headers_[last_header_].back().append(line); if (buffer_.empty()) break; continue; } if (!line.find(':', &pos)) { send_response(HTTPProtocol::BadRequest, "Empty header name."); return; } Buffer key; line.moveout(&key, pos); line.skip(1); Buffer value; while (!line.empty() && line.peek() == ' ') line.skip(1); value = line; std::string header; key.extract(header); message_.headers_[header].push_back(value); last_header_ = header; if (buffer_.empty()) break; } } <|endoftext|>
<commit_before>/* AFE Firmware for smart home devices LICENSE: https://github.com/tschaban/AFE-Firmware/blob/master/LICENSE DOC: http://smart-house.adrian.czabanowski.com/afe-firmware-pl/ */ #include "AFE-Web-Server.h" AFEWebServer::AFEWebServer() {} void AFEWebServer::begin() { httpUpdater.setup(&server); server.begin(); } void AFEWebServer::listener() { server.handleClient(); } boolean AFEWebServer::httpAPIlistener() { return receivedHTTPCommand; } void AFEWebServer::publishHTML(String page) { server.send(200, "text/html", page); } void AFEWebServer::sendJSON(String json) { server.send(200, "application/json", json); } void AFEWebServer::handle(const char *uri, ESP8266WebServer::THandlerFunction handler) { // Serial << endl << "INFO: Added url : " << uri << " for listening"; server.on(uri, handler); } HTTPCOMMAND AFEWebServer::getHTTPCommand() { receivedHTTPCommand = false; return httpCommand; } void AFEWebServer::generate() { if (_refreshConfiguration) { _refreshConfiguration = false; Device.begin(); } /* @TODO this method is not writen well */ if (getOptionName() == "language") { uint8_t data; if (getCommand() == SERVER_CMD_SAVE) { data = getLanguageData(); } publishHTML(ConfigurationPanel.getLanguageConfigurationSite( getOptionName(), getCommand(), data)); if (getCommand() == SERVER_CMD_SAVE) { Device.reboot(Device.getMode()); } } else if (getOptionName() == "device") { DEVICE data; if (getCommand() == SERVER_CMD_SAVE) { data = getDeviceData(); } publishHTML(ConfigurationPanel.getDeviceConfigurationSite( getOptionName(), getCommand(), data)); } else if (getOptionName() == "network") { NETWORK data; if (getCommand() == SERVER_CMD_SAVE) { data = getNetworkData(); } publishHTML(ConfigurationPanel.getNetworkConfigurationSite( getOptionName(), getCommand(), data)); } else if (getOptionName() == "mqtt") { MQTT data; if (getCommand() == SERVER_CMD_SAVE) { data = getMQTTData(); } publishHTML(ConfigurationPanel.getMQTTConfigurationSite( getOptionName(), getCommand(), data)); } else if (getOptionName() == "led") { LED data[5] = {}; uint8_t dataLedID; if (getCommand() == SERVER_CMD_SAVE) { for (uint8_t i = 0; i < 5; i++) { data[i] = getLEDData(i); } dataLedID = getSystemLEDData(); } publishHTML(ConfigurationPanel.getLEDConfigurationSite( getOptionName(), getCommand(), data, dataLedID)); } else if (getOptionName() == "exit") { publishHTML( ConfigurationPanel.getSite(getOptionName(), getCommand(), true)); Device.reboot(MODE_NORMAL); } else if (getOptionName() == "reset") { publishHTML( ConfigurationPanel.getSite(getOptionName(), getCommand(), false)); if (getCommand() == 1) { Device.setDevice(); Device.reboot(MODE_ACCESS_POINT); } } else if (getOptionName() == "help") { publishHTML(ConfigurationPanel.getSite(getOptionName(), getCommand(), getCommand() == 0 ? false : true)); if (getCommand() == 1) { Device.reboot(MODE_CONFIGURATION); } else if (getCommand() == 2) { Device.reboot(MODE_ACCESS_POINT); } } else { for (uint8_t i = 0; i < 4; i++) { if (Device.configuration.isRelay[i]) { if (getOptionName() == "relay" + String(i)) { RELAY data = {}; if (getCommand() == SERVER_CMD_SAVE) { data = getRelayData(i); } publishHTML(ConfigurationPanel.getRelayConfigurationSite( getOptionName(), getCommand(), data, i)); } } } for (uint8_t i = 0; i < 5; i++) { if (Device.configuration.isSwitch[i]) { if (getOptionName() == "switch" + String(i)) { SWITCH data = {}; if (getCommand() == SERVER_CMD_SAVE) { data = getSwitchData(i); } publishHTML(ConfigurationPanel.getSwitchConfigurationSite( getOptionName(), getCommand(), data, i)); } } } } } String AFEWebServer::getOptionName() { if (Device.getMode() == MODE_NORMAL) { /* Recived HTTP API Command */ if (server.hasArg("command")) { /* Constructing command */ server.arg("command").toCharArray(httpCommand.command, sizeof(httpCommand.command)); if (server.arg("device")) { server.arg("device").toCharArray(httpCommand.device, sizeof(httpCommand.device)); } else { memset(httpCommand.device, 0, sizeof httpCommand.device); } if (server.arg("name")) { server.arg("name").toCharArray(httpCommand.name, sizeof(httpCommand.name)); } else { memset(httpCommand.name, 0, sizeof httpCommand.name); } receivedHTTPCommand = true; return server.arg("command"); } else { return "help"; } } else { if (server.hasArg("option")) { return server.arg("option"); } else { return "device"; } } } uint8_t AFEWebServer::getCommand() { if (server.hasArg("cmd")) { return server.arg("cmd").toInt(); } } DEVICE AFEWebServer::getDeviceData() { DEVICE data; _refreshConfiguration = true; // it will cause that device configuration will be refeshed if (server.arg("n").length() > 0) { server.arg("n").toCharArray(data.name, sizeof(data.name)); } server.arg("h").length() > 0 ? data.httpAPI = true : data.httpAPI = false; server.arg("m").length() > 0 ? data.mqttAPI = true : data.mqttAPI = false; for (uint8_t i = 0; i < sizeof(Device.configuration.isLED); i++) { server.arg("hl").toInt() > i ? data.isLED[i] = true : data.isLED[i] = false; } for (uint8_t i = 0; i < sizeof(Device.configuration.isRelay); i++) { server.arg("hr").toInt() > i ? data.isRelay[i] = true : data.isRelay[i] = false; } for (uint8_t i = 0; i < sizeof(Device.configuration.isSwitch); i++) { server.arg("hs").toInt() > i ? data.isSwitch[i] = true : data.isSwitch[i] = false; } return data; } NETWORK AFEWebServer::getNetworkData() { NETWORK data; if (server.arg("n").length() > 0) { server.arg("n").toCharArray(data.ssid, sizeof(data.ssid)); } if (server.arg("p").length() > 0) { server.arg("p").toCharArray(data.password, sizeof(data.password)); } if (server.arg("d").length() > 0) { data.isDHCP = true; } else { data.isDHCP = false; } if (server.arg("i1").length() > 0 && server.arg("i2").length() > 0 && server.arg("i3").length() > 0 && server.arg("i4").length() > 0) { data.ip = IPAddress(server.arg("i1").toInt(), server.arg("i2").toInt(), server.arg("i3").toInt(), server.arg("i4").toInt()); } if (server.arg("g1").length() > 0 && server.arg("g2").length() > 0 && server.arg("g3").length() > 0 && server.arg("g4").length() > 0) { data.gateway = IPAddress(server.arg("g1").toInt(), server.arg("g2").toInt(), server.arg("g3").toInt(), server.arg("g4").toInt()); } if (server.arg("s1").length() > 0 && server.arg("s2").length() > 0 && server.arg("s3").length() > 0 && server.arg("s4").length() > 0) { data.subnet = IPAddress(server.arg("s1").toInt(), server.arg("s2").toInt(), server.arg("s3").toInt(), server.arg("s4").toInt()); } if (server.arg("na").length() > 0) { data.noConnectionAttempts = server.arg("na").toInt(); } if (server.arg("wc").length() > 0) { data.waitTimeConnections = server.arg("wc").toInt(); } if (server.arg("ws").length() > 0) { data.waitTimeSeries = server.arg("ws").toInt(); } return data; } MQTT AFEWebServer::getMQTTData() { MQTT data; if (server.arg("h").length() > 0) { server.arg("h").toCharArray(data.host, sizeof(data.host)); } if (server.arg("m1").length() > 0 && server.arg("m2").length() > 0 && server.arg("m3").length() > 0 && server.arg("m4").length() > 0) { data.ip = IPAddress(server.arg("m1").toInt(), server.arg("m2").toInt(), server.arg("m3").toInt(), server.arg("m4").toInt()); } if (server.arg("p").length() > 0) { data.port = server.arg("p").toInt(); } if (server.arg("u").length() > 0) { server.arg("u").toCharArray(data.user, sizeof(data.user)); } if (server.arg("s").length() > 0) { server.arg("s").toCharArray(data.password, sizeof(data.password)); } if (server.arg("t").length() > 0) { server.arg("t").toCharArray(data.topic, sizeof(data.topic)); } return data; } LED AFEWebServer::getLEDData(uint8_t id) { LED data; if (server.arg("g" + String(id)).length() > 0) { data.gpio = server.arg("g" + String(id)).toInt(); } server.arg("o" + String(id)).length() > 0 ? data.changeToOppositeValue = true : data.changeToOppositeValue = false; return data; } uint8_t AFEWebServer::getSystemLEDData() { uint8_t data; if (server.arg("i").length() > 0) { data = server.arg("i").toInt(); } return data; } RELAY AFEWebServer::getRelayData(uint8_t id) { RELAY data; if (server.arg("g" + String(id)).length() > 0) { data.gpio = server.arg("g" + String(id)).toInt(); } if (server.arg("r" + String(id)).length() > 0) { data.statePowerOn = server.arg("r" + String(id)).toInt(); } if (server.arg("n" + String(id)).length() > 0) { server.arg("n" + String(id)).toCharArray(data.name, sizeof(data.name)); } if (server.arg("c" + String(id)).length() > 0) { data.stateMQTTConnected = server.arg("c" + String(id)).toInt(); } if (server.arg("t" + String(id)).length() > 0) { data.timeToOff = server.arg("t" + String(id)).toFloat(); } if (server.arg("l" + String(id)).length() > 0) { data.ledID = server.arg("l" + String(id)).toInt(); } return data; } SWITCH AFEWebServer::getSwitchData(uint8_t id) { SWITCH data; if (server.arg("t" + String(id)).length() > 0) { data.type = server.arg("t" + String(id)).toInt(); } if (server.arg("s" + String(id)).length() > 0) { data.sensitiveness = server.arg("s" + String(id)).toInt(); } if (server.arg("f" + String(id)).length() > 0) { data.functionality = server.arg("f" + String(id)).toInt(); } if (server.arg("g" + String(id)).length() > 0) { data.gpio = server.arg("g" + String(id)).toInt(); } return data; } uint8_t AFEWebServer::getLanguageData() { return server.arg("l").length() > 0 ? server.arg("l").toInt() : 1; } <commit_msg>added relayID to switch configuration<commit_after>/* AFE Firmware for smart home devices LICENSE: https://github.com/tschaban/AFE-Firmware/blob/master/LICENSE DOC: http://smart-house.adrian.czabanowski.com/afe-firmware-pl/ */ #include "AFE-Web-Server.h" AFEWebServer::AFEWebServer() {} void AFEWebServer::begin() { httpUpdater.setup(&server); server.begin(); } void AFEWebServer::listener() { server.handleClient(); } boolean AFEWebServer::httpAPIlistener() { return receivedHTTPCommand; } void AFEWebServer::publishHTML(String page) { server.send(200, "text/html", page); } void AFEWebServer::sendJSON(String json) { server.send(200, "application/json", json); } void AFEWebServer::handle(const char *uri, ESP8266WebServer::THandlerFunction handler) { // Serial << endl << "INFO: Added url : " << uri << " for listening"; server.on(uri, handler); } HTTPCOMMAND AFEWebServer::getHTTPCommand() { receivedHTTPCommand = false; return httpCommand; } void AFEWebServer::generate() { if (_refreshConfiguration) { _refreshConfiguration = false; Device.begin(); } /* @TODO this method is not writen well */ if (getOptionName() == "language") { uint8_t data; if (getCommand() == SERVER_CMD_SAVE) { data = getLanguageData(); } publishHTML(ConfigurationPanel.getLanguageConfigurationSite( getOptionName(), getCommand(), data)); if (getCommand() == SERVER_CMD_SAVE) { Device.reboot(Device.getMode()); } } else if (getOptionName() == "device") { DEVICE data; if (getCommand() == SERVER_CMD_SAVE) { data = getDeviceData(); } publishHTML(ConfigurationPanel.getDeviceConfigurationSite( getOptionName(), getCommand(), data)); } else if (getOptionName() == "network") { NETWORK data; if (getCommand() == SERVER_CMD_SAVE) { data = getNetworkData(); } publishHTML(ConfigurationPanel.getNetworkConfigurationSite( getOptionName(), getCommand(), data)); } else if (getOptionName() == "mqtt") { MQTT data; if (getCommand() == SERVER_CMD_SAVE) { data = getMQTTData(); } publishHTML(ConfigurationPanel.getMQTTConfigurationSite( getOptionName(), getCommand(), data)); } else if (getOptionName() == "led") { LED data[5] = {}; uint8_t dataLedID; if (getCommand() == SERVER_CMD_SAVE) { for (uint8_t i = 0; i < 5; i++) { data[i] = getLEDData(i); } dataLedID = getSystemLEDData(); } publishHTML(ConfigurationPanel.getLEDConfigurationSite( getOptionName(), getCommand(), data, dataLedID)); } else if (getOptionName() == "exit") { publishHTML( ConfigurationPanel.getSite(getOptionName(), getCommand(), true)); Device.reboot(MODE_NORMAL); } else if (getOptionName() == "reset") { publishHTML( ConfigurationPanel.getSite(getOptionName(), getCommand(), false)); if (getCommand() == 1) { Device.setDevice(); Device.reboot(MODE_ACCESS_POINT); } } else if (getOptionName() == "help") { publishHTML(ConfigurationPanel.getSite(getOptionName(), getCommand(), getCommand() == 0 ? false : true)); if (getCommand() == 1) { Device.reboot(MODE_CONFIGURATION); } else if (getCommand() == 2) { Device.reboot(MODE_ACCESS_POINT); } } else { for (uint8_t i = 0; i < 4; i++) { if (Device.configuration.isRelay[i]) { if (getOptionName() == "relay" + String(i)) { RELAY data = {}; if (getCommand() == SERVER_CMD_SAVE) { data = getRelayData(i); } publishHTML(ConfigurationPanel.getRelayConfigurationSite( getOptionName(), getCommand(), data, i)); } } } for (uint8_t i = 0; i < 5; i++) { if (Device.configuration.isSwitch[i]) { if (getOptionName() == "switch" + String(i)) { SWITCH data = {}; if (getCommand() == SERVER_CMD_SAVE) { data = getSwitchData(i); } publishHTML(ConfigurationPanel.getSwitchConfigurationSite( getOptionName(), getCommand(), data, i)); } } } } } String AFEWebServer::getOptionName() { if (Device.getMode() == MODE_NORMAL) { /* Recived HTTP API Command */ if (server.hasArg("command")) { /* Constructing command */ server.arg("command").toCharArray(httpCommand.command, sizeof(httpCommand.command)); if (server.arg("device")) { server.arg("device").toCharArray(httpCommand.device, sizeof(httpCommand.device)); } else { memset(httpCommand.device, 0, sizeof httpCommand.device); } if (server.arg("name")) { server.arg("name").toCharArray(httpCommand.name, sizeof(httpCommand.name)); } else { memset(httpCommand.name, 0, sizeof httpCommand.name); } receivedHTTPCommand = true; return server.arg("command"); } else { return "help"; } } else { if (server.hasArg("option")) { return server.arg("option"); } else { return "device"; } } } uint8_t AFEWebServer::getCommand() { if (server.hasArg("cmd")) { return server.arg("cmd").toInt(); } } DEVICE AFEWebServer::getDeviceData() { DEVICE data; _refreshConfiguration = true; // it will cause that device configuration will be refeshed if (server.arg("n").length() > 0) { server.arg("n").toCharArray(data.name, sizeof(data.name)); } server.arg("h").length() > 0 ? data.httpAPI = true : data.httpAPI = false; server.arg("m").length() > 0 ? data.mqttAPI = true : data.mqttAPI = false; for (uint8_t i = 0; i < sizeof(Device.configuration.isLED); i++) { server.arg("hl").toInt() > i ? data.isLED[i] = true : data.isLED[i] = false; } for (uint8_t i = 0; i < sizeof(Device.configuration.isRelay); i++) { server.arg("hr").toInt() > i ? data.isRelay[i] = true : data.isRelay[i] = false; } for (uint8_t i = 0; i < sizeof(Device.configuration.isSwitch); i++) { server.arg("hs").toInt() > i ? data.isSwitch[i] = true : data.isSwitch[i] = false; } return data; } NETWORK AFEWebServer::getNetworkData() { NETWORK data; if (server.arg("n").length() > 0) { server.arg("n").toCharArray(data.ssid, sizeof(data.ssid)); } if (server.arg("p").length() > 0) { server.arg("p").toCharArray(data.password, sizeof(data.password)); } if (server.arg("d").length() > 0) { data.isDHCP = true; } else { data.isDHCP = false; } if (server.arg("i1").length() > 0 && server.arg("i2").length() > 0 && server.arg("i3").length() > 0 && server.arg("i4").length() > 0) { data.ip = IPAddress(server.arg("i1").toInt(), server.arg("i2").toInt(), server.arg("i3").toInt(), server.arg("i4").toInt()); } if (server.arg("g1").length() > 0 && server.arg("g2").length() > 0 && server.arg("g3").length() > 0 && server.arg("g4").length() > 0) { data.gateway = IPAddress(server.arg("g1").toInt(), server.arg("g2").toInt(), server.arg("g3").toInt(), server.arg("g4").toInt()); } if (server.arg("s1").length() > 0 && server.arg("s2").length() > 0 && server.arg("s3").length() > 0 && server.arg("s4").length() > 0) { data.subnet = IPAddress(server.arg("s1").toInt(), server.arg("s2").toInt(), server.arg("s3").toInt(), server.arg("s4").toInt()); } if (server.arg("na").length() > 0) { data.noConnectionAttempts = server.arg("na").toInt(); } if (server.arg("wc").length() > 0) { data.waitTimeConnections = server.arg("wc").toInt(); } if (server.arg("ws").length() > 0) { data.waitTimeSeries = server.arg("ws").toInt(); } return data; } MQTT AFEWebServer::getMQTTData() { MQTT data; if (server.arg("h").length() > 0) { server.arg("h").toCharArray(data.host, sizeof(data.host)); } if (server.arg("m1").length() > 0 && server.arg("m2").length() > 0 && server.arg("m3").length() > 0 && server.arg("m4").length() > 0) { data.ip = IPAddress(server.arg("m1").toInt(), server.arg("m2").toInt(), server.arg("m3").toInt(), server.arg("m4").toInt()); } if (server.arg("p").length() > 0) { data.port = server.arg("p").toInt(); } if (server.arg("u").length() > 0) { server.arg("u").toCharArray(data.user, sizeof(data.user)); } if (server.arg("s").length() > 0) { server.arg("s").toCharArray(data.password, sizeof(data.password)); } if (server.arg("t").length() > 0) { server.arg("t").toCharArray(data.topic, sizeof(data.topic)); } return data; } LED AFEWebServer::getLEDData(uint8_t id) { LED data; if (server.arg("g" + String(id)).length() > 0) { data.gpio = server.arg("g" + String(id)).toInt(); } server.arg("o" + String(id)).length() > 0 ? data.changeToOppositeValue = true : data.changeToOppositeValue = false; return data; } uint8_t AFEWebServer::getSystemLEDData() { uint8_t data; if (server.arg("i").length() > 0) { data = server.arg("i").toInt(); } return data; } RELAY AFEWebServer::getRelayData(uint8_t id) { RELAY data; if (server.arg("g" + String(id)).length() > 0) { data.gpio = server.arg("g" + String(id)).toInt(); } if (server.arg("r" + String(id)).length() > 0) { data.statePowerOn = server.arg("r" + String(id)).toInt(); } if (server.arg("n" + String(id)).length() > 0) { server.arg("n" + String(id)).toCharArray(data.name, sizeof(data.name)); } if (server.arg("c" + String(id)).length() > 0) { data.stateMQTTConnected = server.arg("c" + String(id)).toInt(); } if (server.arg("t" + String(id)).length() > 0) { data.timeToOff = server.arg("t" + String(id)).toFloat(); } if (server.arg("l" + String(id)).length() > 0) { data.ledID = server.arg("l" + String(id)).toInt(); } return data; } SWITCH AFEWebServer::getSwitchData(uint8_t id) { SWITCH data; if (server.arg("t" + String(id)).length() > 0) { data.type = server.arg("t" + String(id)).toInt(); } if (server.arg("s" + String(id)).length() > 0) { data.sensitiveness = server.arg("s" + String(id)).toInt(); } if (server.arg("f" + String(id)).length() > 0) { data.functionality = server.arg("f" + String(id)).toInt(); } if (server.arg("g" + String(id)).length() > 0) { data.gpio = server.arg("g" + String(id)).toInt(); } if (server.arg("r" + String(id)).length() > 0) { data.relayID = server.arg("r" + String(id)).toInt(); } return data; } uint8_t AFEWebServer::getLanguageData() { return server.arg("l").length() > 0 ? server.arg("l").toInt() : 1; } <|endoftext|>
<commit_before><commit_msg>Remove unusued function (#1508)<commit_after><|endoftext|>
<commit_before> #include "IntegratorGKMultiPoint_TEST.h" #include "../MathLib/MathConstants.h" #include "../MathLib/MathUtils.h" namespace gk_test_aux { static const char QUADFAIL[] = "***Warning*** - Quadrature Approx Failed!!"; static const char QUADSUCC[] = "Quadrature Approx Succeded!!"; static const char NPREC[] = "Not Sufficient Precision - lacks ~8 digits of Precision"; static const char SPREC[] = "Sufficient Precision"; static const float FPREC{ 23 * ::log10f(static_cast<float>(2)) }; static const double DPREC{ 53 * ::log10(static_cast<double>(2)) }; } const double test::GaussKronordTests::MACHPREC{ 15.9546 }; void test::GaussKronordTests::GK15ExpFunc1() { std::printf("*****Test of Numerical Quadrature - Integrand [e^-px, p > 0]*****\n"); std::printf("Precision of arguments:%.10f\n", gk_test_aux::FPREC); std::printf("Initializing variables.... "); float f_a{ 0.f }; float f_b{ 1.f }; float f_p{ 1.f }; double d_a{ 0.0 }; double d_b{ 1.0 }; double d_p{ 1.0 }; unsigned long long start1, end1, start2, end2; //const char MEQ[] = "Results Equal"; const char MUEQ[] = "Results InEqual"; std::printf("Done\n"); std::printf("lower limit a=%.9f\n", f_a); std::printf("upper limit b=%.9f\n", f_b); std::printf("variable p=%.9f\n", f_p); const float numres{ 0.6321205588f }; std::printf("Started crude timing, TSC used, no affinity set\n"); start1 = __rdtsc(); auto Qres1 = mathlib::IntegratorQK::x_qk15([](float* x)->float{float f_p{ 1.f }; return ::exp(-(f_p* *x)); }, f_a, f_b); end1 = __rdtsc(); if ((end1 - start1) > 0) { std::printf("start time=%lluCycles\n", start1); std::printf("end time=%lluCycles\n", end1); std::printf("x_qk15 executed in:%lluCycles\n", (end1 - start1)); } std::printf("Results Quadrature Comparison FP-32\n\n"); std::printf("%s\n", mathlib::FP_Compare(numres, std::get<0>(Qres1)) ? gk_test_aux::QUADSUCC : gk_test_aux::QUADFAIL); std::printf("Mathematica 10 NIntegrate | QUADPACK QK15 | Abs(delta) | MACHPREC - Abs(delta)\n"); std::printf(" %.9f %.9f %.9f %.9f\n", numres, std::get<0>(Qres1), std::fabs(numres - std::get<0>(Qres1)), std::fabsf(numres - std::get<0>(Qres1)) > EPS_FLT ? MACHPREC - std::fabs(numres - std::get<0>(Qres1)):0.f); std::printf("--------------------------------------------------------------\n "); std::printf("QK15 - Abs Error=%.9f\n",std::get<1>(Qres1)); std::printf("QK15 - approx to Integral j=%.9f\n",std::get<2>(Qres1)); std::printf("QK15 - approx to Integral abs(f-i/(b-a))=%.9f\n",std::get<3>(Qres1)); std::printf("QK15 - End of FP-32 Test\n\n"); std::printf("Start of FP-64 Precision Test\n"); std::printf("lower limit a=%.17f\n", d_a); std::printf("upper limit b=%.17f\n", d_b); std::printf("variable p=%.19f\n", d_p); const double d_numres{ 0.63212055882855768 }; std::printf("Started crude timing, TSC used, no affinity set\n"); start2 = __rdtsc(); auto Qres2 = mathlib::IntegratorQK::x_qk15([](double* x)->double{double p{ 1.0 }; return ::exp(-(p * *x)); }, d_a, d_b); end2 = __rdtsc(); if ((end2 - start2) > 0) { std::printf("start time=%lluCycles\n", start2); std::printf("end time=%lluCycles\n", end2); std::printf("x_qk15 executed in:%lluCycles\n", (end2 - start2)); } std::printf("Results Quadrature Comparison FP-64\n\n"); std::printf("%s\n\n", mathlib::FP_Compare(d_numres,std::get<0>(Qres2)) ? gk_test_aux::QUADSUCC : gk_test_aux::QUADFAIL); std::printf("Mathematica 10 NIntegrate | QUADPACK DQK15 | Abs(delta) | MACHPREC - Abs(delta)\n"); std::printf("%.17f %.17f %.17f %.17f\n", d_numres, std::get<0>(Qres2), std::fabs(d_numres - std::get<0>(Qres2)), std::fabs(d_numres - std::get<0>(Qres2)) > EPS_DBL ? MACHPREC - ::log10(std::fabs(d_numres - std::get<0>(Qres2))):0.0); //std::printf("%s\n",std::fabs(d_numres - std::get<0>(Qres2)) <= std::numeric_limits<double>::epsilon() ? MEQ : MUEQ); std::printf("----------------------------------------------------------------\n"); std::printf("DQK15 - abs error=%.17f\n", std::get<1>(Qres2)); std::printf("DQK15 - approx to Integral j=%.17f\n", std::get<2>(Qres2)); std::printf("DQK15 - approx to Integral abs(f-i/(b-a))=%.17f\n", std::get<3>(Qres2)); std::printf("DQK15 - End of FP-64 Test\n\n"); } void test::GaussKronordTests::GK15ExpFunc2() { std::printf("*****Test of Numerical Quadrature - Integrand [dx/1+e^px, p > 0]*****\n"); std::printf("Precsion of arguments:%.10f\n", gk_test_aux::FPREC); std::printf("Initializing variables.... "); float f_a{ 0.f }; float f_b{ 1.f }; float f_p{ 0.5f }; double d_a{ 0.0 }; double d_b{ 1.0 }; double d_p{ 0.5 }; unsigned long long start1, start2, stop1, stop2; std::printf("Done\n"); std::printf("lower limit a=%.9f\n", f_a); std::printf("upper limit b=%.9f\n", f_b); std::printf("variable p=%.9f\n", f_p); const float numres{ 0.4381403928f }; std::printf("Started crude timing, TSC used, no affinity set\n"); start1 = __rdtsc(); auto Qresf = mathlib::IntegratorQK::x_qk15([](float* x)->float{ float p{ 0.5f }; return 1.f / (1.f + ::exp(p * *x)); }, f_a, f_b); stop1 = __rdtsc(); if ((stop1 - start1) > 0) { std::printf("start1=%lluCycles\n", start1); std::printf("stop1 =%lluCycles\n", stop1); std::printf("x_qk15 excuted in:%lluCycles\n", stop1 - start1); } std::printf("Results Quadrature Comparison FP-32\n\n"); std::printf("%s\n", mathlib::FP_Compare(numres, std::get<0>(Qresf)) ? gk_test_aux::QUADSUCC : gk_test_aux::QUADFAIL); std::printf("Mathematica 10 NIntegrate | QUADPACK QK15 | Abs(delta) | MACHPREC - Abs(delta)\n"); std::printf(" %.9f, %.9f, %.9f, %.9f\n", numres, std::get<0>(Qresf), std::fabsf(numres - std::get<0>(Qresf)), std::fabsf(numres - std::get<0>(Qresf)) > EPS_FLT ? MACHPREC - ::log10f(std::fabsf(numres - std::get<0>(Qresf))) : 0.f); std::printf("--------------------------------------------------------------\n "); std::printf("QK15 Abs error=%.9f\n", std::get<1>(Qresf)); std::printf("QK15 approx to Integral j=%.9f\n", std::get<2>(Qresf)); std::printf("QK15 approx to Integral abs(f-i/(b-a))=%.9f\n\n", std::get<3>(Qresf)); std::printf("Precision of arguments=%.17f\n", gk_test_aux::DPREC); std::printf("lower limit a=%.17f\n", d_a); std::printf("upper limit b=%.17f\n", d_b); std::printf("variable p=%.17f\n", d_p); const double d_numres{ 0.43814039275967725 }; std::printf("Started crude timing, TSC used, no affinity set\n"); start2 = __rdtsc(); auto Qresd = mathlib::IntegratorQK::x_qk15([](double* x)->double{double p{ 0.5 }; return 1.0 / (1.0 + ::exp(p * *x)); }, d_a, d_b); stop2 = __rdtsc(); if ((stop2 - start2) > 0) { std::printf("start2=%lluCycles\n", start2); std::printf("stop2 =%lluCycles\n", stop2); std::printf("x_qk15 executed in:%lluCycles\n", stop2 - start2); } std::printf("Results Quadrature Comparison FP-64\n\n"); std::printf("%s\n\n", mathlib::FP_Compare(d_numres,std::get<0>(Qresd)) ? gk_test_aux::QUADSUCC : gk_test_aux::QUADFAIL); std::printf("Mathematica 10 NIntegrate | QUADPACK QK15 | Abs(delta) | MACHPREC - Abs(delta)\n"); std::printf("%.16f, %.16f, %.16f, %.16f\n", d_numres, std::get<0>(Qresd), std::fabs(d_numres - std::get<0>(Qresd)), std::fabs(d_numres - std::get<0>(Qresd)) > EPS_DBL ? MACHPREC - (-1.0 * ::log10(std::fabs(d_numres - std::get<0>(Qresd)))) : 0.0); std::printf("--------------------------------------------------------------\n "); std::printf("DQK15 Abs error=%.17f\n", std::get<1>(Qresd)); std::printf("DQK15 approx Integral j=%.17f\n", std::get<2>(Qresd)); std::printf("DQK15 aaprox Integral abs(f-i/(b-a))=%.17f\n", std::get<3>(Qresd)); std::printf("DQK15 - End of FP-64 Test\n\n"); } void test::GaussKronordTests::GK15ExpFunc3() { std::printf("*****Numerical Integration of Integrand = [e^-ux/1+e-x, u > 0.0]*****\n"); std::printf("Precsion of arguments:%.10f\n", gk_test_aux::FPREC); std::printf("Initializing variables.... "); float f_a{ 99.f }; float f_b{ 100.f }; float f_u{ 0.33f }; double d_a{ 99.0 }; double d_b{ 100.0 }; double d_u{ 0.33 }; unsigned long long start1, start2, stop1, stop2; std::printf("Done\n"); std::printf("lower limit a=%.9f\n", f_a); std::printf("upper limit b=%.9f\n", f_b); std::printf("variable u=%.9f\n", f_u); const float f_numres{ 5.519624233e-15f }; std::printf("Started crude timing, TSC used, no affinity set\n"); start1 = __rdtsc(); auto Qresf = mathlib::IntegratorQK::x_qk15([](float* x)->float{float u{ 0.33f }; return ::exp(-(u * *x)) / (1.f + ::exp(-*x)); }, f_a, f_b); stop1 = __rdtsc(); if ((stop1 - start1) > 0) { std::printf("start1=%lluCycles\n", start1); std::printf("stop1 =%lluCycles\n", stop1); std::printf("x_qk15 executed in=%llu\n", stop1 - start1); } std::printf("Results Quadrature Comparison FP-32\n\n"); std::printf("%s\n", mathlib::FP_Compare(f_numres, std::get<0>(Qresf)) ? gk_test_aux::QUADSUCC : gk_test_aux::QUADFAIL); std::printf("Mathematica 10 NIntegrate | QUADPACK QK15 | Abs(delta) | MACHPREC - Abs(delta)\n"); std::printf("%.9f %.9f %.9f %.9f\n", f_numres, std::get<0>(Qresf), std::fabsf(f_numres - std::get<0>(Qresf)), std::fabsf(f_numres - std::get<0>(Qresf)) > EPS_FLT ? MACHPREC - ::log10f(std::fabsf(f_numres - std::get<0>(Qresf))) : 0.f); std::printf("%s\n", std::fabs(std::get<0>(Qresf)) < EPS_FLT ? gk_test_aux::NPREC : gk_test_aux::SPREC); std::printf("--------------------------------------------------------------\n "); std::printf("QK15 Abs error=%.9f\n", std::get<1>(Qresf)); std::printf("QK15 approx Integral j=%.9f\n", std::get<2>(Qresf)); std::printf("QK15 approx Integral abs(f-i/(b-a))=%.9f\n\n", std::get<3>(Qresf)); std::printf("Precision of arguments=%.17f\n", gk_test_aux::DPREC); std::printf("lower limit a=%.17f\n", d_a); std::printf("upper limit b=%.17f\n", d_b); std::printf("variable u=%.17f\n", d_u); const double d_numres{ 5.5196242329603281e-15 }; std::printf("Started crude timing, TSC used, no affinity set\n"); start2 = __rdtsc(); auto Qresd = mathlib::IntegratorQK::x_qk15([](double* x)->double{ double u{ 0.33 }; return ::exp(-(u * *x)) / (1.0 + ::exp(-*x)); }, d_a, d_b); stop2 = __rdtsc(); if ((stop2 - start2) > 0) { std::printf("start2=%lluCycles\n", start2); std::printf("stop2 =%lluCycles\n", stop2); std::printf("x_qk15 executed in=%lluCycles\n", stop2 - start2); } std::printf("Results Quadrature Comparison FP-64\n\n"); std::printf("%s\n\n", mathlib::FP_Compare(d_numres,std::get<0>(Qresd)) ? gk_test_aux::QUADSUCC : gk_test_aux::QUADFAIL); std::printf("Mathematica 10 NIntegrate | QUADPACK QK15 | Abs(delta) | MACHPREC - Abs(delta)\n"); std::printf("%.30f %.30f %.30f %.30f\n", d_numres, std::get<0>(Qresd), std::fabs(d_numres - std::get<0>(Qresd)), std::fabs(d_numres - std::get<0>(Qresd)) > EPS_DBL ? MACHPREC - (-1.0 * ::log10(std::fabs(d_numres - std::get<0>(Qresd)))) : 0.0); std::printf("DQK15 Abs error=%.30f\n", std::get<1>(Qresd)); std::printf("DQK15 approx of Integral j=%.30f\n", std::get<2>(Qresd)); std::printf("DQK15 approx of Integral abs(f-i/(b-a))=%.30f\n", std::get<3>(Qresd)); std::printf("DQK15 - End of FP-64 Test\n\n"); } void test::GaussKronordTests::GK15TrigFunc1() { std::printf("*****Numerical Integration of Integrand = [1-cos(x))^n*sin(n*x)dx]*****\n"); std::printf("Precsion of arguments:%.10f\n", gk_test_aux::FPREC); std::printf("Initializing variables.... "); float f_a{ 0.f }; float f_b{ mathlib::MathConstants::TWO_PI_FLT() }; float f_n{ 10.f }; double d_a{ 0.0 }; double d_b{ mathlib::MathConstants::TWO_PI_DBL() }; double d_n{ 10.0 }; unsigned long long start1, start2, stop1, stop2; #if 0 std::printf("Done\n"); std::printf("lower limit a=%.9f\n", f_a); std::printf("upper limit b=%.9f\n", f_b); std::printf("variable n=%.9f\n", f_n); const float f_numres{ 1.385110395e-36f }; const double d_numres{ 1.3851103921886892012e-36 }; std::printf("Started crude timing, TSC used, no affinity set\n"); start1 = __rdtsc(); auto Qresf = mathlib::IntegratorQK::x_qk15([](float* x)->float{ float n{ 10.f }; return ::pow((1 - ::cos(*x)), n) * ::sin(n* *x); }, f_a, f_b); stop1 = __rdtsc(); if ((stop1 - start1) > 0) { std::printf("start1=%lluCycles\n", start1); std::printf("stop1 =%lluCycles\n", stop1); std::printf("x_qk15 executed in:%lluCycles\n",stop1 - start1); } std::printf("Results Quadrature Comparison FP-32\n\n"); std::printf("Mathematica 10 NIntegrate | QUADPACK QK15 | Abs(delta) | MACHPREC - Abs(delta)\n"); std::printf(" %.9f %.9f %.9f %.9f\n", f_numres, std::get<0>(Qresf), std::fabsf(f_numres - std::get<0>(Qresf)), std::fabsf(f_numres - std::get<0>(Qresf)) > std::numeric_limits<float>::epsilon() ? MACHPREC - ::log10f(std::fabsf(f_numres - std::get<0>(Qresf))) : 0.f); std::printf("%s\n", std::fabs(std::get<0>(Qresf)) < std::numeric_limits<float>::epsilon() ? NPREC : SPREC); std::printf("QK15 Abs error=%.9f\n", std::get<1>(Qresf)); std::printf("QK15 approx Integral of j=%.9f\n", std::get<2>(Qresf)); std::printf("QK15 approx Integral abs(f-i/(b-a))=%.9f\n\n", std::get<3>(Qresf)); #endif std::printf("Precision of arguments=%.17f\n", gk_test_aux::DPREC); std::printf("lower limit a=%.17f\n", d_a); std::printf("upper limit b=%.17f\n", d_b); std::printf("variable n=%.17f\n", d_n); /* @ This should fail mainly because the result < EPS_DOUBLE. */ const double d_numres{ 1.3851103921886892012e-36 }; std::printf("Started crude timing, TSC used, no affinity set\n"); start2 = __rdtsc(); auto Qresd = mathlib::IntegratorQK::x_qk15([](double* x)->double{ double n{ 10.0 }; return ::pow((1 - ::cos(*x)), n) * ::sin(n* *x); }, d_a, d_b); stop2 = __rdtsc(); if ((stop2 - start2) > 0) { std::printf("start2=%lluCycles\n", start2); std::printf("stop2 =%lluCycles\n", stop2); std::printf("x_qk15 executed in:%lluCycles\n", stop2 - start2); } std::printf("Results Quadrature Comparison FP-64\n\n"); std::printf("%s\n\n", mathlib::FP_Compare(d_numres,std::get<0>(Qresd)) ? gk_test_aux::QUADSUCC : gk_test_aux::QUADFAIL); std::printf("Mathematica 10 NIntegrate | QUADPACK QK15 | Abs(delta) | MACHPREC - Abs(delta)\n"); std::printf(" %.45f, %.45f, %.30f, %.30f\n", d_numres, std::get<0>(Qresd), std::fabs(d_numres - std::get<0>(Qresd)), std::fabs(d_numres - std::get<0>(Qresd)) > EPS_DBL ? MACHPREC - (-1.0 * ::log10(std::fabs(d_numres - std::get<0>(Qresd)))) : 0.0); std::printf("DQK15 Abs error=%.30f\n", std::get<1>(Qresd)); std::printf("DQK15 approx Integral j=%.30f\n", std::get<2>(Qresd)); std::printf("DQK15 approx Integral abs(f-i/(b-a))=%.30f\n", std::get<3>(Qresd)); std::printf("DQK15 - End of Test\n\n"); } void test::GaussKronordTests::GK15TrigFunc2() { std::printf("****Numerical Integration of Integrand = [sin(nx)/sin(x)dx]*****\n"); std::printf("Precsion of arguments:%.10f\n", gk_test_aux::FPREC); std::printf("Initializing variables.... "); const float f_a{ 0.f }; const float f_b{ mathlib::MathConstants::PI_FLT() }; const float f_n{ 3.f }; const double d_a{ 0.0 }; const double d_b{ mathlib::MathConstants::PI_DBL() }; const double d_n{ 3.0 }; unsigned long long start1, start2, stop1, stop2; std::printf("lower limit a=%.9f\n", f_a); std::printf("upper limit b=%.9f\n", f_b); std::printf("variable n=%.9f\n", f_n); const float f_numres{ 3.141592654F }; const double d_numres{ 3.14159265358979323 }; std::printf("Started crude timing, TSC used, no affinity set\n"); start1 = __rdtsc(); auto Qresf = mathlib::IntegratorQK::x_qk15([](float* x)->float{ float n{ 3.f }; return ::sin(n * *x) / sin(*x); }, f_a, f_b); stop1 = __rdtsc(); if ((stop1 - start1) > 0) { std::printf("start1=%lluCycles\n", start1); std::printf("stop1 =%lluCycles\n", stop1); std::printf("x_qk15 executed in:%lluCycles\n", stop1 - start1); } std::printf("Results Quadrature Comparison FP-32\n\n"); std::printf("%s\n",mathlib::FP_Compare(f_numres,std::get<0>(Qresf)) ? gk_test_aux::QUADSUCC : gk_test_aux::QUADFAIL); std::printf("Mathematica 10 NIntegrate | QUADPACK QK15 | Abs(delta) | MACHPREC - Abs(delta)\n"); std::printf("%.9f %.9f %.9f %.9f\n", f_numres, std::get<0>(Qresf), std::fabsf(std::get<0>(Qresf)-f_numres), std::fabsf(f_numres - std::get<0>(Qresf)) > EPS_FLT ? MACHPREC - ::log10f(std::fabsf(f_numres - std::get<0>(Qresf))) : 0.f); std::printf("%s\n", std::fabs(std::get<0>(Qresf)) < EPS_FLT ? gk_test_aux::NPREC : gk_test_aux::SPREC); std::printf("QK15 Abs error=%.9f\n", std::get<1>(Qresf)); std::printf("QK15 approx Integral of j=%.9f\n", std::get<2>(Qresf)); std::printf("QK15 approx Integral abs(f-i/(b-a))=%.9f\n\n", std::get<3>(Qresf)); std::printf("Precision of arguments=%.17f\n", gk_test_aux::DPREC); std::printf("lower limit a=%.17f\n", d_a); std::printf("upper limit b=%.17f\n", d_b); std::printf("variable n=%.17f\n", d_n); start2 = __rdtsc(); auto Qresd = mathlib::IntegratorQK::x_qk15([](double* x)->double{ double n{ 3.0 }; return ::sin(n * *x) / ::sin(*x); }, d_a, d_b); stop2 = __rdtsc(); if ((stop2 - start2) > 0) { std::printf("start2=%lluCycles\n", start2); std::printf("stop2 =%lluCycles\n", stop2); std::printf("x_qk15 executed in:%lluCycles\n", stop2 - start2); } std::printf("Results Quadrature Comparison FP-64\n\n"); std::printf("%s\n\n", mathlib::FP_Compare(d_numres,std::get<0>(Qresd)) ? gk_test_aux::QUADSUCC : gk_test_aux::QUADFAIL); std::printf("Mathematica 10 NIntegrate | QUADPACK QK15 | Abs(delta) | MACHPREC - Abs(delta)\n"); std::printf(" %.17f %.17f %.17f %.17f\n", d_numres, std::get<0>(Qresd), std::fabs(d_numres - std::get<0>(Qresd)), std::fabs(d_numres - std::get<0>(Qresd)) > EPS_DBL ? MACHPREC - (-1.0 * ::log10(std::fabs(d_numres - std::get<0>(Qresd)))) : 0.0); std::printf("DQK15 Abs error=%.17f\n", std::get<1>(Qresd)); std::printf("DQK15 approx Integral j=%.17f\n", std::get<2>(Qresd)); std::printf("DQK15 approx Integral abs(f-i/(b-a))=%.17f\n", std::get<3>(Qresd)); std::printf("DQK15 - End of Test\n\n"); } void test::GaussKronordTests::RunGK15ExpFuncTests() { GK15ExpFunc1(); GK15ExpFunc2(); GK15ExpFunc3(); } void test::GaussKronordTests::RunGK15TrigFuncTests() { GK15TrigFunc1(); GK15TrigFunc2(); }<commit_msg>Delete IntegratorGKMultiPoint_TEST.cpp<commit_after><|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/hwpf/plat/fapiPlatHwpInvoker.C $ */ /* */ /* IBM CONFIDENTIAL */ /* */ /* COPYRIGHT International Business Machines Corp. 2011,2013 */ /* */ /* p1 */ /* */ /* Object Code Only (OCO) source materials */ /* Licensed Internal Code Source Materials */ /* IBM HostBoot Licensed Internal Code */ /* */ /* The source code for this program is not published or otherwise */ /* divested of its trade secrets, irrespective of what has been */ /* deposited with the U.S. Copyright Office. */ /* */ /* Origin: 30 */ /* */ /* IBM_PROLOG_END_TAG */ /** * @file fapiPlatHwpInvoker.C * * @brief Implements the fapiRcToErrl function. */ #include <fapiTarget.H> #include <fapiReturnCode.H> #include <fapiPlatTrace.H> #include <fapiErrorInfo.H> #include <hwpf/hwpf_reasoncodes.H> #include <errl/errlentry.H> namespace fapi { /** * @brief Translates a FAPI callout priority to an HWAS callout priority * * @param[i] i_fapiPri FAPI callout priority * * @return HWAS callout priority */ HWAS::callOutPriority xlateCalloutPriority( const fapi::CalloutPriorities::CalloutPriority i_fapiPri) { // Use the CalloutPriority enum value as an index HWAS::callOutPriority l_priority = HWAS::SRCI_PRIORITY_HIGH; size_t l_index = i_fapiPri; const HWAS::callOutPriority HWAS_PRI[] = {HWAS::SRCI_PRIORITY_LOW, HWAS::SRCI_PRIORITY_MED, HWAS::SRCI_PRIORITY_HIGH}; if (l_index < (sizeof(HWAS_PRI)/sizeof(HWAS::callOutPriority))) { l_priority = HWAS_PRI[i_fapiPri]; } else { FAPI_ERR("fapi::xlateCalloutPriority: Unknown priority 0x%x, assuming HIGH", i_fapiPri); } return l_priority; } /** * @brief Translates a FAPI procedure callout to an HWAS procedure callout * * @param[i] i_fapiProc FAPI procedure callout * * @return HWAS procedure callout */ HWAS::epubProcedureID xlateProcedureCallout( const fapi::ProcedureCallouts::ProcedureCallout i_fapiProc) { // Use the ProcedureCallout enum value as an index HWAS::epubProcedureID l_proc = HWAS::EPUB_PRC_HB_CODE; size_t l_index = i_fapiProc; const HWAS::epubProcedureID HWAS_PROC[] = { HWAS::EPUB_PRC_HB_CODE, HWAS::EPUB_PRC_LVL_SUPP, HWAS::EPUB_PRC_MEMORY_PLUGGING_ERROR}; if (l_index < (sizeof(HWAS_PROC)/sizeof(HWAS::epubProcedureID))) { l_proc = HWAS_PROC[i_fapiProc]; } else { FAPI_ERR("fapi::xlateProcedureCallout: Unknown proc 0x%x, assuming CODE", i_fapiProc); } return l_proc; } /** * @brief Processes any FFDC in the ReturnCode Error Information and adds them * to the error log * * @param[i] i_errInfo Reference to ReturnCode Error Information * @param[io] io_pError Errorlog Handle */ void processEIFfdcs(const ErrorInfo & i_errInfo, errlHndl_t io_pError) { // Iterate through the FFDC sections, adding each to the error log uint32_t l_size = 0; for (ErrorInfo::ErrorInfoFfdcCItr_t l_itr = i_errInfo.iv_ffdcs.begin(); l_itr != i_errInfo.iv_ffdcs.end(); ++l_itr) { const void * l_pFfdc = (*l_itr)->getData(l_size); uint32_t l_ffdcId = (*l_itr)->getFfdcId(); // Add the FFDC ID as the first word, then the FFDC data ERRORLOG::ErrlUD * l_pUD = io_pError->addFFDC( HWPF_COMP_ID, &l_ffdcId, sizeof(l_ffdcId), 1, HWPF_UDT_HWP_FFDC); if (l_pUD) { io_pError->appendToFFDC(l_pUD, l_pFfdc, l_size); } } } /** * @brief Processes any Procedure callouts requests in the ReturnCode Error * Information and adds them to the error log * * @param[i] i_errInfo Reference to ReturnCode Error Information * @param[io] io_pError Errorlog Handle */ void processEIProcCallouts(const ErrorInfo & i_errInfo, errlHndl_t io_pError) { // Iterate through the procedure callout requests, adding each to the error // log for (ErrorInfo::ErrorInfoProcedureCalloutCItr_t l_itr = i_errInfo.iv_procedureCallouts.begin(); l_itr != i_errInfo.iv_procedureCallouts.end(); ++l_itr) { HWAS::epubProcedureID l_procedure = xlateProcedureCallout((*l_itr)->iv_procedure); HWAS::callOutPriority l_priority = xlateCalloutPriority((*l_itr)->iv_calloutPriority); io_pError->addProcedureCallout(l_procedure, l_priority); } } void processEIBusCallouts(const ErrorInfo & i_errInfo, errlHndl_t io_pError) { // Iterate through the bus callout requests, adding each to the error log for (ErrorInfo::ErrorInfoBusCalloutCItr_t l_itr = i_errInfo.iv_busCallouts.begin(); l_itr != i_errInfo.iv_busCallouts.end(); ++l_itr) { TARGETING::Target * l_pTarget1 = reinterpret_cast<TARGETING::Target*>((*l_itr)->iv_target1.get()); TARGETING::Target * l_pTarget2 = reinterpret_cast<TARGETING::Target*>((*l_itr)->iv_target1.get()); // Issue 72257. Uncomment the following lines to add a bus callout to // the error log, the addBusCallout enums and interfaces are not in place yet // HWAS::callOutPriority l_priority = // xlateCalloutPriority((*l_itr)->iv_calloutPriority); bool l_busTypeValid = true; // HWAS::busTypeEnum l_busType = HWAS::FSI_BUS_TYPE; TARGETING::TYPE l_type1 = l_pTarget1->getAttr<TARGETING::ATTR_TYPE>(); TARGETING::TYPE l_type2 = l_pTarget2->getAttr<TARGETING::ATTR_TYPE>(); if ( ((l_type1 == TARGETING::TYPE_MCS) && (l_type2 == TARGETING::TYPE_MEMBUF)) || ((l_type1 == TARGETING::TYPE_MEMBUF) && (l_type2 == TARGETING::TYPE_MCS)) ) { // l_busType = HWAS::DMI_BUS_TYPE; } else if ((l_type1 == TARGETING::TYPE_ABUS) && (l_type2 == TARGETING::TYPE_ABUS)) { // l_busType = HWAS::A_BUS_TYPE; } else if ((l_type1 == TARGETING::TYPE_XBUS) && (l_type2 == TARGETING::TYPE_XBUS)) { // l_busType = HWAS::X_BUS_TYPE; } else { FAPI_ERR("processEIBusCallouts: Bus between target types not known (0x%08x:0x%08x)", l_type1, l_type2); l_busTypeValid = false; } if (l_busTypeValid) { // io_pError->addBusCallout(l_pTarget1, l_pTarget2, l_busType, // l_priority); } } } /** * @brief Processes any Callout/Deconfigure/GARD requests in the ReturnCode Error * Information and adds them to the error log * * @param[i] i_errInfo Reference to ReturnCode Error Information * @param[io] io_pError Errorlog Handle */ void processEICDGs(const ErrorInfo & i_errInfo, errlHndl_t io_pError) { // TODO: RTC issue 47147 // Need to figure out how connections are called out. Assuming this is done // by calling out Target pairs, then the HWAS::SRCI_PRIORITY will need to // be a 'grouping' priority (MEDA/B/C) // Iterate through the CGD requests, adding each to the error log for (ErrorInfo::ErrorInfoCDGCItr_t l_itr = i_errInfo.iv_CDGs.begin(); l_itr != i_errInfo.iv_CDGs.end(); ++l_itr) { TARGETING::Target * l_pTarget = reinterpret_cast<TARGETING::Target*>((*l_itr)->iv_target.get()); HWAS::callOutPriority l_priority = xlateCalloutPriority((*l_itr)->iv_calloutPriority); HWAS::DeconfigEnum l_deconfig = HWAS::NO_DECONFIG; if ((*l_itr)->iv_deconfigure) { l_deconfig = HWAS::DELAYED_DECONFIG; } HWAS::GARD_ErrorType l_gard = HWAS::GARD_NULL; if ((*l_itr)->iv_gard) { l_gard = HWAS::GARD_Unrecoverable; } io_pError->addHwCallout(l_pTarget, l_priority, l_deconfig, l_gard); } } //****************************************************************************** // fapiRcToErrl function. Converts a fapi::ReturnCode to an error log //****************************************************************************** errlHndl_t fapiRcToErrl(ReturnCode & io_rc) { errlHndl_t l_pError = NULL; if (io_rc) { // ReturnCode contains an error. Find out which component of the HWPF // created the error ReturnCode::returnCodeCreator l_creator = io_rc.getCreator(); if (l_creator == ReturnCode::CREATOR_PLAT) { // PLAT error. Release the errlHndl_t FAPI_ERR("fapiRcToErrl: PLAT error: 0x%x", static_cast<uint32_t>(io_rc)); l_pError = reinterpret_cast<errlHndl_t> (io_rc.releasePlatData()); } else if (l_creator == ReturnCode::CREATOR_HWP) { // HWP Error. Create an error log uint32_t l_rcValue = static_cast<uint32_t>(io_rc); FAPI_ERR("fapiRcToErrl: HWP error: 0x%x", l_rcValue); // TODO What should the severity be? Should it be in the error info? /*@ * @errortype * @moduleid MOD_HWP_RC_TO_ERRL * @reasoncode RC_HWP_GENERATED_ERROR * @userdata1 RC value from HWP * @userdata2 <unused> * @devdesc HW Procedure generated error. See User Data. */ l_pError = new ERRORLOG::ErrlEntry(ERRORLOG::ERRL_SEV_UNRECOVERABLE, MOD_HWP_RC_TO_ERRL, RC_HWP_GENERATED_ERROR, TO_UINT64(l_rcValue)); // Add the rcValue as FFDC. This will explain what the error was l_pError->addFFDC(HWPF_COMP_ID, &l_rcValue, sizeof(l_rcValue), 1, HWPF_UDT_HWP_RCVALUE); // Get the Error Information Pointer const ErrorInfo * l_pErrorInfo = io_rc.getErrorInfo(); if (l_pErrorInfo) { // There is error information associated with the ReturnCode processEIFfdcs(*l_pErrorInfo, l_pError); processEIProcCallouts(*l_pErrorInfo, l_pError); processEIBusCallouts(*l_pErrorInfo, l_pError); processEICDGs(*l_pErrorInfo, l_pError); } else { FAPI_ERR("fapiRcToErrl: No Error Information"); } } else { // FAPI error. Create an error log FAPI_ERR("fapiRcToErrl: FAPI error: 0x%x", static_cast<uint32_t>(io_rc)); // The errlog reason code is the HWPF compID and the rcValue LSB uint32_t l_rcValue = static_cast<uint32_t>(io_rc); uint16_t l_reasonCode = l_rcValue; l_reasonCode &= 0xff; l_reasonCode |= HWPF_COMP_ID; // HostBoot errlog tags for FAPI errors are in hwpfReasonCodes.H l_pError = new ERRORLOG::ErrlEntry(ERRORLOG::ERRL_SEV_UNRECOVERABLE, MOD_FAPI_RC_TO_ERRL, l_reasonCode); // FAPI may have added Error Information. // Get the Error Information Pointer const ErrorInfo * l_pErrorInfo = io_rc.getErrorInfo(); if (l_pErrorInfo) { processEIFfdcs(*l_pErrorInfo, l_pError); processEIProcCallouts(*l_pErrorInfo, l_pError); processEIBusCallouts(*l_pErrorInfo, l_pError); processEICDGs(*l_pErrorInfo, l_pError); } } // Set the ReturnCode to success, this will delete any ErrorInfo or PLAT // DATA associated with the ReturnCode io_rc = FAPI_RC_SUCCESS; // add the fapi traces to the elog l_pError->collectTrace(FAPI_TRACE_NAME, 256 ); l_pError->collectTrace(FAPI_IMP_TRACE_NAME, 256 ); l_pError->collectTrace(FAPI_SCAN_TRACE_NAME, 256 ); } return l_pError; } } // End namespace <commit_msg>Add FAPI Bus callout to error log<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/hwpf/plat/fapiPlatHwpInvoker.C $ */ /* */ /* IBM CONFIDENTIAL */ /* */ /* COPYRIGHT International Business Machines Corp. 2011,2013 */ /* */ /* p1 */ /* */ /* Object Code Only (OCO) source materials */ /* Licensed Internal Code Source Materials */ /* IBM HostBoot Licensed Internal Code */ /* */ /* The source code for this program is not published or otherwise */ /* divested of its trade secrets, irrespective of what has been */ /* deposited with the U.S. Copyright Office. */ /* */ /* Origin: 30 */ /* */ /* IBM_PROLOG_END_TAG */ /** * @file fapiPlatHwpInvoker.C * * @brief Implements the fapiRcToErrl function. */ #include <fapiTarget.H> #include <fapiReturnCode.H> #include <fapiPlatTrace.H> #include <fapiErrorInfo.H> #include <hwpf/hwpf_reasoncodes.H> #include <errl/errlentry.H> namespace fapi { /** * @brief Translates a FAPI callout priority to an HWAS callout priority * * @param[i] i_fapiPri FAPI callout priority * * @return HWAS callout priority */ HWAS::callOutPriority xlateCalloutPriority( const fapi::CalloutPriorities::CalloutPriority i_fapiPri) { // Use the CalloutPriority enum value as an index HWAS::callOutPriority l_priority = HWAS::SRCI_PRIORITY_HIGH; size_t l_index = i_fapiPri; const HWAS::callOutPriority HWAS_PRI[] = {HWAS::SRCI_PRIORITY_LOW, HWAS::SRCI_PRIORITY_MED, HWAS::SRCI_PRIORITY_HIGH}; if (l_index < (sizeof(HWAS_PRI)/sizeof(HWAS::callOutPriority))) { l_priority = HWAS_PRI[i_fapiPri]; } else { FAPI_ERR("fapi::xlateCalloutPriority: Unknown priority 0x%x, assuming HIGH", i_fapiPri); } return l_priority; } /** * @brief Translates a FAPI procedure callout to an HWAS procedure callout * * @param[i] i_fapiProc FAPI procedure callout * * @return HWAS procedure callout */ HWAS::epubProcedureID xlateProcedureCallout( const fapi::ProcedureCallouts::ProcedureCallout i_fapiProc) { // Use the ProcedureCallout enum value as an index HWAS::epubProcedureID l_proc = HWAS::EPUB_PRC_HB_CODE; size_t l_index = i_fapiProc; const HWAS::epubProcedureID HWAS_PROC[] = { HWAS::EPUB_PRC_HB_CODE, HWAS::EPUB_PRC_LVL_SUPP, HWAS::EPUB_PRC_MEMORY_PLUGGING_ERROR}; if (l_index < (sizeof(HWAS_PROC)/sizeof(HWAS::epubProcedureID))) { l_proc = HWAS_PROC[i_fapiProc]; } else { FAPI_ERR("fapi::xlateProcedureCallout: Unknown proc 0x%x, assuming CODE", i_fapiProc); } return l_proc; } /** * @brief Processes any FFDC in the ReturnCode Error Information and adds them * to the error log * * @param[i] i_errInfo Reference to ReturnCode Error Information * @param[io] io_pError Errorlog Handle */ void processEIFfdcs(const ErrorInfo & i_errInfo, errlHndl_t io_pError) { // Iterate through the FFDC sections, adding each to the error log uint32_t l_size = 0; for (ErrorInfo::ErrorInfoFfdcCItr_t l_itr = i_errInfo.iv_ffdcs.begin(); l_itr != i_errInfo.iv_ffdcs.end(); ++l_itr) { const void * l_pFfdc = (*l_itr)->getData(l_size); uint32_t l_ffdcId = (*l_itr)->getFfdcId(); // Add the FFDC ID as the first word, then the FFDC data ERRORLOG::ErrlUD * l_pUD = io_pError->addFFDC( HWPF_COMP_ID, &l_ffdcId, sizeof(l_ffdcId), 1, HWPF_UDT_HWP_FFDC); if (l_pUD) { io_pError->appendToFFDC(l_pUD, l_pFfdc, l_size); } } } /** * @brief Processes any Procedure callouts requests in the ReturnCode Error * Information and adds them to the error log * * @param[i] i_errInfo Reference to ReturnCode Error Information * @param[io] io_pError Errorlog Handle */ void processEIProcCallouts(const ErrorInfo & i_errInfo, errlHndl_t io_pError) { // Iterate through the procedure callout requests, adding each to the error // log for (ErrorInfo::ErrorInfoProcedureCalloutCItr_t l_itr = i_errInfo.iv_procedureCallouts.begin(); l_itr != i_errInfo.iv_procedureCallouts.end(); ++l_itr) { HWAS::epubProcedureID l_procedure = xlateProcedureCallout((*l_itr)->iv_procedure); HWAS::callOutPriority l_priority = xlateCalloutPriority((*l_itr)->iv_calloutPriority); io_pError->addProcedureCallout(l_procedure, l_priority); } } void processEIBusCallouts(const ErrorInfo & i_errInfo, errlHndl_t io_pError) { // Iterate through the bus callout requests, adding each to the error log for (ErrorInfo::ErrorInfoBusCalloutCItr_t l_itr = i_errInfo.iv_busCallouts.begin(); l_itr != i_errInfo.iv_busCallouts.end(); ++l_itr) { TARGETING::Target * l_pTarget1 = reinterpret_cast<TARGETING::Target*>((*l_itr)->iv_target1.get()); TARGETING::Target * l_pTarget2 = reinterpret_cast<TARGETING::Target*>((*l_itr)->iv_target1.get()); HWAS::callOutPriority l_priority = xlateCalloutPriority((*l_itr)->iv_calloutPriority); bool l_busTypeValid = true; HWAS::busTypeEnum l_busType = HWAS::FSI_BUS_TYPE; TARGETING::TYPE l_type1 = l_pTarget1->getAttr<TARGETING::ATTR_TYPE>(); TARGETING::TYPE l_type2 = l_pTarget2->getAttr<TARGETING::ATTR_TYPE>(); if ( ((l_type1 == TARGETING::TYPE_MCS) && (l_type2 == TARGETING::TYPE_MEMBUF)) || ((l_type1 == TARGETING::TYPE_MEMBUF) && (l_type2 == TARGETING::TYPE_MCS)) ) { l_busType = HWAS::DMI_BUS_TYPE; } else if ((l_type1 == TARGETING::TYPE_ABUS) && (l_type2 == TARGETING::TYPE_ABUS)) { l_busType = HWAS::A_BUS_TYPE; } else if ((l_type1 == TARGETING::TYPE_XBUS) && (l_type2 == TARGETING::TYPE_XBUS)) { l_busType = HWAS::X_BUS_TYPE; } else { FAPI_ERR("processEIBusCallouts: Bus between target types not known (0x%08x:0x%08x)", l_type1, l_type2); l_busTypeValid = false; } if (l_busTypeValid) { io_pError->addBusCallout(l_pTarget1, l_pTarget2, l_busType, l_priority); } } } /** * @brief Processes any Callout/Deconfigure/GARD requests in the ReturnCode Error * Information and adds them to the error log * * @param[i] i_errInfo Reference to ReturnCode Error Information * @param[io] io_pError Errorlog Handle */ void processEICDGs(const ErrorInfo & i_errInfo, errlHndl_t io_pError) { // Iterate through the CGD requests, adding each to the error log for (ErrorInfo::ErrorInfoCDGCItr_t l_itr = i_errInfo.iv_CDGs.begin(); l_itr != i_errInfo.iv_CDGs.end(); ++l_itr) { TARGETING::Target * l_pTarget = reinterpret_cast<TARGETING::Target*>((*l_itr)->iv_target.get()); HWAS::callOutPriority l_priority = xlateCalloutPriority((*l_itr)->iv_calloutPriority); HWAS::DeconfigEnum l_deconfig = HWAS::NO_DECONFIG; if ((*l_itr)->iv_deconfigure) { l_deconfig = HWAS::DELAYED_DECONFIG; } HWAS::GARD_ErrorType l_gard = HWAS::GARD_NULL; if ((*l_itr)->iv_gard) { l_gard = HWAS::GARD_Unrecoverable; } io_pError->addHwCallout(l_pTarget, l_priority, l_deconfig, l_gard); } } //****************************************************************************** // fapiRcToErrl function. Converts a fapi::ReturnCode to an error log //****************************************************************************** errlHndl_t fapiRcToErrl(ReturnCode & io_rc) { errlHndl_t l_pError = NULL; if (io_rc) { // ReturnCode contains an error. Find out which component of the HWPF // created the error ReturnCode::returnCodeCreator l_creator = io_rc.getCreator(); if (l_creator == ReturnCode::CREATOR_PLAT) { // PLAT error. Release the errlHndl_t FAPI_ERR("fapiRcToErrl: PLAT error: 0x%x", static_cast<uint32_t>(io_rc)); l_pError = reinterpret_cast<errlHndl_t> (io_rc.releasePlatData()); } else if (l_creator == ReturnCode::CREATOR_HWP) { // HWP Error. Create an error log uint32_t l_rcValue = static_cast<uint32_t>(io_rc); FAPI_ERR("fapiRcToErrl: HWP error: 0x%x", l_rcValue); // TODO What should the severity be? Should it be in the error info? /*@ * @errortype * @moduleid MOD_HWP_RC_TO_ERRL * @reasoncode RC_HWP_GENERATED_ERROR * @userdata1 RC value from HWP * @userdata2 <unused> * @devdesc HW Procedure generated error. See User Data. */ l_pError = new ERRORLOG::ErrlEntry(ERRORLOG::ERRL_SEV_UNRECOVERABLE, MOD_HWP_RC_TO_ERRL, RC_HWP_GENERATED_ERROR, TO_UINT64(l_rcValue)); // Add the rcValue as FFDC. This will explain what the error was l_pError->addFFDC(HWPF_COMP_ID, &l_rcValue, sizeof(l_rcValue), 1, HWPF_UDT_HWP_RCVALUE); // Get the Error Information Pointer const ErrorInfo * l_pErrorInfo = io_rc.getErrorInfo(); if (l_pErrorInfo) { // There is error information associated with the ReturnCode processEIFfdcs(*l_pErrorInfo, l_pError); processEIProcCallouts(*l_pErrorInfo, l_pError); processEIBusCallouts(*l_pErrorInfo, l_pError); processEICDGs(*l_pErrorInfo, l_pError); } else { FAPI_ERR("fapiRcToErrl: No Error Information"); } } else { // FAPI error. Create an error log FAPI_ERR("fapiRcToErrl: FAPI error: 0x%x", static_cast<uint32_t>(io_rc)); // The errlog reason code is the HWPF compID and the rcValue LSB uint32_t l_rcValue = static_cast<uint32_t>(io_rc); uint16_t l_reasonCode = l_rcValue; l_reasonCode &= 0xff; l_reasonCode |= HWPF_COMP_ID; // HostBoot errlog tags for FAPI errors are in hwpfReasonCodes.H l_pError = new ERRORLOG::ErrlEntry(ERRORLOG::ERRL_SEV_UNRECOVERABLE, MOD_FAPI_RC_TO_ERRL, l_reasonCode); // FAPI may have added Error Information. // Get the Error Information Pointer const ErrorInfo * l_pErrorInfo = io_rc.getErrorInfo(); if (l_pErrorInfo) { processEIFfdcs(*l_pErrorInfo, l_pError); processEIProcCallouts(*l_pErrorInfo, l_pError); processEIBusCallouts(*l_pErrorInfo, l_pError); processEICDGs(*l_pErrorInfo, l_pError); } } // Set the ReturnCode to success, this will delete any ErrorInfo or PLAT // DATA associated with the ReturnCode io_rc = FAPI_RC_SUCCESS; // add the fapi traces to the elog l_pError->collectTrace(FAPI_TRACE_NAME, 256 ); l_pError->collectTrace(FAPI_IMP_TRACE_NAME, 256 ); l_pError->collectTrace(FAPI_SCAN_TRACE_NAME, 256 ); } return l_pError; } } // End namespace <|endoftext|>
<commit_before>/* Copyright 2018 The TensorFlow Authors. 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. ==============================================================================*/ #include "tensorflow/compiler/xla/client/lib/sorting.h" #include "tensorflow/compiler/xla/client/lib/comparators.h" #include "tensorflow/compiler/xla/client/lib/constants.h" #include "tensorflow/compiler/xla/client/lib/loops.h" #include "tensorflow/compiler/xla/client/lib/slicing.h" #include "tensorflow/compiler/xla/client/xla_builder.h" #include "tensorflow/compiler/xla/shape_util.h" #include "tensorflow/compiler/xla/util.h" namespace xla { XlaOp TopK(XlaOp input, int64 k) { XlaBuilder* const builder = input.builder(); return builder->ReportErrorOrReturn([&]() -> StatusOr<XlaOp> { TF_ASSIGN_OR_RETURN(Shape input_shape, builder->GetShape(input)); int last_dim = input_shape.dimensions_size() - 1; int64 last_dim_size = input_shape.dimensions(last_dim); // TODO(b/165839365): tune these constants for better performance. int64 kPerPartitionSize = 8192; // 2^13 int64 kLastDimSizeThreshold = 524288; // 2^19 int64 kMinNumPartitions = 8; if ((k > 0) && (k < kPerPartitionSize) && (kPerPartitionSize / k > 2) && last_dim_size >= kLastDimSizeThreshold) { int64 num_partitions = CeilOfRatio(last_dim_size - k, kPerPartitionSize - k); if (num_partitions >= kMinNumPartitions) { return TopKWithPartitions(input, k, num_partitions); } } Shape iota_shape = ShapeUtil::MakeShape(S32, AsInt64Slice(input_shape.dimensions())); XlaOp iota_s32 = Iota(builder, iota_shape, last_dim); for (int64 i = 0; i < input_shape.rank(); ++i) { if (input_shape.is_dynamic_dimension(i)) { // Propagate dynamic dimension from inputs to iota. iota_s32 = SetDimensionSize(iota_s32, GetDimensionSize(input, i), i); } } auto input_dims = input_shape.dimensions(); XlaOp sort_result = Sort({input, iota_s32}, CreateScalarGtComputation({input_shape.element_type(), S32}, iota_s32.builder()), last_dim, /*is_stable=*/true); std::vector<int64> start_indices(input_shape.dimensions_size(), 0); std::vector<int64> limit_indices(input_dims.begin(), input_dims.end()); limit_indices[last_dim] = k; std::vector<int64> strides(input_shape.dimensions_size(), 1); XlaOp values = Slice(GetTupleElement(sort_result, 0), start_indices, limit_indices, strides); XlaOp indices = Slice(GetTupleElement(sort_result, 1), start_indices, limit_indices, strides); return Tuple(builder, {values, indices}); }); } XlaOp TopKWithPartitions(XlaOp input, int64 k, int64 num_partitions) { XlaBuilder* const builder = input.builder(); return builder->ReportErrorOrReturn([&]() -> StatusOr<XlaOp> { TF_ASSIGN_OR_RETURN(Shape input_shape, builder->GetShape(input)); int last_dim = input_shape.dimensions_size() - 1; // Calculate per partition size. auto input_dims = input_shape.dimensions(); int64 last_dim_size = input_shape.dimensions(last_dim); const int64 per_partition_size = CeilOfRatio(last_dim_size, num_partitions); // Do normal TopK when per partition size is smaller than or equal to k. if (k >= per_partition_size) { return TopK(input, k); } Shape iota_shape = ShapeUtil::MakeShape(S32, AsInt64Slice(input_shape.dimensions())); XlaOp iota_s32 = Iota(builder, iota_shape, last_dim); for (int64 i = 0; i < input_shape.rank(); ++i) { if (input_shape.is_dynamic_dimension(i)) { // Propagate dynamic dimension from inputs to iota. iota_s32 = SetDimensionSize(iota_s32, GetDimensionSize(input, i), i); } } auto topk_body_fn = [&](XlaOp partition, absl::Span<const XlaOp> values_and_indices, XlaBuilder* builder) -> StatusOr<std::vector<XlaOp>> { auto values = values_and_indices[0]; auto indices = values_and_indices[1]; auto input = values_and_indices[2]; auto iota_s32 = values_and_indices[3]; // Slice value and indices for this partition. XlaOp start = Mul(Add(partition, ConstantR0<int32>(builder, 1)), ConstantR0<int32>(builder, per_partition_size)); XlaOp sliced_input = DynamicSliceInMinorDims(input, {start}, {per_partition_size}); XlaOp sliced_indices = DynamicSliceInMinorDims(iota_s32, {start}, {per_partition_size}); // Concat with previous results. sliced_input = ConcatInDim(builder, {values, sliced_input}, last_dim); sliced_indices = ConcatInDim(builder, {indices, sliced_indices}, last_dim); // Sort this slice XlaOp sort_result = Sort({sliced_input, sliced_indices}, CreateScalarGtComputation({input_shape.element_type(), S32}, sliced_indices.builder()), last_dim, true); std::vector<int64> start_indices(input_shape.dimensions_size(), 0); std::vector<int64> limit_indices(input_dims.begin(), input_dims.end()); std::vector<int64> strides(input_shape.dimensions_size(), 1); // Slice topk. start_indices[last_dim] = 0; limit_indices[last_dim] = k; values = Slice(GetTupleElement(sort_result, 0), start_indices, limit_indices, strides); indices = Slice(GetTupleElement(sort_result, 1), start_indices, limit_indices, strides); return std::vector<XlaOp>{values, indices, input, iota_s32}; }; // Get the values and indices for the first topk so that they can // be passed to the while loop. std::vector<int64> start_indices(input_shape.dimensions_size(), 0); std::vector<int64> limit_indices(input_dims.begin(), input_dims.end()); std::vector<int64> strides(input_shape.dimensions_size(), 1); start_indices[last_dim] = 0; limit_indices[last_dim] = per_partition_size; // Slice value and indices for the first partition. XlaOp sliced_input = Slice(input, start_indices, limit_indices, strides); XlaOp sliced_indices = Slice(iota_s32, start_indices, limit_indices, strides); // Sort this slice XlaOp sort_result = Sort({sliced_input, sliced_indices}, CreateScalarGtComputation({input_shape.element_type(), S32}, sliced_indices.builder()), last_dim, /*is_stable=*/true); // Slice topk. start_indices[last_dim] = 0; limit_indices[last_dim] = k; XlaOp values = Slice(GetTupleElement(sort_result, 0), start_indices, limit_indices, strides); XlaOp indices = Slice(GetTupleElement(sort_result, 1), start_indices, limit_indices, strides); // Pass the result of the first TopK to the while loop and do // num_partition - 1 iterations. TF_ASSIGN_OR_RETURN(auto values_and_indices, ForEachIndex(num_partitions - 1, S32, topk_body_fn, {values, indices, input, iota_s32}, "topk_with_partition", builder)); return Tuple(builder, {values_and_indices[0], values_and_indices[1]}); }); } } // namespace xla <commit_msg>Increase threshold for K to triggered TopKWithPartition.<commit_after>/* Copyright 2018 The TensorFlow Authors. 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. ==============================================================================*/ #include "tensorflow/compiler/xla/client/lib/sorting.h" #include "tensorflow/compiler/xla/client/lib/comparators.h" #include "tensorflow/compiler/xla/client/lib/constants.h" #include "tensorflow/compiler/xla/client/lib/loops.h" #include "tensorflow/compiler/xla/client/lib/slicing.h" #include "tensorflow/compiler/xla/client/xla_builder.h" #include "tensorflow/compiler/xla/shape_util.h" #include "tensorflow/compiler/xla/util.h" namespace xla { XlaOp TopK(XlaOp input, int64 k) { XlaBuilder* const builder = input.builder(); return builder->ReportErrorOrReturn([&]() -> StatusOr<XlaOp> { TF_ASSIGN_OR_RETURN(Shape input_shape, builder->GetShape(input)); int last_dim = input_shape.dimensions_size() - 1; int64 last_dim_size = input_shape.dimensions(last_dim); // TODO(b/148796364): tune these constants for better performance. const int64 kPerPartitionSize = 8192; // 2^13 const int64 kLastDimSizeThreshold = 524288; // 2^19 const int64 kMinNumPartitions = 8; const int64 kMinimalK = 1000; if ((k >= kMinimalK) && (k < kPerPartitionSize) && (kPerPartitionSize / k > 2) && last_dim_size >= kLastDimSizeThreshold) { int64 num_partitions = CeilOfRatio(last_dim_size - k, kPerPartitionSize - k); if (num_partitions >= kMinNumPartitions) { return TopKWithPartitions(input, k, num_partitions); } } Shape iota_shape = ShapeUtil::MakeShape(S32, AsInt64Slice(input_shape.dimensions())); XlaOp iota_s32 = Iota(builder, iota_shape, last_dim); for (int64 i = 0; i < input_shape.rank(); ++i) { if (input_shape.is_dynamic_dimension(i)) { // Propagate dynamic dimension from inputs to iota. iota_s32 = SetDimensionSize(iota_s32, GetDimensionSize(input, i), i); } } auto input_dims = input_shape.dimensions(); XlaOp sort_result = Sort({input, iota_s32}, CreateScalarGtComputation({input_shape.element_type(), S32}, iota_s32.builder()), last_dim, /*is_stable=*/true); std::vector<int64> start_indices(input_shape.dimensions_size(), 0); std::vector<int64> limit_indices(input_dims.begin(), input_dims.end()); limit_indices[last_dim] = k; std::vector<int64> strides(input_shape.dimensions_size(), 1); XlaOp values = Slice(GetTupleElement(sort_result, 0), start_indices, limit_indices, strides); XlaOp indices = Slice(GetTupleElement(sort_result, 1), start_indices, limit_indices, strides); return Tuple(builder, {values, indices}); }); } XlaOp TopKWithPartitions(XlaOp input, int64 k, int64 num_partitions) { XlaBuilder* const builder = input.builder(); return builder->ReportErrorOrReturn([&]() -> StatusOr<XlaOp> { TF_ASSIGN_OR_RETURN(Shape input_shape, builder->GetShape(input)); int last_dim = input_shape.dimensions_size() - 1; // Calculate per partition size. auto input_dims = input_shape.dimensions(); int64 last_dim_size = input_shape.dimensions(last_dim); const int64 per_partition_size = CeilOfRatio(last_dim_size, num_partitions); // Do normal TopK when per partition size is smaller than or equal to k. if (k >= per_partition_size) { return TopK(input, k); } Shape iota_shape = ShapeUtil::MakeShape(S32, AsInt64Slice(input_shape.dimensions())); XlaOp iota_s32 = Iota(builder, iota_shape, last_dim); for (int64 i = 0; i < input_shape.rank(); ++i) { if (input_shape.is_dynamic_dimension(i)) { // Propagate dynamic dimension from inputs to iota. iota_s32 = SetDimensionSize(iota_s32, GetDimensionSize(input, i), i); } } auto topk_body_fn = [&](XlaOp partition, absl::Span<const XlaOp> values_and_indices, XlaBuilder* builder) -> StatusOr<std::vector<XlaOp>> { auto values = values_and_indices[0]; auto indices = values_and_indices[1]; auto input = values_and_indices[2]; auto iota_s32 = values_and_indices[3]; // Slice value and indices for this partition. XlaOp start = Mul(Add(partition, ConstantR0<int32>(builder, 1)), ConstantR0<int32>(builder, per_partition_size)); XlaOp sliced_input = DynamicSliceInMinorDims(input, {start}, {per_partition_size}); XlaOp sliced_indices = DynamicSliceInMinorDims(iota_s32, {start}, {per_partition_size}); // Concat with previous results. sliced_input = ConcatInDim(builder, {values, sliced_input}, last_dim); sliced_indices = ConcatInDim(builder, {indices, sliced_indices}, last_dim); // Sort this slice XlaOp sort_result = Sort({sliced_input, sliced_indices}, CreateScalarGtComputation({input_shape.element_type(), S32}, sliced_indices.builder()), last_dim, true); std::vector<int64> start_indices(input_shape.dimensions_size(), 0); std::vector<int64> limit_indices(input_dims.begin(), input_dims.end()); std::vector<int64> strides(input_shape.dimensions_size(), 1); // Slice topk. start_indices[last_dim] = 0; limit_indices[last_dim] = k; values = Slice(GetTupleElement(sort_result, 0), start_indices, limit_indices, strides); indices = Slice(GetTupleElement(sort_result, 1), start_indices, limit_indices, strides); return std::vector<XlaOp>{values, indices, input, iota_s32}; }; // Get the values and indices for the first topk so that they can // be passed to the while loop. std::vector<int64> start_indices(input_shape.dimensions_size(), 0); std::vector<int64> limit_indices(input_dims.begin(), input_dims.end()); std::vector<int64> strides(input_shape.dimensions_size(), 1); start_indices[last_dim] = 0; limit_indices[last_dim] = per_partition_size; // Slice value and indices for the first partition. XlaOp sliced_input = Slice(input, start_indices, limit_indices, strides); XlaOp sliced_indices = Slice(iota_s32, start_indices, limit_indices, strides); // Sort this slice XlaOp sort_result = Sort({sliced_input, sliced_indices}, CreateScalarGtComputation({input_shape.element_type(), S32}, sliced_indices.builder()), last_dim, /*is_stable=*/true); // Slice topk. start_indices[last_dim] = 0; limit_indices[last_dim] = k; XlaOp values = Slice(GetTupleElement(sort_result, 0), start_indices, limit_indices, strides); XlaOp indices = Slice(GetTupleElement(sort_result, 1), start_indices, limit_indices, strides); // Pass the result of the first TopK to the while loop and do // num_partition - 1 iterations. TF_ASSIGN_OR_RETURN(auto values_and_indices, ForEachIndex(num_partitions - 1, S32, topk_body_fn, {values, indices, input, iota_s32}, "topk_with_partition", builder)); return Tuple(builder, {values_and_indices[0], values_and_indices[1]}); }); } } // namespace xla <|endoftext|>
<commit_before>/** * @file * @author Jason Lingle * @brief Implementation of src/weapon/monophasic_energy_pulse.hxx */ /* * monophasic_energy_pulse.cxx * * Created on: 12.02.2011 * Author: jason */ #include <cmath> #include <cstdlib> #include <iostream> #include "monophasic_energy_pulse.hxx" #include "src/sim/game_object.hxx" #include "src/sim/game_field.hxx" #include "src/sim/collision.hxx" #include "src/background/explosion.hxx" #include "src/sim/blast.hxx" #include "src/ship/ship.hxx" #include "src/graphics/vec.hxx" #include "src/graphics/matops.hxx" #include "src/graphics/shader.hxx" #include "src/graphics/shader_loader.hxx" #include "src/graphics/cmn_shaders.hxx" #include "src/graphics/square.hxx" #include "src/globals.hxx" using namespace std; #define MAX_LIFE_WAVES 256 #define POWER_MUL MONO_POWER_MUL #define FREQUENCY 0.12f #define SIZE 0.01f #define SPEED_MUL 0.0003f #ifndef AB_OPENGL_14 struct MEPUniform { float visibility; vec3 baseColour; }; #define VERTEX_TYPE shader::VertTexc #define UNIFORM_TYPE MEPUniform DELAY_SHADER(monophasePulse) sizeof(VERTEX_TYPE), VATTRIB(vertex), VATTRIB(texCoord), NULL, true, UNIFLOAT(visibility), UNIFORM(baseColour), NULL END_DELAY_SHADER(static mepShader); #else /* defined(AB_OPENGL_14) */ struct MEPUniform { float visibility; vec3 colour; }; #define VERTEX_TYPE shader::VertTexc #define UNIFORM_TYPE MEPUniform #define baseColour colour; #define monophasePulseQuick quick DELAY_SHADER(monophasePulseQuick) sizeof(VERTEX_TYPE), VATTRIB(vertex), NULL, true, UNIFORM(colour), NULL END_DELAY_SHADER(static mepShader); #endif /* defined(AB_OPENGL_14) */ MonophasicEnergyPulse::MonophasicEnergyPulse(GameField* field, Ship* par, float x, float y, float theta, unsigned el) : GameObject(field, x, y, par->getVX() + getSpeed(el)*cos(theta), par->getVY() + getSpeed(el)*sin(theta)), explodeListeners(NULL), deathWaveNumber(rand()%MAX_LIFE_WAVES+1), timeAlive(0), power(el*POWER_MUL), previousFrameWasFinal(false), parent(par), exploded(false), blame(par->blame) { classification = GameObject::LightWeapon; includeInCollisionDetection=false; colrect.radius=SIZE*1.5f; collisionBounds.push_back(&colrect); isExportable=true; } MonophasicEnergyPulse::MonophasicEnergyPulse(GameField* field, float x, float y, float vx, float vy, float pow, unsigned et) : GameObject(field, x, y, vx, vy), explodeListeners(NULL), deathWaveNumber(100), timeAlive(et), power(pow), previousFrameWasFinal(false), parent(NULL), exploded(false), blame(0xFFFFFF) { classification = GameObject::LightWeapon; includeInCollisionDetection=false; isExportable=true; isRemote=true; colrect.radius=SIZE*1.5f; collisionBounds.push_back(&colrect); } MonophasicEnergyPulse::~MonophasicEnergyPulse() { //Remove any ExplodeListener chain attached if (explodeListeners) explodeListeners->prv = NULL; } bool MonophasicEnergyPulse::update(float et) noth { x += vx*et; y += vy*et; if (isRemote) { REMOTE_XYCK; } if (previousFrameWasFinal) includeInCollisionDetection=false; previousFrameWasFinal = currentVFrameLast || decorative; float oldTime=timeAlive; timeAlive += et; float oldAngle = fmod(oldTime*FREQUENCY*2*pi, 2*pi); float newAngle = fmod(timeAlive*FREQUENCY*2*pi, 2*pi); unsigned wavesAlive = (unsigned)2*timeAlive*FREQUENCY; if (wavesAlive == deathWaveNumber && !isRemote) return false; //Check if we need to become collideable if (!isRemote) { if ((oldAngle < pi/2 && newAngle >= pi/2) || (oldAngle < 3*pi/2 && newAngle >= 3*pi/2)) { includeInCollisionDetection=true; //Update collision bounds colrect.vertices[0] = make_pair(x-SIZE/2, y-SIZE/2); colrect.vertices[1] = make_pair(x+SIZE/2, y-SIZE/2); colrect.vertices[2] = make_pair(x+SIZE/2, y+SIZE/2); colrect.vertices[3] = make_pair(x-SIZE/2, y+SIZE/2); } } return true; } void MonophasicEnergyPulse::draw() noth { BEGINGP("MonophasicEP") float angle = timeAlive*FREQUENCY*2*pi; MEPUniform uni = { 1.0f, {{ fabs(sin(8*angle)), fabs(sin(4*angle)), fabs(sin(2*angle))*0.25f+0.75f }}}; square_graphic::bind(); mPush(); mTrans(x,y); mUScale(SIZE); //Draw a bit larger if zoomed out too much if (cameraZoom < 0.3f) mUScale(2.0f); mTrans(-0.5f,-0.5f); mepShader->activate(&uni); square_graphic::draw(); mPop(); ENDGP } float MonophasicEnergyPulse::getRadius() const noth { return SIZE/2*1.5f; } CollisionResult MonophasicEnergyPulse::checkCollision(GameObject* obj) noth { //We never collide with anything if we are remote if (obj==parent || isRemote) return NoCollision; if (!obj->isCollideable()) return UnlikelyCollision; if (objectsCollide(this, obj)) return YesCollision; else return UnlikelyCollision; } void MonophasicEnergyPulse::explode(GameObject* obj) noth { if (!obj) obj = this; if (EXPCLOSE(x,y)) field->add(new Explosion(field, Explosion::Simple, 0.3f, 0.5f, 1.0f, 1.0f, 0.01f, 1000, x, y, obj->getVX(), obj->getVY())); exploded=true; //Reset velocity to match obj so that the velocity of the explosion //can be communicated over the network. vx = obj->getVX(); vy = obj->getVY(); for (ExplodeListener<MonophasicEnergyPulse>* l = explodeListeners; l; l = l->nxt) l->exploded(this); } bool MonophasicEnergyPulse::collideWith(GameObject* obj) noth { if (obj != this) { field->inject(new Blast(field, blame, x, y, SIZE*5, power, true, 0)); explode(obj); } return false; } float MonophasicEnergyPulse::getWavelength(unsigned level) noth { return getSpeed(level)/FREQUENCY; } float MonophasicEnergyPulse::getSurvivalProbability(unsigned level, float dist) noth { float waves = dist / getWavelength(level); return 1.0f - waves/MAX_LIFE_WAVES; } float MonophasicEnergyPulse::getSpeed(unsigned level) noth { return SPEED_MUL * level; } <commit_msg>Reduce explosive radius of MonophasicEnergyPulse.<commit_after>/** * @file * @author Jason Lingle * @brief Implementation of src/weapon/monophasic_energy_pulse.hxx */ /* * monophasic_energy_pulse.cxx * * Created on: 12.02.2011 * Author: jason */ #include <cmath> #include <cstdlib> #include <iostream> #include "monophasic_energy_pulse.hxx" #include "src/sim/game_object.hxx" #include "src/sim/game_field.hxx" #include "src/sim/collision.hxx" #include "src/background/explosion.hxx" #include "src/sim/blast.hxx" #include "src/ship/ship.hxx" #include "src/graphics/vec.hxx" #include "src/graphics/matops.hxx" #include "src/graphics/shader.hxx" #include "src/graphics/shader_loader.hxx" #include "src/graphics/cmn_shaders.hxx" #include "src/graphics/square.hxx" #include "src/globals.hxx" using namespace std; #define MAX_LIFE_WAVES 256 #define POWER_MUL MONO_POWER_MUL #define FREQUENCY 0.12f #define SIZE 0.01f #define SPEED_MUL 0.0003f #ifndef AB_OPENGL_14 struct MEPUniform { float visibility; vec3 baseColour; }; #define VERTEX_TYPE shader::VertTexc #define UNIFORM_TYPE MEPUniform DELAY_SHADER(monophasePulse) sizeof(VERTEX_TYPE), VATTRIB(vertex), VATTRIB(texCoord), NULL, true, UNIFLOAT(visibility), UNIFORM(baseColour), NULL END_DELAY_SHADER(static mepShader); #else /* defined(AB_OPENGL_14) */ struct MEPUniform { float visibility; vec3 colour; }; #define VERTEX_TYPE shader::VertTexc #define UNIFORM_TYPE MEPUniform #define baseColour colour; #define monophasePulseQuick quick DELAY_SHADER(monophasePulseQuick) sizeof(VERTEX_TYPE), VATTRIB(vertex), NULL, true, UNIFORM(colour), NULL END_DELAY_SHADER(static mepShader); #endif /* defined(AB_OPENGL_14) */ MonophasicEnergyPulse::MonophasicEnergyPulse(GameField* field, Ship* par, float x, float y, float theta, unsigned el) : GameObject(field, x, y, par->getVX() + getSpeed(el)*cos(theta), par->getVY() + getSpeed(el)*sin(theta)), explodeListeners(NULL), deathWaveNumber(rand()%MAX_LIFE_WAVES+1), timeAlive(0), power(el*POWER_MUL), previousFrameWasFinal(false), parent(par), exploded(false), blame(par->blame) { classification = GameObject::LightWeapon; includeInCollisionDetection=false; colrect.radius=SIZE*1.5f; collisionBounds.push_back(&colrect); isExportable=true; } MonophasicEnergyPulse::MonophasicEnergyPulse(GameField* field, float x, float y, float vx, float vy, float pow, unsigned et) : GameObject(field, x, y, vx, vy), explodeListeners(NULL), deathWaveNumber(100), timeAlive(et), power(pow), previousFrameWasFinal(false), parent(NULL), exploded(false), blame(0xFFFFFF) { classification = GameObject::LightWeapon; includeInCollisionDetection=false; isExportable=true; isRemote=true; colrect.radius=SIZE*1.5f; collisionBounds.push_back(&colrect); } MonophasicEnergyPulse::~MonophasicEnergyPulse() { //Remove any ExplodeListener chain attached if (explodeListeners) explodeListeners->prv = NULL; } bool MonophasicEnergyPulse::update(float et) noth { x += vx*et; y += vy*et; if (isRemote) { REMOTE_XYCK; } if (previousFrameWasFinal) includeInCollisionDetection=false; previousFrameWasFinal = currentVFrameLast || decorative; float oldTime=timeAlive; timeAlive += et; float oldAngle = fmod(oldTime*FREQUENCY*2*pi, 2*pi); float newAngle = fmod(timeAlive*FREQUENCY*2*pi, 2*pi); unsigned wavesAlive = (unsigned)2*timeAlive*FREQUENCY; if (wavesAlive == deathWaveNumber && !isRemote) return false; //Check if we need to become collideable if (!isRemote) { if ((oldAngle < pi/2 && newAngle >= pi/2) || (oldAngle < 3*pi/2 && newAngle >= 3*pi/2)) { includeInCollisionDetection=true; //Update collision bounds colrect.vertices[0] = make_pair(x-SIZE/2, y-SIZE/2); colrect.vertices[1] = make_pair(x+SIZE/2, y-SIZE/2); colrect.vertices[2] = make_pair(x+SIZE/2, y+SIZE/2); colrect.vertices[3] = make_pair(x-SIZE/2, y+SIZE/2); } } return true; } void MonophasicEnergyPulse::draw() noth { BEGINGP("MonophasicEP") float angle = timeAlive*FREQUENCY*2*pi; MEPUniform uni = { 1.0f, {{ fabs(sin(8*angle)), fabs(sin(4*angle)), fabs(sin(2*angle))*0.25f+0.75f }}}; square_graphic::bind(); mPush(); mTrans(x,y); mUScale(SIZE); //Draw a bit larger if zoomed out too much if (cameraZoom < 0.3f) mUScale(2.0f); mTrans(-0.5f,-0.5f); mepShader->activate(&uni); square_graphic::draw(); mPop(); ENDGP } float MonophasicEnergyPulse::getRadius() const noth { return SIZE/2*1.5f; } CollisionResult MonophasicEnergyPulse::checkCollision(GameObject* obj) noth { //We never collide with anything if we are remote if (obj==parent || isRemote) return NoCollision; if (!obj->isCollideable()) return UnlikelyCollision; if (objectsCollide(this, obj)) return YesCollision; else return UnlikelyCollision; } void MonophasicEnergyPulse::explode(GameObject* obj) noth { if (!obj) obj = this; if (EXPCLOSE(x,y)) field->add(new Explosion(field, Explosion::Simple, 0.3f, 0.5f, 1.0f, 1.0f, 0.01f, 1000, x, y, obj->getVX(), obj->getVY())); exploded=true; //Reset velocity to match obj so that the velocity of the explosion //can be communicated over the network. vx = obj->getVX(); vy = obj->getVY(); for (ExplodeListener<MonophasicEnergyPulse>* l = explodeListeners; l; l = l->nxt) l->exploded(this); } bool MonophasicEnergyPulse::collideWith(GameObject* obj) noth { if (obj != this) { field->inject(new Blast(field, blame, x, y, SIZE*2, power, true, 0)); explode(obj); } return false; } float MonophasicEnergyPulse::getWavelength(unsigned level) noth { return getSpeed(level)/FREQUENCY; } float MonophasicEnergyPulse::getSurvivalProbability(unsigned level, float dist) noth { float waves = dist / getWavelength(level); return 1.0f - waves/MAX_LIFE_WAVES; } float MonophasicEnergyPulse::getSpeed(unsigned level) noth { return SPEED_MUL * level; } <|endoftext|>
<commit_before>/* Copyright 2015 The TensorFlow Authors. 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. ==============================================================================*/ #include "tensorflow/core/common_runtime/copy_tensor.h" #include <atomic> #include <utility> #include <vector> #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/tracing.h" namespace tensorflow { namespace { struct RegistrationInfo { RegistrationInfo(DeviceType s, DeviceType r, CopyTensor::CopyFunction cf) : sender_device_type(std::move(s)), receiver_device_type(std::move(r)), copy_function(cf) {} DeviceType sender_device_type; DeviceType receiver_device_type; CopyTensor::CopyFunction copy_function; }; // We use a vector instead of a map since we expect there to be very // few registrations. std::vector<RegistrationInfo>* MutableRegistry() { static std::vector<RegistrationInfo>* registry = new std::vector<RegistrationInfo>; return registry; } } // namespace // static void CopyTensor::ViaDMA(StringPiece edge_name, DeviceContext* send_dev_context, DeviceContext* recv_dev_context, Device* src, Device* dst, const AllocatorAttributes src_alloc_attr, const AllocatorAttributes dst_alloc_attr, const Tensor* input, Tensor* output, StatusCallback done) { port::Tracing::ScopedAnnotation annotation(edge_name); VLOG(1) << "Copy " << edge_name; const DeviceType src_device_type( src_alloc_attr.on_host() ? DEVICE_CPU : src->attributes().device_type()); const DeviceType dst_device_type( dst_alloc_attr.on_host() ? DEVICE_CPU : dst->attributes().device_type()); const bool non_cpu_src = src_device_type != DeviceType(DEVICE_CPU); const bool non_cpu_dst = dst_device_type != DeviceType(DEVICE_CPU); // E.g., gpu -> gpu if (non_cpu_src && non_cpu_dst) { // Device to device copy. Look through registry for an appropriate // CopyFunction. std::vector<RegistrationInfo>* registry = MutableRegistry(); for (const RegistrationInfo& ri : *registry) { if (ri.sender_device_type == src_device_type && ri.receiver_device_type == dst_device_type) { ri.copy_function(send_dev_context, recv_dev_context, src, dst, src_alloc_attr, dst_alloc_attr, input, output, done); return; } } // TODO(josh11b): If no CopyFunction is found, we currently fail // but we could copy between devices via CPU. done(errors::Unimplemented( "No function registered to copy from devices of type ", src_device_type.type(), " to devices of type ", dst_device_type.type())); return; } // E.g., gpu -> cpu if (non_cpu_src && !non_cpu_dst) { // Device to host copy. send_dev_context->CopyDeviceTensorToCPU(input, edge_name, src, output, done); return; } // E.g., cpu -> gpu if (!non_cpu_src && non_cpu_dst) { // Host to Device copy. recv_dev_context->CopyCPUTensorToDevice(input, dst, output, done); return; } // cpu -> cpu CHECK(!non_cpu_src && !non_cpu_dst); *output = *input; done(Status::OK()); } // static Status CopyTensor::Register(DeviceType sender_device_type, DeviceType receiver_device_type, CopyFunction copy_function) { std::vector<RegistrationInfo>* registry = MutableRegistry(); registry->emplace_back(sender_device_type, receiver_device_type, copy_function); return Status::OK(); } } // namespace tensorflow <commit_msg>Add fallback path for device->device copies that copies via the host. Change: 136164533<commit_after>/* Copyright 2015 The TensorFlow Authors. 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. ==============================================================================*/ #include "tensorflow/core/common_runtime/copy_tensor.h" #include <atomic> #include <utility> #include <vector> #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/tracing.h" namespace tensorflow { namespace { struct RegistrationInfo { RegistrationInfo(DeviceType s, DeviceType r, CopyTensor::CopyFunction cf) : sender_device_type(std::move(s)), receiver_device_type(std::move(r)), copy_function(cf) {} DeviceType sender_device_type; DeviceType receiver_device_type; CopyTensor::CopyFunction copy_function; }; // We use a vector instead of a map since we expect there to be very // few registrations. std::vector<RegistrationInfo>* MutableRegistry() { static std::vector<RegistrationInfo>* registry = new std::vector<RegistrationInfo>; return registry; } } // namespace // static void CopyTensor::ViaDMA(StringPiece edge_name, DeviceContext* send_dev_context, DeviceContext* recv_dev_context, Device* src, Device* dst, const AllocatorAttributes src_alloc_attr, const AllocatorAttributes dst_alloc_attr, const Tensor* input, Tensor* output, StatusCallback done) { port::Tracing::ScopedAnnotation annotation(edge_name); VLOG(1) << "Copy " << edge_name; const DeviceType src_device_type( src_alloc_attr.on_host() ? DEVICE_CPU : src->attributes().device_type()); const DeviceType dst_device_type( dst_alloc_attr.on_host() ? DEVICE_CPU : dst->attributes().device_type()); const bool non_cpu_src = src_device_type != DeviceType(DEVICE_CPU); const bool non_cpu_dst = dst_device_type != DeviceType(DEVICE_CPU); // E.g., gpu -> gpu if (non_cpu_src && non_cpu_dst) { // Device to device copy. Look through registry for an appropriate // CopyFunction. std::vector<RegistrationInfo>* registry = MutableRegistry(); for (const RegistrationInfo& ri : *registry) { if (ri.sender_device_type == src_device_type && ri.receiver_device_type == dst_device_type) { ri.copy_function(send_dev_context, recv_dev_context, src, dst, src_alloc_attr, dst_alloc_attr, input, output, done); return; } } // Fall back to copying via the host. VLOG(1) << "No function registered to copy from devices of type " << src_device_type.type() << " to devices of type " << dst_device_type.type() << ". Falling back to copying via the host."; // TODO(phawkins): choose an allocator optimal for both the src and dst // devices, not just the src device. AllocatorAttributes host_alloc_attrs; host_alloc_attrs.set_gpu_compatible(true); host_alloc_attrs.set_on_host(true); Allocator* cpu_allocator = src->GetAllocator(host_alloc_attrs); Tensor* cpu_tensor = new Tensor(cpu_allocator, input->dtype(), input->shape()); auto delete_and_done = [cpu_tensor, done](const Status& status) { delete cpu_tensor; done(status); }; send_dev_context->CopyDeviceTensorToCPU( input, edge_name, src, cpu_tensor, [recv_dev_context, cpu_tensor, dst, output, delete_and_done](const Status& status) { if (!status.ok()) { delete_and_done(status); return; } recv_dev_context->CopyCPUTensorToDevice(cpu_tensor, dst, output, delete_and_done); }); return; } // E.g., gpu -> cpu if (non_cpu_src && !non_cpu_dst) { // Device to host copy. send_dev_context->CopyDeviceTensorToCPU(input, edge_name, src, output, done); return; } // E.g., cpu -> gpu if (!non_cpu_src && non_cpu_dst) { // Host to Device copy. recv_dev_context->CopyCPUTensorToDevice(input, dst, output, done); return; } // cpu -> cpu CHECK(!non_cpu_src && !non_cpu_dst); *output = *input; done(Status::OK()); } // static Status CopyTensor::Register(DeviceType sender_device_type, DeviceType receiver_device_type, CopyFunction copy_function) { std::vector<RegistrationInfo>* registry = MutableRegistry(); registry->emplace_back(sender_device_type, receiver_device_type, copy_function); return Status::OK(); } } // namespace tensorflow <|endoftext|>
<commit_before>/* Copyright 2016 The TensorFlow Authors. 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. ==============================================================================*/ #include "tensorflow/core/distributed_runtime/worker.h" #include "tensorflow/core/common_runtime/device_mgr.h" #include "tensorflow/core/common_runtime/process_util.h" #include "tensorflow/core/common_runtime/step_stats_collector.h" #include "tensorflow/core/distributed_runtime/rendezvous_mgr_interface.h" #include "tensorflow/core/distributed_runtime/tensor_coding.h" #include "tensorflow/core/distributed_runtime/worker_session.h" #include "tensorflow/core/platform/tracing.h" namespace tensorflow { Worker::Worker(WorkerEnv* env) : env_(env), cancellation_manager_(new CancellationManager) {} void Worker::GetStatusAsync(const GetStatusRequest* request, GetStatusResponse* response, StatusCallback done) { DeviceMgr* dm = env_->device_mgr; std::vector<DeviceAttributes> devices; dm->ListDeviceAttributes(&devices); response->mutable_device_attributes()->Reserve(devices.size()); for (size_t i = 0; i < devices.size(); ++i) { response->add_device_attributes()->Swap(&devices[i]); } done(Status::OK()); } void Worker::CreateWorkerSessionAsync(const CreateWorkerSessionRequest* request, CreateWorkerSessionResponse* response, StatusCallback done) { Status s = env_->session_mgr->CreateSession(request->session_handle(), request->server_def()); done(s); } void Worker::RegisterGraphAsync(const RegisterGraphRequest* request, RegisterGraphResponse* response, StatusCallback done) { WorkerSession* session = env_->session_mgr->WorkerSessionForSession(request->session_handle()); Status s = session->graph_mgr->Register( request->session_handle(), request->graph_def(), request->graph_options(), request->debug_options(), response->mutable_graph_handle()); done(s); } void Worker::DeregisterGraphAsync(const DeregisterGraphRequest* request, DeregisterGraphResponse* response, StatusCallback done) { WorkerSession* session = env_->session_mgr->WorkerSessionForSession(request->session_handle()); Status s = session->graph_mgr->Deregister(request->graph_handle()); done(s); } void Worker::AbortStep(int64 step_id) { Rendezvous* rendez = env_->rendezvous_mgr->Find(step_id); SchedNonBlockingClosureAfter(1000000, [rendez, step_id]() { // Delay a bit before aborting the step. This way, the root // cause may return first back to the client instead of this // cancellation generated abort error. rendez->StartAbort(errors::Aborted("Step ", step_id)); rendez->Unref(); }); } Status Worker::PrepareRunGraph(RunGraphRequestWrapper* req, GraphMgr::NamedTensors* in, GraphMgr::NamedTensors* out) { static Tensor empty_tensor(DT_FLOAT); if (req->num_sends() > 0) { Tensor val; for (size_t i = 0; i < req->num_sends(); ++i) { TF_RETURN_IF_ERROR(req->SendValue(i, &val)); in->insert({req->send_key(i), val}); } } for (size_t i = 0; i < req->num_recvs(); ++i) { out->insert({req->recv_key(i), empty_tensor}); } return Status::OK(); } void Worker::RunGraphAsync(CallOptions* opts, RunGraphRequestWrapper* request, MutableRunGraphResponseWrapper* response, StatusCallback done) { if (request->is_partial()) { DoPartialRunGraph(opts, request, response, std::move(done)); } else { DoRunGraph(opts, request, response, std::move(done)); } } MutableRunGraphRequestWrapper* Worker::CreateRunGraphRequest() { return new InMemoryRunGraphRequest; } MutableRunGraphResponseWrapper* Worker::CreateRunGraphResponse() { return new InMemoryRunGraphResponse; } void Worker::DoRunGraph(CallOptions* opts, RunGraphRequestWrapper* request, MutableRunGraphResponseWrapper* response, StatusCallback done) { const int64 step_id = request->step_id(); TRACEPRINTF("RunGraph: %lld", step_id); WorkerSession* session = env_->session_mgr->WorkerSessionForSession(request->session_handle()); GraphMgr::NamedTensors in; GraphMgr::NamedTensors* out = new GraphMgr::NamedTensors; Status s = PrepareRunGraph(request, &in, out); if (!s.ok()) { delete out; done(s); return; } StepStatsCollector* collector = nullptr; if (request->exec_opts().record_timeline() || request->exec_opts().record_costs()) { collector = new StepStatsCollector(response->mutable_step_stats()); // TODO(mrry,pbar): GPU tracing for distributed steps. } CancellationManager* cm = new CancellationManager; opts->SetCancelCallback([this, cm, step_id]() { cm->StartCancel(); AbortStep(step_id); }); CancellationToken token; { mutex_lock l(mu_); token = cancellation_manager_->get_cancellation_token(); bool already_cancelled = !cancellation_manager_->RegisterCallback( token, [cm]() { cm->StartCancel(); }); if (already_cancelled) { opts->ClearCancelCallback(); delete cm; delete collector; delete out; done(errors::Aborted("Call was aborted")); return; } } session->graph_mgr->ExecuteAsync( request->graph_handle(), step_id, session, request->exec_opts(), collector, response, cm, in, [this, step_id, response, session, cm, out, token, collector, opts, done](Status s) { if (s.ok()) { s = session->graph_mgr->RecvOutputs(step_id, out); } opts->ClearCancelCallback(); { mutex_lock l(mu_); cancellation_manager_->DeregisterCallback(token); } delete cm; if (s.ok()) { for (const auto& p : *out) { const string& key = p.first; const Tensor& val = p.second; response->AddRecv(key, val); } } delete collector; delete out; done(s); }); } // TODO(suharshs): Add stats collection support to partial run. void Worker::DoPartialRunGraph(CallOptions* opts, RunGraphRequestWrapper* request, MutableRunGraphResponseWrapper* response, StatusCallback done) { const int64 step_id = request->step_id(); const string& graph_handle = request->graph_handle(); TRACEPRINTF("PartialRunGraph: %lld", step_id); WorkerSession* session = env_->session_mgr->WorkerSessionForSession(request->session_handle()); GraphMgr::NamedTensors in; GraphMgr::NamedTensors* out = new GraphMgr::NamedTensors; Status s = PrepareRunGraph(request, &in, out); auto finish = [this, done, out, opts](const Status& s) { opts->ClearCancelCallback(); delete out; done(s); }; if (!s.ok()) { finish(s); return; } CancellationManager* cm = nullptr; bool is_new_partial_run = partial_run_mgr_.FindOrCreate(step_id, &cm); // Before we start doing anything, we set the RPC cancellation. opts->SetCancelCallback([this, cm, step_id]() { cm->StartCancel(); AbortStep(step_id); }); // If this is a new partial run request, the request will need to start the // executors. if (is_new_partial_run) { CancellationToken token; { mutex_lock l(mu_); token = cancellation_manager_->get_cancellation_token(); cancellation_manager_->RegisterCallback(token, [cm]() { cm->StartCancel(); }); } session->graph_mgr->ExecuteAsync( graph_handle, step_id, session, request->exec_opts(), nullptr /* collector */, nullptr /* response */, cm, in, [this, token, step_id, cm](Status s) { { mutex_lock l(mu_); cancellation_manager_->DeregisterCallback(token); } partial_run_mgr_.ExecutorDone(step_id, s); }); } else { // Send the partial run's new inputs. s = session->graph_mgr->SendInputs(step_id, in); if (!s.ok()) { finish(s); return; } } session->graph_mgr->RecvOutputsAsync( step_id, out, [this, out, request, response, step_id, finish](Status s) { if (s.ok()) { // Construct and return the resp. for (const auto& p : *out) { const string& key = p.first; const Tensor& val = p.second; response->AddRecv(key, val); } } if (request->is_last_partial_run()) { partial_run_mgr_.PartialRunDone(step_id, finish, s); } else { finish(s); } }); } void Worker::CleanupGraphAsync(const CleanupGraphRequest* request, CleanupGraphResponse* response, StatusCallback done) { const int64 step_id = request->step_id(); env_->rendezvous_mgr->Cleanup(step_id); done(Status::OK()); } void Worker::CleanupAllAsync(const CleanupAllRequest* request, CleanupAllResponse* response, StatusCallback done) { std::vector<string> containers; for (const auto& c : request->container()) containers.push_back(c); env_->device_mgr->ClearContainers(containers); done(Status::OK()); } void Worker::LoggingAsync(const LoggingRequest* request, LoggingResponse* response, StatusCallback done) { done(errors::Unimplemented("Logging")); } void Worker::TracingAsync(const TracingRequest* request, TracingResponse* response, StatusCallback done) { done(errors::Unimplemented("Tracing")); } // Helper for RecvTensor. Validates "key" and returns the source // device in "*src_dev". Status Worker::PrepareRecvTensor(const Rendezvous::ParsedKey& parsed, Device** src_dev) { // Figures out which device the tensor is hosted on. string local_name = DeviceNameUtils::LocalName(parsed.src_device); TF_RETURN_IF_ERROR(env_->device_mgr->LookupDevice(local_name, src_dev)); // Does the device have the right incarnation number we expect? if ((*src_dev)->attributes().incarnation() != parsed.src_incarnation) { return errors::Aborted( "RecvTensor expects a different device incarnation: ", parsed.src_incarnation, " vs. ", (*src_dev)->attributes().incarnation(), ". Your worker job was probably restarted. Check your " "worker job for the reason why it was restarted."); } return Status::OK(); } void Worker::RecvTensorAsync(CallOptions* opts, const RecvTensorRequest* request, TensorResponse* response, StatusCallback done) { // The base Worker class does not implement RecvTensorAsync, because // it is not currently used for worker-to-worker communication. Use a // transport-specific implementation (such as `GrpcWorker::RecvTensorAsync()`) // instead. done(errors::Unimplemented("Worker::RecvTensorAsync()")); } } // namespace tensorflow <commit_msg>replace loop with ranged-for from worker's get_status (#12477)<commit_after>/* Copyright 2016 The TensorFlow Authors. 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. ==============================================================================*/ #include "tensorflow/core/distributed_runtime/worker.h" #include "tensorflow/core/common_runtime/device_mgr.h" #include "tensorflow/core/common_runtime/process_util.h" #include "tensorflow/core/common_runtime/step_stats_collector.h" #include "tensorflow/core/distributed_runtime/rendezvous_mgr_interface.h" #include "tensorflow/core/distributed_runtime/tensor_coding.h" #include "tensorflow/core/distributed_runtime/worker_session.h" #include "tensorflow/core/platform/tracing.h" namespace tensorflow { Worker::Worker(WorkerEnv* env) : env_(env), cancellation_manager_(new CancellationManager) {} void Worker::GetStatusAsync(const GetStatusRequest* request, GetStatusResponse* response, StatusCallback done) { DeviceMgr* dm = env_->device_mgr; std::vector<DeviceAttributes> devices; dm->ListDeviceAttributes(&devices); response->mutable_device_attributes()->Reserve(devices.size()); for (auto& d : devices) { response->add_device_attributes()->Swap(&d); } done(Status::OK()); } void Worker::CreateWorkerSessionAsync(const CreateWorkerSessionRequest* request, CreateWorkerSessionResponse* response, StatusCallback done) { Status s = env_->session_mgr->CreateSession(request->session_handle(), request->server_def()); done(s); } void Worker::RegisterGraphAsync(const RegisterGraphRequest* request, RegisterGraphResponse* response, StatusCallback done) { WorkerSession* session = env_->session_mgr->WorkerSessionForSession(request->session_handle()); Status s = session->graph_mgr->Register( request->session_handle(), request->graph_def(), request->graph_options(), request->debug_options(), response->mutable_graph_handle()); done(s); } void Worker::DeregisterGraphAsync(const DeregisterGraphRequest* request, DeregisterGraphResponse* response, StatusCallback done) { WorkerSession* session = env_->session_mgr->WorkerSessionForSession(request->session_handle()); Status s = session->graph_mgr->Deregister(request->graph_handle()); done(s); } void Worker::AbortStep(int64 step_id) { Rendezvous* rendez = env_->rendezvous_mgr->Find(step_id); SchedNonBlockingClosureAfter(1000000, [rendez, step_id]() { // Delay a bit before aborting the step. This way, the root // cause may return first back to the client instead of this // cancellation generated abort error. rendez->StartAbort(errors::Aborted("Step ", step_id)); rendez->Unref(); }); } Status Worker::PrepareRunGraph(RunGraphRequestWrapper* req, GraphMgr::NamedTensors* in, GraphMgr::NamedTensors* out) { static Tensor empty_tensor(DT_FLOAT); if (req->num_sends() > 0) { Tensor val; for (size_t i = 0; i < req->num_sends(); ++i) { TF_RETURN_IF_ERROR(req->SendValue(i, &val)); in->insert({req->send_key(i), val}); } } for (size_t i = 0; i < req->num_recvs(); ++i) { out->insert({req->recv_key(i), empty_tensor}); } return Status::OK(); } void Worker::RunGraphAsync(CallOptions* opts, RunGraphRequestWrapper* request, MutableRunGraphResponseWrapper* response, StatusCallback done) { if (request->is_partial()) { DoPartialRunGraph(opts, request, response, std::move(done)); } else { DoRunGraph(opts, request, response, std::move(done)); } } MutableRunGraphRequestWrapper* Worker::CreateRunGraphRequest() { return new InMemoryRunGraphRequest; } MutableRunGraphResponseWrapper* Worker::CreateRunGraphResponse() { return new InMemoryRunGraphResponse; } void Worker::DoRunGraph(CallOptions* opts, RunGraphRequestWrapper* request, MutableRunGraphResponseWrapper* response, StatusCallback done) { const int64 step_id = request->step_id(); TRACEPRINTF("RunGraph: %lld", step_id); WorkerSession* session = env_->session_mgr->WorkerSessionForSession(request->session_handle()); GraphMgr::NamedTensors in; GraphMgr::NamedTensors* out = new GraphMgr::NamedTensors; Status s = PrepareRunGraph(request, &in, out); if (!s.ok()) { delete out; done(s); return; } StepStatsCollector* collector = nullptr; if (request->exec_opts().record_timeline() || request->exec_opts().record_costs()) { collector = new StepStatsCollector(response->mutable_step_stats()); // TODO(mrry,pbar): GPU tracing for distributed steps. } CancellationManager* cm = new CancellationManager; opts->SetCancelCallback([this, cm, step_id]() { cm->StartCancel(); AbortStep(step_id); }); CancellationToken token; { mutex_lock l(mu_); token = cancellation_manager_->get_cancellation_token(); bool already_cancelled = !cancellation_manager_->RegisterCallback( token, [cm]() { cm->StartCancel(); }); if (already_cancelled) { opts->ClearCancelCallback(); delete cm; delete collector; delete out; done(errors::Aborted("Call was aborted")); return; } } session->graph_mgr->ExecuteAsync( request->graph_handle(), step_id, session, request->exec_opts(), collector, response, cm, in, [this, step_id, response, session, cm, out, token, collector, opts, done](Status s) { if (s.ok()) { s = session->graph_mgr->RecvOutputs(step_id, out); } opts->ClearCancelCallback(); { mutex_lock l(mu_); cancellation_manager_->DeregisterCallback(token); } delete cm; if (s.ok()) { for (const auto& p : *out) { const string& key = p.first; const Tensor& val = p.second; response->AddRecv(key, val); } } delete collector; delete out; done(s); }); } // TODO(suharshs): Add stats collection support to partial run. void Worker::DoPartialRunGraph(CallOptions* opts, RunGraphRequestWrapper* request, MutableRunGraphResponseWrapper* response, StatusCallback done) { const int64 step_id = request->step_id(); const string& graph_handle = request->graph_handle(); TRACEPRINTF("PartialRunGraph: %lld", step_id); WorkerSession* session = env_->session_mgr->WorkerSessionForSession(request->session_handle()); GraphMgr::NamedTensors in; GraphMgr::NamedTensors* out = new GraphMgr::NamedTensors; Status s = PrepareRunGraph(request, &in, out); auto finish = [this, done, out, opts](const Status& s) { opts->ClearCancelCallback(); delete out; done(s); }; if (!s.ok()) { finish(s); return; } CancellationManager* cm = nullptr; bool is_new_partial_run = partial_run_mgr_.FindOrCreate(step_id, &cm); // Before we start doing anything, we set the RPC cancellation. opts->SetCancelCallback([this, cm, step_id]() { cm->StartCancel(); AbortStep(step_id); }); // If this is a new partial run request, the request will need to start the // executors. if (is_new_partial_run) { CancellationToken token; { mutex_lock l(mu_); token = cancellation_manager_->get_cancellation_token(); cancellation_manager_->RegisterCallback(token, [cm]() { cm->StartCancel(); }); } session->graph_mgr->ExecuteAsync( graph_handle, step_id, session, request->exec_opts(), nullptr /* collector */, nullptr /* response */, cm, in, [this, token, step_id, cm](Status s) { { mutex_lock l(mu_); cancellation_manager_->DeregisterCallback(token); } partial_run_mgr_.ExecutorDone(step_id, s); }); } else { // Send the partial run's new inputs. s = session->graph_mgr->SendInputs(step_id, in); if (!s.ok()) { finish(s); return; } } session->graph_mgr->RecvOutputsAsync( step_id, out, [this, out, request, response, step_id, finish](Status s) { if (s.ok()) { // Construct and return the resp. for (const auto& p : *out) { const string& key = p.first; const Tensor& val = p.second; response->AddRecv(key, val); } } if (request->is_last_partial_run()) { partial_run_mgr_.PartialRunDone(step_id, finish, s); } else { finish(s); } }); } void Worker::CleanupGraphAsync(const CleanupGraphRequest* request, CleanupGraphResponse* response, StatusCallback done) { const int64 step_id = request->step_id(); env_->rendezvous_mgr->Cleanup(step_id); done(Status::OK()); } void Worker::CleanupAllAsync(const CleanupAllRequest* request, CleanupAllResponse* response, StatusCallback done) { std::vector<string> containers; for (const auto& c : request->container()) containers.push_back(c); env_->device_mgr->ClearContainers(containers); done(Status::OK()); } void Worker::LoggingAsync(const LoggingRequest* request, LoggingResponse* response, StatusCallback done) { done(errors::Unimplemented("Logging")); } void Worker::TracingAsync(const TracingRequest* request, TracingResponse* response, StatusCallback done) { done(errors::Unimplemented("Tracing")); } // Helper for RecvTensor. Validates "key" and returns the source // device in "*src_dev". Status Worker::PrepareRecvTensor(const Rendezvous::ParsedKey& parsed, Device** src_dev) { // Figures out which device the tensor is hosted on. string local_name = DeviceNameUtils::LocalName(parsed.src_device); TF_RETURN_IF_ERROR(env_->device_mgr->LookupDevice(local_name, src_dev)); // Does the device have the right incarnation number we expect? if ((*src_dev)->attributes().incarnation() != parsed.src_incarnation) { return errors::Aborted( "RecvTensor expects a different device incarnation: ", parsed.src_incarnation, " vs. ", (*src_dev)->attributes().incarnation(), ". Your worker job was probably restarted. Check your " "worker job for the reason why it was restarted."); } return Status::OK(); } void Worker::RecvTensorAsync(CallOptions* opts, const RecvTensorRequest* request, TensorResponse* response, StatusCallback done) { // The base Worker class does not implement RecvTensorAsync, because // it is not currently used for worker-to-worker communication. Use a // transport-specific implementation (such as `GrpcWorker::RecvTensorAsync()`) // instead. done(errors::Unimplemented("Worker::RecvTensorAsync()")); } } // namespace tensorflow <|endoftext|>
<commit_before>/* Copyright 2015 The TensorFlow Authors. 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. ==============================================================================*/ #include "tensorflow/core/framework/run_handler_util.h" #include <algorithm> #include <cmath> #include "tensorflow/core/platform/logging.h" namespace tensorflow { void ComputeInterOpSchedulingRanges(int num_active_requests, int num_threads, int min_threads_per_request, std::vector<std::uint_fast32_t>* start_vec, std::vector<std::uint_fast32_t>* end_vec) { // Each request is expected to have weight W[i] = num_active_requests - i. // Therefore, total_weight = sum of all request weights. float total_weight = 0.5f * num_active_requests * (num_active_requests + 1); float demand_factor = static_cast<float>(num_threads) / total_weight; float last_cumulative_weight = 0.0; min_threads_per_request = std::max(1, min_threads_per_request); for (int i = 0; i != num_active_requests; i++) { float cumulative_weight = static_cast<float>(i + 1) * (num_active_requests - static_cast<float>(i) * 0.5f); float weight = cumulative_weight - last_cumulative_weight; // Quantize thread_demand by rounding up, and also satisfying // `min_threads_per_request` constraint. // Note: We subtract a small epsilon (0.00001) to prevent ceil(..) from // rounding weights like 4.0 to 5. int demand = std::max(min_threads_per_request, static_cast<int>(ceil(weight * demand_factor - 0.00001f))); // For the quantized range [start, end); compute the floor of real start, // and expand downwards from there with length `demand` and adjust for // boundary conditions. int start = last_cumulative_weight * demand_factor; int end = std::min(num_threads, start + demand); start = std::max(0, std::min(start, end - demand)); start_vec->at(i) = start; end_vec->at(i) = end; last_cumulative_weight = cumulative_weight; } } void ComputeInterOpStealingRanges(int num_threads, int min_threads_per_domain, std::vector<std::uint_fast32_t>* start_vec, std::vector<std::uint_fast32_t>* end_vec) { int steal_domain_size = std::min(min_threads_per_domain, num_threads); unsigned steal_start = 0, steal_end = steal_domain_size; for (int i = 0; i < num_threads; ++i) { if (i >= steal_end) { if (steal_end + steal_domain_size < num_threads) { steal_start = steal_end; steal_end += steal_domain_size; } else { steal_end = num_threads; steal_start = steal_end - steal_domain_size; } } start_vec->at(i) = steal_start; end_vec->at(i) = steal_end; } } } // namespace tensorflow <commit_msg>Qualify calls to some functions from <cmath>.<commit_after>/* Copyright 2015 The TensorFlow Authors. 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. ==============================================================================*/ #include "tensorflow/core/framework/run_handler_util.h" #include <algorithm> #include <cmath> #include "tensorflow/core/platform/logging.h" namespace tensorflow { void ComputeInterOpSchedulingRanges(int num_active_requests, int num_threads, int min_threads_per_request, std::vector<std::uint_fast32_t>* start_vec, std::vector<std::uint_fast32_t>* end_vec) { // Each request is expected to have weight W[i] = num_active_requests - i. // Therefore, total_weight = sum of all request weights. float total_weight = 0.5f * num_active_requests * (num_active_requests + 1); float demand_factor = static_cast<float>(num_threads) / total_weight; float last_cumulative_weight = 0.0; min_threads_per_request = std::max(1, min_threads_per_request); for (int i = 0; i != num_active_requests; i++) { float cumulative_weight = static_cast<float>(i + 1) * (num_active_requests - static_cast<float>(i) * 0.5f); float weight = cumulative_weight - last_cumulative_weight; // Quantize thread_demand by rounding up, and also satisfying // `min_threads_per_request` constraint. // Note: We subtract a small epsilon (0.00001) to prevent ceil(..) from // rounding weights like 4.0 to 5. int demand = std::max( min_threads_per_request, static_cast<int>(std::ceil(weight * demand_factor - 0.00001f))); // For the quantized range [start, end); compute the floor of real start, // and expand downwards from there with length `demand` and adjust for // boundary conditions. int start = last_cumulative_weight * demand_factor; int end = std::min(num_threads, start + demand); start = std::max(0, std::min(start, end - demand)); start_vec->at(i) = start; end_vec->at(i) = end; last_cumulative_weight = cumulative_weight; } } void ComputeInterOpStealingRanges(int num_threads, int min_threads_per_domain, std::vector<std::uint_fast32_t>* start_vec, std::vector<std::uint_fast32_t>* end_vec) { int steal_domain_size = std::min(min_threads_per_domain, num_threads); unsigned steal_start = 0, steal_end = steal_domain_size; for (int i = 0; i < num_threads; ++i) { if (i >= steal_end) { if (steal_end + steal_domain_size < num_threads) { steal_start = steal_end; steal_end += steal_domain_size; } else { steal_end = num_threads; steal_start = steal_end - steal_domain_size; } } start_vec->at(i) = steal_start; end_vec->at(i) = steal_end; } } } // namespace tensorflow <|endoftext|>
<commit_before>// RUN: %clang_cc1 -std=c++0x -fsyntax-only -verify %s template<typename... Types> struct Tuple; // FIXME: Many more bullets to go // In a template-argument-list (14.3); the pattern is a template-argument. template<typename ...Types> struct tuple_of_refs { typedef Tuple<Types& ...> types; }; Tuple<int&, float&> *t_int_ref_float_ref; tuple_of_refs<int&, float&>::types *t_int_ref_float_ref_2 = t_int_ref_float_ref; <commit_msg>Test template instantiation of pack expansions where the parameter pack is in a nested-name-specifier<commit_after>// RUN: %clang_cc1 -std=c++0x -fsyntax-only -verify %s template<typename... Types> struct tuple; // FIXME: Many more bullets to go // In a template-argument-list (14.3); the pattern is a template-argument. template<typename ...Types> struct tuple_of_refs { typedef tuple<Types& ...> types; }; tuple<int&, float&> *t_int_ref_float_ref; tuple_of_refs<int&, float&>::types *t_int_ref_float_ref_2 = t_int_ref_float_ref; template<typename ...Types> struct extract_nested_types { typedef tuple<typename Types::type...> types; }; template<typename T> struct identity { typedef T type; }; tuple<int, float> *t_int_float; extract_nested_types<identity<int>, identity<float> >::types *t_int_float_2 = t_int_float; <|endoftext|>
<commit_before>void AliAnalysisTaskMEVertexingHFTest() { // // Test macro for the AliAnalysisTaskME for heavy-flavour event mixing // r.romita@gsi.de // Bool_t useParFiles=kFALSE; gROOT->LoadMacro("$ALICE_ROOT/PWG3/vertexingHF/LoadLibraries.C"); LoadLibraries(useParFiles); // Local files TChain* chain = new TChain("aodTree"); Char_t fileName[100]; sprintf(fileName,"AliAODs.root"); chain->Add(fileName); // Create the analysis manager AliAnalysisManager *mgr = new AliAnalysisManager("My Manager","My Manager"); // Input Handler AliMultiEventInputHandler *inputHandler = new AliMultiEventInputHandler(4,1); AliEventPoolOTF* pool = new AliEventPoolOTF("event pool", "AOD"); // apply selections pool->SetMultiplicityBin(0, 100, 2); pool->SetZVertexBinning(-20., 20., 2); pool->Init(); //set tag directory Char_t tagDir[100]; sprintf(tagDir,"."); pool->SetTagDirectory(tagDir); mgr->SetInputEventHandler(inputHandler); mgr->SetEventPool(pool); inputHandler->SetEventPool(pool); // Output AliAODHandler *aodHandler = new AliAODHandler(); aodHandler->SetOutputFileName("AliAOD.VertexingHF.root"); aodHandler->SetCreateNonStandardAOD(); mgr->SetOutputEventHandler(aodHandler); gROOT->LoadMacro("AddTaskMixing.C"); AliAnalysisTaskMEVertexingHF *hfTask = AddTaskHFMixing(); // // Run the analysis // printf("CHAIN HAS %d ENTRIES\n",(Int_t)chain->GetEntries()); if(!mgr->InitAnalysis()) return; mgr->PrintStatus(); TStopwatch watch; watch.Start(); mgr->StartAnalysis("mix",chain, 1000); watch.Stop(); watch.Print(); delete mgr; return; } <commit_msg>Fixed typo<commit_after>void AliAnalysisTaskMEVertexingHFTest() { // // Test macro for the AliAnalysisTaskME for heavy-flavour event mixing // r.romita@gsi.de // Bool_t useParFiles=kFALSE; gROOT->LoadMacro("$ALICE_ROOT/PWG3/vertexingHF/LoadLibraries.C"); LoadLibraries(useParFiles); // Local files TChain* chain = new TChain("aodTree"); Char_t fileName[100]; sprintf(fileName,"AliAODs.root"); chain->Add(fileName); // Create the analysis manager AliAnalysisManager *mgr = new AliAnalysisManager("My Manager","My Manager"); // Input Handler AliMultiEventInputHandler *inputHandler = new AliMultiEventInputHandler(4,1); AliEventPoolOTF* pool = new AliEventPoolOTF("event pool", "AOD"); // apply selections pool->SetMultiplicityBin(0, 100, 2); pool->SetZVertexBinning(-20., 20., 2); pool->Init(); //set tag directory Char_t tagDir[100]; sprintf(tagDir,"."); pool->SetTagDirectory(tagDir); mgr->SetInputEventHandler(inputHandler); mgr->SetEventPool(pool); inputHandler->SetEventPool(pool); // Output AliAODHandler *aodHandler = new AliAODHandler(); aodHandler->SetOutputFileName("AliAOD.VertexingHF.root"); aodHandler->SetCreateNonStandardAOD(); mgr->SetOutputEventHandler(aodHandler); gROOT->LoadMacro("AddTaskHFMixing.C"); AliAnalysisTaskMEVertexingHF *hfTask = AddTaskHFMixing(); // // Run the analysis // printf("CHAIN HAS %d ENTRIES\n",(Int_t)chain->GetEntries()); if(!mgr->InitAnalysis()) return; mgr->PrintStatus(); TStopwatch watch; watch.Start(); mgr->StartAnalysis("mix",chain, 1000); watch.Stop(); watch.Print(); delete mgr; return; } <|endoftext|>
<commit_before>#include "Halide.h" #include <stdio.h> using namespace Halide; int main(int argc, char **argv) { Target target = get_jit_target_from_environment(); if (!target.has_gpu_feature() && !target.has_feature(Target::OpenGLCompute)) { printf("No gpu target enabled. Skipping test.\n"); return 0; } Func f("f"), g("g"), h("h"), out("out"); Var x("x"), y("y"), z("z"); f(x, y, z) = x + y + z; f(x, y, z) += 1; g(x, y, z) = f(x, y, z); g(x, y, z) += 1; h(x, y, z) = g(x, y, z); h(x, y, z) += 1; out(x, y, z) = h(x, y, z); out(x, y, z) += 1; Var xi("xi"), yi("yi"), zi("zi"); out.gpu_tile(x, y, z, xi, yi, zi, 4, 4, 4); out.update().gpu_tile(x, y, xi, yi, 4, 4); h.compute_at(out, x).gpu_threads(x, y); h.update().gpu_threads(x); g.compute_at(h, y).gpu_threads(x); g.update(); f.compute_at(g, x); f.update(); Buffer<int> o = out.realize(64, 64, 64); for (int z = 0; z < 64; z++) { for (int y = 0; y < 64; y++) { for (int x = 0; x < 64; x++) { int correct = x + y + z + 4; if (o(x, y, z) != correct) { printf("out(%d, %d, %d) = %d instead of %d\n", x, y, z, o(x, y, z), correct); return -1; } } } } printf("Success!\n"); return 0; } <commit_msg>Workaround weakness in NormalizeDimensionality<commit_after>#include "Halide.h" #include <stdio.h> using namespace Halide; int main(int argc, char **argv) { Target target = get_jit_target_from_environment(); if (!target.has_gpu_feature() && !target.has_feature(Target::OpenGLCompute)) { printf("No gpu target enabled. Skipping test.\n"); return 0; } Func f("f"), g("g"), h("h"), out("out"); Var x("x"), y("y"), z("z"); f(x, y, z) = x + y + z; f(x, y, z) += 1; g(x, y, z) = f(x, y, z); g(x, y, z) += 1; h(x, y, z) = g(x, y, z); h(x, y, z) += 1; out(x, y, z) = h(x, y, z); out(x, y, z) += 1; Var xi("xi"), yi("yi"), zi("zi"); out.gpu_tile(x, y, z, xi, yi, zi, 4, 4, 4); out.update().gpu_tile(x, y, xi, yi, 4, 4); h.compute_at(out, x).gpu_threads(x, y); h.update().gpu_threads(x); // TODO: NormalizeDimensionality in FuseGPUThreadLoops.cpp doesn't work in the following case. //g.compute_at(h, y).gpu_threads(x); //g.update(); g.compute_at(h, x); g.update(); f.compute_at(g, x); f.update(); Buffer<int> o = out.realize(64, 64, 64); for (int z = 0; z < 64; z++) { for (int y = 0; y < 64; y++) { for (int x = 0; x < 64; x++) { int correct = x + y + z + 4; if (o(x, y, z) != correct) { printf("out(%d, %d, %d) = %d instead of %d\n", x, y, z, o(x, y, z), correct); return -1; } } } } printf("Success!\n"); return 0; } <|endoftext|>
<commit_before>#include <sstream> #include <plorth/plorth-context.hpp> #include "./utils.hpp" namespace plorth { Context::Context(const Ref<Runtime>& runtime) : m_runtime(runtime) {} void Context::SetError(Error::ErrorCode code, const std::string& message) { m_error = new (m_runtime) Error(code, message); } void Context::ClearError() { m_error.Clear(); } bool Context::CallWord(const std::string& name) { Ref<Value> value; // Look from prototype of current item. if (!m_stack.empty()) { const Ref<Object> prototype = m_stack.back()->GetPrototype(m_runtime); if (prototype && (value = prototype->GetOwnProperty(name))) { if (value->GetType() == Value::TYPE_QUOTE) { return value.As<Quote>()->Call(this); } m_stack.push_back(value); return true; } } // Look for word from dictionary of current context. { const auto word = m_dictionary.find(name); if (word != end(m_dictionary)) { value = word->second; if (value->GetType() == Value::TYPE_QUOTE) { return value.As<Quote>()->Call(this); } m_stack.push_back(value); return true; } } // TODO: If not found, see if it's a "fully qualified" name, e.g. a name // with a namespace name, colon and a word - Such as "num:+", and then look // for that from the specified namespace. // Look from global dictionary. if (m_runtime->FindWord(name, value)) { if (value->GetType() == Value::TYPE_QUOTE) { return value.As<Quote>()->Call(this); } m_stack.push_back(value); return true; } // If the name of the word can be converted into number, then do just that. if (str_is_number(name)) { PushNumber(name); return true; } // Otherwise it's reference error. SetError(Error::ERROR_CODE_REFERENCE, "Unrecognized word: `" + name + "'"); return false; } void Context::AddWord(const std::string& name, const Ref<Value>& value) { m_dictionary[name] = value; } bool Context::Peek(Ref<Value>& slot) { if (m_stack.empty()) { SetError(Error::ERROR_CODE_RANGE, "Stack underflow."); return false; } slot = m_stack.back(); return true; } bool Context::Peek(Ref<Value>& slot, Value::Type type) { if (!Peek(slot)) { return false; } else if (slot->GetType() != type) { std::stringstream ss; ss << "Expected " << type << ", got " << slot->GetType() << " instead."; SetError(Error::ERROR_CODE_TYPE, ss.str()); return false; } return true; } bool Context::PeekArray(Ref<Array>& slot) { Ref<Value> value; if (Peek(value, Value::TYPE_ARRAY)) { slot = value.As<Array>(); return true; } return false; } bool Context::PeekBool(bool& slot) { Ref<Value> value; if (Peek(value, Value::TYPE_BOOL)) { slot = value.As<Bool>()->GetValue(); return true; } return false; } bool Context::PeekError(Ref<Error>& slot) { Ref<Value> value; if (Peek(value, Value::TYPE_ERROR)) { slot = value.As<Error>(); return true; } return false; } bool Context::PeekNumber(Ref<Number>& slot) { Ref<Value> value; if (Peek(value, Value::TYPE_NUMBER)) { slot = value.As<Number>(); return true; } return false; } bool Context::PeekObject(Ref<Object>& slot) { Ref<Value> value; if (Peek(value, Value::TYPE_OBJECT)) { slot = value.As<Object>(); return true; } return false; } bool Context::PeekQuote(Ref<Quote>& slot) { Ref<Value> value; if (Peek(value, Value::TYPE_QUOTE)) { slot = value.As<Quote>(); return true; } return false; } bool Context::PeekString(Ref<String>& slot) { Ref<Value> value; if (Peek(value, Value::TYPE_STRING)) { slot = value.As<String>(); return true; } return false; } void Context::Push(const Ref<Value>& value) { m_stack.push_back(value); } void Context::PushArray(const std::vector<Ref<Value>>& elements) { m_stack.push_back(m_runtime->NewArray(elements)); } void Context::PushBool(bool value) { m_stack.push_back(value ? m_runtime->GetTrueValue() : m_runtime->GetFalseValue()); } void Context::PushNull() { m_stack.push_back(m_runtime->GetNullValue()); } void Context::PushNumber(std::int64_t value) { m_stack.push_back(m_runtime->NewNumber(value)); } void Context::PushNumber(double value) { m_stack.push_back(m_runtime->NewNumber(value)); } void Context::PushNumber(const mpz_class& value) { m_stack.push_back(m_runtime->NewNumber(value)); } void Context::PushNumber(const std::string& value) { m_stack.push_back(m_runtime->NewNumber(value)); } void Context::PushObject() { m_stack.push_back(m_runtime->NewObject()); } void Context::PushObject(const Object::Dictionary& properties) { m_stack.push_back(m_runtime->NewObject(properties)); } void Context::PushString(const std::string& value) { m_stack.push_back(m_runtime->NewString(value)); } bool Context::Pop() { if (m_stack.empty()) { SetError(Error::ERROR_CODE_RANGE, "Stack underflow."); return false; } m_stack.pop_back(); return true; } bool Context::Pop(Ref<Value>& slot) { if (!Peek(slot)) { return false; } m_stack.pop_back(); return true; } bool Context::Pop(Ref<Value>& slot, Value::Type type) { if (!Peek(slot, type)) { return false; } m_stack.pop_back(); return true; } bool Context::PopArray(Ref<Array>& slot) { if (!PeekArray(slot)) { return false; } m_stack.pop_back(); return true; } bool Context::PopBool(bool& slot) { Ref<Value> value; if (Pop(value, Value::TYPE_BOOL)) { slot = value.As<Bool>()->GetValue(); return true; } return false; } bool Context::PopError(Ref<Error>& slot) { if (!PeekError(slot)) { return false; } m_stack.pop_back(); return true; } bool Context::PopNumber(Ref<Number>& slot) { if (!PeekNumber(slot)) { return false; } m_stack.pop_back(); return true; } bool Context::PopObject(Ref<Object>& slot) { if (!PeekObject(slot)) { return false; } m_stack.pop_back(); return true; } bool Context::PopQuote(Ref<Quote>& slot) { if (!PeekQuote(slot)) { return false; } m_stack.pop_back(); return true; } bool Context::PopString(Ref<String>& slot) { if (!PeekString(slot)) { return false; } m_stack.pop_back(); return true; } } <commit_msg>Fix pop methods<commit_after>#include <sstream> #include <plorth/plorth-context.hpp> #include "./utils.hpp" namespace plorth { Context::Context(const Ref<Runtime>& runtime) : m_runtime(runtime) {} void Context::SetError(Error::ErrorCode code, const std::string& message) { m_error = new (m_runtime) Error(code, message); } void Context::ClearError() { m_error.Clear(); } bool Context::CallWord(const std::string& name) { Ref<Value> value; // Look from prototype of current item. if (!m_stack.empty()) { const Ref<Object> prototype = m_stack.back()->GetPrototype(m_runtime); if (prototype && (value = prototype->GetOwnProperty(name))) { if (value->GetType() == Value::TYPE_QUOTE) { return value.As<Quote>()->Call(this); } m_stack.push_back(value); return true; } } // Look for word from dictionary of current context. { const auto word = m_dictionary.find(name); if (word != end(m_dictionary)) { value = word->second; if (value->GetType() == Value::TYPE_QUOTE) { return value.As<Quote>()->Call(this); } m_stack.push_back(value); return true; } } // TODO: If not found, see if it's a "fully qualified" name, e.g. a name // with a namespace name, colon and a word - Such as "num:+", and then look // for that from the specified namespace. // Look from global dictionary. if (m_runtime->FindWord(name, value)) { if (value->GetType() == Value::TYPE_QUOTE) { return value.As<Quote>()->Call(this); } m_stack.push_back(value); return true; } // If the name of the word can be converted into number, then do just that. if (str_is_number(name)) { PushNumber(name); return true; } // Otherwise it's reference error. SetError(Error::ERROR_CODE_REFERENCE, "Unrecognized word: `" + name + "'"); return false; } void Context::AddWord(const std::string& name, const Ref<Value>& value) { m_dictionary[name] = value; } bool Context::Peek(Ref<Value>& slot) { if (m_stack.empty()) { SetError(Error::ERROR_CODE_RANGE, "Stack underflow."); return false; } slot = m_stack.back(); return true; } bool Context::Peek(Ref<Value>& slot, Value::Type type) { if (!Peek(slot)) { return false; } else if (slot->GetType() != type) { std::stringstream ss; ss << "Expected " << type << ", got " << slot->GetType() << " instead."; SetError(Error::ERROR_CODE_TYPE, ss.str()); return false; } return true; } bool Context::PeekArray(Ref<Array>& slot) { Ref<Value> value; if (Peek(value, Value::TYPE_ARRAY)) { slot = value.As<Array>(); return true; } return false; } bool Context::PeekBool(bool& slot) { Ref<Value> value; if (Peek(value, Value::TYPE_BOOL)) { slot = value.As<Bool>()->GetValue(); return true; } return false; } bool Context::PeekError(Ref<Error>& slot) { Ref<Value> value; if (Peek(value, Value::TYPE_ERROR)) { slot = value.As<Error>(); return true; } return false; } bool Context::PeekNumber(Ref<Number>& slot) { Ref<Value> value; if (Peek(value, Value::TYPE_NUMBER)) { slot = value.As<Number>(); return true; } return false; } bool Context::PeekObject(Ref<Object>& slot) { Ref<Value> value; if (Peek(value, Value::TYPE_OBJECT)) { slot = value.As<Object>(); return true; } return false; } bool Context::PeekQuote(Ref<Quote>& slot) { Ref<Value> value; if (Peek(value, Value::TYPE_QUOTE)) { slot = value.As<Quote>(); return true; } return false; } bool Context::PeekString(Ref<String>& slot) { Ref<Value> value; if (Peek(value, Value::TYPE_STRING)) { slot = value.As<String>(); return true; } return false; } void Context::Push(const Ref<Value>& value) { m_stack.push_back(value); } void Context::PushArray(const std::vector<Ref<Value>>& elements) { m_stack.push_back(m_runtime->NewArray(elements)); } void Context::PushBool(bool value) { m_stack.push_back(value ? m_runtime->GetTrueValue() : m_runtime->GetFalseValue()); } void Context::PushNull() { m_stack.push_back(m_runtime->GetNullValue()); } void Context::PushNumber(std::int64_t value) { m_stack.push_back(m_runtime->NewNumber(value)); } void Context::PushNumber(double value) { m_stack.push_back(m_runtime->NewNumber(value)); } void Context::PushNumber(const mpz_class& value) { m_stack.push_back(m_runtime->NewNumber(value)); } void Context::PushNumber(const std::string& value) { m_stack.push_back(m_runtime->NewNumber(value)); } void Context::PushObject() { m_stack.push_back(m_runtime->NewObject()); } void Context::PushObject(const Object::Dictionary& properties) { m_stack.push_back(m_runtime->NewObject(properties)); } void Context::PushString(const std::string& value) { m_stack.push_back(m_runtime->NewString(value)); } bool Context::Pop() { if (m_stack.empty()) { SetError(Error::ERROR_CODE_RANGE, "Stack underflow."); return false; } m_stack.pop_back(); return true; } bool Context::Pop(Ref<Value>& slot) { if (!Peek(slot)) { return false; } m_stack.pop_back(); return true; } bool Context::Pop(Ref<Value>& slot, Value::Type type) { if (!Peek(slot)) { return false; } m_stack.pop_back(); if (slot->GetType() != type) { std::stringstream ss; ss << "Expected " << type << ", got " << slot->GetType() << " instead."; SetError(Error::ERROR_CODE_TYPE, ss.str()); return false; } return true; } bool Context::PopArray(Ref<Array>& slot) { Ref<Value> value; if (Pop(value, Value::TYPE_ARRAY)) { slot = value.As<Array>(); return true; } return false; } bool Context::PopBool(bool& slot) { Ref<Value> value; if (Pop(value, Value::TYPE_BOOL)) { slot = value.As<Bool>()->GetValue(); return true; } return false; } bool Context::PopError(Ref<Error>& slot) { Ref<Value> value; if (Pop(value, Value::TYPE_ERROR)) { slot = value.As<Error>(); return true; } return false; } bool Context::PopNumber(Ref<Number>& slot) { Ref<Value> value; if (Pop(value, Value::TYPE_NUMBER)) { slot = value.As<Number>(); return true; } return false; } bool Context::PopObject(Ref<Object>& slot) { Ref<Value> value; if (Pop(value, Value::TYPE_OBJECT)) { slot = value.As<Object>(); return true; } return false; } bool Context::PopQuote(Ref<Quote>& slot) { Ref<Value> value; if (Pop(value, Value::TYPE_QUOTE)) { slot = value.As<Quote>(); return true; } return false; } bool Context::PopString(Ref<String>& slot) { Ref<Value> value; if (Pop(value, Value::TYPE_STRING)) { slot = value.As<String>(); return true; } return false; } } <|endoftext|>
<commit_before>/* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <stdio.h> #include <memory> #include <gflags/gflags.h> #include <gtest/gtest.h> #include <folly/dynamic.h> #include <folly/FileUtil.h> #include <folly/io/async/EventBase.h> #include <folly/Memory.h> #include "mcrouter/_router.h" #include "mcrouter/config.h" #include "mcrouter/proxy.h" #include "mcrouter/ProxyThread.h" #include "mcrouter/router.h" #include "mcrouter/lib/network/test/TestUtil.h" #include "mcrouter/test/cpp_unit_tests/mcrouter_test_client.h" #include "mcrouter/test/cpp_unit_tests/MemcacheLocal.h" using namespace facebook::memcache::mcrouter; using namespace facebook::memcache::test; using namespace folly; using facebook::memcache::McrouterOptions; /* * * * * * * * * * SPECIAL NOTE : SPECIAL NOTE : SPECIAL NOTE * * * * * * * * * * * This tester program tests the functional behavior of libmcrouter, which * communicates with a running memcached server. To deterministically test the * functional behavior, libmcrouter is configured to use a local memcached * server instead of the production servers. The configuration string for * libmcrouter is generated by generateConfigString(char *buf, int port) * function, which assumes memcached is running in the localhost. * * Before starting the tests, we need the "Local Memcached" up, and generate * the configuration string for libmcrouer. The try block in the main(..) * function takes care of these tasks. * * * * * * * * * RECOMMENDED PRACTICES : RECOMMENDED PRACTICES * * * * * * * * * * * * Before calling RUN_ALL_TESTS(..) first check memcacheLocal variable * as a gate. This variable should not be null when the tests are run. * */ std::string configString; std::unique_ptr<MemcacheLocal> memcacheLocal = nullptr; // local memcached std::string kInvalidPoolConfig = "mcrouter/test/cpp_unit_tests/files/libmcrouter_invalid_pools.json"; namespace { /** * @return File descriptor */ int connectToLocalPort(uint16_t port) { struct addrinfo hints; struct addrinfo* res; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; CHECK(!getaddrinfo("localhost", folly::to<std::string>(port).data(), &hints, &res)); auto client_socket = socket(res->ai_family, res->ai_socktype, res->ai_protocol); CHECK(client_socket >= 0); CHECK(!connect(client_socket, res->ai_addr, res->ai_addrlen)); freeaddrinfo(res); return client_socket; } void checkRequestReply(int fd, folly::StringPiece request, folly::StringPiece reply) { size_t n = folly::writeFull(fd, request.data(), request.size()); CHECK(n == request.size()); char replyBuf[1000]; n = folly::readFull(fd, replyBuf, reply.size()); CHECK(n == reply.size()); EXPECT_TRUE(folly::StringPiece(replyBuf, n) == reply); } } // namespace TEST(libmcrouter, sanity) { auto opts = defaultTestOptions(); opts.config_str = configString; MCRouterTestClient client("sanity", opts); int nkeys = 100; dynamic keys = {}; dynamic kv_pairs = dynamic::object; keys.resize(nkeys); for (dynamic i = 0; i < nkeys; i ++) { keys[i] = "rajeshn-testkey" + i.asString(); kv_pairs[keys[i]] = "value" + i.asString(); } // clean everything out dynamic delete_results = dynamic::object; client.del(keys, true, delete_results); // start the test dynamic set_results = dynamic::object; EXPECT_TRUE(client.set(kv_pairs, set_results) == nkeys); for (auto& res : set_results.values()) { EXPECT_TRUE(res.asBool()); } dynamic get_results = dynamic::object; EXPECT_TRUE(client.get(keys, get_results) == nkeys); // make sure we get what we set for (auto& res_pair : get_results.items()) { auto pos = kv_pairs.find(res_pair.first); EXPECT_FALSE(pos == get_results.items().end()); EXPECT_TRUE(kv_pairs[res_pair.first] == res_pair.second); } delete_results = dynamic::object; EXPECT_TRUE(client.del(keys, true, delete_results) == nkeys); for (auto& res : delete_results.values()) { EXPECT_TRUE(res.asBool()); } delete_results = dynamic::object; EXPECT_TRUE(client.del(keys, true, delete_results) == 0); for (auto& res : delete_results.values()) { EXPECT_FALSE(res.asBool()); } } static std::atomic<int> on_reply_count{0}; void on_reply(mcrouter_msg_t* router_req, void* context) { on_reply_count++; mc_msg_decref(router_req->req); } static std::atomic<int> on_cancel_count{0}; void on_cancel(void* request_context, void* client_context) { on_cancel_count++; } TEST(libmcrouter, premature_disconnect) { auto opts = defaultTestOptions(); opts.config_str = configString; mcrouter_t *router = mcrouter_new(opts); for (int i = 0; i < 10; i++) { on_reply_count = 0; on_cancel_count = 0; { auto client = McrouterClient::create( router, {on_reply, on_cancel, nullptr}, nullptr, 0); const char key[] = "__mockmc__.want_timeout(50)"; mc_msg_t *mc_msg = mc_msg_new(sizeof(key)); mc_msg->key.str = (char*) &mc_msg[1]; strcpy(mc_msg->key.str, key); mc_msg->key.len = strlen(key); mc_msg->op = mc_op_get; mcrouter_msg_t router_msg; router_msg.req = mc_msg; client->send(&router_msg, 1); mc_msg_decref(mc_msg); } for (size_t j = 0; on_cancel_count + on_reply_count == 0 && j < 20; ++j) { std::this_thread::sleep_for(std::chrono::milliseconds(10)); } EXPECT_EQ(0, on_reply_count); EXPECT_EQ(1, on_cancel_count); } mcrouter_free(router); } TEST(libmcrouter, invalid_pools) { auto opts = defaultTestOptions(); std::string configStr; EXPECT_TRUE(folly::readFile(kInvalidPoolConfig.data(), configStr)); opts.config_str = configStr; opts.default_route = "/a/b/"; mcrouter_t *router = mcrouter_new(opts); EXPECT_TRUE(router == nullptr); } TEST(libmcrouter, standalone) { auto opts = defaultTestOptions(); opts.standalone = true; opts.config_str = configString; mcrouter_t* router = mcrouter_init("standalone_test", opts); mcrouter_t* router2 = nullptr; folly::EventBase evb; for (size_t i = 0; i < router->opts.num_proxies; ++i) { router->getProxy(i)->attachEventBase(&evb); } { auto client = McrouterClient::create(router, {on_reply, nullptr}, nullptr, 0); const char key[] = "mcrouter_test:standalone:key:1"; mc_msg_t *mc_msg = mc_msg_new(sizeof(key)); mc_msg->key.str = (char*) &mc_msg[1]; strcpy(mc_msg->key.str, key); mc_msg->key.len = strlen(key); mc_msg->op = mc_op_get; mcrouter_msg_t msg; msg.req = mc_msg; on_reply_count = 0; client->send(&msg, 1); while (on_reply_count == 0) { mcrouterLoopOnce(&evb); } EXPECT_TRUE(on_reply_count == 1); /* Allocating a new router in standalone mode should return a new router! */ router2 = mcrouter_init("standalone_test", opts); EXPECT_TRUE(router != router2); } mcrouter_free(router); mcrouter_free(router2); } TEST(libmcrouter, listenSock) { /* Create a listen socket, pass it to a child mcrouter and check that communication through the socket works */ auto listen_socket = facebook::memcache::createListenSocket(); auto port = facebook::memcache::getListenPort(listen_socket); std::vector<std::string> args{MCROUTER_INSTALL_PATH "mcrouter/mcrouter", "--listen-sock-fd", folly::to<std::string>(listen_socket), "--config-str", configString }; auto testArgs = defaultTestCommandLineArgs(); args.insert(args.end(), testArgs.begin(), testArgs.end()); folly::Subprocess mcr(args); const std::string kSetRequest = "set testkey 0 0 1\r\nv\r\n"; const std::string kStoredReply = "STORED\r\n"; const std::string kGetRequest = "get testkey\r\n"; const std::string kGetReply = "VALUE testkey 0 1\r\nv\r\n"; auto mcr_socket = connectToLocalPort(port); checkRequestReply(mcr_socket, kSetRequest, kStoredReply); checkRequestReply(mcr_socket, kGetRequest, kGetReply); CHECK(!close(mcr_socket)); auto mc_socket = connectToLocalPort(memcacheLocal->getPort()); checkRequestReply(mc_socket, kGetRequest, kGetReply); CHECK(!close(mc_socket)); mcr.terminate(); mcr.wait(); } // for backward compatibility with gflags namespace gflags { } namespace google { using namespace gflags; } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); google::ParseCommandLineFlags(&argc, &argv, true); google::InitGoogleLogging(argv[0]); try { //blocks until local memcache server ready memcacheLocal = folly::make_unique<MemcacheLocal> (); configString = memcacheLocal->generateMcrouterConfigString(); } catch (const SubprocessError& e) { // declared in Subprocess.h LOG(ERROR) << "SubprocessError:" << std::endl << e.what(); } EXPECT_TRUE(memcacheLocal != nullptr); // gate to check if memcached is up return RUN_ALL_TESTS(); } <commit_msg>Fix unit tests<commit_after>/* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <stdio.h> #include <memory> #include <gflags/gflags.h> #include <gtest/gtest.h> #include <folly/dynamic.h> #include <folly/FileUtil.h> #include <folly/io/async/EventBase.h> #include <folly/Memory.h> #include "mcrouter/_router.h" #include "mcrouter/config.h" #include "mcrouter/proxy.h" #include "mcrouter/ProxyThread.h" #include "mcrouter/router.h" #include "mcrouter/lib/network/test/TestUtil.h" #include "mcrouter/test/cpp_unit_tests/mcrouter_test_client.h" #include "mcrouter/test/cpp_unit_tests/MemcacheLocal.h" using namespace facebook::memcache::mcrouter; using namespace facebook::memcache::test; using namespace folly; using facebook::memcache::McrouterOptions; /* * * * * * * * * * SPECIAL NOTE : SPECIAL NOTE : SPECIAL NOTE * * * * * * * * * * * This tester program tests the functional behavior of libmcrouter, which * communicates with a running memcached server. To deterministically test the * functional behavior, libmcrouter is configured to use a local memcached * server instead of the production servers. The configuration string for * libmcrouter is generated by generateConfigString(char *buf, int port) * function, which assumes memcached is running in the localhost. * * Before starting the tests, we need the "Local Memcached" up, and generate * the configuration string for libmcrouer. The try block in the main(..) * function takes care of these tasks. * * * * * * * * * RECOMMENDED PRACTICES : RECOMMENDED PRACTICES * * * * * * * * * * * * Before calling RUN_ALL_TESTS(..) first check memcacheLocal variable * as a gate. This variable should not be null when the tests are run. * */ std::string configString; std::unique_ptr<MemcacheLocal> memcacheLocal = nullptr; // local memcached std::string kInvalidPoolConfig = "mcrouter/test/cpp_unit_tests/files/libmcrouter_invalid_pools.json"; namespace { /** * @return File descriptor */ int connectToLocalPort(uint16_t port) { struct addrinfo hints; struct addrinfo* res; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; CHECK(!getaddrinfo("localhost", folly::to<std::string>(port).data(), &hints, &res)); auto client_socket = socket(res->ai_family, res->ai_socktype, res->ai_protocol); CHECK(client_socket >= 0); CHECK(!connect(client_socket, res->ai_addr, res->ai_addrlen)); freeaddrinfo(res); return client_socket; } void checkRequestReply(int fd, folly::StringPiece request, folly::StringPiece reply) { size_t n = folly::writeFull(fd, request.data(), request.size()); CHECK(n == request.size()); char replyBuf[1000]; n = folly::readFull(fd, replyBuf, reply.size()); CHECK(n == reply.size()); EXPECT_TRUE(folly::StringPiece(replyBuf, n) == reply); } } // namespace TEST(libmcrouter, sanity) { auto opts = defaultTestOptions(); opts.config_str = configString; MCRouterTestClient client("sanity", opts); int nkeys = 100; dynamic keys = {}; dynamic kv_pairs = dynamic::object; keys.resize(nkeys); for (dynamic i = 0; i < nkeys; i ++) { keys[i] = "rajeshn-testkey" + i.asString(); kv_pairs[keys[i]] = "value" + i.asString(); } // clean everything out dynamic delete_results = dynamic::object; client.del(keys, true, delete_results); // start the test dynamic set_results = dynamic::object; EXPECT_TRUE(client.set(kv_pairs, set_results) == nkeys); for (auto& res : set_results.values()) { EXPECT_TRUE(res.asBool()); } dynamic get_results = dynamic::object; EXPECT_TRUE(client.get(keys, get_results) == nkeys); // make sure we get what we set for (auto& res_pair : get_results.items()) { auto pos = kv_pairs.find(res_pair.first); EXPECT_FALSE(pos == get_results.items().end()); EXPECT_TRUE(kv_pairs[res_pair.first] == res_pair.second); } delete_results = dynamic::object; EXPECT_TRUE(client.del(keys, true, delete_results) == nkeys); for (auto& res : delete_results.values()) { EXPECT_TRUE(res.asBool()); } delete_results = dynamic::object; EXPECT_TRUE(client.del(keys, true, delete_results) == 0); for (auto& res : delete_results.values()) { EXPECT_FALSE(res.asBool()); } } static std::atomic<int> on_reply_count{0}; void on_reply(mcrouter_msg_t* router_req, void* context) { on_reply_count++; mc_msg_decref(router_req->req); } static std::atomic<int> on_cancel_count{0}; void on_cancel(void* request_context, void* client_context) { on_cancel_count++; } TEST(libmcrouter, premature_disconnect) { auto opts = defaultTestOptions(); opts.config_str = configString; mcrouter_t *router = mcrouter_new(opts); for (int i = 0; i < 10; i++) { on_reply_count = 0; on_cancel_count = 0; { auto client = McrouterClient::create( router, {on_reply, on_cancel, nullptr}, nullptr, 0); const char key[] = "__mockmc__.want_timeout(50)"; mc_msg_t *mc_msg = mc_msg_new(sizeof(key)); mc_msg->key.str = (char*) &mc_msg[1]; strcpy(mc_msg->key.str, key); mc_msg->key.len = strlen(key); mc_msg->op = mc_op_get; mcrouter_msg_t router_msg; router_msg.req = mc_msg; client->send(&router_msg, 1); mc_msg_decref(mc_msg); } for (size_t j = 0; on_cancel_count + on_reply_count == 0 && j < 20; ++j) { std::this_thread::sleep_for(std::chrono::milliseconds(10)); } EXPECT_EQ(0, on_reply_count); EXPECT_EQ(1, on_cancel_count); } mcrouter_free(router); } TEST(libmcrouter, invalid_pools) { auto opts = defaultTestOptions(); std::string configStr; EXPECT_TRUE(folly::readFile(kInvalidPoolConfig.data(), configStr)); opts.config_str = configStr; opts.default_route = "/a/b/"; mcrouter_t *router = mcrouter_new(opts); EXPECT_TRUE(router == nullptr); } TEST(libmcrouter, listenSock) { /* Create a listen socket, pass it to a child mcrouter and check that communication through the socket works */ auto listen_socket = facebook::memcache::createListenSocket(); auto port = facebook::memcache::getListenPort(listen_socket); std::vector<std::string> args{MCROUTER_INSTALL_PATH "mcrouter/mcrouter", "--listen-sock-fd", folly::to<std::string>(listen_socket), "--config-str", configString }; auto testArgs = defaultTestCommandLineArgs(); args.insert(args.end(), testArgs.begin(), testArgs.end()); folly::Subprocess mcr(args); const std::string kSetRequest = "set testkey 0 0 1\r\nv\r\n"; const std::string kStoredReply = "STORED\r\n"; const std::string kGetRequest = "get testkey\r\n"; const std::string kGetReply = "VALUE testkey 0 1\r\nv\r\n"; auto mcr_socket = connectToLocalPort(port); checkRequestReply(mcr_socket, kSetRequest, kStoredReply); checkRequestReply(mcr_socket, kGetRequest, kGetReply); CHECK(!close(mcr_socket)); auto mc_socket = connectToLocalPort(memcacheLocal->getPort()); checkRequestReply(mc_socket, kGetRequest, kGetReply); CHECK(!close(mc_socket)); mcr.terminate(); mcr.wait(); } // for backward compatibility with gflags namespace gflags { } namespace google { using namespace gflags; } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); google::ParseCommandLineFlags(&argc, &argv, true); google::InitGoogleLogging(argv[0]); try { //blocks until local memcache server ready memcacheLocal = folly::make_unique<MemcacheLocal> (); configString = memcacheLocal->generateMcrouterConfigString(); } catch (const SubprocessError& e) { // declared in Subprocess.h LOG(ERROR) << "SubprocessError:" << std::endl << e.what(); } EXPECT_TRUE(memcacheLocal != nullptr); // gate to check if memcached is up return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>#pragma once #include <Communicator.hpp> #include <Addressing.hpp> #include <Collective.hpp> #include <ParallelLoop.hpp> #include <GlobalAllocator.hpp> #include <Delegate.hpp> #include <AsyncDelegate.hpp> #include <Array.hpp> #include <algorithm> #include "common.h" // #define USE_MPI3_COLLECTIVES #undef USE_MPI3_COLLECTIVES #ifdef USE_MPI3_COLLECTIVES #include <mpi.h> #endif using namespace Grappa; struct Vertex { int64_t * local_adj; // adjacencies that are local int64_t nadj; // number of adjacencies int64_t local_sz; // size of local allocation (regardless of how full it is) // int64_t parent; void * vertex_data; Vertex(): local_adj(nullptr), nadj(0), local_sz(0) {} ~Vertex() {} template< typename F > void forall_adj(F body) { for (int64_t i=0; i<nadj; i++) { body(local_adj[i]); } } auto adj_iter() -> decltype(util::iterator(local_adj)) { return util::iterator(local_adj, nadj); } }; // vertex with parent struct VertexP : public Vertex { VertexP(): Vertex() { parent(-1); } int64_t parent() { return (int64_t)vertex_data; } void parent(int64_t parent) { vertex_data = (void*)parent; } }; template< class V = Vertex > struct Graph { static_assert(block_size % sizeof(V) == 0, "V size not evenly divisible into blocks!"); // // Helpers (for if we go with custom cyclic distribution) // inline Core vertex_owner (int64_t v) { return v % cores(); } // inline int64_t vertex_offset(int64_t v) { return v / cores(); } // Fields GlobalAddress<V> vs; int64_t nv, nadj, nadj_local; // Internal fields int64_t * adj_buf; int64_t * scratch; GlobalAddress<Graph> self; char _pad[block_size - sizeof(vs)-sizeof(nv)-sizeof(nadj)-sizeof(nadj_local)-sizeof(adj_buf)-sizeof(scratch)-sizeof(self)]; Graph(GlobalAddress<Graph> self, GlobalAddress<V> vs, int64_t nv) : self(self) , vs(vs) , nv(nv) , nadj(0) , nadj_local(0) , adj_buf(nullptr) , scratch(nullptr) { } ~Graph() { for (V& v : iterate_local(vs, nv)) { v.~V(); } if (adj_buf) locale_free(adj_buf); } void destroy() { auto self = this->self; global_free(this->vs); call_on_all_cores([self]{ self->~Graph(); }); global_free(self); } template< int LEVEL = 0 > static void dump(GlobalAddress<Graph> g) { for (int64_t i=0; i<g->nv; i++) { delegate::call(g->vs+i, [i](V * v){ std::stringstream ss; ss << "<" << i << ">"; for (int64_t i=0; i<v->nadj; i++) ss << " " << v->local_adj[i]; VLOG(LEVEL) << ss.str(); }); } } /// Cast graph to new type, and allow user to re-initialize each V by providing a /// functor (the body of a forall_localized() over the vertices) template< typename VNew, typename VOld, typename InitFunc = decltype(nullptr) > static GlobalAddress<Graph<VNew>> transform_vertices(GlobalAddress<Graph<VOld>> o, InitFunc init) { static_assert(sizeof(VNew) == sizeof(V), "transformed vertex size must be the unchanged."); auto g = static_cast<GlobalAddress<Graph<VNew>>>(o); forall_localized(g->vs, g->nv, init); return g; } // Constructor static GlobalAddress<Graph> create(tuple_graph& tg) { double t; auto g = mirrored_global_alloc<Graph<V>>(); // find nv t = walltime(); forall_localized(tg.edges, tg.nedge, [g](packed_edge& e){ if (e.v0 > g->nv) { g->nv = e.v0; } else if (e.v1 > g->nv) { g->nv = e.v1; } }); on_all_cores([g]{ g->nv = Grappa::allreduce<int64_t,collective_max>(g->nv) + 1; }); VLOG(1) << "find_nv_time: " << walltime() - t; auto vs = global_alloc<V>(g->nv); auto self = g; on_all_cores([g,vs]{ new (g.localize()) Graph(g, vs, g->nv); for (V& v : iterate_local(g->vs, g->nv)) { new (&v) V(); } #ifdef SMALL_GRAPH // g->scratch = locale_alloc<int64_t>(g->nv); if (locale_mycore() == 0) g->scratch = locale_alloc<int64_t>(g->nv); barrier(); if (locale_mycore() == 0) { memset(g->scratch, 0, sizeof(int64_t)*g->nv); } else { g->scratch = delegate::call(mylocale()*locale_cores(), [g]{ return g->scratch; }); } VLOG(0) << "locale = " << mylocale() << ", scratch = " << g->scratch; #endif }); t = walltime(); forall_localized(tg.edges, tg.nedge, [g](packed_edge& e){ CHECK_LT(e.v0, g->nv); CHECK_LT(e.v1, g->nv); #ifdef SMALL_GRAPH // g->scratch[e.v0]++; // g->scratch[e.v1]++; __sync_fetch_and_add(g->scratch+e.v0, 1); __sync_fetch_and_add(g->scratch+e.v1, 1); #else auto count = [](GlobalAddress<V> v){ delegate::call_async(*shared_pool, v.core(), [v]{ v->local_sz++; }); }; count(g->vs+e.v0); count(g->vs+e.v1); #endif }); VLOG(1) << "count_time: " << walltime() - t; #ifdef SMALL_GRAPH t = walltime(); #ifdef USE_MPI3_COLLECTIVES on_all_cores([g]{ MPI_Request r; int done; MPI_Iallreduce(MPI_IN_PLACE, g->scratch, g->nv, MPI_INT64_T, MPI_SUM, MPI_COMM_WORLD, &r); do { MPI_Test( &r, &done, MPI_STATUS_IGNORE ); if(!done) { Grappa_yield(); } } while(!done); }); #else on_all_cores([g]{ allreduce_inplace<int64_t,collective_add>(g->scratch, g->nv); }); #endif // USE_MPI3_COLLECTIVES VLOG(1) << "allreduce_inplace_time: " << walltime() - t; // on_all_cores([g]{ VLOG(5) << util::array_str("scratch", g->scratch, g->nv, 25); }); #endif // SMALL_GRAPH // allocate space for each vertex's adjacencies (+ duplicates) forall_localized(g->vs, g->nv, [g](int64_t i, V& v) { #ifdef SMALL_GRAPH // adjust b/c allreduce didn't account for having 1 instance per locale v.local_sz = g->scratch[i] / locale_cores(); #endif v.nadj = 0; if (v.local_sz > 0) v.local_adj = new int64_t[v.local_sz]; }); VLOG(3) << "after adj allocs"; // scatter forall_localized(tg.edges, tg.nedge, [g](packed_edge& e){ auto scatter = [g](int64_t vi, int64_t adj) { auto vaddr = g->vs+vi; delegate::call_async(*shared_pool, vaddr.core(), [vaddr,adj]{ auto& v = *vaddr.pointer(); v.local_adj[v.nadj++] = adj; }); }; scatter(e.v0, e.v1); scatter(e.v1, e.v0); }); VLOG(3) << "after scatter, nv = " << g->nv; // sort & de-dup forall_localized(g->vs, g->nv, [g](int64_t vi, V& v){ CHECK_EQ(v.nadj, v.local_sz); std::sort(v.local_adj, v.local_adj+v.nadj); int64_t tail = 0; for (int64_t i=0; i<v.nadj; i++, tail++) { v.local_adj[tail] = v.local_adj[i]; while (v.local_adj[tail] == v.local_adj[i+1]) i++; } v.nadj = tail; // VLOG(0) << "<" << vi << ">" << util::array_str("", v.local_adj, v.nadj); g->nadj_local += v.nadj; }); VLOG(3) << "after sort"; // compact on_all_cores([g]{ #ifdef SMALL_GRAPH if (locale_mycore() == 0) locale_free(g->scratch); #endif VLOG(2) << "nadj_local = " << g->nadj_local; // allocate storage for local vertices' adjacencies g->adj_buf = locale_alloc<int64_t>(g->nadj_local); // compute total nadj g->nadj = allreduce<int64_t,collective_add>(g->nadj_local); int64_t * adj = g->adj_buf; for (V& v : iterate_local(g->vs, g->nv)) { Grappa::memcpy(adj, v.local_adj, v.nadj); if (v.local_sz > 0) delete[] v.local_adj; v.local_sz = v.nadj; v.local_adj = adj; adj += v.nadj; } CHECK_EQ(adj - g->adj_buf, g->nadj_local); }); return g; } }; <commit_msg>oops, fix another use of util::iterator->iterate<commit_after>#pragma once #include <Communicator.hpp> #include <Addressing.hpp> #include <Collective.hpp> #include <ParallelLoop.hpp> #include <GlobalAllocator.hpp> #include <Delegate.hpp> #include <AsyncDelegate.hpp> #include <Array.hpp> #include <algorithm> #include "common.h" // #define USE_MPI3_COLLECTIVES #undef USE_MPI3_COLLECTIVES #ifdef USE_MPI3_COLLECTIVES #include <mpi.h> #endif using namespace Grappa; struct Vertex { int64_t * local_adj; // adjacencies that are local int64_t nadj; // number of adjacencies int64_t local_sz; // size of local allocation (regardless of how full it is) // int64_t parent; void * vertex_data; Vertex(): local_adj(nullptr), nadj(0), local_sz(0) {} ~Vertex() {} template< typename F > void forall_adj(F body) { for (int64_t i=0; i<nadj; i++) { body(local_adj[i]); } } auto adj_iter() -> decltype(util::iterate(local_adj)) { return util::iterate(local_adj, nadj); } }; // vertex with parent struct VertexP : public Vertex { VertexP(): Vertex() { parent(-1); } int64_t parent() { return (int64_t)vertex_data; } void parent(int64_t parent) { vertex_data = (void*)parent; } }; template< class V = Vertex > struct Graph { static_assert(block_size % sizeof(V) == 0, "V size not evenly divisible into blocks!"); // // Helpers (for if we go with custom cyclic distribution) // inline Core vertex_owner (int64_t v) { return v % cores(); } // inline int64_t vertex_offset(int64_t v) { return v / cores(); } // Fields GlobalAddress<V> vs; int64_t nv, nadj, nadj_local; // Internal fields int64_t * adj_buf; int64_t * scratch; GlobalAddress<Graph> self; char _pad[block_size - sizeof(vs)-sizeof(nv)-sizeof(nadj)-sizeof(nadj_local)-sizeof(adj_buf)-sizeof(scratch)-sizeof(self)]; Graph(GlobalAddress<Graph> self, GlobalAddress<V> vs, int64_t nv) : self(self) , vs(vs) , nv(nv) , nadj(0) , nadj_local(0) , adj_buf(nullptr) , scratch(nullptr) { } ~Graph() { for (V& v : iterate_local(vs, nv)) { v.~V(); } if (adj_buf) locale_free(adj_buf); } void destroy() { auto self = this->self; global_free(this->vs); call_on_all_cores([self]{ self->~Graph(); }); global_free(self); } template< int LEVEL = 0 > static void dump(GlobalAddress<Graph> g) { for (int64_t i=0; i<g->nv; i++) { delegate::call(g->vs+i, [i](V * v){ std::stringstream ss; ss << "<" << i << ">"; for (int64_t i=0; i<v->nadj; i++) ss << " " << v->local_adj[i]; VLOG(LEVEL) << ss.str(); }); } } /// Cast graph to new type, and allow user to re-initialize each V by providing a /// functor (the body of a forall_localized() over the vertices) template< typename VNew, typename VOld, typename InitFunc = decltype(nullptr) > static GlobalAddress<Graph<VNew>> transform_vertices(GlobalAddress<Graph<VOld>> o, InitFunc init) { static_assert(sizeof(VNew) == sizeof(V), "transformed vertex size must be the unchanged."); auto g = static_cast<GlobalAddress<Graph<VNew>>>(o); forall_localized(g->vs, g->nv, init); return g; } // Constructor static GlobalAddress<Graph> create(tuple_graph& tg) { double t; auto g = mirrored_global_alloc<Graph<V>>(); // find nv t = walltime(); forall_localized(tg.edges, tg.nedge, [g](packed_edge& e){ if (e.v0 > g->nv) { g->nv = e.v0; } else if (e.v1 > g->nv) { g->nv = e.v1; } }); on_all_cores([g]{ g->nv = Grappa::allreduce<int64_t,collective_max>(g->nv) + 1; }); VLOG(1) << "find_nv_time: " << walltime() - t; auto vs = global_alloc<V>(g->nv); auto self = g; on_all_cores([g,vs]{ new (g.localize()) Graph(g, vs, g->nv); for (V& v : iterate_local(g->vs, g->nv)) { new (&v) V(); } #ifdef SMALL_GRAPH // g->scratch = locale_alloc<int64_t>(g->nv); if (locale_mycore() == 0) g->scratch = locale_alloc<int64_t>(g->nv); barrier(); if (locale_mycore() == 0) { memset(g->scratch, 0, sizeof(int64_t)*g->nv); } else { g->scratch = delegate::call(mylocale()*locale_cores(), [g]{ return g->scratch; }); } VLOG(0) << "locale = " << mylocale() << ", scratch = " << g->scratch; #endif }); t = walltime(); forall_localized(tg.edges, tg.nedge, [g](packed_edge& e){ CHECK_LT(e.v0, g->nv); CHECK_LT(e.v1, g->nv); #ifdef SMALL_GRAPH // g->scratch[e.v0]++; // g->scratch[e.v1]++; __sync_fetch_and_add(g->scratch+e.v0, 1); __sync_fetch_and_add(g->scratch+e.v1, 1); #else auto count = [](GlobalAddress<V> v){ delegate::call_async(*shared_pool, v.core(), [v]{ v->local_sz++; }); }; count(g->vs+e.v0); count(g->vs+e.v1); #endif }); VLOG(1) << "count_time: " << walltime() - t; #ifdef SMALL_GRAPH t = walltime(); #ifdef USE_MPI3_COLLECTIVES on_all_cores([g]{ MPI_Request r; int done; MPI_Iallreduce(MPI_IN_PLACE, g->scratch, g->nv, MPI_INT64_T, MPI_SUM, MPI_COMM_WORLD, &r); do { MPI_Test( &r, &done, MPI_STATUS_IGNORE ); if(!done) { Grappa_yield(); } } while(!done); }); #else on_all_cores([g]{ allreduce_inplace<int64_t,collective_add>(g->scratch, g->nv); }); #endif // USE_MPI3_COLLECTIVES VLOG(1) << "allreduce_inplace_time: " << walltime() - t; // on_all_cores([g]{ VLOG(5) << util::array_str("scratch", g->scratch, g->nv, 25); }); #endif // SMALL_GRAPH // allocate space for each vertex's adjacencies (+ duplicates) forall_localized(g->vs, g->nv, [g](int64_t i, V& v) { #ifdef SMALL_GRAPH // adjust b/c allreduce didn't account for having 1 instance per locale v.local_sz = g->scratch[i] / locale_cores(); #endif v.nadj = 0; if (v.local_sz > 0) v.local_adj = new int64_t[v.local_sz]; }); VLOG(3) << "after adj allocs"; // scatter forall_localized(tg.edges, tg.nedge, [g](packed_edge& e){ auto scatter = [g](int64_t vi, int64_t adj) { auto vaddr = g->vs+vi; delegate::call_async(*shared_pool, vaddr.core(), [vaddr,adj]{ auto& v = *vaddr.pointer(); v.local_adj[v.nadj++] = adj; }); }; scatter(e.v0, e.v1); scatter(e.v1, e.v0); }); VLOG(3) << "after scatter, nv = " << g->nv; // sort & de-dup forall_localized(g->vs, g->nv, [g](int64_t vi, V& v){ CHECK_EQ(v.nadj, v.local_sz); std::sort(v.local_adj, v.local_adj+v.nadj); int64_t tail = 0; for (int64_t i=0; i<v.nadj; i++, tail++) { v.local_adj[tail] = v.local_adj[i]; while (v.local_adj[tail] == v.local_adj[i+1]) i++; } v.nadj = tail; // VLOG(0) << "<" << vi << ">" << util::array_str("", v.local_adj, v.nadj); g->nadj_local += v.nadj; }); VLOG(3) << "after sort"; // compact on_all_cores([g]{ #ifdef SMALL_GRAPH if (locale_mycore() == 0) locale_free(g->scratch); #endif VLOG(2) << "nadj_local = " << g->nadj_local; // allocate storage for local vertices' adjacencies g->adj_buf = locale_alloc<int64_t>(g->nadj_local); // compute total nadj g->nadj = allreduce<int64_t,collective_add>(g->nadj_local); int64_t * adj = g->adj_buf; for (V& v : iterate_local(g->vs, g->nv)) { Grappa::memcpy(adj, v.local_adj, v.nadj); if (v.local_sz > 0) delete[] v.local_adj; v.local_sz = v.nadj; v.local_adj = adj; adj += v.nadj; } CHECK_EQ(adj - g->adj_buf, g->nadj_local); }); return g; } }; <|endoftext|>
<commit_before>// -*- c++ -*- /* * Copyright 2002, The libsigc++ Development Team * * 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 * */ #include <sigc++/trackable.h> #include <iostream> SIGC_USING_STD(ostream) using namespace std; namespace sigc { trackable::trackable() : callback_list_(nullptr) {} /* Don't copy the notification list. The objects watching src don't need to be notified when the new object dies. */ trackable::trackable(const trackable& /*src*/) : callback_list_(nullptr) {} trackable::trackable(trackable&& src) : callback_list_(std::move(src.callback_list_)) { } trackable& trackable::operator=(const trackable& src) { if(this != &src) notify_callbacks(); //Make sure that we have finished with existing stuff before replacing it. return *this; } trackable::~trackable() { notify_callbacks(); } void trackable::add_destroy_notify_callback(void* data, func_destroy_notify func) const { callback_list()->add_callback(data, func); } void trackable::remove_destroy_notify_callback(void* data) const { callback_list()->remove_callback(data); } void trackable::notify_callbacks() { if (callback_list_) delete callback_list_; //This invokes all of the callbacks. callback_list_ = nullptr; } internal::trackable_callback_list* trackable::callback_list() const { if (!callback_list_) callback_list_ = new internal::trackable_callback_list; return callback_list_; } namespace internal { trackable_callback_list::trackable_callback_list(trackable_callback_list&& src) noexcept : callbacks_(std::move(src.callbacks_)), clearing_(std::move(src.clearing_)) { src.callbacks_.clear(); src.clearing_ = false; } trackable_callback_list& trackable_callback_list::operator=(trackable_callback_list&& src) noexcept { callbacks_ = std::move(src.callbacks_); clearing_ = std::move(src.clearing_); src.callbacks_.clear(); src.clearing_ = false; return *this; } trackable_callback_list::~trackable_callback_list() { clearing_ = true; for (auto& callback : callbacks_) if (callback.func_) callback.func_(callback.data_); } void trackable_callback_list::add_callback(void* data, func_destroy_notify func) { if (!clearing_) // TODO: Is it okay to silently ignore attempts to add dependencies when the list is being cleared? // I'd consider this a serious application bug, since the app is likely to segfault. // But then, how should we handle it? Throw an exception? Martin. callbacks_.push_back(trackable_callback(data, func)); } void trackable_callback_list::clear() { clearing_ = true; for (auto& callback : callbacks_) if (callback.func_) callback.func_(callback.data_); callbacks_.clear(); clearing_ = false; } void trackable_callback_list::remove_callback(void* data) { for (callback_list::iterator i = callbacks_.begin(); i != callbacks_.end(); ++i) { auto& callback = *i; if (callback.data_ == data && callback.func_ != nullptr) { //Don't remove a list element while the list is being cleared. //It could invalidate the iterator in ~trackable_callback_list() or clear(). //But it may be necessary to invalidate the callback. See bug 589202. if (clearing_) callback.func_ = nullptr; else callbacks_.erase(i); return; } } } } /* namespace internal */ } /* namespace sigc */ <commit_msg>trackable: Add missing operator=(&&) implementation.<commit_after>// -*- c++ -*- /* * Copyright 2002, The libsigc++ Development Team * * 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 * */ #include <sigc++/trackable.h> #include <iostream> SIGC_USING_STD(ostream) using namespace std; namespace sigc { trackable::trackable() : callback_list_(nullptr) {} /* Don't copy the notification list. The objects watching src don't need to be notified when the new object dies. */ trackable::trackable(const trackable& /*src*/) : callback_list_(nullptr) {} trackable::trackable(trackable&& src) : callback_list_(std::move(src.callback_list_)) { } trackable& trackable::operator=(const trackable& src) { if(this != &src) notify_callbacks(); //Make sure that we have finished with existing stuff before replacing it. return *this; } trackable& trackable::operator=(trackable&& src) { if(this != &src) notify_callbacks(); //Make sure that we have finished with existing stuff before replacing it. callback_list_ = std::move(src.callback_list_); return *this; } trackable::~trackable() { notify_callbacks(); } void trackable::add_destroy_notify_callback(void* data, func_destroy_notify func) const { callback_list()->add_callback(data, func); } void trackable::remove_destroy_notify_callback(void* data) const { callback_list()->remove_callback(data); } void trackable::notify_callbacks() { if (callback_list_) delete callback_list_; //This invokes all of the callbacks. callback_list_ = nullptr; } internal::trackable_callback_list* trackable::callback_list() const { if (!callback_list_) callback_list_ = new internal::trackable_callback_list; return callback_list_; } namespace internal { trackable_callback_list::trackable_callback_list(trackable_callback_list&& src) noexcept : callbacks_(std::move(src.callbacks_)), clearing_(std::move(src.clearing_)) { src.callbacks_.clear(); src.clearing_ = false; } trackable_callback_list& trackable_callback_list::operator=(trackable_callback_list&& src) noexcept { callbacks_ = std::move(src.callbacks_); clearing_ = std::move(src.clearing_); src.callbacks_.clear(); src.clearing_ = false; return *this; } trackable_callback_list::~trackable_callback_list() { clearing_ = true; for (auto& callback : callbacks_) if (callback.func_) callback.func_(callback.data_); } void trackable_callback_list::add_callback(void* data, func_destroy_notify func) { if (!clearing_) // TODO: Is it okay to silently ignore attempts to add dependencies when the list is being cleared? // I'd consider this a serious application bug, since the app is likely to segfault. // But then, how should we handle it? Throw an exception? Martin. callbacks_.push_back(trackable_callback(data, func)); } void trackable_callback_list::clear() { clearing_ = true; for (auto& callback : callbacks_) if (callback.func_) callback.func_(callback.data_); callbacks_.clear(); clearing_ = false; } void trackable_callback_list::remove_callback(void* data) { for (callback_list::iterator i = callbacks_.begin(); i != callbacks_.end(); ++i) { auto& callback = *i; if (callback.data_ == data && callback.func_ != nullptr) { //Don't remove a list element while the list is being cleared. //It could invalidate the iterator in ~trackable_callback_list() or clear(). //But it may be necessary to invalidate the callback. See bug 589202. if (clearing_) callback.func_ = nullptr; else callbacks_.erase(i); return; } } } } /* namespace internal */ } /* namespace sigc */ <|endoftext|>
<commit_before>/* * Copyright (c) 2002-2005 The Regents of The University of Michigan * 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 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: Steve Reinhardt * Nathan Binkert */ #include <iostream> #include <string> #include <sstream> #include "base/cprintf.hh" #include "base/loader/symtab.hh" #include "base/misc.hh" #include "base/output.hh" #include "base/trace.hh" #include "cpu/base.hh" #include "cpu/cpuevent.hh" #include "cpu/thread_context.hh" #include "cpu/profile.hh" #include "params/BaseCPU.hh" #include "sim/sim_exit.hh" #include "sim/process.hh" #include "sim/sim_events.hh" #include "sim/system.hh" // Hack #include "sim/stat_control.hh" using namespace std; vector<BaseCPU *> BaseCPU::cpuList; // This variable reflects the max number of threads in any CPU. Be // careful to only use it once all the CPUs that you care about have // been initialized int maxThreadsPerCPU = 1; CPUProgressEvent::CPUProgressEvent(BaseCPU *_cpu, Tick ival) : Event(Event::Progress_Event_Pri), _interval(ival), lastNumInst(0), cpu(_cpu), _repeatEvent(true) { if (_interval) cpu->schedule(this, curTick + _interval); } void CPUProgressEvent::process() { Counter temp = cpu->totalInstructions(); #ifndef NDEBUG double ipc = double(temp - lastNumInst) / (_interval / cpu->ticks(1)); DPRINTFN("%s progress event, total committed:%i, progress insts committed: " "%lli, IPC: %0.8d\n", cpu->name(), temp, temp - lastNumInst, ipc); ipc = 0.0; #else cprintf("%lli: %s progress event, total committed:%i, progress insts " "committed: %lli\n", curTick, cpu->name(), temp, temp - lastNumInst); #endif lastNumInst = temp; if (_repeatEvent) cpu->schedule(this, curTick + _interval); } const char * CPUProgressEvent::description() const { return "CPU Progress"; } #if FULL_SYSTEM BaseCPU::BaseCPU(Params *p) : MemObject(p), clock(p->clock), instCnt(0), _cpuId(p->cpu_id), interrupts(p->interrupts), numThreads(p->numThreads), system(p->system), phase(p->phase) #else BaseCPU::BaseCPU(Params *p) : MemObject(p), clock(p->clock), _cpuId(p->cpu_id), numThreads(p->numThreads), system(p->system), phase(p->phase) #endif { // currentTick = curTick; // if Python did not provide a valid ID, do it here if (_cpuId == -1 ) { _cpuId = cpuList.size(); } // add self to global list of CPUs cpuList.push_back(this); DPRINTF(SyscallVerbose, "Constructing CPU with id %d\n", _cpuId); if (numThreads > maxThreadsPerCPU) maxThreadsPerCPU = numThreads; // allocate per-thread instruction-based event queues comInstEventQueue = new EventQueue *[numThreads]; for (ThreadID tid = 0; tid < numThreads; ++tid) comInstEventQueue[tid] = new EventQueue("instruction-based event queue"); // // set up instruction-count-based termination events, if any // if (p->max_insts_any_thread != 0) { const char *cause = "a thread reached the max instruction count"; for (ThreadID tid = 0; tid < numThreads; ++tid) { Event *event = new SimLoopExitEvent(cause, 0); comInstEventQueue[tid]->schedule(event, p->max_insts_any_thread); } } if (p->max_insts_all_threads != 0) { const char *cause = "all threads reached the max instruction count"; // allocate & initialize shared downcounter: each event will // decrement this when triggered; simulation will terminate // when counter reaches 0 int *counter = new int; *counter = numThreads; for (ThreadID tid = 0; tid < numThreads; ++tid) { Event *event = new CountedExitEvent(cause, *counter); comInstEventQueue[tid]->schedule(event, p->max_insts_any_thread); } } // allocate per-thread load-based event queues comLoadEventQueue = new EventQueue *[numThreads]; for (ThreadID tid = 0; tid < numThreads; ++tid) comLoadEventQueue[tid] = new EventQueue("load-based event queue"); // // set up instruction-count-based termination events, if any // if (p->max_loads_any_thread != 0) { const char *cause = "a thread reached the max load count"; for (ThreadID tid = 0; tid < numThreads; ++tid) { Event *event = new SimLoopExitEvent(cause, 0); comLoadEventQueue[tid]->schedule(event, p->max_loads_any_thread); } } if (p->max_loads_all_threads != 0) { const char *cause = "all threads reached the max load count"; // allocate & initialize shared downcounter: each event will // decrement this when triggered; simulation will terminate // when counter reaches 0 int *counter = new int; *counter = numThreads; for (ThreadID tid = 0; tid < numThreads; ++tid) { Event *event = new CountedExitEvent(cause, *counter); comLoadEventQueue[tid]->schedule(event, p->max_loads_all_threads); } } functionTracingEnabled = false; if (p->function_trace) { functionTraceStream = simout.find(csprintf("ftrace.%s", name())); currentFunctionStart = currentFunctionEnd = 0; functionEntryTick = p->function_trace_start; if (p->function_trace_start == 0) { functionTracingEnabled = true; } else { typedef EventWrapper<BaseCPU, &BaseCPU::enableFunctionTrace> wrap; Event *event = new wrap(this, true); schedule(event, p->function_trace_start); } } #if FULL_SYSTEM interrupts->setCPU(this); profileEvent = NULL; if (params()->profile) profileEvent = new ProfileEvent(this, params()->profile); #endif tracer = params()->tracer; } void BaseCPU::enableFunctionTrace() { functionTracingEnabled = true; } BaseCPU::~BaseCPU() { } void BaseCPU::init() { if (!params()->defer_registration) registerThreadContexts(); } void BaseCPU::startup() { #if FULL_SYSTEM if (!params()->defer_registration && profileEvent) schedule(profileEvent, curTick); #endif if (params()->progress_interval) { Tick num_ticks = ticks(params()->progress_interval); Event *event; event = new CPUProgressEvent(this, num_ticks); } } void BaseCPU::regStats() { using namespace Stats; numCycles .name(name() + ".numCycles") .desc("number of cpu cycles simulated") ; int size = threadContexts.size(); if (size > 1) { for (int i = 0; i < size; ++i) { stringstream namestr; ccprintf(namestr, "%s.ctx%d", name(), i); threadContexts[i]->regStats(namestr.str()); } } else if (size == 1) threadContexts[0]->regStats(name()); #if FULL_SYSTEM #endif } Tick BaseCPU::nextCycle() { Tick next_tick = curTick - phase + clock - 1; next_tick -= (next_tick % clock); next_tick += phase; return next_tick; } Tick BaseCPU::nextCycle(Tick begin_tick) { Tick next_tick = begin_tick; if (next_tick % clock != 0) next_tick = next_tick - (next_tick % clock) + clock; next_tick += phase; assert(next_tick >= curTick); return next_tick; } void BaseCPU::registerThreadContexts() { ThreadID size = threadContexts.size(); for (ThreadID tid = 0; tid < size; ++tid) { ThreadContext *tc = threadContexts[tid]; /** This is so that contextId and cpuId match where there is a * 1cpu:1context relationship. Otherwise, the order of registration * could affect the assignment and cpu 1 could have context id 3, for * example. We may even want to do something like this for SMT so that * cpu 0 has the lowest thread contexts and cpu N has the highest, but * I'll just do this for now */ if (numThreads == 1) tc->setContextId(system->registerThreadContext(tc, _cpuId)); else tc->setContextId(system->registerThreadContext(tc)); #if !FULL_SYSTEM tc->getProcessPtr()->assignThreadContext(tc->contextId()); #endif } } int BaseCPU::findContext(ThreadContext *tc) { ThreadID size = threadContexts.size(); for (ThreadID tid = 0; tid < size; ++tid) { if (tc == threadContexts[tid]) return tid; } return 0; } void BaseCPU::switchOut() { // panic("This CPU doesn't support sampling!"); #if FULL_SYSTEM if (profileEvent && profileEvent->scheduled()) deschedule(profileEvent); #endif } void BaseCPU::takeOverFrom(BaseCPU *oldCPU, Port *ic, Port *dc) { assert(threadContexts.size() == oldCPU->threadContexts.size()); _cpuId = oldCPU->cpuId(); ThreadID size = threadContexts.size(); for (ThreadID i = 0; i < size; ++i) { ThreadContext *newTC = threadContexts[i]; ThreadContext *oldTC = oldCPU->threadContexts[i]; newTC->takeOverFrom(oldTC); CpuEvent::replaceThreadContext(oldTC, newTC); assert(newTC->contextId() == oldTC->contextId()); assert(newTC->threadId() == oldTC->threadId()); system->replaceThreadContext(newTC, newTC->contextId()); /* This code no longer works since the zero register (e.g., * r31 on Alpha) doesn't necessarily contain zero at this * point. if (DTRACE(Context)) ThreadContext::compare(oldTC, newTC); */ } #if FULL_SYSTEM interrupts = oldCPU->interrupts; interrupts->setCPU(this); for (ThreadID i = 0; i < size; ++i) threadContexts[i]->profileClear(); if (profileEvent) schedule(profileEvent, curTick); #endif // Connect new CPU to old CPU's memory only if new CPU isn't // connected to anything. Also connect old CPU's memory to new // CPU. if (!ic->isConnected()) { Port *peer = oldCPU->getPort("icache_port")->getPeer(); ic->setPeer(peer); peer->setPeer(ic); } if (!dc->isConnected()) { Port *peer = oldCPU->getPort("dcache_port")->getPeer(); dc->setPeer(peer); peer->setPeer(dc); } } #if FULL_SYSTEM BaseCPU::ProfileEvent::ProfileEvent(BaseCPU *_cpu, Tick _interval) : cpu(_cpu), interval(_interval) { } void BaseCPU::ProfileEvent::process() { ThreadID size = cpu->threadContexts.size(); for (ThreadID i = 0; i < size; ++i) { ThreadContext *tc = cpu->threadContexts[i]; tc->profileSample(); } cpu->schedule(this, curTick + interval); } void BaseCPU::serialize(std::ostream &os) { SERIALIZE_SCALAR(instCnt); interrupts->serialize(os); } void BaseCPU::unserialize(Checkpoint *cp, const std::string &section) { UNSERIALIZE_SCALAR(instCnt); interrupts->unserialize(cp, section); } #endif // FULL_SYSTEM void BaseCPU::traceFunctionsInternal(Addr pc) { if (!debugSymbolTable) return; // if pc enters different function, print new function symbol and // update saved range. Otherwise do nothing. if (pc < currentFunctionStart || pc >= currentFunctionEnd) { string sym_str; bool found = debugSymbolTable->findNearestSymbol(pc, sym_str, currentFunctionStart, currentFunctionEnd); if (!found) { // no symbol found: use addr as label sym_str = csprintf("0x%x", pc); currentFunctionStart = pc; currentFunctionEnd = pc + 1; } ccprintf(*functionTraceStream, " (%d)\n%d: %s", curTick - functionEntryTick, curTick, sym_str); functionEntryTick = curTick; } } <commit_msg>commit Soumyaroop's bug catch about max_insts_all_threads<commit_after>/* * Copyright (c) 2002-2005 The Regents of The University of Michigan * 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 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: Steve Reinhardt * Nathan Binkert */ #include <iostream> #include <string> #include <sstream> #include "base/cprintf.hh" #include "base/loader/symtab.hh" #include "base/misc.hh" #include "base/output.hh" #include "base/trace.hh" #include "cpu/base.hh" #include "cpu/cpuevent.hh" #include "cpu/thread_context.hh" #include "cpu/profile.hh" #include "params/BaseCPU.hh" #include "sim/sim_exit.hh" #include "sim/process.hh" #include "sim/sim_events.hh" #include "sim/system.hh" // Hack #include "sim/stat_control.hh" using namespace std; vector<BaseCPU *> BaseCPU::cpuList; // This variable reflects the max number of threads in any CPU. Be // careful to only use it once all the CPUs that you care about have // been initialized int maxThreadsPerCPU = 1; CPUProgressEvent::CPUProgressEvent(BaseCPU *_cpu, Tick ival) : Event(Event::Progress_Event_Pri), _interval(ival), lastNumInst(0), cpu(_cpu), _repeatEvent(true) { if (_interval) cpu->schedule(this, curTick + _interval); } void CPUProgressEvent::process() { Counter temp = cpu->totalInstructions(); #ifndef NDEBUG double ipc = double(temp - lastNumInst) / (_interval / cpu->ticks(1)); DPRINTFN("%s progress event, total committed:%i, progress insts committed: " "%lli, IPC: %0.8d\n", cpu->name(), temp, temp - lastNumInst, ipc); ipc = 0.0; #else cprintf("%lli: %s progress event, total committed:%i, progress insts " "committed: %lli\n", curTick, cpu->name(), temp, temp - lastNumInst); #endif lastNumInst = temp; if (_repeatEvent) cpu->schedule(this, curTick + _interval); } const char * CPUProgressEvent::description() const { return "CPU Progress"; } #if FULL_SYSTEM BaseCPU::BaseCPU(Params *p) : MemObject(p), clock(p->clock), instCnt(0), _cpuId(p->cpu_id), interrupts(p->interrupts), numThreads(p->numThreads), system(p->system), phase(p->phase) #else BaseCPU::BaseCPU(Params *p) : MemObject(p), clock(p->clock), _cpuId(p->cpu_id), numThreads(p->numThreads), system(p->system), phase(p->phase) #endif { // currentTick = curTick; // if Python did not provide a valid ID, do it here if (_cpuId == -1 ) { _cpuId = cpuList.size(); } // add self to global list of CPUs cpuList.push_back(this); DPRINTF(SyscallVerbose, "Constructing CPU with id %d\n", _cpuId); if (numThreads > maxThreadsPerCPU) maxThreadsPerCPU = numThreads; // allocate per-thread instruction-based event queues comInstEventQueue = new EventQueue *[numThreads]; for (ThreadID tid = 0; tid < numThreads; ++tid) comInstEventQueue[tid] = new EventQueue("instruction-based event queue"); // // set up instruction-count-based termination events, if any // if (p->max_insts_any_thread != 0) { const char *cause = "a thread reached the max instruction count"; for (ThreadID tid = 0; tid < numThreads; ++tid) { Event *event = new SimLoopExitEvent(cause, 0); comInstEventQueue[tid]->schedule(event, p->max_insts_any_thread); } } if (p->max_insts_all_threads != 0) { const char *cause = "all threads reached the max instruction count"; // allocate & initialize shared downcounter: each event will // decrement this when triggered; simulation will terminate // when counter reaches 0 int *counter = new int; *counter = numThreads; for (ThreadID tid = 0; tid < numThreads; ++tid) { Event *event = new CountedExitEvent(cause, *counter); comInstEventQueue[tid]->schedule(event, p->max_insts_all_threads); } } // allocate per-thread load-based event queues comLoadEventQueue = new EventQueue *[numThreads]; for (ThreadID tid = 0; tid < numThreads; ++tid) comLoadEventQueue[tid] = new EventQueue("load-based event queue"); // // set up instruction-count-based termination events, if any // if (p->max_loads_any_thread != 0) { const char *cause = "a thread reached the max load count"; for (ThreadID tid = 0; tid < numThreads; ++tid) { Event *event = new SimLoopExitEvent(cause, 0); comLoadEventQueue[tid]->schedule(event, p->max_loads_any_thread); } } if (p->max_loads_all_threads != 0) { const char *cause = "all threads reached the max load count"; // allocate & initialize shared downcounter: each event will // decrement this when triggered; simulation will terminate // when counter reaches 0 int *counter = new int; *counter = numThreads; for (ThreadID tid = 0; tid < numThreads; ++tid) { Event *event = new CountedExitEvent(cause, *counter); comLoadEventQueue[tid]->schedule(event, p->max_loads_all_threads); } } functionTracingEnabled = false; if (p->function_trace) { functionTraceStream = simout.find(csprintf("ftrace.%s", name())); currentFunctionStart = currentFunctionEnd = 0; functionEntryTick = p->function_trace_start; if (p->function_trace_start == 0) { functionTracingEnabled = true; } else { typedef EventWrapper<BaseCPU, &BaseCPU::enableFunctionTrace> wrap; Event *event = new wrap(this, true); schedule(event, p->function_trace_start); } } #if FULL_SYSTEM interrupts->setCPU(this); profileEvent = NULL; if (params()->profile) profileEvent = new ProfileEvent(this, params()->profile); #endif tracer = params()->tracer; } void BaseCPU::enableFunctionTrace() { functionTracingEnabled = true; } BaseCPU::~BaseCPU() { } void BaseCPU::init() { if (!params()->defer_registration) registerThreadContexts(); } void BaseCPU::startup() { #if FULL_SYSTEM if (!params()->defer_registration && profileEvent) schedule(profileEvent, curTick); #endif if (params()->progress_interval) { Tick num_ticks = ticks(params()->progress_interval); Event *event; event = new CPUProgressEvent(this, num_ticks); } } void BaseCPU::regStats() { using namespace Stats; numCycles .name(name() + ".numCycles") .desc("number of cpu cycles simulated") ; int size = threadContexts.size(); if (size > 1) { for (int i = 0; i < size; ++i) { stringstream namestr; ccprintf(namestr, "%s.ctx%d", name(), i); threadContexts[i]->regStats(namestr.str()); } } else if (size == 1) threadContexts[0]->regStats(name()); #if FULL_SYSTEM #endif } Tick BaseCPU::nextCycle() { Tick next_tick = curTick - phase + clock - 1; next_tick -= (next_tick % clock); next_tick += phase; return next_tick; } Tick BaseCPU::nextCycle(Tick begin_tick) { Tick next_tick = begin_tick; if (next_tick % clock != 0) next_tick = next_tick - (next_tick % clock) + clock; next_tick += phase; assert(next_tick >= curTick); return next_tick; } void BaseCPU::registerThreadContexts() { ThreadID size = threadContexts.size(); for (ThreadID tid = 0; tid < size; ++tid) { ThreadContext *tc = threadContexts[tid]; /** This is so that contextId and cpuId match where there is a * 1cpu:1context relationship. Otherwise, the order of registration * could affect the assignment and cpu 1 could have context id 3, for * example. We may even want to do something like this for SMT so that * cpu 0 has the lowest thread contexts and cpu N has the highest, but * I'll just do this for now */ if (numThreads == 1) tc->setContextId(system->registerThreadContext(tc, _cpuId)); else tc->setContextId(system->registerThreadContext(tc)); #if !FULL_SYSTEM tc->getProcessPtr()->assignThreadContext(tc->contextId()); #endif } } int BaseCPU::findContext(ThreadContext *tc) { ThreadID size = threadContexts.size(); for (ThreadID tid = 0; tid < size; ++tid) { if (tc == threadContexts[tid]) return tid; } return 0; } void BaseCPU::switchOut() { // panic("This CPU doesn't support sampling!"); #if FULL_SYSTEM if (profileEvent && profileEvent->scheduled()) deschedule(profileEvent); #endif } void BaseCPU::takeOverFrom(BaseCPU *oldCPU, Port *ic, Port *dc) { assert(threadContexts.size() == oldCPU->threadContexts.size()); _cpuId = oldCPU->cpuId(); ThreadID size = threadContexts.size(); for (ThreadID i = 0; i < size; ++i) { ThreadContext *newTC = threadContexts[i]; ThreadContext *oldTC = oldCPU->threadContexts[i]; newTC->takeOverFrom(oldTC); CpuEvent::replaceThreadContext(oldTC, newTC); assert(newTC->contextId() == oldTC->contextId()); assert(newTC->threadId() == oldTC->threadId()); system->replaceThreadContext(newTC, newTC->contextId()); /* This code no longer works since the zero register (e.g., * r31 on Alpha) doesn't necessarily contain zero at this * point. if (DTRACE(Context)) ThreadContext::compare(oldTC, newTC); */ } #if FULL_SYSTEM interrupts = oldCPU->interrupts; interrupts->setCPU(this); for (ThreadID i = 0; i < size; ++i) threadContexts[i]->profileClear(); if (profileEvent) schedule(profileEvent, curTick); #endif // Connect new CPU to old CPU's memory only if new CPU isn't // connected to anything. Also connect old CPU's memory to new // CPU. if (!ic->isConnected()) { Port *peer = oldCPU->getPort("icache_port")->getPeer(); ic->setPeer(peer); peer->setPeer(ic); } if (!dc->isConnected()) { Port *peer = oldCPU->getPort("dcache_port")->getPeer(); dc->setPeer(peer); peer->setPeer(dc); } } #if FULL_SYSTEM BaseCPU::ProfileEvent::ProfileEvent(BaseCPU *_cpu, Tick _interval) : cpu(_cpu), interval(_interval) { } void BaseCPU::ProfileEvent::process() { ThreadID size = cpu->threadContexts.size(); for (ThreadID i = 0; i < size; ++i) { ThreadContext *tc = cpu->threadContexts[i]; tc->profileSample(); } cpu->schedule(this, curTick + interval); } void BaseCPU::serialize(std::ostream &os) { SERIALIZE_SCALAR(instCnt); interrupts->serialize(os); } void BaseCPU::unserialize(Checkpoint *cp, const std::string &section) { UNSERIALIZE_SCALAR(instCnt); interrupts->unserialize(cp, section); } #endif // FULL_SYSTEM void BaseCPU::traceFunctionsInternal(Addr pc) { if (!debugSymbolTable) return; // if pc enters different function, print new function symbol and // update saved range. Otherwise do nothing. if (pc < currentFunctionStart || pc >= currentFunctionEnd) { string sym_str; bool found = debugSymbolTable->findNearestSymbol(pc, sym_str, currentFunctionStart, currentFunctionEnd); if (!found) { // no symbol found: use addr as label sym_str = csprintf("0x%x", pc); currentFunctionStart = pc; currentFunctionEnd = pc + 1; } ccprintf(*functionTraceStream, " (%d)\n%d: %s", curTick - functionEntryTick, curTick, sym_str); functionEntryTick = curTick; } } <|endoftext|>
<commit_before>#include <gmi_mesh.h> #include <apfMDS.h> #include <apfMesh2.h> #include <apf.h> #include <PCU.h> int main(int argc, char** argv) { assert(argc==3); MPI_Init(&argc,&argv); PCU_Comm_Init(); gmi_register_mesh(); apf::Mesh2* m = apf::loadMdsMesh(argv[1],argv[2]); m->verify(); m->destroyNative(); apf::destroyMesh(m); PCU_Comm_Free(); MPI_Finalize(); } <commit_msg>allow verify.cc to use simmetrix models<commit_after>#include <gmi_mesh.h> #include <gmi_sim.h> #include <apfMDS.h> #include <apfMesh2.h> #include <apf.h> #include <PCU.h> #include <SimUtil.h> #include <SimModel.h> int main(int argc, char** argv) { assert(argc==3); MPI_Init(&argc,&argv); PCU_Comm_Init(); Sim_readLicenseFile(0); SimModel_start(); gmi_register_mesh(); gmi_register_sim(); apf::Mesh2* m = apf::loadMdsMesh(argv[1],argv[2]); m->verify(); m->destroyNative(); apf::destroyMesh(m); SimModel_stop(); Sim_unregisterAllKeys(); PCU_Comm_Free(); MPI_Finalize(); } <|endoftext|>
<commit_before>#ifndef _GRL_REALTIME_HPP_ #define _GRL_REALTIME_HPP_ #ifdef __APPLE__ #include <mach/mach.h> #include <mach/mach_time.h> #include <mach/mach_init.h> #include <mach/thread_policy.h> #include <mach/sched.h> #include <pthread.h> #include <unistd.h> #include <err.h> #include <sys/param.h> static inline uint64_t nanos_to_abs(uint64_t ns, uint32_t numer, uint32_t denom) { return (uint64_t)(ns * (((double)denom) / ((double)numer))); } /** * THREAD_TIME_CONSTRAINT_POLICY: * * This scheduling mode is for threads which have real time * constraints on their execution. * * Parameters: * * @param period: This is the nominal amount of time between separate * processing arrivals, specified in absolute time units. A * value of 0 indicates that there is no inherent periodicity in * the computation. (nanoseconds) * * @param computation: This is the nominal amount of computation * time needed during a separate processing arrival, specified * in absolute time units. (nanoseconds) * * @param constraint: This is the maximum amount of real time that * may elapse from the start of a separate processing arrival * to the end of computation for logically correct functioning, * specified in absolute time units. Must be (>= computation). * Note that latency = (constraint - computation). (nanoseconds) * * @param preemptible: This indicates that the computation may be * interrupted, subject to the constraint specified above * Should almost always be false unless you really need it. (bool) * * @see http://www.opensource.apple.com/source/xnu/xnu-2050.18.24/tools/tests/xnu_quick_test/sched_tests.c * @see https://developer.apple.com/library/mac/documentation/Darwin/Conceptual/KernelProgramming/scheduler/scheduler.html */ inline int set_realtime(int period, int computation, int constraint, bool preemptible = false) { struct mach_timebase_info mti; struct thread_time_constraint_policy ttcpolicy; kern_return_t kret; kret = mach_timebase_info(&mti); if (kret != KERN_SUCCESS) { warnx("Could not get timebase info %d", kret); return; } thread_port_t threadport = pthread_mach_thread_np(pthread_self()); ttcpolicy.period = nanos_to_abs(period, mti.numer, mti.denom); ttcpolicy.computation = nanos_to_abs(computation, mti.numer, mti.denom); // HZ/3300; ttcpolicy.constraint = nanos_to_abs(constraint, mti.numer, mti.denom); // HZ/2200; ttcpolicy.preemptible = preemptible; if ((kret=thread_policy_set(threadport, THREAD_TIME_CONSTRAINT_POLICY, (thread_policy_t)&ttcpolicy, THREAD_TIME_CONSTRAINT_POLICY_COUNT)) != KERN_SUCCESS) { fprintf(stderr, "set_realtime() failed.\n"); warnx("Failed to set_realtime %d", kret); return 0; } return 1; } #endif // __APPLE__ #endif<commit_msg>small changes to realtime.hpp<commit_after>#ifndef _GRL_REALTIME_HPP_ #define _GRL_REALTIME_HPP_ #ifdef __APPLE__ #include <mach/mach.h> #include <mach/mach_time.h> #include <mach/mach_init.h> #include <mach/thread_policy.h> //#include <mach/sched.h> #include <pthread.h> #include <unistd.h> #include <err.h> #include <sys/param.h> static inline uint64_t nanos_to_abs(uint64_t ns, uint32_t numer, uint32_t denom) { return (uint64_t)(ns * (((double)denom) / ((double)numer))); } /** * THREAD_TIME_CONSTRAINT_POLICY: * * This scheduling mode is for threads which have real time * constraints on their execution. * * Parameters: * * @param period: This is the nominal amount of time between separate * processing arrivals, specified in absolute time units. A * value of 0 indicates that there is no inherent periodicity in * the computation. (nanoseconds) * * @param computation: This is the nominal amount of computation * time needed during a separate processing arrival, specified * in absolute time units. (nanoseconds) * * @param constraint: This is the maximum amount of real time that * may elapse from the start of a separate processing arrival * to the end of computation for logically correct functioning, * specified in absolute time units. Must be (>= computation). * Note that latency = (constraint - computation). (nanoseconds) * * @param preemptible: This indicates that the computation may be * interrupted, subject to the constraint specified above * Should almost always be false unless you really need it. (bool) * * @see http://www.opensource.apple.com/source/xnu/xnu-2050.18.24/tools/tests/xnu_quick_test/sched_tests.c * @see https://developer.apple.com/library/mac/documentation/Darwin/Conceptual/KernelProgramming/scheduler/scheduler.html */ inline int set_realtime(int period, int computation, int constraint, bool preemptible = false) { struct mach_timebase_info mti; struct thread_time_constraint_policy ttcpolicy; kern_return_t kret; kret = mach_timebase_info(&mti); if (kret != KERN_SUCCESS) { warnx("Could not get timebase info %d", kret); return 0; } thread_port_t threadport = pthread_mach_thread_np(pthread_self()); ttcpolicy.period = nanos_to_abs(period, mti.numer, mti.denom); ttcpolicy.computation = nanos_to_abs(computation, mti.numer, mti.denom); // HZ/3300; ttcpolicy.constraint = nanos_to_abs(constraint, mti.numer, mti.denom); // HZ/2200; ttcpolicy.preemptible = preemptible; if ((kret=thread_policy_set(threadport, THREAD_TIME_CONSTRAINT_POLICY, (thread_policy_t)&ttcpolicy, THREAD_TIME_CONSTRAINT_POLICY_COUNT)) != KERN_SUCCESS) { fprintf(stderr, "set_realtime() failed.\n"); warnx("Failed to set_realtime %d", kret); return 0; } return 1; } #endif // __APPLE__ #endif<|endoftext|>
<commit_before>#include <boost/asio.hpp> #include <boost/bind.hpp> #include <boost/lambda/lambda.hpp> #include <boost/lambda/construct.hpp> #include <libport/thread.hh> namespace libport { namespace netdetail { #ifndef LIBPORT_NO_SSL struct SSLSettings { boost::asio::ssl::context_base::method context; boost::asio::ssl::context::options options; std::string privateKeyFile; std::string certChainFile; std::string tmpDHFile; std::string cipherList; }; #endif template<class T> struct SocketFromAcceptor { typedef typename T::protocol_type::socket type; }; // FIXME: use the delete_ptr in boost::lambda. template<class T> void deletor(T* ptr) { delete ptr; } inline void runIoService(boost::asio::io_service* io) { // Trick to boost::asio::io_service::work work(*io); io->run(); } inline boost::asio::io_service& get_io_service() { static boost::asio::io_service* io = 0; if (!io) { io = new boost::asio::io_service; libport::startThread(boost::bind(&runIoService, io)); } std::cerr << "ioserv is " << io << std::endl; return *io; } template<typename SocketPtr> void socketClose(SocketPtr s) { s->lowest_layer().close(); } template<typename SocketPtr> void socketWrite(SocketPtr s, void* data, int sz) { boost::asio::streambuf* request = new boost::asio::streambuf(); std::ostream request_stream(request); request_stream.write((char*)data, sz); boost::asio::async_write (*s, *request, boost::bind(&deletor<boost::asio::streambuf>, request)); } template<typename SocketPtr> bool onReadDemux(BaseSocket* bs, SocketPtr, boost::asio::streambuf& buf, boost::system::error_code erc) { if (erc) { bs->connected_ = false; std::cerr << "readdemux error " << erc.message() << std::endl; bs->onErrorFunc(erc); return false; } else { bs->onReadFunc(buf); return true; } } template<typename SocketPtr, typename Buf> void readOne (boost::system::error_code erc, SocketPtr s, boost::function3<bool, SocketPtr, boost::asio::streambuf&, boost::system::error_code> onRead, Buf buf ) { std::cerr << "ReadOne"<< std::endl; if (onRead(s, *buf, erc)) { std::cerr << "async_read(readone)" << std::endl; boost::asio::async_read(*s, *buf, boost::asio::transfer_at_least(1), boost::bind(&readOne<SocketPtr, Buf>, _1, s, onRead, buf)); } } template<typename SocketPtr> void runReader (SocketPtr s, boost::function3<bool, SocketPtr, boost::asio::streambuf&, boost::system::error_code> onRead ) { std::cerr <<"runreader on " << s.get() << std::endl; typedef boost::shared_ptr<boost::asio::streambuf> Buf; Buf buf(new boost::asio::streambuf); boost::asio::async_read(*s, *buf, boost::asio::transfer_at_least(1), boost::bind(&readOne<SocketPtr, Buf>, _1, s, onRead, buf)); } template<typename SocketPtr> bool onAccept(SocketPtr sock, SocketFactory fact) { BaseSocket* s = fact(); if (!s) return false; s->close = boost::bind(&socketClose<SocketPtr>, sock); s->write = boost::bind(&socketWrite<SocketPtr>, sock, _1, _2); runReader<SocketPtr>(sock, boost::bind(&onReadDemux<SocketPtr>, s, _1, _2, _3)); return true; } #ifndef LIBPORT_NO_SSL template<typename SocketPtr> bool onAcceptSSL(SocketPtr sock, SocketFactory fact, SSLSettings settings) { using namespace boost::asio; boost::system::error_code erc; ssl::context context(sock->get_io_service(), boost::asio::ssl::context::sslv23_server); context.set_options(settings.options); if (!settings.cipherList.empty()) { SSL_CTX* ctx = context.impl(); if (!SSL_CTX_set_cipher_list(ctx, settings.cipherList.c_str())) throw std::runtime_error("SSL_CTX_set_cipher_list failed"); } #define comma , #define CHECK_CALL(param, call, args) do \ if (!param.empty()) { call(param, args erc); if (erc) throw erc;} while(0) CHECK_CALL(settings.tmpDHFile, context.use_tmp_dh_file, ); CHECK_CALL(settings.certChainFile, context.use_certificate_chain_file, ); CHECK_CALL(settings.privateKeyFile, context.use_private_key_file, ssl::context_base::pem comma); #undef CHECK_CALL typedef boost::shared_ptr<ssl::stream<typename SocketPtr::element_type&> > SSLSocketPtr; SSLSocketPtr sslSock( new boost::asio::ssl::stream<typename SocketPtr::element_type&>(*sock, context)); sslSock->handshake(sslSock->server, erc); if (erc) { /// FIXME: add error reporting mechanism. std::cerr << "Handshake error " << erc.message() << std::endl; return true; } BaseSocket* s = fact(); if (!s) return true; s->close = boost::bind(&socketClose<SSLSocketPtr>, sslSock); s->write = boost::bind(&socketWrite<SSLSocketPtr>, sslSock, _1, _2); // At the end of this function, sock will die. So keep a sharedptr on it, // and destroy it when the BaseSocket dies. SocketPtr* sockHandle = new SocketPtr(sock); s->deletor << boost::bind(&deletor<SocketPtr>, sockHandle); runReader<SSLSocketPtr>(sslSock, boost::bind(&onReadDemux<SSLSocketPtr>, s, _1, _2, _3)); return true; } #endif template<typename Acceptor, typename CB> void acceptOne (Acceptor& a, CB onAccept, boost::shared_ptr<typename netdetail::SocketFromAcceptor<Acceptor>::type> s, const boost::system::error_code& error) { if (!error && onAccept(s)) { boost::shared_ptr<typename SocketFromAcceptor<Acceptor>::type> sptr (new typename SocketFromAcceptor<Acceptor>::type(a.get_io_service())); a.async_accept(*sptr.get(), boost::bind(&acceptOne<Acceptor, CB>, boost::ref(a), onAccept, sptr, _1)); } } template<typename Acceptor, typename CB> void runAcceptor(Acceptor& a, CB onAccept) { boost::shared_ptr<typename SocketFromAcceptor<Acceptor>::type> sptr (new typename SocketFromAcceptor<Acceptor>::type(a.get_io_service())); a.async_accept(*sptr.get(), boost::bind(&acceptOne<Acceptor, CB>, boost::ref(a), onAccept, sptr, _1)); } } //namespace netdetail inline void BaseSocket::destroy() { netdetail::get_io_service().post(boost::bind( netdetail::deletor<BaseSocket>, this)); //std::cerr <<"Done posting destroy message on " << (void*)this << std::endl; } inline Socket::Socket() { onReadFunc = boost::bind(&Socket::onRead_, this, _1); onErrorFunc = boost::bind(&Socket::onError, this, _1); } inline bool Socket::onRead_(boost::asio::streambuf& buf) { // Dump the stream in our linear buffer std::istream is(&buf); while (true) { int c = is.get(); if (!is.good()) break; buffer += (char)c; } // Call unread until it eats 0 characters. int r; do { r = onRead(buffer.c_str(), buffer.length()); if (r) buffer = buffer.substr(r, buffer.npos); } while(r && !buffer.empty()); return true; } inline boost::system::error_code BaseSocket::connect(const std::string& host, const std::string& port, bool) { using namespace netdetail; typedef boost::shared_ptr<boost::asio::ip::tcp::socket> SocketPtr; SocketPtr ptr(new SocketPtr::element_type(netdetail::get_io_service())); boost::asio::ip::tcp::resolver::query query(host, port); boost::system::error_code erc; boost::asio::ip::tcp::resolver resolver(netdetail::get_io_service()); boost::asio::ip::tcp::resolver::iterator iter = resolver.resolve(query,erc); if (erc) { std::cerr << "Resolver error " << std::endl; return erc; } ptr->connect(*iter, erc); if (erc) return erc; this->close = boost::bind(&socketClose<SocketPtr>, ptr); this->write = boost::bind(&socketWrite<SocketPtr>, ptr, _1, _2); boost::function3<bool, SocketPtr, boost::asio::streambuf&, boost::system::error_code> f = boost::bind(&onReadDemux<SocketPtr>, this, _1, _2, _3); netdetail::runReader<SocketPtr>(ptr,f); connected_ = true; return boost::system::error_code(); } inline Handle listenTCP(SocketFactory f, const std::string& , int port) { boost::asio::io_service& io = netdetail::get_io_service(); typedef boost::shared_ptr<boost::asio::ip::tcp::socket> SocketPtr; boost::asio::ip::tcp::acceptor* acceptor = new boost::asio::ip::tcp::acceptor (io, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port)); boost::function1<bool, SocketPtr> adapter = boost::bind (&netdetail::onAccept<SocketPtr>, _1, f); netdetail::runAcceptor(*acceptor, adapter); return 0; } #ifndef LIBPORT_NO_SSL inline Handle listenSSL(SocketFactory f, const std::string& , int port, boost::asio::ssl::context_base::method ctx, boost::asio::ssl::context::options options, const std::string& privateKeyFile, const std::string& certChainFile, const std::string& tmpDHFile, const std::string& cipherList) { netdetail::SSLSettings settings; settings.context = ctx; settings.options = options; settings.privateKeyFile = privateKeyFile; settings.certChainFile = certChainFile; settings.tmpDHFile = tmpDHFile; settings.cipherList = cipherList; boost::asio::io_service& io = netdetail::get_io_service(); typedef boost::shared_ptr<boost::asio::ip::tcp::socket> SocketPtr; boost::asio::ip::tcp::acceptor* acceptor = new boost::asio::ip::tcp::acceptor (io, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port)); boost::function1<bool, SocketPtr> adapter = boost::bind (&netdetail::onAcceptSSL<SocketPtr>, _1, f, settings); netdetail::runAcceptor(*acceptor, adapter); return 0; } #endif inline Handle listen(SocketFactory f, const std::string& host, int port, bool udp) { if (!udp) return listenTCP(f, host, port); else return 0; } } <commit_msg>Remove debug messages in nominal case.<commit_after>#include <boost/asio.hpp> #include <boost/bind.hpp> #include <boost/lambda/lambda.hpp> #include <boost/lambda/construct.hpp> #include <libport/thread.hh> namespace libport { namespace netdetail { #ifndef LIBPORT_NO_SSL struct SSLSettings { boost::asio::ssl::context_base::method context; boost::asio::ssl::context::options options; std::string privateKeyFile; std::string certChainFile; std::string tmpDHFile; std::string cipherList; }; #endif template<class T> struct SocketFromAcceptor { typedef typename T::protocol_type::socket type; }; // FIXME: use the delete_ptr in boost::lambda. template<class T> void deletor(T* ptr) { delete ptr; } inline void runIoService(boost::asio::io_service* io) { // Trick to boost::asio::io_service::work work(*io); io->run(); } inline boost::asio::io_service& get_io_service() { static boost::asio::io_service* io = 0; if (!io) { io = new boost::asio::io_service; libport::startThread(boost::bind(&runIoService, io)); } return *io; } template<typename SocketPtr> void socketClose(SocketPtr s) { s->lowest_layer().close(); } template<typename SocketPtr> void socketWrite(SocketPtr s, void* data, int sz) { boost::asio::streambuf* request = new boost::asio::streambuf(); std::ostream request_stream(request); request_stream.write((char*)data, sz); boost::asio::async_write (*s, *request, boost::bind(&deletor<boost::asio::streambuf>, request)); } template<typename SocketPtr> bool onReadDemux(BaseSocket* bs, SocketPtr, boost::asio::streambuf& buf, boost::system::error_code erc) { if (erc) { bs->connected_ = false; std::cerr << "readdemux error " << erc.message() << std::endl; bs->onErrorFunc(erc); return false; } else { bs->onReadFunc(buf); return true; } } template<typename SocketPtr, typename Buf> void readOne (boost::system::error_code erc, SocketPtr s, boost::function3<bool, SocketPtr, boost::asio::streambuf&, boost::system::error_code> onRead, Buf buf ) { if (onRead(s, *buf, erc)) { boost::asio::async_read(*s, *buf, boost::asio::transfer_at_least(1), boost::bind(&readOne<SocketPtr, Buf>, _1, s, onRead, buf)); } } template<typename SocketPtr> void runReader (SocketPtr s, boost::function3<bool, SocketPtr, boost::asio::streambuf&, boost::system::error_code> onRead ) { typedef boost::shared_ptr<boost::asio::streambuf> Buf; Buf buf(new boost::asio::streambuf); boost::asio::async_read(*s, *buf, boost::asio::transfer_at_least(1), boost::bind(&readOne<SocketPtr, Buf>, _1, s, onRead, buf)); } template<typename SocketPtr> bool onAccept(SocketPtr sock, SocketFactory fact) { BaseSocket* s = fact(); if (!s) return false; s->close = boost::bind(&socketClose<SocketPtr>, sock); s->write = boost::bind(&socketWrite<SocketPtr>, sock, _1, _2); runReader<SocketPtr>(sock, boost::bind(&onReadDemux<SocketPtr>, s, _1, _2, _3)); return true; } #ifndef LIBPORT_NO_SSL template<typename SocketPtr> bool onAcceptSSL(SocketPtr sock, SocketFactory fact, SSLSettings settings) { using namespace boost::asio; boost::system::error_code erc; ssl::context context(sock->get_io_service(), boost::asio::ssl::context::sslv23_server); context.set_options(settings.options); if (!settings.cipherList.empty()) { SSL_CTX* ctx = context.impl(); if (!SSL_CTX_set_cipher_list(ctx, settings.cipherList.c_str())) throw std::runtime_error("SSL_CTX_set_cipher_list failed"); } #define comma , #define CHECK_CALL(param, call, args) do \ if (!param.empty()) { call(param, args erc); if (erc) throw erc;} while(0) CHECK_CALL(settings.tmpDHFile, context.use_tmp_dh_file, ); CHECK_CALL(settings.certChainFile, context.use_certificate_chain_file, ); CHECK_CALL(settings.privateKeyFile, context.use_private_key_file, ssl::context_base::pem comma); #undef CHECK_CALL typedef boost::shared_ptr<ssl::stream<typename SocketPtr::element_type&> > SSLSocketPtr; SSLSocketPtr sslSock( new boost::asio::ssl::stream<typename SocketPtr::element_type&>(*sock, context)); sslSock->handshake(sslSock->server, erc); if (erc) { /// FIXME: add error reporting mechanism. std::cerr << "Handshake error " << erc.message() << std::endl; return true; } BaseSocket* s = fact(); if (!s) return true; s->close = boost::bind(&socketClose<SSLSocketPtr>, sslSock); s->write = boost::bind(&socketWrite<SSLSocketPtr>, sslSock, _1, _2); // At the end of this function, sock will die. So keep a sharedptr on it, // and destroy it when the BaseSocket dies. SocketPtr* sockHandle = new SocketPtr(sock); s->deletor << boost::bind(&deletor<SocketPtr>, sockHandle); runReader<SSLSocketPtr>(sslSock, boost::bind(&onReadDemux<SSLSocketPtr>, s, _1, _2, _3)); return true; } #endif template<typename Acceptor, typename CB> void acceptOne (Acceptor& a, CB onAccept, boost::shared_ptr<typename netdetail::SocketFromAcceptor<Acceptor>::type> s, const boost::system::error_code& error) { if (!error && onAccept(s)) { boost::shared_ptr<typename SocketFromAcceptor<Acceptor>::type> sptr (new typename SocketFromAcceptor<Acceptor>::type(a.get_io_service())); a.async_accept(*sptr.get(), boost::bind(&acceptOne<Acceptor, CB>, boost::ref(a), onAccept, sptr, _1)); } } template<typename Acceptor, typename CB> void runAcceptor(Acceptor& a, CB onAccept) { boost::shared_ptr<typename SocketFromAcceptor<Acceptor>::type> sptr (new typename SocketFromAcceptor<Acceptor>::type(a.get_io_service())); a.async_accept(*sptr.get(), boost::bind(&acceptOne<Acceptor, CB>, boost::ref(a), onAccept, sptr, _1)); } } //namespace netdetail inline void BaseSocket::destroy() { netdetail::get_io_service().post(boost::bind( netdetail::deletor<BaseSocket>, this)); //std::cerr <<"Done posting destroy message on " << (void*)this << std::endl; } inline Socket::Socket() { onReadFunc = boost::bind(&Socket::onRead_, this, _1); onErrorFunc = boost::bind(&Socket::onError, this, _1); } inline bool Socket::onRead_(boost::asio::streambuf& buf) { // Dump the stream in our linear buffer std::istream is(&buf); while (true) { int c = is.get(); if (!is.good()) break; buffer += (char)c; } // Call unread until it eats 0 characters. int r; do { r = onRead(buffer.c_str(), buffer.length()); if (r) buffer = buffer.substr(r, buffer.npos); } while(r && !buffer.empty()); return true; } inline boost::system::error_code BaseSocket::connect(const std::string& host, const std::string& port, bool) { using namespace netdetail; typedef boost::shared_ptr<boost::asio::ip::tcp::socket> SocketPtr; SocketPtr ptr(new SocketPtr::element_type(netdetail::get_io_service())); boost::asio::ip::tcp::resolver::query query(host, port); boost::system::error_code erc; boost::asio::ip::tcp::resolver resolver(netdetail::get_io_service()); boost::asio::ip::tcp::resolver::iterator iter = resolver.resolve(query,erc); if (erc) { std::cerr << "Resolver error " << std::endl; return erc; } ptr->connect(*iter, erc); if (erc) return erc; this->close = boost::bind(&socketClose<SocketPtr>, ptr); this->write = boost::bind(&socketWrite<SocketPtr>, ptr, _1, _2); boost::function3<bool, SocketPtr, boost::asio::streambuf&, boost::system::error_code> f = boost::bind(&onReadDemux<SocketPtr>, this, _1, _2, _3); netdetail::runReader<SocketPtr>(ptr,f); connected_ = true; return boost::system::error_code(); } inline Handle listenTCP(SocketFactory f, const std::string& , int port) { boost::asio::io_service& io = netdetail::get_io_service(); typedef boost::shared_ptr<boost::asio::ip::tcp::socket> SocketPtr; boost::asio::ip::tcp::acceptor* acceptor = new boost::asio::ip::tcp::acceptor (io, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port)); boost::function1<bool, SocketPtr> adapter = boost::bind (&netdetail::onAccept<SocketPtr>, _1, f); netdetail::runAcceptor(*acceptor, adapter); return 0; } #ifndef LIBPORT_NO_SSL inline Handle listenSSL(SocketFactory f, const std::string& , int port, boost::asio::ssl::context_base::method ctx, boost::asio::ssl::context::options options, const std::string& privateKeyFile, const std::string& certChainFile, const std::string& tmpDHFile, const std::string& cipherList) { netdetail::SSLSettings settings; settings.context = ctx; settings.options = options; settings.privateKeyFile = privateKeyFile; settings.certChainFile = certChainFile; settings.tmpDHFile = tmpDHFile; settings.cipherList = cipherList; boost::asio::io_service& io = netdetail::get_io_service(); typedef boost::shared_ptr<boost::asio::ip::tcp::socket> SocketPtr; boost::asio::ip::tcp::acceptor* acceptor = new boost::asio::ip::tcp::acceptor (io, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port)); boost::function1<bool, SocketPtr> adapter = boost::bind (&netdetail::onAcceptSSL<SocketPtr>, _1, f, settings); netdetail::runAcceptor(*acceptor, adapter); return 0; } #endif inline Handle listen(SocketFactory f, const std::string& host, int port, bool udp) { if (!udp) return listenTCP(f, host, port); else return 0; } } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 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 * *****************************************************************************/ //$Id$ #ifndef VALUE_HPP #define VALUE_HPP // mapnik #include <mapnik/unicode.hpp> #include <mapnik/config_error.hpp> // boost #include <boost/variant.hpp> #include <boost/scoped_array.hpp> // stl #include <iostream> #include <string> #include <sstream> #include <iomanip> // uci #include <unicode/unistr.h> #include <unicode/ustring.h> namespace mapnik { inline void to_utf8(UnicodeString const& input, std::string & target) { if (input.length() == 0) return; const int BUF_SIZE = 256; char buf [BUF_SIZE]; int len; UErrorCode err = U_ZERO_ERROR; u_strToUTF8(buf, BUF_SIZE, &len, input.getBuffer(), input.length(), &err); if (err == U_BUFFER_OVERFLOW_ERROR || err == U_STRING_NOT_TERMINATED_WARNING ) { boost::scoped_array<char> buf_ptr(new char [len+1]); err = U_ZERO_ERROR; u_strToUTF8(buf_ptr.get() , len + 1, &len, input.getBuffer(), input.length(), &err); target.assign(buf_ptr.get() , len); } else { target.assign(buf, len); } } struct value_null { }; typedef boost::variant<value_null,bool,int,double,UnicodeString> value_base; namespace impl { struct equals : public boost::static_visitor<bool> { template <typename T, typename U> bool operator() (const T &, const U &) const { return false; } template <typename T> bool operator() (T lhs, T rhs) const { return lhs == rhs; } bool operator() (int lhs, double rhs) const { return lhs == rhs; } bool operator() (double lhs, int rhs) const { return lhs == rhs; } bool operator() (UnicodeString const& lhs, UnicodeString const& rhs) const { return lhs == rhs; } bool operator() (value_null, value_null) const { return false; } }; struct not_equals : public boost::static_visitor<bool> { template <typename T, typename U> bool operator() (const T &, const U &) const { return true; } template <typename T> bool operator() (T lhs, T rhs) const { return lhs != rhs; } bool operator() (int lhs, double rhs) const { return lhs != rhs; } bool operator() (double lhs, int rhs) const { return lhs != rhs; } bool operator() (UnicodeString const& lhs, UnicodeString const& rhs) const { return lhs != rhs; } bool operator() (value_null, value_null) const { return false; } template <typename T> bool operator() (value_null, const T &) const { return false; } template <typename T> bool operator() (const T &, value_null) const { return false; } }; struct greater_than : public boost::static_visitor<bool> { template <typename T, typename U> bool operator()(const T &, const U &) const { return false; } template <typename T> bool operator()(T lhs, T rhs) const { return lhs > rhs; } bool operator() (int lhs, double rhs) const { return lhs > rhs; } bool operator() (double lhs, int rhs) const { return lhs > rhs; } bool operator() (UnicodeString const& lhs, UnicodeString const& rhs) const { return lhs > rhs; } bool operator() (value_null, value_null) const { return false; } }; struct greater_or_equal : public boost::static_visitor<bool> { template <typename T, typename U> bool operator()(const T &, const U &) const { return false; } template <typename T> bool operator() (T lhs, T rhs) const { return lhs >= rhs; } bool operator() (int lhs, double rhs) const { return lhs >= rhs; } bool operator() (double lhs, int rhs) const { return lhs >= rhs; } bool operator() (UnicodeString const& lhs, UnicodeString const& rhs) const { return lhs >= rhs; } bool operator() (value_null, value_null) const { return false; } }; struct less_than : public boost::static_visitor<bool> { template <typename T, typename U> bool operator()(const T &, const U &) const { return false; } template <typename T> bool operator()(T lhs, T rhs) const { return lhs < rhs; } bool operator() (int lhs, double rhs) const { return lhs < rhs; } bool operator() (double lhs, int rhs) const { return lhs < rhs; } bool operator()(UnicodeString const& lhs, UnicodeString const& rhs ) const { return lhs < rhs; } bool operator() (value_null, value_null) const { return false; } }; struct less_or_equal : public boost::static_visitor<bool> { template <typename T, typename U> bool operator()(const T &, const U &) const { return false; } template <typename T> bool operator()(T lhs, T rhs) const { return lhs <= rhs; } bool operator() (int lhs, double rhs) const { return lhs <= rhs; } bool operator() (double lhs, int rhs) const { return lhs <= rhs; } template <typename T> bool operator()(UnicodeString const& lhs, UnicodeString const& rhs ) const { return lhs <= rhs; } bool operator() (value_null, value_null) const { return false; } }; template <typename V> struct add : public boost::static_visitor<V> { typedef V value_type; template <typename T1, typename T2> value_type operator() (T1 const& lhs, T2 const&) const { return lhs; } template <typename T> value_type operator() (T lhs, T rhs) const { return lhs + rhs ; } value_type operator() (UnicodeString const& lhs , UnicodeString const& rhs ) const { return lhs + rhs; } value_type operator() (double lhs, int rhs) const { return lhs + rhs; } value_type operator() (int lhs, double rhs) const { return lhs + rhs; } }; template <typename V> struct sub : public boost::static_visitor<V> { typedef V value_type; template <typename T1, typename T2> value_type operator() (T1 const& lhs, T2 const&) const { return lhs; } template <typename T> value_type operator() (T lhs, T rhs) const { return lhs - rhs ; } value_type operator() (UnicodeString const& lhs, UnicodeString const& ) const { return lhs; } value_type operator() (double lhs, int rhs) const { return lhs - rhs; } value_type operator() (int lhs, double rhs) const { return lhs - rhs; } }; template <typename V> struct mult : public boost::static_visitor<V> { typedef V value_type; template <typename T1, typename T2> value_type operator() (T1 const& lhs , T2 const& ) const { return lhs; } template <typename T> value_type operator() (T lhs, T rhs) const { return lhs * rhs; } value_type operator() (UnicodeString const& lhs, UnicodeString const& ) const { return lhs; } value_type operator() (double lhs, int rhs) const { return lhs * rhs; } value_type operator() (int lhs, double rhs) const { return lhs * rhs; } }; template <typename V> struct div: public boost::static_visitor<V> { typedef V value_type; template <typename T1, typename T2> value_type operator() (T1 const& lhs, T2 const&) const { return lhs; } template <typename T> value_type operator() (T lhs, T rhs) const { return lhs / rhs; } value_type operator() (UnicodeString const& lhs, UnicodeString const&) const { return lhs; } value_type operator() (double lhs, int rhs) const { return lhs / rhs; } value_type operator() (int lhs, double rhs) const { return lhs / rhs; } }; struct to_bool : public boost::static_visitor<bool> { template <typename T> bool operator() (T val) const { throw config_error("Boolean value expected"); } bool operator() (bool val) const { return val; } }; struct to_string : public boost::static_visitor<std::string> { template <typename T> std::string operator() (T val) const { std::stringstream ss; ss << val; return ss.str(); } // specializations std::string operator() (UnicodeString const& val) const { //std::stringstream ss; //std::wstring::const_iterator pos = val.begin(); //ss << std::hex ; //for (;pos!=val.end();++pos) //{ // wchar_t c = *pos; // if (c < 0x80) // { // ss << char(c); // } // else // { // ss << "\\x"; // unsigned c0 = (c >> 8) & 0xff; // if (c0) ss << c0; // ss << (c & 0xff); // } //} //return ss.str(); return "TODO"; } std::string operator() (double val) const { std::stringstream ss; ss << std::setprecision(16) << val; return ss.str(); } std::string operator() (value_null const& val) const { return ""; } }; struct to_unicode : public boost::static_visitor<UnicodeString> { template <typename T> UnicodeString operator() (T val) const { std::basic_ostringstream<char> out; out << val; return UnicodeString(out.str().c_str()); } // specializations UnicodeString const& operator() (UnicodeString const& val) const { return val; } UnicodeString operator() (double val) const { std::basic_ostringstream<char> out; out << std::setprecision(16) << val; return UnicodeString(out.str().c_str()); } UnicodeString operator() (value_null const& val) const { return UnicodeString(""); } }; struct to_expression_string : public boost::static_visitor<std::string> { std::string operator() (UnicodeString const& val) const { std::string utf8; to_utf8(val,utf8); return "'" + utf8 + "'"; } template <typename T> std::string operator() (T val) const { std::stringstream ss; ss << val; return ss.str(); } std::string operator() (double val) const { std::stringstream ss; ss << std::setprecision(16) << val; return ss.str(); } std::string operator() (value_null const& val) const { return "null"; } }; } class value { value_base base_; friend const value operator+(value const&,value const&); friend const value operator-(value const&,value const&); friend const value operator*(value const&,value const&); friend const value operator/(value const&,value const&); public: value () : base_(value_null()) {} template <typename T> value(T _val_) : base_(_val_) {} bool operator==(value const& other) const { return boost::apply_visitor(impl::equals(),base_,other.base_); } bool operator!=(value const& other) const { return boost::apply_visitor(impl::not_equals(),base_,other.base_); } bool operator>(value const& other) const { return boost::apply_visitor(impl::greater_than(),base_,other.base_); } bool operator>=(value const& other) const { return boost::apply_visitor(impl::greater_or_equal(),base_,other.base_); } bool operator<(value const& other) const { return boost::apply_visitor(impl::less_than(),base_,other.base_); } bool operator<=(value const& other) const { return boost::apply_visitor(impl::less_or_equal(),base_,other.base_); } value_base const& base() const { return base_; } bool to_bool() const { return boost::apply_visitor(impl::to_bool(),base_); } std::string to_expression_string() const { return boost::apply_visitor(impl::to_expression_string(),base_); } std::string to_string() const { return boost::apply_visitor(impl::to_string(),base_); } UnicodeString to_unicode() const { return boost::apply_visitor(impl::to_unicode(),base_); } }; inline const value operator+(value const& p1,value const& p2) { return value(boost::apply_visitor(impl::add<value>(),p1.base_, p2.base_)); } inline const value operator-(value const& p1,value const& p2) { return value(boost::apply_visitor(impl::sub<value>(),p1.base_, p2.base_)); } inline const value operator*(value const& p1,value const& p2) { return value(boost::apply_visitor(impl::mult<value>(),p1.base_, p2.base_)); } inline const value operator/(value const& p1,value const& p2) { return value(boost::apply_visitor(impl::div<value>(),p1.base_, p2.base_)); } template <typename charT, typename traits> inline std::basic_ostream<charT,traits>& operator << (std::basic_ostream<charT,traits>& out, value const& v) { out << v.to_string(); return out; } } #endif //VALUE_HPP <commit_msg> + return UTF-8 in to_string <commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 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 * *****************************************************************************/ //$Id$ #ifndef VALUE_HPP #define VALUE_HPP // mapnik #include <mapnik/unicode.hpp> #include <mapnik/config_error.hpp> // boost #include <boost/variant.hpp> #include <boost/scoped_array.hpp> // stl #include <iostream> #include <string> #include <sstream> #include <iomanip> // uci #include <unicode/unistr.h> #include <unicode/ustring.h> namespace mapnik { inline void to_utf8(UnicodeString const& input, std::string & target) { if (input.length() == 0) return; const int BUF_SIZE = 256; char buf [BUF_SIZE]; int len; UErrorCode err = U_ZERO_ERROR; u_strToUTF8(buf, BUF_SIZE, &len, input.getBuffer(), input.length(), &err); if (err == U_BUFFER_OVERFLOW_ERROR || err == U_STRING_NOT_TERMINATED_WARNING ) { boost::scoped_array<char> buf_ptr(new char [len+1]); err = U_ZERO_ERROR; u_strToUTF8(buf_ptr.get() , len + 1, &len, input.getBuffer(), input.length(), &err); target.assign(buf_ptr.get() , len); } else { target.assign(buf, len); } } struct value_null { }; typedef boost::variant<value_null,bool,int,double,UnicodeString> value_base; namespace impl { struct equals : public boost::static_visitor<bool> { template <typename T, typename U> bool operator() (const T &, const U &) const { return false; } template <typename T> bool operator() (T lhs, T rhs) const { return lhs == rhs; } bool operator() (int lhs, double rhs) const { return lhs == rhs; } bool operator() (double lhs, int rhs) const { return lhs == rhs; } bool operator() (UnicodeString const& lhs, UnicodeString const& rhs) const { return lhs == rhs; } bool operator() (value_null, value_null) const { return false; } }; struct not_equals : public boost::static_visitor<bool> { template <typename T, typename U> bool operator() (const T &, const U &) const { return true; } template <typename T> bool operator() (T lhs, T rhs) const { return lhs != rhs; } bool operator() (int lhs, double rhs) const { return lhs != rhs; } bool operator() (double lhs, int rhs) const { return lhs != rhs; } bool operator() (UnicodeString const& lhs, UnicodeString const& rhs) const { return lhs != rhs; } bool operator() (value_null, value_null) const { return false; } template <typename T> bool operator() (value_null, const T &) const { return false; } template <typename T> bool operator() (const T &, value_null) const { return false; } }; struct greater_than : public boost::static_visitor<bool> { template <typename T, typename U> bool operator()(const T &, const U &) const { return false; } template <typename T> bool operator()(T lhs, T rhs) const { return lhs > rhs; } bool operator() (int lhs, double rhs) const { return lhs > rhs; } bool operator() (double lhs, int rhs) const { return lhs > rhs; } bool operator() (UnicodeString const& lhs, UnicodeString const& rhs) const { return lhs > rhs; } bool operator() (value_null, value_null) const { return false; } }; struct greater_or_equal : public boost::static_visitor<bool> { template <typename T, typename U> bool operator()(const T &, const U &) const { return false; } template <typename T> bool operator() (T lhs, T rhs) const { return lhs >= rhs; } bool operator() (int lhs, double rhs) const { return lhs >= rhs; } bool operator() (double lhs, int rhs) const { return lhs >= rhs; } bool operator() (UnicodeString const& lhs, UnicodeString const& rhs) const { return lhs >= rhs; } bool operator() (value_null, value_null) const { return false; } }; struct less_than : public boost::static_visitor<bool> { template <typename T, typename U> bool operator()(const T &, const U &) const { return false; } template <typename T> bool operator()(T lhs, T rhs) const { return lhs < rhs; } bool operator() (int lhs, double rhs) const { return lhs < rhs; } bool operator() (double lhs, int rhs) const { return lhs < rhs; } bool operator()(UnicodeString const& lhs, UnicodeString const& rhs ) const { return lhs < rhs; } bool operator() (value_null, value_null) const { return false; } }; struct less_or_equal : public boost::static_visitor<bool> { template <typename T, typename U> bool operator()(const T &, const U &) const { return false; } template <typename T> bool operator()(T lhs, T rhs) const { return lhs <= rhs; } bool operator() (int lhs, double rhs) const { return lhs <= rhs; } bool operator() (double lhs, int rhs) const { return lhs <= rhs; } template <typename T> bool operator()(UnicodeString const& lhs, UnicodeString const& rhs ) const { return lhs <= rhs; } bool operator() (value_null, value_null) const { return false; } }; template <typename V> struct add : public boost::static_visitor<V> { typedef V value_type; template <typename T1, typename T2> value_type operator() (T1 const& lhs, T2 const&) const { return lhs; } template <typename T> value_type operator() (T lhs, T rhs) const { return lhs + rhs ; } value_type operator() (UnicodeString const& lhs , UnicodeString const& rhs ) const { return lhs + rhs; } value_type operator() (double lhs, int rhs) const { return lhs + rhs; } value_type operator() (int lhs, double rhs) const { return lhs + rhs; } }; template <typename V> struct sub : public boost::static_visitor<V> { typedef V value_type; template <typename T1, typename T2> value_type operator() (T1 const& lhs, T2 const&) const { return lhs; } template <typename T> value_type operator() (T lhs, T rhs) const { return lhs - rhs ; } value_type operator() (UnicodeString const& lhs, UnicodeString const& ) const { return lhs; } value_type operator() (double lhs, int rhs) const { return lhs - rhs; } value_type operator() (int lhs, double rhs) const { return lhs - rhs; } }; template <typename V> struct mult : public boost::static_visitor<V> { typedef V value_type; template <typename T1, typename T2> value_type operator() (T1 const& lhs , T2 const& ) const { return lhs; } template <typename T> value_type operator() (T lhs, T rhs) const { return lhs * rhs; } value_type operator() (UnicodeString const& lhs, UnicodeString const& ) const { return lhs; } value_type operator() (double lhs, int rhs) const { return lhs * rhs; } value_type operator() (int lhs, double rhs) const { return lhs * rhs; } }; template <typename V> struct div: public boost::static_visitor<V> { typedef V value_type; template <typename T1, typename T2> value_type operator() (T1 const& lhs, T2 const&) const { return lhs; } template <typename T> value_type operator() (T lhs, T rhs) const { return lhs / rhs; } value_type operator() (UnicodeString const& lhs, UnicodeString const&) const { return lhs; } value_type operator() (double lhs, int rhs) const { return lhs / rhs; } value_type operator() (int lhs, double rhs) const { return lhs / rhs; } }; struct to_bool : public boost::static_visitor<bool> { template <typename T> bool operator() (T val) const { throw config_error("Boolean value expected"); } bool operator() (bool val) const { return val; } }; struct to_string : public boost::static_visitor<std::string> { template <typename T> std::string operator() (T val) const { std::stringstream ss; ss << val; return ss.str(); } // specializations std::string operator() (UnicodeString const& val) const { std::string utf8; to_utf8(val,utf8); return utf8; } std::string operator() (double val) const { std::stringstream ss; ss << std::setprecision(16) << val; return ss.str(); } std::string operator() (value_null const& val) const { return ""; } }; struct to_unicode : public boost::static_visitor<UnicodeString> { template <typename T> UnicodeString operator() (T val) const { std::basic_ostringstream<char> out; out << val; return UnicodeString(out.str().c_str()); } // specializations UnicodeString const& operator() (UnicodeString const& val) const { return val; } UnicodeString operator() (double val) const { std::basic_ostringstream<char> out; out << std::setprecision(16) << val; return UnicodeString(out.str().c_str()); } UnicodeString operator() (value_null const& val) const { return UnicodeString(""); } }; struct to_expression_string : public boost::static_visitor<std::string> { std::string operator() (UnicodeString const& val) const { std::string utf8; to_utf8(val,utf8); return "'" + utf8 + "'"; } template <typename T> std::string operator() (T val) const { std::stringstream ss; ss << val; return ss.str(); } std::string operator() (double val) const { std::stringstream ss; ss << std::setprecision(16) << val; return ss.str(); } std::string operator() (value_null const& val) const { return "null"; } }; } class value { value_base base_; friend const value operator+(value const&,value const&); friend const value operator-(value const&,value const&); friend const value operator*(value const&,value const&); friend const value operator/(value const&,value const&); public: value () : base_(value_null()) {} template <typename T> value(T _val_) : base_(_val_) {} bool operator==(value const& other) const { return boost::apply_visitor(impl::equals(),base_,other.base_); } bool operator!=(value const& other) const { return boost::apply_visitor(impl::not_equals(),base_,other.base_); } bool operator>(value const& other) const { return boost::apply_visitor(impl::greater_than(),base_,other.base_); } bool operator>=(value const& other) const { return boost::apply_visitor(impl::greater_or_equal(),base_,other.base_); } bool operator<(value const& other) const { return boost::apply_visitor(impl::less_than(),base_,other.base_); } bool operator<=(value const& other) const { return boost::apply_visitor(impl::less_or_equal(),base_,other.base_); } value_base const& base() const { return base_; } bool to_bool() const { return boost::apply_visitor(impl::to_bool(),base_); } std::string to_expression_string() const { return boost::apply_visitor(impl::to_expression_string(),base_); } std::string to_string() const { return boost::apply_visitor(impl::to_string(),base_); } UnicodeString to_unicode() const { return boost::apply_visitor(impl::to_unicode(),base_); } }; inline const value operator+(value const& p1,value const& p2) { return value(boost::apply_visitor(impl::add<value>(),p1.base_, p2.base_)); } inline const value operator-(value const& p1,value const& p2) { return value(boost::apply_visitor(impl::sub<value>(),p1.base_, p2.base_)); } inline const value operator*(value const& p1,value const& p2) { return value(boost::apply_visitor(impl::mult<value>(),p1.base_, p2.base_)); } inline const value operator/(value const& p1,value const& p2) { return value(boost::apply_visitor(impl::div<value>(),p1.base_, p2.base_)); } template <typename charT, typename traits> inline std::basic_ostream<charT,traits>& operator << (std::basic_ostream<charT,traits>& out, value const& v) { out << v.to_string(); return out; } } #endif //VALUE_HPP <|endoftext|>
<commit_before>#pragma once #include <chrono> #include <memory> #include <string> #include <vector> #include <mutex> #include <condition_variable> #include <map> #include <thread> #include <algorithm> #include "exception.hpp" #include "services/builder.hpp" #include "services/inotify.hpp" #include "services/logger.hpp" #include "utils/config.hpp" #include "utils/string.hpp" #include "utils/concurrency.hpp" using namespace std::chrono_literals; #define Concat(one, two) one ## two #define _Stringify(expr) #expr #define Stringify(expr) _Stringify(expr) #define DefineModule(ModuleName, ModuleType) struct ModuleName : public ModuleType<ModuleName> #define CastModule(ModuleName) static_cast<ModuleName *>(this) #define ConstCastModule(ModuleName) static_cast<ModuleName const &>(*this) #define DEFAULT_FORMAT "format" DefineBaseException(ModuleError); DefineChildException(UndefinedFormat, ModuleError); DefineChildException(UndefinedFormatTag, ModuleError); class ModuleFormatter { public: struct Format { std::string value; std::vector<std::string> tags; std::string fg, bg, ul, ol; int spacing, padding, margin, offset; std::string decorate(Builder *builder, std::string output); }; std::string module_name; std::map<std::string, std::unique_ptr<Format>> formats; public: explicit ModuleFormatter(std::string module_name) : module_name(module_name) {} void add(std::string name, std::string fallback, std::vector<std::string>&& tags, std::vector<std::string>&& whitelist = {}); std::unique_ptr<Format>& get(std::string format_name); bool has(std::string tag, std::string format_name); bool has(std::string tag); }; namespace modules { void broadcast_module_update(std::string module_name); std::string get_tag_name(std::string tag); struct ModuleInterface { public: virtual ~ModuleInterface(){} virtual std::string name() const = 0; virtual void start() = 0; virtual void stop() = 0; virtual void refresh() = 0; virtual std::string operator()() = 0; virtual bool handle_command(std::string cmd) = 0; }; template<typename ModuleImpl> class Module : public ModuleInterface { concurrency::Atomic<bool> enabled_flag; concurrency::Value<std::string> cache; protected: concurrency::SpinLock output_lock; concurrency::SpinLock broadcast_lock; std::mutex sleep_lock; std::condition_variable sleep_handler; std::string name_; std::unique_ptr<Builder> builder; std::unique_ptr<ModuleFormatter> formatter; std::vector<std::thread> threads; public: Module(const std::string& name, bool lazy_builder = true) : name_("module/"+ name), builder(std::make_unique<Builder>(lazy_builder)) { this->enable(false); this->cache = ""; this->formatter = std::make_unique<ModuleFormatter>(ConstCastModule(ModuleImpl).name()); } ~Module() { if (this->enabled()) this->stop(); std::lock_guard<concurrency::SpinLock> lck(this->broadcast_lock); for (auto &&t : this->threads) { if (t.joinable()) t.join(); else log_warning("["+ ConstCastModule(ModuleImpl).name() +"] Runner thread not joinable"); } log_trace(name()); } std::string name() const { return name_; } void stop() { log_trace(name()); this->wakeup(); std::lock_guard<concurrency::SpinLock> lck(this->broadcast_lock); this->enable(false); } void refresh() { this->cache = CastModule(ModuleImpl)->get_output(); } std::string operator()() { return this->cache(); } bool handle_command(std::string cmd) { return CastModule(ModuleImpl)->handle_command(cmd); } protected: bool enabled() { return this->enabled_flag(); } void enable(bool state) { this->enabled_flag = state; } void broadcast() { std::lock_guard<concurrency::SpinLock> lck(this->broadcast_lock); broadcast_module_update(ConstCastModule(ModuleImpl).name()); } void sleep(std::chrono::duration<double> sleep_duration) { std::unique_lock<std::mutex> lck(this->sleep_lock); std::thread sleep_thread([&]{ auto start = std::chrono::system_clock::now(); while ((std::chrono::system_clock::now() - start) < sleep_duration) { std::this_thread::sleep_for(50ms); } this->wakeup(); }); sleep_thread.detach(); this->sleep_handler.wait(lck); } void wakeup() { log_trace("Releasing sleep lock for "+ this->name_); this->sleep_handler.notify_one(); } std::string get_format() { return DEFAULT_FORMAT; } std::string get_output() { std::lock_guard<concurrency::SpinLock> lck(this->output_lock); log_trace(ConstCastModule(ModuleImpl).name()); if (!this->enabled()) { log_trace(ConstCastModule(ModuleImpl).name() +" is disabled"); return ""; } auto format_name = CastModule(ModuleImpl)->get_format(); auto &&format = this->formatter->get(format_name); int i = 0; for (auto tag : string::split(format->value, ' ')) { if ((i > 0 && !tag.empty()) || tag.empty()) { this->builder->space(format->spacing); } if (tag[0] == '<' && tag[tag.length()-1] == '>') { if (!CastModule(ModuleImpl)->build(this->builder.get(), tag)) { this->builder->remove_trailing_space(format->spacing); } } else { this->builder->node(tag); } i++; } return format->decorate(this->builder.get(), this->builder->flush()); } }; template<typename ModuleImpl> class StaticModule : public Module<ModuleImpl> { using Module<ModuleImpl>::Module; public: void start() { this->enable(true); this->threads.emplace_back(std::thread(&StaticModule::broadcast, this)); } bool build(Builder *builder, std::string tag) { return true; } }; template<typename ModuleImpl> class TimerModule : public Module<ModuleImpl> { protected: std::chrono::duration<double> interval = 1s; concurrency::SpinLock update_lock; void runner() { while (this->enabled()) { { std::lock_guard<concurrency::SpinLock> lck(this->update_lock); if (CastModule(ModuleImpl)->update()) CastModule(ModuleImpl)->broadcast(); } this->sleep(this->interval); } } public: template<typename I> TimerModule(std::string name, I const &interval) : Module<ModuleImpl>(name), interval(interval) {} void start() { this->enable(true); this->threads.emplace_back(std::thread(&TimerModule::runner, this)); } }; template<typename ModuleImpl> class EventModule : public Module<ModuleImpl> { using Module<ModuleImpl>::Module; protected: concurrency::SpinLock update_lock; void runner() { // warmup CastModule(ModuleImpl)->update(); CastModule(ModuleImpl)->broadcast(); while (this->enabled()) { std::lock_guard<concurrency::SpinLock> lck(this->update_lock); if (!CastModule(ModuleImpl)->has_event()) continue; if (!CastModule(ModuleImpl)->update()) continue; CastModule(ModuleImpl)->broadcast(); } } public: void start() { this->enable(true); this->threads.emplace_back(std::thread(&EventModule::runner, this)); } }; template<typename ModuleImpl> class InotifyModule : public Module<ModuleImpl> { using Module<ModuleImpl>::Module; protected: std::map<std::string, int> watch_list; concurrency::SpinLock update_lock; void runner() { // warmup if (CastModule(ModuleImpl)->on_event(nullptr)) CastModule(ModuleImpl)->broadcast(); while (this->enabled()) { try { this->poll_events(); } catch (InotifyException &e) { get_logger()->fatal(e.what()); } } } void idle() const { // std::this_thread::sleep_for(1s); } void poll_events() { std::lock_guard<concurrency::SpinLock> lck(this->update_lock); std::vector<std::unique_ptr<InotifyWatch>> watches; try { for (auto &&w : this->watch_list) watches.emplace_back(std::make_unique<InotifyWatch>(w.first, w.second)); } catch (InotifyException &e) { watches.clear(); get_logger()->error(e.what()); std::this_thread::sleep_for(100ms); return; } while (this->enabled()) { ConstCastModule(ModuleImpl).idle(); for (auto &&w : watches) { log_trace("Polling inotify event for watch at "+ (*w)()); if (w->has_event(500 / watches.size())) { std::unique_ptr<InotifyEvent> event = w->get_event(); watches.clear(); if (CastModule(ModuleImpl)->on_event(event.get())) CastModule(ModuleImpl)->broadcast(); return; } } } } void watch(const std::string& path, int mask = InotifyEvent::ALL) { log_trace(path); this->watch_list.insert(std::make_pair(path, mask)); } public: InotifyModule(const std::string& name, const std::string& path, int mask = InotifyEvent::ALL) : Module<ModuleImpl>(name) { this->watch(path, mask); } InotifyModule(const std::string& name, std::vector<std::string> paths, int mask = InotifyEvent::ALL) : Module<ModuleImpl>(name) { for (auto &&path : paths) this->watch(path, mask); } void start() { this->enable(true); this->threads.emplace_back(std::thread(&InotifyModule::runner, this)); } }; } <commit_msg>feat: Throttle module broadcasts<commit_after>#pragma once #include <chrono> #include <memory> #include <string> #include <vector> #include <mutex> #include <condition_variable> #include <map> #include <thread> #include <algorithm> #include "exception.hpp" #include "services/builder.hpp" #include "services/inotify.hpp" #include "services/logger.hpp" #include "services/event_throttler.hpp" #include "utils/config.hpp" #include "utils/string.hpp" #include "utils/concurrency.hpp" using namespace std::chrono_literals; #define Concat(one, two) one ## two #define _Stringify(expr) #expr #define Stringify(expr) _Stringify(expr) #define DefineModule(ModuleName, ModuleType) struct ModuleName : public ModuleType<ModuleName> #define CastModule(ModuleName) static_cast<ModuleName *>(this) #define ConstCastModule(ModuleName) static_cast<ModuleName const &>(*this) #define DEFAULT_FORMAT "format" DefineBaseException(ModuleError); DefineChildException(UndefinedFormat, ModuleError); DefineChildException(UndefinedFormatTag, ModuleError); class ModuleFormatter { public: struct Format { std::string value; std::vector<std::string> tags; std::string fg, bg, ul, ol; int spacing, padding, margin, offset; std::string decorate(Builder *builder, std::string output); }; std::string module_name; std::map<std::string, std::unique_ptr<Format>> formats; public: explicit ModuleFormatter(std::string module_name) : module_name(module_name) {} void add(std::string name, std::string fallback, std::vector<std::string>&& tags, std::vector<std::string>&& whitelist = {}); std::unique_ptr<Format>& get(std::string format_name); bool has(std::string tag, std::string format_name); bool has(std::string tag); }; namespace modules { void broadcast_module_update(std::string module_name); std::string get_tag_name(std::string tag); struct ModuleInterface { public: virtual ~ModuleInterface(){} virtual std::string name() const = 0; virtual void start() = 0; virtual void stop() = 0; virtual void refresh() = 0; virtual std::string operator()() = 0; virtual bool handle_command(std::string cmd) = 0; }; template<typename ModuleImpl> class Module : public ModuleInterface { concurrency::Atomic<bool> enabled_flag; concurrency::Value<std::string> cache; protected: concurrency::SpinLock output_lock; concurrency::SpinLock broadcast_lock; std::mutex sleep_lock; std::condition_variable sleep_handler; std::string name_; std::unique_ptr<Builder> builder; std::unique_ptr<EventThrottler> broadcast_throttler; std::unique_ptr<ModuleFormatter> formatter; std::vector<std::thread> threads; public: Module(std::string name, bool lazy_builder = true) : name_("module/"+ name) , builder(std::make_unique<Builder>(lazy_builder)) , broadcast_throttler(std::make_unique<EventThrottler>(event_throttler::limit_t(1), event_throttler::timewindow_t(25))) { this->enable(false); this->cache = ""; this->formatter = std::make_unique<ModuleFormatter>(ConstCastModule(ModuleImpl).name()); } ~Module() { if (this->enabled()) this->stop(); std::lock_guard<concurrency::SpinLock> lck(this->broadcast_lock); for (auto &&t : this->threads) { if (t.joinable()) t.join(); else log_warning("["+ ConstCastModule(ModuleImpl).name() +"] Runner thread not joinable"); } log_trace(name()); } std::string name() const { return name_; } void stop() { log_trace(name()); this->wakeup(); std::lock_guard<concurrency::SpinLock> lck(this->broadcast_lock); this->enable(false); } void refresh() { this->cache = CastModule(ModuleImpl)->get_output(); } std::string operator()() { return this->cache(); } bool handle_command(std::string cmd) { return CastModule(ModuleImpl)->handle_command(cmd); } protected: bool enabled() { return this->enabled_flag(); } void enable(bool state) { this->enabled_flag = state; } void broadcast() { std::lock_guard<concurrency::SpinLock> lck(this->broadcast_lock); if (!this->broadcast_throttler->passthrough()) { log_trace("Throttled broadcast for: "+ this->name_); return; } broadcast_module_update(ConstCastModule(ModuleImpl).name()); } void sleep(std::chrono::duration<double> sleep_duration) { std::unique_lock<std::mutex> lck(this->sleep_lock); std::thread sleep_thread([&]{ auto start = std::chrono::system_clock::now(); while ((std::chrono::system_clock::now() - start) < sleep_duration) { std::this_thread::sleep_for(50ms); } this->wakeup(); }); sleep_thread.detach(); this->sleep_handler.wait(lck); } void wakeup() { log_trace("Releasing sleep lock for "+ this->name_); this->sleep_handler.notify_one(); } std::string get_format() { return DEFAULT_FORMAT; } std::string get_output() { std::lock_guard<concurrency::SpinLock> lck(this->output_lock); log_trace(ConstCastModule(ModuleImpl).name()); if (!this->enabled()) { log_trace(ConstCastModule(ModuleImpl).name() +" is disabled"); return ""; } auto format_name = CastModule(ModuleImpl)->get_format(); auto &&format = this->formatter->get(format_name); int i = 0; for (auto tag : string::split(format->value, ' ')) { if ((i > 0 && !tag.empty()) || tag.empty()) { this->builder->space(format->spacing); } if (tag[0] == '<' && tag[tag.length()-1] == '>') { if (!CastModule(ModuleImpl)->build(this->builder.get(), tag)) { this->builder->remove_trailing_space(format->spacing); } } else { this->builder->node(tag); } i++; } return format->decorate(this->builder.get(), this->builder->flush()); } }; template<typename ModuleImpl> class StaticModule : public Module<ModuleImpl> { using Module<ModuleImpl>::Module; public: void start() { this->enable(true); this->threads.emplace_back(std::thread(&StaticModule::broadcast, this)); } bool build(Builder *builder, std::string tag) { return true; } }; template<typename ModuleImpl> class TimerModule : public Module<ModuleImpl> { protected: std::chrono::duration<double> interval = 1s; concurrency::SpinLock update_lock; void runner() { while (this->enabled()) { { std::lock_guard<concurrency::SpinLock> lck(this->update_lock); if (CastModule(ModuleImpl)->update()) CastModule(ModuleImpl)->broadcast(); } this->sleep(this->interval); } } public: template<typename I> TimerModule(std::string name, I const &interval) : Module<ModuleImpl>(name), interval(interval) {} void start() { this->enable(true); this->threads.emplace_back(std::thread(&TimerModule::runner, this)); } }; template<typename ModuleImpl> class EventModule : public Module<ModuleImpl> { using Module<ModuleImpl>::Module; protected: concurrency::SpinLock update_lock; void runner() { // warmup CastModule(ModuleImpl)->update(); CastModule(ModuleImpl)->broadcast(); while (this->enabled()) { std::lock_guard<concurrency::SpinLock> lck(this->update_lock); if (!CastModule(ModuleImpl)->has_event()) continue; if (!CastModule(ModuleImpl)->update()) continue; CastModule(ModuleImpl)->broadcast(); } } public: void start() { this->enable(true); this->threads.emplace_back(std::thread(&EventModule::runner, this)); } }; template<typename ModuleImpl> class InotifyModule : public Module<ModuleImpl> { using Module<ModuleImpl>::Module; protected: std::map<std::string, int> watch_list; concurrency::SpinLock update_lock; void runner() { // warmup if (CastModule(ModuleImpl)->on_event(nullptr)) CastModule(ModuleImpl)->broadcast(); while (this->enabled()) { try { this->poll_events(); } catch (InotifyException &e) { get_logger()->fatal(e.what()); } } } void idle() const { // std::this_thread::sleep_for(1s); } void poll_events() { std::lock_guard<concurrency::SpinLock> lck(this->update_lock); std::vector<std::unique_ptr<InotifyWatch>> watches; try { for (auto &&w : this->watch_list) watches.emplace_back(std::make_unique<InotifyWatch>(w.first, w.second)); } catch (InotifyException &e) { watches.clear(); get_logger()->error(e.what()); std::this_thread::sleep_for(100ms); return; } while (this->enabled()) { ConstCastModule(ModuleImpl).idle(); for (auto &&w : watches) { log_trace("Polling inotify event for watch at "+ (*w)()); if (w->has_event(500 / watches.size())) { std::unique_ptr<InotifyEvent> event = w->get_event(); watches.clear(); if (CastModule(ModuleImpl)->on_event(event.get())) CastModule(ModuleImpl)->broadcast(); return; } } } } void watch(const std::string& path, int mask = InotifyEvent::ALL) { log_trace(path); this->watch_list.insert(std::make_pair(path, mask)); } public: InotifyModule(const std::string& name, const std::string& path, int mask = InotifyEvent::ALL) : Module<ModuleImpl>(name) { this->watch(path, mask); } InotifyModule(const std::string& name, std::vector<std::string> paths, int mask = InotifyEvent::ALL) : Module<ModuleImpl>(name) { for (auto &&path : paths) this->watch(path, mask); } void start() { this->enable(true); this->threads.emplace_back(std::thread(&InotifyModule::runner, this)); } }; } <|endoftext|>
<commit_before>#include <iostream> #include <set> #include <utils/function.h> #include <algebra/sparse_matrix.h> #include <numerics/iteratsolv.h> #include <numerics/bezier.h> #include <Ldomain/ldomain_jl_basis.h> #include <Ldomain/ldomain_jl_evaluate.h> #include <Ldomain/ldomain_jl_expansion.h> #define _WAVELETTL_GALERKINUTILS_VERBOSITY 0 #include <galerkin/ldomain_jl_gramian.h> #include <galerkin/galerkin_utils.h> #include "ldomain_solutions.h" using namespace std; using namespace MathTL; using namespace WaveletTL; int main() { cout << "Testing LDomainJLGramian ..." << endl; typedef LDomainJLBasis Basis; typedef Basis::Index Index; Basis basis; const int solution = 2; Function<2> *uexact = 0, *f = 0; switch(solution) { case 1: uexact = new PolySolution(); f = new PolySolution(); break; case 2: uexact = new EigenSolution(); f = new EigenSolution(); break; case 3: uexact = new CubicHermiteInterpolant2D_td(1, 0, 0, -1, -1); f = new CubicHermiteInterpolant2D_td(1, 0, 0, -1, -1); // uexact = new CubicHermiteInterpolant2D_td(1, 1, 1, -1, -2); // f = new CubicHermiteInterpolant2D_td(1, 1, 1, -1, -2); break; default: break; } #if 0 // temporary hack, choose f=1 just to see the inner products delete f; f = new ConstantFunction<2>(Vector<double>(1, "1")); #endif const int jmax = 4; typedef LDomainJLGramian Problem; Problem problem(basis, InfiniteVector<double,Index>()); InfiniteVector<double,Index> fcoeffs; expand(f, basis, true, jmax, fcoeffs); problem.set_rhs(fcoeffs); // cout << "- integrals of f against the primal wavelets:" << endl // << fcoeffs << endl; set<Index> Lambda; for (Index lambda = basis.first_generator(basis.j0());; ++lambda) { Lambda.insert(lambda); // if (lambda == basis.last_generator(basis.j0())) break; if (lambda == basis.last_wavelet(jmax)) break; } cout << "- set up Gramian matrix..." << endl; clock_t tstart, tend; double time; tstart = clock(); SparseMatrix<double> A; setup_stiffness_matrix(problem, Lambda, A); tend = clock(); time = (double)(tend-tstart)/CLOCKS_PER_SEC; cout << " ... done, time needed: " << time << " seconds" << endl; // cout << "- Gramian matrix A=" << endl << A << endl; #if 1 A.matlab_output("LdomainJL_gramian", "G", 1); #endif #if 0 cout << "- validate entries of the (unpreconditioned) Gramian matrix:" << endl; for (set<Index>::const_iterator itlambda = Lambda.begin(); itlambda != Lambda.end(); ++itlambda) { cout << "* checking row " << *itlambda << "..." << endl; for (set<Index>::const_iterator itmu = Lambda.begin(); itmu != Lambda.end(); ++itmu) { const int N = 2000; const double h = 1./N; double s = 0; FixedArray1D<Array1D<double>,2> lambdavalues, muvalues; FixedArray1D<Array1D<double>,2> knots; knots[0].resize(N+1); knots[1].resize(N+1); const Index& lambda = *itlambda; const Index& mu = *itmu; // patch Omega_0 = [-1,0]x[0,1] if (lambda.k()[0] <= 0 && lambda.k()[1] >= 0 && mu.k()[0] <= 0 && mu.k()[1] >= 0) { for (int k0 = 0; k0 < N; k0++) knots[0][k0] = -1.0+k0*h; evaluate(0, lambda.j(), lambda.e()[0], lambda.c()[0], lambda.k()[0], knots[0], lambdavalues[0]); evaluate(0, mu.j(), mu.e()[0], mu.c()[0], mu.k()[0], knots[0], muvalues[0]); for (int k1 = 0; k1 < N; k1++) knots[1][k1] = k1*h; evaluate(0, lambda.j(), lambda.e()[1], lambda.c()[1], lambda.k()[1], knots[1], lambdavalues[1]); evaluate(0, mu.j(), mu.e()[1], mu.c()[1], mu.k()[1], knots[1], muvalues[1]); for (int k0 = 0; k0 < N; k0++) { for (int k1 = 1; k1 < N; k1++) { s += lambdavalues[0][k0] * lambdavalues[1][k1] * muvalues[0][k0] * muvalues[1][k1]; } } } // patch Omega_1 = [-1,0]x[-1,0] if (lambda.k()[0] <= 0 && lambda.k()[1] <= 0 && mu.k()[0] <= 0 && mu.k()[1] <= 0) { for (int k0 = 0; k0 < N; k0++) knots[0][k0] = -1.0+k0*h; evaluate(0, lambda.j(), lambda.e()[0], lambda.c()[0], lambda.k()[0], knots[0], lambdavalues[0]); evaluate(0, mu.j(), mu.e()[0], mu.c()[0], mu.k()[0], knots[0], muvalues[0]); for (int k1 = 0; k1 < N; k1++) knots[1][k1] = -1.0+k1*h; evaluate(0, lambda.j(), lambda.e()[1], lambda.c()[1], lambda.k()[1], knots[1], lambdavalues[1]); evaluate(0, mu.j(), mu.e()[1], mu.c()[1], mu.k()[1], knots[1], muvalues[1]); for (int k0 = 0; k0 < N; k0++) { for (int k1 = 1; k1 < N; k1++) { s += lambdavalues[0][k0] * lambdavalues[1][k1] * muvalues[0][k0] * muvalues[1][k1]; } } } // patch Omega_2 = [0,1]x[-1,0] if (lambda.k()[0] >= 0 && lambda.k()[1] <= 0 && mu.k()[0] >= 0 && mu.k()[1] <= 0) { for (int k0 = 0; k0 < N; k0++) knots[0][k0] = k0*h; evaluate(0, lambda.j(), lambda.e()[0], lambda.c()[0], lambda.k()[0], knots[0], lambdavalues[0]); evaluate(0, mu.j(), mu.e()[0], mu.c()[0], mu.k()[0], knots[0], muvalues[0]); for (int k1 = 0; k1 < N; k1++) knots[1][k1] = -1.0+k1*h; evaluate(0, lambda.j(), lambda.e()[1], lambda.c()[1], lambda.k()[1], knots[1], lambdavalues[1]); evaluate(0, mu.j(), mu.e()[1], mu.c()[1], mu.k()[1], knots[1], muvalues[1]); for (int k0 = 0; k0 < N; k0++) { for (int k1 = 1; k1 < N; k1++) { s += lambdavalues[0][k0] * lambdavalues[1][k1] * muvalues[0][k0] * muvalues[1][k1]; } } } const double alambdamu = problem.a(*itlambda,*itmu); const double alambdamuapprox = s*h*h; const double dev = fabs(alambdamu-alambdamuapprox); if (dev > 1e-6) cout << "lambda=" << *itlambda << ", mu=" << *itmu << ": " << "a(.,.)=" << alambdamu << ", approx.=" << alambdamuapprox << ", dev.=" << dev << endl; } } #endif cout << "- set up right-hand side..." << endl; tstart = clock(); Vector<double> b; setup_righthand_side(problem, Lambda, b); tend = clock(); time = (double)(tend-tstart)/CLOCKS_PER_SEC; cout << " ... done, time needed: " << time << " seconds" << endl; // cout << "- right hand side: " << b << endl; Vector<double> x(Lambda.size()), err(Lambda.size()); x = 0; unsigned int iterations; CG(A, b, x, 1e-15, 200, iterations); // cout << "- solution coefficients: " << x; cout << "- residual (infinity) norm: "; A.apply(x, err); err -= b; cout << linfty_norm(err) << endl; #if 1 cout << "- point values of the solution:" << endl; InfiniteVector<double,Index> u; unsigned int i = 0; for (set<Index>::const_iterator it = Lambda.begin(); it != Lambda.end(); ++it, ++i) u.set_coefficient(*it, x[i]); u.scale(&problem, -1); Array1D<SampledMapping<2> > s(evaluate(problem.basis(), u, 1<<5)); std::ofstream u_Lambda_stream("u_lambda.m"); matlab_output(u_Lambda_stream, s); u_Lambda_stream.close(); cout << " ... done, see file 'u_lambda.m'" << endl; for (int i = 0; i <= 2; i++) { s[i].add(-1.0, SampledMapping<2>(s[i], *uexact)); cout << " pointwise error on patch " << i << ": " << row_sum_norm(s[i].values()) << endl; } #endif if (uexact) delete uexact; if (f) delete f; return 0; } <commit_msg>commit -> cluster<commit_after>#include <iostream> #include <set> #include <utils/function.h> #include <algebra/sparse_matrix.h> #include <numerics/iteratsolv.h> #include <numerics/bezier.h> #include <Ldomain/ldomain_jl_basis.h> #include <Ldomain/ldomain_jl_evaluate.h> #include <Ldomain/ldomain_jl_expansion.h> #define _WAVELETTL_GALERKINUTILS_VERBOSITY 0 #include <galerkin/ldomain_jl_gramian.h> #include <galerkin/galerkin_utils.h> #include "ldomain_solutions.h" using namespace std; using namespace MathTL; using namespace WaveletTL; int main() { cout << "Testing LDomainJLGramian ..." << endl; typedef LDomainJLBasis Basis; typedef Basis::Index Index; Basis basis; const int solution = 2; Function<2> *uexact = 0, *f = 0; switch(solution) { case 1: uexact = new PolySolution(); f = new PolySolution(); break; case 2: uexact = new EigenSolution(); f = new EigenSolution(); break; case 3: uexact = new CubicHermiteInterpolant2D_td(1, 0, 0, -1, -1); f = new CubicHermiteInterpolant2D_td(1, 0, 0, -1, -1); // uexact = new CubicHermiteInterpolant2D_td(1, 1, 1, -1, -2); // f = new CubicHermiteInterpolant2D_td(1, 1, 1, -1, -2); break; default: break; } #if 0 // temporary hack, choose f=1 just to see the inner products delete f; f = new ConstantFunction<2>(Vector<double>(1, "1")); #endif const int jmax = 5; typedef LDomainJLGramian Problem; Problem problem(basis, InfiniteVector<double,Index>()); InfiniteVector<double,Index> fcoeffs; expand(f, basis, true, jmax, fcoeffs); problem.set_rhs(fcoeffs); // cout << "- integrals of f against the primal wavelets:" << endl // << fcoeffs << endl; set<Index> Lambda; for (Index lambda = basis.first_generator(basis.j0());; ++lambda) { Lambda.insert(lambda); // if (lambda == basis.last_generator(basis.j0())) break; if (lambda == basis.last_wavelet(jmax)) break; } cout << "- set up Gramian matrix..." << endl; clock_t tstart, tend; double time; tstart = clock(); SparseMatrix<double> A; setup_stiffness_matrix(problem, Lambda, A); tend = clock(); time = (double)(tend-tstart)/CLOCKS_PER_SEC; cout << " ... done, time needed: " << time << " seconds" << endl; // cout << "- Gramian matrix A=" << endl << A << endl; #if 1 A.matlab_output("LdomainJL_gramian", "G", 1); #endif #if 0 cout << "- validate entries of the (unpreconditioned) Gramian matrix:" << endl; for (set<Index>::const_iterator itlambda = Lambda.begin(); itlambda != Lambda.end(); ++itlambda) { cout << "* checking row " << *itlambda << "..." << endl; for (set<Index>::const_iterator itmu = Lambda.begin(); itmu != Lambda.end(); ++itmu) { const int N = 2000; const double h = 1./N; double s = 0; FixedArray1D<Array1D<double>,2> lambdavalues, muvalues; FixedArray1D<Array1D<double>,2> knots; knots[0].resize(N+1); knots[1].resize(N+1); const Index& lambda = *itlambda; const Index& mu = *itmu; // patch Omega_0 = [-1,0]x[0,1] if (lambda.k()[0] <= 0 && lambda.k()[1] >= 0 && mu.k()[0] <= 0 && mu.k()[1] >= 0) { for (int k0 = 0; k0 < N; k0++) knots[0][k0] = -1.0+k0*h; evaluate(0, lambda.j(), lambda.e()[0], lambda.c()[0], lambda.k()[0], knots[0], lambdavalues[0]); evaluate(0, mu.j(), mu.e()[0], mu.c()[0], mu.k()[0], knots[0], muvalues[0]); for (int k1 = 0; k1 < N; k1++) knots[1][k1] = k1*h; evaluate(0, lambda.j(), lambda.e()[1], lambda.c()[1], lambda.k()[1], knots[1], lambdavalues[1]); evaluate(0, mu.j(), mu.e()[1], mu.c()[1], mu.k()[1], knots[1], muvalues[1]); for (int k0 = 0; k0 < N; k0++) { for (int k1 = 1; k1 < N; k1++) { s += lambdavalues[0][k0] * lambdavalues[1][k1] * muvalues[0][k0] * muvalues[1][k1]; } } } // patch Omega_1 = [-1,0]x[-1,0] if (lambda.k()[0] <= 0 && lambda.k()[1] <= 0 && mu.k()[0] <= 0 && mu.k()[1] <= 0) { for (int k0 = 0; k0 < N; k0++) knots[0][k0] = -1.0+k0*h; evaluate(0, lambda.j(), lambda.e()[0], lambda.c()[0], lambda.k()[0], knots[0], lambdavalues[0]); evaluate(0, mu.j(), mu.e()[0], mu.c()[0], mu.k()[0], knots[0], muvalues[0]); for (int k1 = 0; k1 < N; k1++) knots[1][k1] = -1.0+k1*h; evaluate(0, lambda.j(), lambda.e()[1], lambda.c()[1], lambda.k()[1], knots[1], lambdavalues[1]); evaluate(0, mu.j(), mu.e()[1], mu.c()[1], mu.k()[1], knots[1], muvalues[1]); for (int k0 = 0; k0 < N; k0++) { for (int k1 = 1; k1 < N; k1++) { s += lambdavalues[0][k0] * lambdavalues[1][k1] * muvalues[0][k0] * muvalues[1][k1]; } } } // patch Omega_2 = [0,1]x[-1,0] if (lambda.k()[0] >= 0 && lambda.k()[1] <= 0 && mu.k()[0] >= 0 && mu.k()[1] <= 0) { for (int k0 = 0; k0 < N; k0++) knots[0][k0] = k0*h; evaluate(0, lambda.j(), lambda.e()[0], lambda.c()[0], lambda.k()[0], knots[0], lambdavalues[0]); evaluate(0, mu.j(), mu.e()[0], mu.c()[0], mu.k()[0], knots[0], muvalues[0]); for (int k1 = 0; k1 < N; k1++) knots[1][k1] = -1.0+k1*h; evaluate(0, lambda.j(), lambda.e()[1], lambda.c()[1], lambda.k()[1], knots[1], lambdavalues[1]); evaluate(0, mu.j(), mu.e()[1], mu.c()[1], mu.k()[1], knots[1], muvalues[1]); for (int k0 = 0; k0 < N; k0++) { for (int k1 = 1; k1 < N; k1++) { s += lambdavalues[0][k0] * lambdavalues[1][k1] * muvalues[0][k0] * muvalues[1][k1]; } } } const double alambdamu = problem.a(*itlambda,*itmu); const double alambdamuapprox = s*h*h; const double dev = fabs(alambdamu-alambdamuapprox); if (dev > 1e-6) cout << "lambda=" << *itlambda << ", mu=" << *itmu << ": " << "a(.,.)=" << alambdamu << ", approx.=" << alambdamuapprox << ", dev.=" << dev << endl; } } #endif cout << "- set up right-hand side..." << endl; tstart = clock(); Vector<double> b; setup_righthand_side(problem, Lambda, b); tend = clock(); time = (double)(tend-tstart)/CLOCKS_PER_SEC; cout << " ... done, time needed: " << time << " seconds" << endl; // cout << "- right hand side: " << b << endl; Vector<double> x(Lambda.size()), err(Lambda.size()); x = 0; unsigned int iterations; CG(A, b, x, 1e-15, 200, iterations); // cout << "- solution coefficients: " << x; cout << "- residual (infinity) norm: "; A.apply(x, err); err -= b; cout << linfty_norm(err) << endl; #if 1 cout << "- point values of the solution:" << endl; InfiniteVector<double,Index> u; unsigned int i = 0; for (set<Index>::const_iterator it = Lambda.begin(); it != Lambda.end(); ++it, ++i) u.set_coefficient(*it, x[i]); u.scale(&problem, -1); Array1D<SampledMapping<2> > s(evaluate(problem.basis(), u, 1<<5)); std::ofstream u_Lambda_stream("u_lambda.m"); matlab_output(u_Lambda_stream, s); u_Lambda_stream.close(); cout << " ... done, see file 'u_lambda.m'" << endl; for (int i = 0; i <= 2; i++) { s[i].add(-1.0, SampledMapping<2>(s[i], *uexact)); cout << " pointwise error on patch " << i << ": " << row_sum_norm(s[i].values()) << endl; } #endif if (uexact) delete uexact; if (f) delete f; return 0; } <|endoftext|>
<commit_before>#pragma once #include <algorithm> #include <condition_variable> #include <fastdelegate/fastdelegate.hpp> #include <mutex> #include "common.hpp" #include "components/builder.hpp" #include "components/config.hpp" #include "components/logger.hpp" #include "utils/inotify.hpp" #include "utils/string.hpp" #include "utils/threading.hpp" LEMONBUDDY_NS #define DEFAULT_FORMAT "format" #define DEFINE_MODULE(name, type) struct name : public type<name> #define CONST_CAST_MODULE(name) static_cast<name const&>(*this) #define CAST_MODULE(name) static_cast<name*>(this) namespace modules { using namespace drawtypes; DEFINE_ERROR(module_error); DEFINE_CHILD_ERROR(undefined_format, module_error); DEFINE_CHILD_ERROR(undefined_format_tag, module_error); // class definition : module_format {{{ struct module_format { string value; vector<string> tags; string fg; string bg; string ul; string ol; int spacing; int padding; int margin; int offset; string decorate(builder* builder, string output) { if (offset != 0) builder->offset(offset); if (margin > 0) builder->space(margin); if (!bg.empty()) builder->background(bg); if (!fg.empty()) builder->color(fg); if (!ul.empty()) builder->underline(ul); if (!ol.empty()) builder->overline(ol); if (padding > 0) builder->space(padding); builder->append(output); if (padding > 0) builder->space(padding); if (!ol.empty()) builder->overline_close(); if (!ul.empty()) builder->underline_close(); if (!fg.empty()) builder->color_close(); if (!bg.empty()) builder->background_close(); if (margin > 0) builder->space(margin); return builder->flush(); } }; // }}} // class definition : module_formatter {{{ class module_formatter { public: explicit module_formatter(const config& conf, string modname) : m_conf(conf), m_modname(modname) {} void add(string name, string fallback, vector<string>&& tags, vector<string>&& whitelist = {}) { auto format = make_unique<module_format>(); format->value = m_conf.get<string>(m_modname, name, fallback); format->fg = m_conf.get<string>(m_modname, name + "-foreground", ""); format->bg = m_conf.get<string>(m_modname, name + "-background", ""); format->ul = m_conf.get<string>(m_modname, name + "-underline", ""); format->ol = m_conf.get<string>(m_modname, name + "-overline", ""); format->spacing = m_conf.get<int>(m_modname, name + "-spacing", DEFAULT_SPACING); format->padding = m_conf.get<int>(m_modname, name + "-padding", 0); format->margin = m_conf.get<int>(m_modname, name + "-margin", 0); format->offset = m_conf.get<int>(m_modname, name + "-offset", 0); format->tags.swap(tags); for (auto&& tag : string_util::split(format->value, ' ')) { if (tag[0] != '<' || tag[tag.length() - 1] != '>') continue; if (std::find(format->tags.begin(), format->tags.end(), tag) != format->tags.end()) continue; if (std::find(whitelist.begin(), whitelist.end(), tag) != whitelist.end()) continue; throw undefined_format_tag("[" + m_modname + "] Undefined \"" + name + "\" tag: " + tag); } m_formats.insert(make_pair(name, std::move(format))); } shared_ptr<module_format> get(string format_name) { auto format = m_formats.find(format_name); if (format == m_formats.end()) throw undefined_format("Format \"" + format_name + "\" has not been added"); return format->second; } bool has(string tag, string format_name) { auto format = m_formats.find(format_name); if (format == m_formats.end()) throw undefined_format(format_name.c_str()); return format->second->value.find(tag) != string::npos; } bool has(string tag) { for (auto&& format : m_formats) if (format.second->value.find(tag) != string::npos) return true; return false; } protected: const config& m_conf; string m_modname; map<string, shared_ptr<module_format>> m_formats; }; // }}} // class definition : module_interface {{{ struct module_interface { public: virtual ~module_interface() {} virtual string name() const = 0; virtual bool running() const = 0; virtual void setup() = 0; virtual void start() = 0; virtual void stop() = 0; virtual void refresh() = 0; virtual string contents() = 0; virtual bool handle_event(string cmd) = 0; virtual bool receive_events() const = 0; delegate::Signal1<string> on_update; delegate::Signal1<string> on_stop; }; // }}} // class definition : module {{{ template <class Impl> class module : public module_interface { public: module(const bar_settings bar, const logger& logger, const config& config, string name) : m_bar(bar) , m_log(logger) , m_conf(config) , m_name("module/" + name) , m_builder(make_unique<builder>(bar)) , m_formatter(make_unique<module_formatter>(m_conf, m_name)) {} ~module() { if (enabled()) stop(); std::lock_guard<threading_util::spin_lock> lck(this->update_lock); { for (auto&& thread_ : m_threads) { if (thread_.joinable()) thread_.join(); } m_threads.clear(); } m_log.trace("%s: Done cleaning up", name()); } string name() const { return m_name; } bool running() const { return enabled(); } void setup() { m_log.trace("%s: Setup", name()); CAST_MODULE(Impl)->setup(); } void stop() { if (!enabled()) return; m_log.trace("%s: Stop", name()); enable(false); wakeup(); if (!on_stop.empty()) on_stop.emit(name()); } void refresh() { m_cache = CAST_MODULE(Impl)->get_output(); } string contents() { return m_cache; } bool handle_event(string cmd) { return CAST_MODULE(Impl)->handle_event(cmd); } bool receive_events() const { return false; } protected: bool enabled() const { return m_enabled; } void enable(bool state) { m_enabled = state; } void broadcast() { if (!enabled()) return; refresh(); if (contents().empty()) return; else if (on_update.empty()) m_log.warn("%s: No signal handlers connected... ignoring broadcast", name()); else on_update.emit(name()); } void idle() {} void sleep(chrono::duration<double> sleep_duration) { std::unique_lock<std::mutex> lck(m_sleeplock); m_sleephandler.wait_for(lck, sleep_duration); } void wakeup() { std::unique_lock<std::mutex> lck(m_sleeplock); m_log.trace("%s: Release sleep lock", name()); m_sleephandler.notify_all(); } string get_format() const { return DEFAULT_FORMAT; } string get_output() { if (!enabled()) { m_log.trace("%s: Module is disabled", name()); return ""; } auto format_name = CAST_MODULE(Impl)->get_format(); auto format = m_formatter->get(format_name); int i = 0; bool tag_built = true; for (auto tag : string_util::split(format->value, ' ')) { bool is_blankspace = tag.empty(); if (tag[0] == '<' && tag[tag.length() - 1] == '>') { if (i > 0) m_builder->space(format->spacing); if (!(tag_built = CAST_MODULE(Impl)->build(m_builder.get(), tag)) && i > 0) m_builder->remove_trailing_space(format->spacing); if (tag_built) i++; } else if (is_blankspace && tag_built) { m_builder->node(" "); } else if (!is_blankspace) { m_builder->node(tag); } } return format->decorate(m_builder.get(), m_builder->flush()); } protected: // concurrency::SpinLock output_lock; // concurrency::SpinLock broadcast_lock; threading_util::spin_lock update_lock; const bar_settings m_bar; const logger& m_log; const config& m_conf; std::mutex m_sleeplock; std::condition_variable m_sleephandler; string m_name; unique_ptr<builder> m_builder; unique_ptr<module_formatter> m_formatter; vector<thread> m_threads; private: stateflag m_enabled{false}; string m_cache; }; // }}} // class definition : static_module {{{ template <class Impl> class static_module : public module<Impl> { public: using module<Impl>::module; void start() { CAST_MODULE(Impl)->setup(); CAST_MODULE(Impl)->enable(true); CAST_MODULE(Impl)->broadcast(); } bool build(builder*, string) { return true; } }; // }}} // class definition : timer_module {{{ using interval_t = chrono::duration<double>; template <class Impl> class timer_module : public module<Impl> { public: using module<Impl>::module; void start() { CAST_MODULE(Impl)->enable(true); CAST_MODULE(Impl)->m_threads.emplace_back(thread(&timer_module::runner, this)); } protected: interval_t m_interval = 1s; void runner() { try { CAST_MODULE(Impl)->setup(); while (CONST_CAST_MODULE(Impl).enabled()) { { std::lock_guard<threading_util::spin_lock> lck(this->update_lock); if (CAST_MODULE(Impl)->update()) CAST_MODULE(Impl)->broadcast(); } CAST_MODULE(Impl)->sleep(m_interval); } } catch (const application_error& err) { this->m_log.err("%s: %s", this->name(), err.what()); this->m_log.warn("Stopping '%s'...", this->name()); CAST_MODULE(Impl)->stop(); } } }; // }}} // class definition : event_module {{{ template <class Impl> class event_module : public module<Impl> { public: using module<Impl>::module; void start() { CAST_MODULE(Impl)->enable(true); CAST_MODULE(Impl)->m_threads.emplace_back(thread(&event_module::runner, this)); } protected: void runner() { try { CAST_MODULE(Impl)->setup(); // warmup CAST_MODULE(Impl)->update(); CAST_MODULE(Impl)->broadcast(); while (CONST_CAST_MODULE(Impl).enabled()) { std::unique_lock<threading_util::spin_lock> lck(this->update_lock); if (!CAST_MODULE(Impl)->has_event()) continue; if (!CAST_MODULE(Impl)->update()) continue; CAST_MODULE(Impl)->broadcast(); lck.unlock(); CAST_MODULE(Impl)->idle(); } } catch (const application_error& err) { this->m_log.err("%s: %s", this->name(), err.what()); this->m_log.warn("Stopping '%s'...", this->name()); CAST_MODULE(Impl)->stop(); } } }; // }}} // class definition : inotify_module {{{ template <class Impl> class inotify_module : public module<Impl> { public: using module<Impl>::module; void start() { CAST_MODULE(Impl)->enable(true); CAST_MODULE(Impl)->m_threads.emplace_back(thread(&inotify_module::runner, this)); } protected: void runner() { try { CAST_MODULE(Impl)->setup(); CAST_MODULE(Impl)->on_event(nullptr); // warmup CAST_MODULE(Impl)->broadcast(); while (CAST_MODULE(Impl)->enabled()) { std::lock_guard<threading_util::spin_lock> lck(this->update_lock); CAST_MODULE(Impl)->poll_events(); } } catch (const application_error& err) { this->m_log.err("%s: %s", this->name(), err.what()); this->m_log.warn("Stopping '%s'...", this->name()); CAST_MODULE(Impl)->stop(); } } void watch(string path, int mask = IN_ALL_EVENTS) { this->m_log.trace("%s: Attach inotify at %s", this->name(), path); m_watchlist.insert(make_pair(path, mask)); } void idle() { CAST_MODULE(Impl)->sleep(200ms); } void poll_events() { vector<unique_ptr<inotify_watch>> watches; try { for (auto&& w : m_watchlist) { watches.emplace_back(inotify_util::make_watch(w.first)); watches.back()->attach(w.second); } } catch (const system_error& e) { watches.clear(); this->m_log.err( "%s: Error while creating inotify watch (what: %s)", this->name(), e.what()); CAST_MODULE(Impl)->sleep(0.1s); return; } while (CONST_CAST_MODULE(Impl).enabled()) { for (auto&& w : watches) { this->m_log.trace("%s: Poll inotify watch %s", this->name(), w->path()); if (w->poll(1000 / watches.size())) { auto event = w->get_event(); w->remove(); if (CAST_MODULE(Impl)->on_event(event.get())) CAST_MODULE(Impl)->broadcast(); return; } } CAST_MODULE(Impl)->idle(); } } private: map<string, int> m_watchlist; }; // }}} } LEMONBUDDY_NS_END <commit_msg>fix(modules): Generic method for broadcasting handled events<commit_after>#pragma once #include <algorithm> #include <condition_variable> #include <fastdelegate/fastdelegate.hpp> #include <mutex> #include "common.hpp" #include "components/builder.hpp" #include "components/config.hpp" #include "components/logger.hpp" #include "utils/inotify.hpp" #include "utils/string.hpp" #include "utils/threading.hpp" LEMONBUDDY_NS #define DEFAULT_FORMAT "format" #define DEFINE_MODULE(name, type) struct name : public type<name> #define CONST_CAST_MODULE(name) static_cast<name const&>(*this) #define CAST_MODULE(name) static_cast<name*>(this) namespace modules { using namespace drawtypes; DEFINE_ERROR(module_error); DEFINE_CHILD_ERROR(undefined_format, module_error); DEFINE_CHILD_ERROR(undefined_format_tag, module_error); // class definition : module_format {{{ struct module_format { string value; vector<string> tags; string fg; string bg; string ul; string ol; int spacing; int padding; int margin; int offset; string decorate(builder* builder, string output) { if (offset != 0) builder->offset(offset); if (margin > 0) builder->space(margin); if (!bg.empty()) builder->background(bg); if (!fg.empty()) builder->color(fg); if (!ul.empty()) builder->underline(ul); if (!ol.empty()) builder->overline(ol); if (padding > 0) builder->space(padding); builder->append(output); if (padding > 0) builder->space(padding); if (!ol.empty()) builder->overline_close(); if (!ul.empty()) builder->underline_close(); if (!fg.empty()) builder->color_close(); if (!bg.empty()) builder->background_close(); if (margin > 0) builder->space(margin); return builder->flush(); } }; // }}} // class definition : module_formatter {{{ class module_formatter { public: explicit module_formatter(const config& conf, string modname) : m_conf(conf), m_modname(modname) {} void add(string name, string fallback, vector<string>&& tags, vector<string>&& whitelist = {}) { auto format = make_unique<module_format>(); format->value = m_conf.get<string>(m_modname, name, fallback); format->fg = m_conf.get<string>(m_modname, name + "-foreground", ""); format->bg = m_conf.get<string>(m_modname, name + "-background", ""); format->ul = m_conf.get<string>(m_modname, name + "-underline", ""); format->ol = m_conf.get<string>(m_modname, name + "-overline", ""); format->spacing = m_conf.get<int>(m_modname, name + "-spacing", DEFAULT_SPACING); format->padding = m_conf.get<int>(m_modname, name + "-padding", 0); format->margin = m_conf.get<int>(m_modname, name + "-margin", 0); format->offset = m_conf.get<int>(m_modname, name + "-offset", 0); format->tags.swap(tags); for (auto&& tag : string_util::split(format->value, ' ')) { if (tag[0] != '<' || tag[tag.length() - 1] != '>') continue; if (std::find(format->tags.begin(), format->tags.end(), tag) != format->tags.end()) continue; if (std::find(whitelist.begin(), whitelist.end(), tag) != whitelist.end()) continue; throw undefined_format_tag("[" + m_modname + "] Undefined \"" + name + "\" tag: " + tag); } m_formats.insert(make_pair(name, std::move(format))); } shared_ptr<module_format> get(string format_name) { auto format = m_formats.find(format_name); if (format == m_formats.end()) throw undefined_format("Format \"" + format_name + "\" has not been added"); return format->second; } bool has(string tag, string format_name) { auto format = m_formats.find(format_name); if (format == m_formats.end()) throw undefined_format(format_name.c_str()); return format->second->value.find(tag) != string::npos; } bool has(string tag) { for (auto&& format : m_formats) if (format.second->value.find(tag) != string::npos) return true; return false; } protected: const config& m_conf; string m_modname; map<string, shared_ptr<module_format>> m_formats; }; // }}} // class definition : module_interface {{{ struct module_interface { public: virtual ~module_interface() {} virtual string name() const = 0; virtual bool running() const = 0; virtual void setup() = 0; virtual void start() = 0; virtual void stop() = 0; virtual void refresh() = 0; virtual string contents() = 0; virtual bool handle_event(string cmd) = 0; virtual bool receive_events() const = 0; delegate::Signal1<string> on_update; delegate::Signal1<string> on_stop; }; // }}} // class definition : module {{{ template <class Impl> class module : public module_interface { public: module(const bar_settings bar, const logger& logger, const config& config, string name) : m_bar(bar) , m_log(logger) , m_conf(config) , m_name("module/" + name) , m_builder(make_unique<builder>(bar)) , m_formatter(make_unique<module_formatter>(m_conf, m_name)) {} ~module() { if (enabled()) stop(); std::lock_guard<threading_util::spin_lock> lck(this->update_lock); { if (m_broadcast_thread.joinable()) m_broadcast_thread.join(); for (auto&& thread_ : m_threads) { if (thread_.joinable()) thread_.join(); } m_threads.clear(); } m_log.trace("%s: Done cleaning up", name()); } string name() const { return m_name; } bool running() const { return enabled(); } void setup() { m_log.trace("%s: Setup", name()); CAST_MODULE(Impl)->setup(); } void stop() { if (!enabled()) return; m_log.trace("%s: Stop", name()); enable(false); wakeup(); if (!on_stop.empty()) on_stop.emit(name()); } void refresh() { m_cache = CAST_MODULE(Impl)->get_output(); } string contents() { return m_cache; } bool handle_event(string cmd) { return CAST_MODULE(Impl)->handle_event(cmd); } bool receive_events() const { return false; } protected: bool enabled() const { return m_enabled; } void enable(bool state) { m_enabled = state; } void broadcast() { if (!enabled()) return; refresh(); if (contents().empty()) return; else if (on_update.empty()) m_log.warn("%s: No signal handlers connected... ignoring broadcast", name()); else on_update.emit(name()); } void idle() {} void sleep(chrono::duration<double> sleep_duration) { std::unique_lock<std::mutex> lck(m_sleeplock); m_sleephandler.wait_for(lck, sleep_duration); } void wakeup() { std::unique_lock<std::mutex> lck(m_sleeplock); m_log.trace("%s: Release sleep lock", name()); m_sleephandler.notify_all(); } string get_format() const { return DEFAULT_FORMAT; } string get_output() { if (!enabled()) { m_log.trace("%s: Module is disabled", name()); return ""; } auto format_name = CAST_MODULE(Impl)->get_format(); auto format = m_formatter->get(format_name); int i = 0; bool tag_built = true; for (auto tag : string_util::split(format->value, ' ')) { bool is_blankspace = tag.empty(); if (tag[0] == '<' && tag[tag.length() - 1] == '>') { if (i > 0) m_builder->space(format->spacing); if (!(tag_built = CAST_MODULE(Impl)->build(m_builder.get(), tag)) && i > 0) m_builder->remove_trailing_space(format->spacing); if (tag_built) i++; } else if (is_blankspace && tag_built) { m_builder->node(" "); } else if (!is_blankspace) { m_builder->node(tag); } } return format->decorate(m_builder.get(), m_builder->flush()); } protected: // Called by modules after handling action events void event_handled() { std::lock_guard<threading_util::spin_lock> lck(this->update_lock); { if (m_broadcast_thread.joinable()) m_broadcast_thread.join(); m_broadcast_thread = thread(&module::broadcast, this); } } // concurrency::SpinLock output_lock; // concurrency::SpinLock broadcast_lock; threading_util::spin_lock update_lock; const bar_settings m_bar; const logger& m_log; const config& m_conf; std::mutex m_sleeplock; std::condition_variable m_sleephandler; string m_name; unique_ptr<builder> m_builder; unique_ptr<module_formatter> m_formatter; vector<thread> m_threads; private: stateflag m_enabled{false}; string m_cache; thread m_broadcast_thread; }; // }}} // class definition : static_module {{{ template <class Impl> class static_module : public module<Impl> { public: using module<Impl>::module; void start() { CAST_MODULE(Impl)->setup(); CAST_MODULE(Impl)->enable(true); CAST_MODULE(Impl)->broadcast(); } bool build(builder*, string) { return true; } }; // }}} // class definition : timer_module {{{ using interval_t = chrono::duration<double>; template <class Impl> class timer_module : public module<Impl> { public: using module<Impl>::module; void start() { CAST_MODULE(Impl)->enable(true); CAST_MODULE(Impl)->m_threads.emplace_back(thread(&timer_module::runner, this)); } protected: interval_t m_interval = 1s; void runner() { try { CAST_MODULE(Impl)->setup(); while (CONST_CAST_MODULE(Impl).enabled()) { { std::lock_guard<threading_util::spin_lock> lck(this->update_lock); if (CAST_MODULE(Impl)->update()) CAST_MODULE(Impl)->broadcast(); } CAST_MODULE(Impl)->sleep(m_interval); } } catch (const application_error& err) { this->m_log.err("%s: %s", this->name(), err.what()); this->m_log.warn("Stopping '%s'...", this->name()); CAST_MODULE(Impl)->stop(); } } }; // }}} // class definition : event_module {{{ template <class Impl> class event_module : public module<Impl> { public: using module<Impl>::module; void start() { CAST_MODULE(Impl)->enable(true); CAST_MODULE(Impl)->m_threads.emplace_back(thread(&event_module::runner, this)); } protected: void runner() { try { CAST_MODULE(Impl)->setup(); // warmup CAST_MODULE(Impl)->update(); CAST_MODULE(Impl)->broadcast(); while (CONST_CAST_MODULE(Impl).enabled()) { std::unique_lock<threading_util::spin_lock> lck(this->update_lock); if (!CAST_MODULE(Impl)->has_event()) continue; if (!CAST_MODULE(Impl)->update()) continue; CAST_MODULE(Impl)->broadcast(); lck.unlock(); CAST_MODULE(Impl)->idle(); } } catch (const application_error& err) { this->m_log.err("%s: %s", this->name(), err.what()); this->m_log.warn("Stopping '%s'...", this->name()); CAST_MODULE(Impl)->stop(); } } }; // }}} // class definition : inotify_module {{{ template <class Impl> class inotify_module : public module<Impl> { public: using module<Impl>::module; void start() { CAST_MODULE(Impl)->enable(true); CAST_MODULE(Impl)->m_threads.emplace_back(thread(&inotify_module::runner, this)); } protected: void runner() { try { CAST_MODULE(Impl)->setup(); CAST_MODULE(Impl)->on_event(nullptr); // warmup CAST_MODULE(Impl)->broadcast(); while (CAST_MODULE(Impl)->enabled()) { std::lock_guard<threading_util::spin_lock> lck(this->update_lock); CAST_MODULE(Impl)->poll_events(); } } catch (const application_error& err) { this->m_log.err("%s: %s", this->name(), err.what()); this->m_log.warn("Stopping '%s'...", this->name()); CAST_MODULE(Impl)->stop(); } } void watch(string path, int mask = IN_ALL_EVENTS) { this->m_log.trace("%s: Attach inotify at %s", this->name(), path); m_watchlist.insert(make_pair(path, mask)); } void idle() { CAST_MODULE(Impl)->sleep(200ms); } void poll_events() { vector<unique_ptr<inotify_watch>> watches; try { for (auto&& w : m_watchlist) { watches.emplace_back(inotify_util::make_watch(w.first)); watches.back()->attach(w.second); } } catch (const system_error& e) { watches.clear(); this->m_log.err( "%s: Error while creating inotify watch (what: %s)", this->name(), e.what()); CAST_MODULE(Impl)->sleep(0.1s); return; } while (CONST_CAST_MODULE(Impl).enabled()) { for (auto&& w : watches) { this->m_log.trace("%s: Poll inotify watch %s", this->name(), w->path()); if (w->poll(1000 / watches.size())) { auto event = w->get_event(); w->remove(); if (CAST_MODULE(Impl)->on_event(event.get())) CAST_MODULE(Impl)->broadcast(); return; } } CAST_MODULE(Impl)->idle(); } } private: map<string, int> m_watchlist; }; // }}} } LEMONBUDDY_NS_END <|endoftext|>
<commit_before>// Copyright 2015 Open Source Robotics Foundation, 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 <gtest/gtest.h> #include <memory> #include <string> #include <utility> #include "lifecycle_msgs/msg/state.hpp" #include "lifecycle_msgs/msg/transition.hpp" #include "rclcpp/rclcpp.hpp" #include "rclcpp_lifecycle/lifecycle_node.hpp" using lifecycle_msgs::msg::State; using lifecycle_msgs::msg::Transition; class TestRegisterCustomCallbacks : public ::testing::Test { protected: static void SetUpTestCase() { rclcpp::init(0, nullptr); } }; class CustomLifecycleNode : public rclcpp_lifecycle::LifecycleNode { public: explicit CustomLifecycleNode(std::string node_name) : rclcpp_lifecycle::LifecycleNode(std::move(node_name)) {} size_t number_of_callbacks = 0; protected: rcl_lifecycle_transition_key_t on_configure(const rclcpp_lifecycle::State &) { ADD_FAILURE(); ++number_of_callbacks; return lifecycle_msgs::msg::Transition::TRANSITION_CALLBACK_SUCCESS; } rcl_lifecycle_transition_key_t on_activate(const rclcpp_lifecycle::State &) { ADD_FAILURE(); ++number_of_callbacks; return lifecycle_msgs::msg::Transition::TRANSITION_CALLBACK_SUCCESS; } rcl_lifecycle_transition_key_t on_deactivate(const rclcpp_lifecycle::State &) { ADD_FAILURE(); ++number_of_callbacks; return lifecycle_msgs::msg::Transition::TRANSITION_CALLBACK_SUCCESS; } rcl_lifecycle_transition_key_t on_cleanup(const rclcpp_lifecycle::State &) { ADD_FAILURE(); ++number_of_callbacks; return lifecycle_msgs::msg::Transition::TRANSITION_CALLBACK_SUCCESS; } rcl_lifecycle_transition_key_t on_shutdown(const rclcpp_lifecycle::State &) { ADD_FAILURE(); ++number_of_callbacks; return lifecycle_msgs::msg::Transition::TRANSITION_CALLBACK_SUCCESS; } // Custom callbacks public: rcl_lifecycle_transition_key_t on_custom_configure(const rclcpp_lifecycle::State & previous_state) { EXPECT_EQ(State::PRIMARY_STATE_UNCONFIGURED, previous_state.id()); EXPECT_EQ(State::TRANSITION_STATE_CONFIGURING, get_current_state().id()); ++number_of_callbacks; return lifecycle_msgs::msg::Transition::TRANSITION_CALLBACK_SUCCESS; } rcl_lifecycle_transition_key_t on_custom_activate(const rclcpp_lifecycle::State & previous_state) { EXPECT_EQ(State::PRIMARY_STATE_INACTIVE, previous_state.id()); EXPECT_EQ(State::TRANSITION_STATE_ACTIVATING, get_current_state().id()); ++number_of_callbacks; return lifecycle_msgs::msg::Transition::TRANSITION_CALLBACK_SUCCESS; } rcl_lifecycle_transition_key_t on_custom_deactivate(const rclcpp_lifecycle::State & previous_state) { EXPECT_EQ(State::PRIMARY_STATE_ACTIVE, previous_state.id()); EXPECT_EQ(State::TRANSITION_STATE_DEACTIVATING, get_current_state().id()); ++number_of_callbacks; return lifecycle_msgs::msg::Transition::TRANSITION_CALLBACK_SUCCESS; } rcl_lifecycle_transition_key_t on_custom_cleanup(const rclcpp_lifecycle::State & previous_state) { EXPECT_EQ(State::PRIMARY_STATE_INACTIVE, previous_state.id()); EXPECT_EQ(State::TRANSITION_STATE_CLEANINGUP, get_current_state().id()); ++number_of_callbacks; return lifecycle_msgs::msg::Transition::TRANSITION_CALLBACK_SUCCESS; } rcl_lifecycle_transition_key_t on_custom_shutdown(const rclcpp_lifecycle::State &) { EXPECT_EQ(State::TRANSITION_STATE_SHUTTINGDOWN, get_current_state().id()); ++number_of_callbacks; return lifecycle_msgs::msg::Transition::TRANSITION_CALLBACK_SUCCESS; } }; TEST_F(TestRegisterCustomCallbacks, custom_callbacks) { auto test_node = std::make_shared<CustomLifecycleNode>("testnode"); test_node->register_on_configure( std::bind(&CustomLifecycleNode::on_custom_configure, test_node, std::placeholders::_1)); test_node->register_on_cleanup(std::bind(&CustomLifecycleNode::on_custom_cleanup, test_node, std::placeholders::_1)); test_node->register_on_shutdown(std::bind(&CustomLifecycleNode::on_custom_shutdown, test_node, std::placeholders::_1)); test_node->register_on_activate(std::bind(&CustomLifecycleNode::on_custom_activate, test_node, std::placeholders::_1)); test_node->register_on_deactivate(std::bind(&CustomLifecycleNode::on_custom_deactivate, test_node, std::placeholders::_1)); EXPECT_EQ(State::PRIMARY_STATE_UNCONFIGURED, test_node->get_current_state().id()); EXPECT_EQ(State::PRIMARY_STATE_INACTIVE, test_node->trigger_transition( rclcpp_lifecycle::Transition(Transition::TRANSITION_CONFIGURE)).id()); EXPECT_EQ(State::PRIMARY_STATE_ACTIVE, test_node->trigger_transition( rclcpp_lifecycle::Transition(Transition::TRANSITION_ACTIVATE)).id()); EXPECT_EQ(State::PRIMARY_STATE_INACTIVE, test_node->trigger_transition( rclcpp_lifecycle::Transition(Transition::TRANSITION_DEACTIVATE)).id()); EXPECT_EQ(State::PRIMARY_STATE_UNCONFIGURED, test_node->trigger_transition( rclcpp_lifecycle::Transition(Transition::TRANSITION_CLEANUP)).id()); EXPECT_EQ(State::PRIMARY_STATE_FINALIZED, test_node->trigger_transition( rclcpp_lifecycle::Transition(Transition::TRANSITION_SHUTDOWN)).id()); // check if all callbacks were successfully overwritten EXPECT_EQ(static_cast<size_t>(5), test_node->number_of_callbacks); } <commit_msg>Fix bug when mixing shared_ptr and bind. (#470)<commit_after>// Copyright 2015 Open Source Robotics Foundation, 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 <gtest/gtest.h> #include <memory> #include <string> #include <utility> #include "lifecycle_msgs/msg/state.hpp" #include "lifecycle_msgs/msg/transition.hpp" #include "rclcpp/rclcpp.hpp" #include "rclcpp_lifecycle/lifecycle_node.hpp" using lifecycle_msgs::msg::State; using lifecycle_msgs::msg::Transition; class TestRegisterCustomCallbacks : public ::testing::Test { protected: static void SetUpTestCase() { rclcpp::init(0, nullptr); } }; class CustomLifecycleNode : public rclcpp_lifecycle::LifecycleNode { public: explicit CustomLifecycleNode(std::string node_name) : rclcpp_lifecycle::LifecycleNode(std::move(node_name)) {} size_t number_of_callbacks = 0; protected: rcl_lifecycle_transition_key_t on_configure(const rclcpp_lifecycle::State &) { ADD_FAILURE(); ++number_of_callbacks; return lifecycle_msgs::msg::Transition::TRANSITION_CALLBACK_SUCCESS; } rcl_lifecycle_transition_key_t on_activate(const rclcpp_lifecycle::State &) { ADD_FAILURE(); ++number_of_callbacks; return lifecycle_msgs::msg::Transition::TRANSITION_CALLBACK_SUCCESS; } rcl_lifecycle_transition_key_t on_deactivate(const rclcpp_lifecycle::State &) { ADD_FAILURE(); ++number_of_callbacks; return lifecycle_msgs::msg::Transition::TRANSITION_CALLBACK_SUCCESS; } rcl_lifecycle_transition_key_t on_cleanup(const rclcpp_lifecycle::State &) { ADD_FAILURE(); ++number_of_callbacks; return lifecycle_msgs::msg::Transition::TRANSITION_CALLBACK_SUCCESS; } rcl_lifecycle_transition_key_t on_shutdown(const rclcpp_lifecycle::State &) { ADD_FAILURE(); ++number_of_callbacks; return lifecycle_msgs::msg::Transition::TRANSITION_CALLBACK_SUCCESS; } // Custom callbacks public: rcl_lifecycle_transition_key_t on_custom_configure(const rclcpp_lifecycle::State & previous_state) { EXPECT_EQ(State::PRIMARY_STATE_UNCONFIGURED, previous_state.id()); EXPECT_EQ(State::TRANSITION_STATE_CONFIGURING, get_current_state().id()); ++number_of_callbacks; return lifecycle_msgs::msg::Transition::TRANSITION_CALLBACK_SUCCESS; } rcl_lifecycle_transition_key_t on_custom_activate(const rclcpp_lifecycle::State & previous_state) { EXPECT_EQ(State::PRIMARY_STATE_INACTIVE, previous_state.id()); EXPECT_EQ(State::TRANSITION_STATE_ACTIVATING, get_current_state().id()); ++number_of_callbacks; return lifecycle_msgs::msg::Transition::TRANSITION_CALLBACK_SUCCESS; } rcl_lifecycle_transition_key_t on_custom_deactivate(const rclcpp_lifecycle::State & previous_state) { EXPECT_EQ(State::PRIMARY_STATE_ACTIVE, previous_state.id()); EXPECT_EQ(State::TRANSITION_STATE_DEACTIVATING, get_current_state().id()); ++number_of_callbacks; return lifecycle_msgs::msg::Transition::TRANSITION_CALLBACK_SUCCESS; } rcl_lifecycle_transition_key_t on_custom_cleanup(const rclcpp_lifecycle::State & previous_state) { EXPECT_EQ(State::PRIMARY_STATE_INACTIVE, previous_state.id()); EXPECT_EQ(State::TRANSITION_STATE_CLEANINGUP, get_current_state().id()); ++number_of_callbacks; return lifecycle_msgs::msg::Transition::TRANSITION_CALLBACK_SUCCESS; } rcl_lifecycle_transition_key_t on_custom_shutdown(const rclcpp_lifecycle::State &) { EXPECT_EQ(State::TRANSITION_STATE_SHUTTINGDOWN, get_current_state().id()); ++number_of_callbacks; return lifecycle_msgs::msg::Transition::TRANSITION_CALLBACK_SUCCESS; } }; TEST_F(TestRegisterCustomCallbacks, custom_callbacks) { auto test_node = std::make_shared<CustomLifecycleNode>("testnode"); test_node->register_on_configure(std::bind(&CustomLifecycleNode::on_custom_configure, test_node.get(), std::placeholders::_1)); test_node->register_on_cleanup(std::bind(&CustomLifecycleNode::on_custom_cleanup, test_node.get(), std::placeholders::_1)); test_node->register_on_shutdown(std::bind(&CustomLifecycleNode::on_custom_shutdown, test_node.get(), std::placeholders::_1)); test_node->register_on_activate(std::bind(&CustomLifecycleNode::on_custom_activate, test_node.get(), std::placeholders::_1)); test_node->register_on_deactivate(std::bind(&CustomLifecycleNode::on_custom_deactivate, test_node.get(), std::placeholders::_1)); EXPECT_EQ(State::PRIMARY_STATE_UNCONFIGURED, test_node->get_current_state().id()); EXPECT_EQ(State::PRIMARY_STATE_INACTIVE, test_node->trigger_transition( rclcpp_lifecycle::Transition(Transition::TRANSITION_CONFIGURE)).id()); EXPECT_EQ(State::PRIMARY_STATE_ACTIVE, test_node->trigger_transition( rclcpp_lifecycle::Transition(Transition::TRANSITION_ACTIVATE)).id()); EXPECT_EQ(State::PRIMARY_STATE_INACTIVE, test_node->trigger_transition( rclcpp_lifecycle::Transition(Transition::TRANSITION_DEACTIVATE)).id()); EXPECT_EQ(State::PRIMARY_STATE_UNCONFIGURED, test_node->trigger_transition( rclcpp_lifecycle::Transition(Transition::TRANSITION_CLEANUP)).id()); EXPECT_EQ(State::PRIMARY_STATE_FINALIZED, test_node->trigger_transition( rclcpp_lifecycle::Transition(Transition::TRANSITION_SHUTDOWN)).id()); // check if all callbacks were successfully overwritten EXPECT_EQ(static_cast<size_t>(5), test_node->number_of_callbacks); } <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "catch.hpp" #include "etl/fast_matrix.hpp" #include "etl/fast_vector.hpp" #include "etl/dyn_matrix.hpp" #include "etl/dyn_vector.hpp" ///{{{ Dim TEST_CASE( "dim/fast_matrix_1", "dim<1>" ) { etl::fast_matrix<double, 2, 3> a({1.0, -2.0, 4.0, 3.0, 0.5, -0.1}); etl::fast_vector<double, 3> b(etl::dim<1>(a, 0)); etl::fast_vector<double, 3> c(etl::dim<1>(a, 1)); REQUIRE(etl::etl_traits<remove_cv_t<remove_reference_t<decltype(b)>>>::is_fast); REQUIRE(etl::etl_traits<remove_cv_t<remove_reference_t<decltype(c)>>>::is_fast); REQUIRE(b[0] == 1.0); REQUIRE(b[1] == -2.0); REQUIRE(b[2] == 4.0); REQUIRE(c[0] == 3.0); REQUIRE(c[1] == 0.5); REQUIRE(c[2] == -0.1); } TEST_CASE( "dim/fast_matrix_2", "dim<2>" ) { etl::fast_matrix<double, 2, 3> a({1.0, -2.0, 4.0, 3.0, 0.5, -0.1}); etl::fast_vector<double, 2> b(etl::dim<2>(a, 0)); etl::fast_vector<double, 2> c(etl::dim<2>(a, 1)); etl::fast_vector<double, 2> d(etl::dim<2>(a, 2)); REQUIRE(etl::etl_traits<remove_cv_t<remove_reference_t<decltype(b)>>>::is_fast); REQUIRE(etl::etl_traits<remove_cv_t<remove_reference_t<decltype(c)>>>::is_fast); REQUIRE(etl::etl_traits<remove_cv_t<remove_reference_t<decltype(d)>>>::is_fast); REQUIRE(b[0] == 1.0); REQUIRE(b[1] == 3.0); REQUIRE(c[0] == -2.0); REQUIRE(c[1] == 0.5); REQUIRE(d[0] == 4.0); REQUIRE(d[1] == -0.1); } TEST_CASE( "dim/fast_matrix_3", "row" ) { etl::fast_matrix<double, 2, 3> a({1.0, -2.0, 4.0, 3.0, 0.5, -0.1}); etl::fast_vector<double, 3> b(etl::row(a, 0)); etl::fast_vector<double, 3> c(etl::row(a, 1)); REQUIRE(etl::etl_traits<remove_cv_t<remove_reference_t<decltype(b)>>>::is_fast); REQUIRE(etl::etl_traits<remove_cv_t<remove_reference_t<decltype(c)>>>::is_fast); REQUIRE(b[0] == 1.0); REQUIRE(b[1] == -2.0); REQUIRE(b[2] == 4.0); REQUIRE(c[0] == 3.0); REQUIRE(c[1] == 0.5); REQUIRE(c[2] == -0.1); } TEST_CASE( "dim/fast_matrix_4", "col" ) { etl::fast_matrix<double, 2, 3> a({1.0, -2.0, 4.0, 3.0, 0.5, -0.1}); etl::fast_vector<double, 2> b(etl::col(a, 0)); etl::fast_vector<double, 2> c(etl::col(a, 1)); etl::fast_vector<double, 2> d(etl::col(a, 2)); REQUIRE(etl::etl_traits<remove_cv_t<remove_reference_t<decltype(b)>>>::is_fast); REQUIRE(etl::etl_traits<remove_cv_t<remove_reference_t<decltype(c)>>>::is_fast); REQUIRE(etl::etl_traits<remove_cv_t<remove_reference_t<decltype(d)>>>::is_fast); REQUIRE(b[0] == 1.0); REQUIRE(b[1] == 3.0); REQUIRE(c[0] == -2.0); REQUIRE(c[1] == 0.5); REQUIRE(d[0] == 4.0); REQUIRE(d[1] == -0.1); } TEST_CASE( "dim/dyn_matrix_1", "dim<1>" ) { etl::dyn_matrix<double> a(2, 3, {1.0, -2.0, 4.0, 3.0, 0.5, -0.1}); etl::dyn_vector<double> b(etl::dim<1>(a, 0)); etl::dyn_vector<double> c(etl::dim<1>(a, 1)); REQUIRE(!etl::etl_traits<remove_cv_t<remove_reference_t<decltype(b)>>>::is_fast); REQUIRE(!etl::etl_traits<remove_cv_t<remove_reference_t<decltype(c)>>>::is_fast); REQUIRE(b[0] == 1.0); REQUIRE(b[1] == -2.0); REQUIRE(b[2] == 4.0); REQUIRE(c[0] == 3.0); REQUIRE(c[1] == 0.5); REQUIRE(c[2] == -0.1); } TEST_CASE( "dim/dyn_matrix_2", "dim<2>" ) { etl::dyn_matrix<double> a(2, 3, {1.0, -2.0, 4.0, 3.0, 0.5, -0.1}); etl::dyn_vector<double> b(etl::dim<2>(a, 0)); etl::dyn_vector<double> c(etl::dim<2>(a, 1)); etl::dyn_vector<double> d(etl::dim<2>(a, 2)); REQUIRE(!etl::etl_traits<remove_cv_t<remove_reference_t<decltype(b)>>>::is_fast); REQUIRE(!etl::etl_traits<remove_cv_t<remove_reference_t<decltype(c)>>>::is_fast); REQUIRE(!etl::etl_traits<remove_cv_t<remove_reference_t<decltype(d)>>>::is_fast); REQUIRE(b[0] == 1.0); REQUIRE(b[1] == 3.0); REQUIRE(c[0] == -2.0); REQUIRE(c[1] == 0.5); REQUIRE(d[0] == 4.0); REQUIRE(d[1] == -0.1); } TEST_CASE( "dim/mix", "dim" ) { etl::fast_matrix<double, 2, 3> a({1.0, -2.0, 4.0, 3.0, 0.5, -0.1}); etl::fast_vector<double, 3> b({0.1, 0.2, 0.3}); etl::fast_vector<double, 3> c(b * row(a,1)); REQUIRE(c[0] == Approx(0.3)); REQUIRE(c[1] == Approx(0.1)); REQUIRE(c[2] == Approx(-0.03)); } ///}}} //{{{ reshape TEST_CASE( "reshape/fast_vector_1", "reshape<2,2>" ) { etl::fast_vector<double, 4> a({1,2,3,4}); etl::fast_matrix<double, 2, 2> b(etl::reshape<2,2>(a)); REQUIRE(b(0,0) == 1.0); REQUIRE(b(0,1) == 2.0); REQUIRE(b(1,0) == 3.0); REQUIRE(b(1,1) == 4.0); } TEST_CASE( "reshape/fast_vector_2", "reshape<2,3>" ) { etl::fast_vector<double, 6> a({1,2,3,4,5,6}); etl::fast_matrix<double, 2, 3> b(etl::reshape<2,3>(a)); REQUIRE(b(0,0) == 1.0); REQUIRE(b(0,1) == 2.0); REQUIRE(b(0,2) == 3.0); REQUIRE(b(1,0) == 4.0); REQUIRE(b(1,1) == 5.0); REQUIRE(b(1,2) == 6.0); } TEST_CASE( "reshape/traits", "traits<reshape<2,3>>" ) { etl::fast_vector<double, 6> a({1,2,3,4,5,6}); using expr_type = decltype(etl::reshape<2,3>(a)); expr_type expr((etl::fast_matrix_view<etl::fast_vector<double, 6>, 2, 3>(a))); REQUIRE(etl::etl_traits<expr_type>::size(expr) == 6); REQUIRE(etl::size(expr) == 6); REQUIRE(etl::etl_traits<expr_type>::rows(expr) == 2); REQUIRE(etl::rows(expr) == 2); REQUIRE(etl::etl_traits<expr_type>::columns(expr) == 3); REQUIRE(etl::columns(expr) == 3); REQUIRE(etl::etl_traits<expr_type>::is_matrix); REQUIRE(!etl::etl_traits<expr_type>::is_value); REQUIRE(etl::etl_traits<expr_type>::is_fast); REQUIRE(!etl::etl_traits<expr_type>::is_vector); constexpr const auto size_1 = etl::etl_traits<expr_type>::size(); constexpr const auto rows_1 = etl::etl_traits<expr_type>::rows(); constexpr const auto columns_1 = etl::etl_traits<expr_type>::columns(); REQUIRE(size_1 == 6); REQUIRE(rows_1 == 2); REQUIRE(columns_1 == 3); constexpr const auto size_2 = etl::size(expr); constexpr const auto rows_2 = etl::rows(expr); constexpr const auto columns_2 = etl::columns(expr); REQUIRE(size_2 == 6); REQUIRE(rows_2 == 2); REQUIRE(columns_2 == 3); } //}}}<commit_msg>Add test for reshape on dyn_matrix<commit_after>//======================================================================= // Copyright (c) 2014 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "catch.hpp" #include "etl/fast_matrix.hpp" #include "etl/fast_vector.hpp" #include "etl/dyn_matrix.hpp" #include "etl/dyn_vector.hpp" ///{{{ Dim TEST_CASE( "dim/fast_matrix_1", "dim<1>" ) { etl::fast_matrix<double, 2, 3> a({1.0, -2.0, 4.0, 3.0, 0.5, -0.1}); etl::fast_vector<double, 3> b(etl::dim<1>(a, 0)); etl::fast_vector<double, 3> c(etl::dim<1>(a, 1)); REQUIRE(etl::etl_traits<remove_cv_t<remove_reference_t<decltype(b)>>>::is_fast); REQUIRE(etl::etl_traits<remove_cv_t<remove_reference_t<decltype(c)>>>::is_fast); REQUIRE(b[0] == 1.0); REQUIRE(b[1] == -2.0); REQUIRE(b[2] == 4.0); REQUIRE(c[0] == 3.0); REQUIRE(c[1] == 0.5); REQUIRE(c[2] == -0.1); } TEST_CASE( "dim/fast_matrix_2", "dim<2>" ) { etl::fast_matrix<double, 2, 3> a({1.0, -2.0, 4.0, 3.0, 0.5, -0.1}); etl::fast_vector<double, 2> b(etl::dim<2>(a, 0)); etl::fast_vector<double, 2> c(etl::dim<2>(a, 1)); etl::fast_vector<double, 2> d(etl::dim<2>(a, 2)); REQUIRE(etl::etl_traits<remove_cv_t<remove_reference_t<decltype(b)>>>::is_fast); REQUIRE(etl::etl_traits<remove_cv_t<remove_reference_t<decltype(c)>>>::is_fast); REQUIRE(etl::etl_traits<remove_cv_t<remove_reference_t<decltype(d)>>>::is_fast); REQUIRE(b[0] == 1.0); REQUIRE(b[1] == 3.0); REQUIRE(c[0] == -2.0); REQUIRE(c[1] == 0.5); REQUIRE(d[0] == 4.0); REQUIRE(d[1] == -0.1); } TEST_CASE( "dim/fast_matrix_3", "row" ) { etl::fast_matrix<double, 2, 3> a({1.0, -2.0, 4.0, 3.0, 0.5, -0.1}); etl::fast_vector<double, 3> b(etl::row(a, 0)); etl::fast_vector<double, 3> c(etl::row(a, 1)); REQUIRE(etl::etl_traits<remove_cv_t<remove_reference_t<decltype(b)>>>::is_fast); REQUIRE(etl::etl_traits<remove_cv_t<remove_reference_t<decltype(c)>>>::is_fast); REQUIRE(b[0] == 1.0); REQUIRE(b[1] == -2.0); REQUIRE(b[2] == 4.0); REQUIRE(c[0] == 3.0); REQUIRE(c[1] == 0.5); REQUIRE(c[2] == -0.1); } TEST_CASE( "dim/fast_matrix_4", "col" ) { etl::fast_matrix<double, 2, 3> a({1.0, -2.0, 4.0, 3.0, 0.5, -0.1}); etl::fast_vector<double, 2> b(etl::col(a, 0)); etl::fast_vector<double, 2> c(etl::col(a, 1)); etl::fast_vector<double, 2> d(etl::col(a, 2)); REQUIRE(etl::etl_traits<remove_cv_t<remove_reference_t<decltype(b)>>>::is_fast); REQUIRE(etl::etl_traits<remove_cv_t<remove_reference_t<decltype(c)>>>::is_fast); REQUIRE(etl::etl_traits<remove_cv_t<remove_reference_t<decltype(d)>>>::is_fast); REQUIRE(b[0] == 1.0); REQUIRE(b[1] == 3.0); REQUIRE(c[0] == -2.0); REQUIRE(c[1] == 0.5); REQUIRE(d[0] == 4.0); REQUIRE(d[1] == -0.1); } TEST_CASE( "dim/dyn_matrix_1", "dim<1>" ) { etl::dyn_matrix<double> a(2, 3, {1.0, -2.0, 4.0, 3.0, 0.5, -0.1}); etl::dyn_vector<double> b(etl::dim<1>(a, 0)); etl::dyn_vector<double> c(etl::dim<1>(a, 1)); REQUIRE(!etl::etl_traits<remove_cv_t<remove_reference_t<decltype(b)>>>::is_fast); REQUIRE(!etl::etl_traits<remove_cv_t<remove_reference_t<decltype(c)>>>::is_fast); REQUIRE(b[0] == 1.0); REQUIRE(b[1] == -2.0); REQUIRE(b[2] == 4.0); REQUIRE(c[0] == 3.0); REQUIRE(c[1] == 0.5); REQUIRE(c[2] == -0.1); } TEST_CASE( "dim/dyn_matrix_2", "dim<2>" ) { etl::dyn_matrix<double> a(2, 3, {1.0, -2.0, 4.0, 3.0, 0.5, -0.1}); etl::dyn_vector<double> b(etl::dim<2>(a, 0)); etl::dyn_vector<double> c(etl::dim<2>(a, 1)); etl::dyn_vector<double> d(etl::dim<2>(a, 2)); REQUIRE(!etl::etl_traits<remove_cv_t<remove_reference_t<decltype(b)>>>::is_fast); REQUIRE(!etl::etl_traits<remove_cv_t<remove_reference_t<decltype(c)>>>::is_fast); REQUIRE(!etl::etl_traits<remove_cv_t<remove_reference_t<decltype(d)>>>::is_fast); REQUIRE(b[0] == 1.0); REQUIRE(b[1] == 3.0); REQUIRE(c[0] == -2.0); REQUIRE(c[1] == 0.5); REQUIRE(d[0] == 4.0); REQUIRE(d[1] == -0.1); } TEST_CASE( "dim/mix", "dim" ) { etl::fast_matrix<double, 2, 3> a({1.0, -2.0, 4.0, 3.0, 0.5, -0.1}); etl::fast_vector<double, 3> b({0.1, 0.2, 0.3}); etl::fast_vector<double, 3> c(b * row(a,1)); REQUIRE(c[0] == Approx(0.3)); REQUIRE(c[1] == Approx(0.1)); REQUIRE(c[2] == Approx(-0.03)); } ///}}} //{{{ reshape TEST_CASE( "reshape/fast_vector_1", "reshape<2,2>" ) { etl::fast_vector<double, 4> a({1,2,3,4}); etl::fast_matrix<double, 2, 2> b(etl::reshape<2,2>(a)); REQUIRE(b(0,0) == 1.0); REQUIRE(b(0,1) == 2.0); REQUIRE(b(1,0) == 3.0); REQUIRE(b(1,1) == 4.0); } TEST_CASE( "reshape/fast_vector_2", "reshape<2,3>" ) { etl::fast_vector<double, 6> a({1,2,3,4,5,6}); etl::fast_matrix<double, 2, 3> b(etl::reshape<2,3>(a)); REQUIRE(b(0,0) == 1.0); REQUIRE(b(0,1) == 2.0); REQUIRE(b(0,2) == 3.0); REQUIRE(b(1,0) == 4.0); REQUIRE(b(1,1) == 5.0); REQUIRE(b(1,2) == 6.0); } TEST_CASE( "reshape/traits", "traits<reshape<2,3>>" ) { etl::fast_vector<double, 6> a({1,2,3,4,5,6}); using expr_type = decltype(etl::reshape<2,3>(a)); expr_type expr((etl::fast_matrix_view<etl::fast_vector<double, 6>, 2, 3>(a))); REQUIRE(etl::etl_traits<expr_type>::size(expr) == 6); REQUIRE(etl::size(expr) == 6); REQUIRE(etl::etl_traits<expr_type>::rows(expr) == 2); REQUIRE(etl::rows(expr) == 2); REQUIRE(etl::etl_traits<expr_type>::columns(expr) == 3); REQUIRE(etl::columns(expr) == 3); REQUIRE(etl::etl_traits<expr_type>::is_matrix); REQUIRE(!etl::etl_traits<expr_type>::is_value); REQUIRE(etl::etl_traits<expr_type>::is_fast); REQUIRE(!etl::etl_traits<expr_type>::is_vector); constexpr const auto size_1 = etl::etl_traits<expr_type>::size(); constexpr const auto rows_1 = etl::etl_traits<expr_type>::rows(); constexpr const auto columns_1 = etl::etl_traits<expr_type>::columns(); REQUIRE(size_1 == 6); REQUIRE(rows_1 == 2); REQUIRE(columns_1 == 3); constexpr const auto size_2 = etl::size(expr); constexpr const auto rows_2 = etl::rows(expr); constexpr const auto columns_2 = etl::columns(expr); REQUIRE(size_2 == 6); REQUIRE(rows_2 == 2); REQUIRE(columns_2 == 3); } TEST_CASE( "reshape/dyn_vector_1", "reshape(2,2)" ) { etl::dyn_vector<double> a({1,2,3,4}); etl::dyn_matrix<double> b(etl::reshape(a,2,2)); REQUIRE(b(0,0) == 1.0); REQUIRE(b(0,1) == 2.0); REQUIRE(b(1,0) == 3.0); REQUIRE(b(1,1) == 4.0); } TEST_CASE( "reshape/dyn_vector_2", "reshape(2,3)" ) { etl::dyn_vector<double> a({1,2,3,4,5,6}); etl::dyn_matrix<double> b(etl::reshape(a,2,3)); REQUIRE(b(0,0) == 1.0); REQUIRE(b(0,1) == 2.0); REQUIRE(b(0,2) == 3.0); REQUIRE(b(1,0) == 4.0); REQUIRE(b(1,1) == 5.0); REQUIRE(b(1,2) == 6.0); } TEST_CASE( "reshape/dyn_traits", "traits<reshape<2,3>>" ) { etl::dyn_vector<double> a({1,2,3,4,5,6}); using expr_type = decltype(etl::reshape(a,2,3)); expr_type expr((etl::dyn_matrix_view<etl::dyn_vector<double>>(a,2,3))); REQUIRE(etl::etl_traits<expr_type>::size(expr) == 6); REQUIRE(etl::size(expr) == 6); REQUIRE(etl::etl_traits<expr_type>::rows(expr) == 2); REQUIRE(etl::rows(expr) == 2); REQUIRE(etl::etl_traits<expr_type>::columns(expr) == 3); REQUIRE(etl::columns(expr) == 3); REQUIRE(etl::etl_traits<expr_type>::is_matrix); REQUIRE(!etl::etl_traits<expr_type>::is_value); REQUIRE(!etl::etl_traits<expr_type>::is_fast); REQUIRE(!etl::etl_traits<expr_type>::is_vector); } //}}}<|endoftext|>
<commit_before>#include "application.h" #include "Adafruit_LEDBackpack.h" #include <math.h> #define TEMP_SENSOR 0x27 #define FAN_PIN A0 #define HEAT_PIN A1 #define POT_PIN A2 #define PIR_PIN A3 #define DESIRED_TEMP_FLASH_ADDRESS 0x80400 Adafruit_8x8matrix matrix1; Adafruit_8x8matrix matrix2; Adafruit_8x8matrix matrix3; static const uint8_t smile[] = { 0b00111100, 0b01000010, 0b10100101, 0b10000001, 0b10100101, 0b10011001, 0b01000010, 0b00111100 }; int currentTemperature = 0; int desiredTemperature = 0; bool isHeatOn = false; bool isFanOn = false; int lastChangedPot = -80; void displayTemperature(void) { char ones = desiredTemperature % 10; char tens = (desiredTemperature / 10) % 10; matrix1.clear(); matrix1.setCursor(0, 0); matrix1.write(tens + '0'); matrix1.writeDisplay(); matrix2.clear(); matrix2.setCursor(0, 0); matrix2.write(ones + '0'); matrix2.writeDisplay(); } void saveTemperature() { Serial.println("Saving temperature to flash"); sFLASH_WriteByte(DESIRED_TEMP_FLASH_ADDRESS, (uint8_t)desiredTemperature); } void loadTemperature() { Serial.println("Loading and displaying temperature from flash"); uint8_t temp; sFLASH_ReadBuffer(&temp, DESIRED_TEMP_FLASH_ADDRESS, 1); desiredTemperature = temp; displayTemperature(); } int setTemperature(int t) { desiredTemperature = t; displayTemperature(); saveTemperature(); return desiredTemperature; } int setTemperatureFromString(String t) { // TODO more robust error handling // what if t is not a number // what if t is outside 50-90 range Serial.print("Setting desired temp from web to "); Serial.println(t); return setTemperature(t.toInt()); } void setupMatrix(Adafruit_8x8matrix m) { m.clear(); m.writeDisplay(); m.setTextSize(1); m.setTextWrap(false); m.setTextColor(LED_ON); m.setRotation(0); m.setCursor(0, 0); } void setup() { Wire.begin(); matrix1.begin(0x70); matrix2.begin(0x71); matrix3.begin(0x72); setupMatrix(matrix1); setupMatrix(matrix2); setupMatrix(matrix3); Spark.function("set_temp", setTemperatureFromString); Spark.variable("current_temp", &currentTemperature, INT); Spark.variable("desired_temp", &desiredTemperature, INT); Spark.variable("is_heat_on", &isHeatOn, BOOLEAN); Spark.variable("is_fan_on", &isFanOn, BOOLEAN); loadTemperature(); pinMode(FAN_PIN, OUTPUT); pinMode(HEAT_PIN, OUTPUT); pinMode(POT_PIN, INPUT); pinMode(PIR_PIN, INPUT); Serial.begin(9600); } void loop() { static int wait = 1000; if (!wait) { wait = 1000; Wire.beginTransmission(TEMP_SENSOR); Wire.endTransmission(); delay(40); Wire.requestFrom(TEMP_SENSOR, 4); uint8_t b = Wire.read(); Serial.print("I2C Status bits are "); Serial.println(b >> 6); int humidity = (b << 8) & 0x3f00; humidity |= Wire.read(); float percentHumidity = humidity / 163.83; Serial.print("Relative humidity is "); Serial.println(percentHumidity); int temp = (Wire.read() << 6) & 0x3fc0; temp |= Wire.read() >> 2; temp *= 165; float fTemp = temp / 16383.0 - 40.0; fTemp = fTemp * 1.8 + 32.0; // convert to fahrenheit currentTemperature = roundf(fTemp); Serial.print("Temperature is "); Serial.println(fTemp); } int pot = 4095 - analogRead(POT_PIN); if (1000 == wait) { Serial.print("Potentiometer reading: "); Serial.println(pot); } // If user has adjusted the potentiometer if (fabsf(pot - lastChangedPot) > 64) { // Don't set temp on boot if (lastChangedPot >= 0) { // map 0-4095 pot range to 50-90 temperature range int t = roundf(pot * (40.0/4095.0) + 50.0); setTemperature(t); Serial.print("Setting desired temp based on potentiometer to "); Serial.println(t); } lastChangedPot = pot; } digitalWrite(HEAT_PIN, desiredTemperature > currentTemperature); // placeholder nonsense... probably need to attach interrupt to PIR digitalWrite(FAN_PIN, digitalRead(PIR_PIN)); --wait; } <commit_msg>Flash read/write works now<commit_after>#include "application.h" #include "Adafruit_LEDBackpack.h" #include <math.h> #define TEMP_SENSOR 0x27 #define FAN_PIN A0 #define HEAT_PIN A1 #define POT_PIN A2 #define PIR_PIN A3 #define DESIRED_TEMP_FLASH_ADDRESS 0x80000 Adafruit_8x8matrix matrix1; Adafruit_8x8matrix matrix2; Adafruit_8x8matrix matrix3; static const uint8_t smile[] = { 0b00111100, 0b01000010, 0b10100101, 0b10000001, 0b10100101, 0b10011001, 0b01000010, 0b00111100 }; int currentTemperature = 0; int desiredTemperature = 0; bool isHeatOn = false; bool isFanOn = false; bool motionDetected = false; int lastChangedPot = -80; void displayTemperature(void) { char ones = desiredTemperature % 10; char tens = (desiredTemperature / 10) % 10; matrix1.clear(); matrix1.setCursor(0, 0); matrix1.write(tens + '0'); matrix1.writeDisplay(); matrix2.clear(); matrix2.setCursor(0, 0); matrix2.write(ones + '0'); matrix2.writeDisplay(); } void saveTemperature() { sFLASH_EraseSector(DESIRED_TEMP_FLASH_ADDRESS); Serial.println("Saving temperature to flash"); uint8_t values[2] = { (uint8_t)desiredTemperature, 0 }; sFLASH_WritePage(values, DESIRED_TEMP_FLASH_ADDRESS, 2); } void loadTemperature() { Serial.println("Loading and displaying temperature from flash"); uint8_t values[2]; sFLASH_ReadBuffer(values, DESIRED_TEMP_FLASH_ADDRESS, 2); desiredTemperature = values[0]; displayTemperature(); } int setTemperature(int t) { desiredTemperature = t; displayTemperature(); saveTemperature(); return desiredTemperature; } int setTemperatureFromString(String t) { // TODO more robust error handling // what if t is not a number // what if t is outside 50-90 range Serial.print("Setting desired temp from web to "); Serial.println(t); return setTemperature(t.toInt()); } void setupMatrix(Adafruit_8x8matrix m) { m.clear(); m.writeDisplay(); m.setTextSize(1); m.setTextWrap(false); m.setTextColor(LED_ON); m.setRotation(0); m.setCursor(0, 0); } void setup() { Wire.begin(); matrix1.begin(0x70); matrix2.begin(0x71); matrix3.begin(0x72); setupMatrix(matrix1); setupMatrix(matrix2); setupMatrix(matrix3); Spark.function("set_temp", setTemperatureFromString); Spark.variable("current_temp", &currentTemperature, INT); Spark.variable("desired_temp", &desiredTemperature, INT); Spark.variable("is_heat_on", &isHeatOn, BOOLEAN); Spark.variable("is_fan_on", &isFanOn, BOOLEAN); Serial.begin(9600); loadTemperature(); pinMode(FAN_PIN, OUTPUT); pinMode(HEAT_PIN, OUTPUT); pinMode(POT_PIN, INPUT); pinMode(PIR_PIN, INPUT); } void loop() { static int wait = 0; if (!wait) { wait = 1000; Wire.beginTransmission(TEMP_SENSOR); Wire.endTransmission(); delay(40); Wire.requestFrom(TEMP_SENSOR, 4); uint8_t b = Wire.read(); Serial.print("I2C Status bits are "); Serial.println(b >> 6); int humidity = (b << 8) & 0x3f00; humidity |= Wire.read(); float percentHumidity = humidity / 163.83; Serial.print("Relative humidity is "); Serial.println(percentHumidity); int temp = (Wire.read() << 6) & 0x3fc0; temp |= Wire.read() >> 2; temp *= 165; float fTemp = temp / 16383.0 - 40.0; fTemp = fTemp * 1.8 + 32.0; // convert to fahrenheit currentTemperature = roundf(fTemp); Serial.print("Temperature is "); Serial.println(fTemp); } int pot = 4095 - analogRead(POT_PIN); if (1000 == wait) { Serial.print("Potentiometer reading: "); Serial.println(pot); Serial.print("PIR reading: "); Serial.println(analogRead(PIR_PIN)); } if (3550 < analogRead(PIR_PIN)) { motionDetected = true; // lean more toward comfort than energy efficiency } // If user has adjusted the potentiometer if (fabsf(pot - lastChangedPot) > 64) { // Don't set temp on boot if (lastChangedPot >= 0) { // map 0-4095 pot range to 50-90 temperature range int t = roundf(pot * (40.0/4095.0) + 50.0); setTemperature(t); Serial.print("Setting desired temp based on potentiometer to "); Serial.println(t); } lastChangedPot = pot; } isHeatOn = desiredTemperature > currentTemperature; digitalWrite(HEAT_PIN, isHeatOn); // just run them at the same time for now isFanOn = isHeatOn; digitalWrite(FAN_PIN, isFanOn); --wait; } <|endoftext|>
<commit_before> #ifndef AT_GLOBALS_HPP #define AT_GLOBALS_HPP #include <math.h> enum { AT_X = 0, AT_Y = 1, AT_Z = 2, AT_W = 3, AT_H = 0, AT_P = 1, AT_R = 2, AT_RED = 0, AT_GREEN = 1, AT_BLUE = 2, AT_ALPHA = 3 }; #define AT_PI (3.14159265358979) #define AT_DEFAULT_TOLERANCE (1E-12) // Various useful macros #define AT_SQR(x) ( (x) * (x) ) // Convert from degrees to radians #define AT_DEG2RAD(x) ( (x) * AT_PI / 180.0 ) // Convert from radians to degrees #define AT_RAD2DEG(x) ( (x) * 180.0 / AT_PI ) // Determine if two floating-point values are close enough to be equal #define AT_EQUAL(x,y) ( fabs((x) - (y)) < AT_DEFAULT_TOLERANCE ) // Find the maximum (or minimum) of any two values #define AT_MAX(x,y) ( ((x) > (y)) ? (x) : (y) ) #define AT_MIN(x,y) ( ((x) < (y)) ? (x) : (y) ) // Constants for use in conversion to/from Euler rotations // The three axes of rotation are specified in left to right order // i.e. XYZ means rotate around the X-axis, then the Y-axis, finally the Z-axis // The last letter ('S' or 'R') indicates static or relative rotation axes. // With static axes, the coordinate axes stay fixed during rotations; each // rotation around a particular axis rotates points the same way, regardless // of what other rotations have been done. Relative coordinate axes move with // each rotation; two X-axis rotations will move in different directions // if there is an intervening Y or Z-axis rotation. The two types are opposites // of each other: XYZ static produces the same effect as ZYX relative. enum atMathEulerAxisOrder { AT_EULER_ANGLES_XYZ_S, AT_EULER_ANGLES_XZY_S, AT_EULER_ANGLES_YXZ_S, AT_EULER_ANGLES_YZX_S, AT_EULER_ANGLES_ZXY_S, AT_EULER_ANGLES_ZYX_S, AT_EULER_ANGLES_XYX_S, AT_EULER_ANGLES_XZX_S, AT_EULER_ANGLES_YXY_S, AT_EULER_ANGLES_YZY_S, AT_EULER_ANGLES_ZXZ_S, AT_EULER_ANGLES_ZYZ_S, AT_EULER_ANGLES_XYZ_R, AT_EULER_ANGLES_XZY_R, AT_EULER_ANGLES_YXZ_R, AT_EULER_ANGLES_YZX_R, AT_EULER_ANGLES_ZXY_R, AT_EULER_ANGLES_ZYX_R, AT_EULER_ANGLES_XYX_R, AT_EULER_ANGLES_XZX_R, AT_EULER_ANGLES_YXY_R, AT_EULER_ANGLES_YZY_R, AT_EULER_ANGLES_ZXZ_R, AT_EULER_ANGLES_ZYZ_R }; #endif <commit_msg>Increased AT_PI precision to completely fill a double<commit_after> #ifndef AT_GLOBALS_HPP #define AT_GLOBALS_HPP #include <math.h> enum { AT_X = 0, AT_Y = 1, AT_Z = 2, AT_W = 3, AT_H = 0, AT_P = 1, AT_R = 2, AT_RED = 0, AT_GREEN = 1, AT_BLUE = 2, AT_ALPHA = 3 }; #define AT_PI (3.14159265358979323846) #define AT_DEFAULT_TOLERANCE (1E-12) // Various useful macros #define AT_SQR(x) ( (x) * (x) ) // Convert from degrees to radians #define AT_DEG2RAD(x) ( (x) * AT_PI / 180.0 ) // Convert from radians to degrees #define AT_RAD2DEG(x) ( (x) * 180.0 / AT_PI ) // Determine if two floating-point values are close enough to be equal #define AT_EQUAL(x,y) ( fabs((x) - (y)) < AT_DEFAULT_TOLERANCE ) // Find the maximum (or minimum) of any two values #define AT_MAX(x,y) ( ((x) > (y)) ? (x) : (y) ) #define AT_MIN(x,y) ( ((x) < (y)) ? (x) : (y) ) // Constants for use in conversion to/from Euler rotations // The three axes of rotation are specified in left to right order // i.e. XYZ means rotate around the X-axis, then the Y-axis, finally the Z-axis // The last letter ('S' or 'R') indicates static or relative rotation axes. // With static axes, the coordinate axes stay fixed during rotations; each // rotation around a particular axis rotates points the same way, regardless // of what other rotations have been done. Relative coordinate axes move with // each rotation; two X-axis rotations will move in different directions // if there is an intervening Y or Z-axis rotation. The two types are opposites // of each other: XYZ static produces the same effect as ZYX relative. enum atMathEulerAxisOrder { AT_EULER_ANGLES_XYZ_S, AT_EULER_ANGLES_XZY_S, AT_EULER_ANGLES_YXZ_S, AT_EULER_ANGLES_YZX_S, AT_EULER_ANGLES_ZXY_S, AT_EULER_ANGLES_ZYX_S, AT_EULER_ANGLES_XYX_S, AT_EULER_ANGLES_XZX_S, AT_EULER_ANGLES_YXY_S, AT_EULER_ANGLES_YZY_S, AT_EULER_ANGLES_ZXZ_S, AT_EULER_ANGLES_ZYZ_S, AT_EULER_ANGLES_XYZ_R, AT_EULER_ANGLES_XZY_R, AT_EULER_ANGLES_YXZ_R, AT_EULER_ANGLES_YZX_R, AT_EULER_ANGLES_ZXY_R, AT_EULER_ANGLES_ZYX_R, AT_EULER_ANGLES_XYX_R, AT_EULER_ANGLES_XZX_R, AT_EULER_ANGLES_YXY_R, AT_EULER_ANGLES_YZY_R, AT_EULER_ANGLES_ZXZ_R, AT_EULER_ANGLES_ZYZ_R }; #endif <|endoftext|>
<commit_before>// Copyright 2012 Google Inc. 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. #include "deps_log.h" #include <assert.h> #include <stdio.h> #include <errno.h> #include <string.h> #ifndef _WIN32 #include <unistd.h> #endif #include "graph.h" #include "metrics.h" #include "state.h" #include "util.h" // The version is stored as 4 bytes after the signature and also serves as a // byte order mark. Signature and version combined are 16 bytes long. const char kFileSignature[] = "# ninjadeps\n"; const int kCurrentVersion = 3; // Record size is currently limited to less than the full 32 bit, due to // internal buffers having to have this size. const unsigned kMaxRecordSize = (1 << 19) - 1; DepsLog::~DepsLog() { Close(); } bool DepsLog::OpenForWrite(const string& path, string* err) { if (needs_recompaction_) { if (!Recompact(path, err)) return false; } file_ = fopen(path.c_str(), "ab"); if (!file_) { *err = strerror(errno); return false; } // Set the buffer size to this and flush the file buffer after every record // to make sure records aren't written partially. setvbuf(file_, NULL, _IOFBF, kMaxRecordSize + 1); SetCloseOnExec(fileno(file_)); // Opening a file in append mode doesn't set the file pointer to the file's // end on Windows. Do that explicitly. fseek(file_, 0, SEEK_END); if (ftell(file_) == 0) { if (fwrite(kFileSignature, sizeof(kFileSignature) - 1, 1, file_) < 1) { *err = strerror(errno); return false; } if (fwrite(&kCurrentVersion, 4, 1, file_) < 1) { *err = strerror(errno); return false; } } if (fflush(file_) != 0) { *err = strerror(errno); return false; } return true; } bool DepsLog::RecordDeps(Node* node, TimeStamp mtime, const vector<Node*>& nodes) { return RecordDeps(node, mtime, nodes.size(), nodes.empty() ? NULL : (Node**)&nodes.front()); } bool DepsLog::RecordDeps(Node* node, TimeStamp mtime, int node_count, Node** nodes) { // Track whether there's any new data to be recorded. bool made_change = false; // Assign ids to all nodes that are missing one. if (node->id() < 0) { if (!RecordId(node)) return false; made_change = true; } for (int i = 0; i < node_count; ++i) { if (nodes[i]->id() < 0) { if (!RecordId(nodes[i])) return false; made_change = true; } } // See if the new data is different than the existing data, if any. if (!made_change) { Deps* deps = GetDeps(node); if (!deps || deps->mtime != mtime || deps->node_count != node_count) { made_change = true; } else { for (int i = 0; i < node_count; ++i) { if (deps->nodes[i] != nodes[i]) { made_change = true; break; } } } } // Don't write anything if there's no new info. if (!made_change) return true; // Update on-disk representation. unsigned size = 4 * (1 + 1 + node_count); if (size > kMaxRecordSize) { errno = ERANGE; return false; } size |= 0x80000000; // Deps record: set high bit. if (fwrite(&size, 4, 1, file_) < 1) return false; int id = node->id(); if (fwrite(&id, 4, 1, file_) < 1) return false; int timestamp = mtime; if (fwrite(&timestamp, 4, 1, file_) < 1) return false; for (int i = 0; i < node_count; ++i) { id = nodes[i]->id(); if (fwrite(&id, 4, 1, file_) < 1) return false; } if (fflush(file_) != 0) return false; // Update in-memory representation. Deps* deps = new Deps(mtime, node_count); for (int i = 0; i < node_count; ++i) deps->nodes[i] = nodes[i]; UpdateDeps(node->id(), deps); return true; } void DepsLog::Close() { if (file_) fclose(file_); file_ = NULL; } bool DepsLog::Load(const string& path, State* state, string* err) { METRIC_RECORD(".ninja_deps load"); char buf[kMaxRecordSize + 1]; FILE* f = fopen(path.c_str(), "rb"); if (!f) { if (errno == ENOENT) return true; *err = strerror(errno); return false; } bool valid_header = true; int version = 0; if (!fgets(buf, sizeof(buf), f) || fread(&version, 4, 1, f) < 1) valid_header = false; // Note: For version differences, this should migrate to the new format. // But the v1 format could sometimes (rarely) end up with invalid data, so // don't migrate v1 to v3 to force a rebuild. (v2 only existed for a few days, // and there was no release with it, so pretend that it never happened.) if (!valid_header || strcmp(buf, kFileSignature) != 0 || version != kCurrentVersion) { if (version == 1) *err = "deps log version change; rebuilding"; else *err = "bad deps log signature or version; starting over"; fclose(f); unlink(path.c_str()); // Don't report this as a failure. An empty deps log will cause // us to rebuild the outputs anyway. return true; } long offset; bool read_failed = false; int unique_dep_record_count = 0; int total_dep_record_count = 0; for (;;) { offset = ftell(f); unsigned size; if (fread(&size, 4, 1, f) < 1) { if (!feof(f)) read_failed = true; break; } bool is_deps = (size >> 31) != 0; size = size & 0x7FFFFFFF; if (fread(buf, size, 1, f) < 1 || size > kMaxRecordSize) { read_failed = true; break; } if (is_deps) { assert(size % 4 == 0); int* deps_data = reinterpret_cast<int*>(buf); int out_id = deps_data[0]; int mtime = deps_data[1]; deps_data += 2; int deps_count = (size / 4) - 2; Deps* deps = new Deps(mtime, deps_count); for (int i = 0; i < deps_count; ++i) { assert(deps_data[i] < (int)nodes_.size()); assert(nodes_[deps_data[i]]); deps->nodes[i] = nodes_[deps_data[i]]; } total_dep_record_count++; if (!UpdateDeps(out_id, deps)) ++unique_dep_record_count; } else { int path_size = size - 4; assert(path_size > 0); // CanonicalizePath() rejects empty paths. // There can be up to 3 bytes of padding. if (buf[path_size - 1] == '\0') --path_size; if (buf[path_size - 1] == '\0') --path_size; if (buf[path_size - 1] == '\0') --path_size; StringPiece subpath(buf, path_size); // It is not necessary to pass in a correct slash_bits here. It will // either be a Node that's in the manifest (in which case it will already // have a correct slash_bits that GetNode will look up), or it is an // implicit dependency from a .d which does not affect the build command // (and so need not have its slashes maintained). Node* node = state->GetNode(subpath, 0); // Check that the expected index matches the actual index. This can only // happen if two ninja processes write to the same deps log concurrently. // (This uses unary complement to make the checksum look less like a // dependency record entry.) unsigned checksum = *reinterpret_cast<unsigned*>(buf + size - 4); int expected_id = ~checksum; int id = nodes_.size(); if (id != expected_id) { read_failed = true; break; } assert(node->id() < 0); node->set_id(id); nodes_.push_back(node); } } if (read_failed) { // An error occurred while loading; try to recover by truncating the // file to the last fully-read record. if (ferror(f)) { *err = strerror(ferror(f)); } else { *err = "premature end of file"; } fclose(f); if (!Truncate(path, offset, err)) return false; // The truncate succeeded; we'll just report the load error as a // warning because the build can proceed. *err += "; recovering"; return true; } fclose(f); // Rebuild the log if there are too many dead records. int kMinCompactionEntryCount = 1000; int kCompactionRatio = 3; if (total_dep_record_count > kMinCompactionEntryCount && total_dep_record_count > unique_dep_record_count * kCompactionRatio) { needs_recompaction_ = true; } return true; } DepsLog::Deps* DepsLog::GetDeps(Node* node) { // Abort if the node has no id (never referenced in the deps) or if // there's no deps recorded for the node. if (node->id() < 0 || node->id() >= (int)deps_.size()) return NULL; return deps_[node->id()]; } bool DepsLog::Recompact(const string& path, string* err) { METRIC_RECORD(".ninja_deps recompact"); Close(); string temp_path = path + ".recompact"; // OpenForWrite() opens for append. Make sure it's not appending to a // left-over file from a previous recompaction attempt that crashed somehow. unlink(temp_path.c_str()); DepsLog new_log; if (!new_log.OpenForWrite(temp_path, err)) return false; // Clear all known ids so that new ones can be reassigned. The new indices // will refer to the ordering in new_log, not in the current log. for (vector<Node*>::iterator i = nodes_.begin(); i != nodes_.end(); ++i) (*i)->set_id(-1); // Write out all deps again. for (int old_id = 0; old_id < (int)deps_.size(); ++old_id) { Deps* deps = deps_[old_id]; if (!deps) continue; // If nodes_[old_id] is a leaf, it has no deps. if (!IsDepsEntryLiveFor(nodes_[old_id])) continue; if (!new_log.RecordDeps(nodes_[old_id], deps->mtime, deps->node_count, deps->nodes)) { new_log.Close(); return false; } } new_log.Close(); // All nodes now have ids that refer to new_log, so steal its data. deps_.swap(new_log.deps_); nodes_.swap(new_log.nodes_); if (unlink(path.c_str()) < 0) { *err = strerror(errno); return false; } if (rename(temp_path.c_str(), path.c_str()) < 0) { *err = strerror(errno); return false; } return true; } bool DepsLog::IsDepsEntryLiveFor(Node* node) { // Skip entries that don't have in-edges or whose edges don't have a // "deps" attribute. They were in the deps log from previous builds, but // the the files they were for were removed from the build and their deps // entries are no longer needed. // (Without the check for "deps", a chain of two or more nodes that each // had deps wouldn't be collected in a single recompaction.) return node->in_edge() && !node->in_edge()->GetBinding("deps").empty(); } bool DepsLog::UpdateDeps(int out_id, Deps* deps) { if (out_id >= (int)deps_.size()) deps_.resize(out_id + 1); bool delete_old = deps_[out_id] != NULL; if (delete_old) delete deps_[out_id]; deps_[out_id] = deps; return delete_old; } bool DepsLog::RecordId(Node* node) { int path_size = node->path().size(); int padding = (4 - path_size % 4) % 4; // Pad path to 4 byte boundary. unsigned size = path_size + padding + 4; if (size > kMaxRecordSize) { errno = ERANGE; return false; } if (fwrite(&size, 4, 1, file_) < 1) return false; if (fwrite(node->path().data(), path_size, 1, file_) < 1) { assert(node->path().size() > 0); return false; } if (padding && fwrite("\0\0", padding, 1, file_) < 1) return false; int id = nodes_.size(); unsigned checksum = ~(unsigned)id; if (fwrite(&checksum, 4, 1, file_) < 1) return false; if (fflush(file_) != 0) return false; node->set_id(id); nodes_.push_back(node); return true; } <commit_msg>Fix potential buffer overrun<commit_after>// Copyright 2012 Google Inc. 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. #include "deps_log.h" #include <assert.h> #include <stdio.h> #include <errno.h> #include <string.h> #ifndef _WIN32 #include <unistd.h> #endif #include "graph.h" #include "metrics.h" #include "state.h" #include "util.h" // The version is stored as 4 bytes after the signature and also serves as a // byte order mark. Signature and version combined are 16 bytes long. const char kFileSignature[] = "# ninjadeps\n"; const int kCurrentVersion = 3; // Record size is currently limited to less than the full 32 bit, due to // internal buffers having to have this size. const unsigned kMaxRecordSize = (1 << 19) - 1; DepsLog::~DepsLog() { Close(); } bool DepsLog::OpenForWrite(const string& path, string* err) { if (needs_recompaction_) { if (!Recompact(path, err)) return false; } file_ = fopen(path.c_str(), "ab"); if (!file_) { *err = strerror(errno); return false; } // Set the buffer size to this and flush the file buffer after every record // to make sure records aren't written partially. setvbuf(file_, NULL, _IOFBF, kMaxRecordSize + 1); SetCloseOnExec(fileno(file_)); // Opening a file in append mode doesn't set the file pointer to the file's // end on Windows. Do that explicitly. fseek(file_, 0, SEEK_END); if (ftell(file_) == 0) { if (fwrite(kFileSignature, sizeof(kFileSignature) - 1, 1, file_) < 1) { *err = strerror(errno); return false; } if (fwrite(&kCurrentVersion, 4, 1, file_) < 1) { *err = strerror(errno); return false; } } if (fflush(file_) != 0) { *err = strerror(errno); return false; } return true; } bool DepsLog::RecordDeps(Node* node, TimeStamp mtime, const vector<Node*>& nodes) { return RecordDeps(node, mtime, nodes.size(), nodes.empty() ? NULL : (Node**)&nodes.front()); } bool DepsLog::RecordDeps(Node* node, TimeStamp mtime, int node_count, Node** nodes) { // Track whether there's any new data to be recorded. bool made_change = false; // Assign ids to all nodes that are missing one. if (node->id() < 0) { if (!RecordId(node)) return false; made_change = true; } for (int i = 0; i < node_count; ++i) { if (nodes[i]->id() < 0) { if (!RecordId(nodes[i])) return false; made_change = true; } } // See if the new data is different than the existing data, if any. if (!made_change) { Deps* deps = GetDeps(node); if (!deps || deps->mtime != mtime || deps->node_count != node_count) { made_change = true; } else { for (int i = 0; i < node_count; ++i) { if (deps->nodes[i] != nodes[i]) { made_change = true; break; } } } } // Don't write anything if there's no new info. if (!made_change) return true; // Update on-disk representation. unsigned size = 4 * (1 + 1 + node_count); if (size > kMaxRecordSize) { errno = ERANGE; return false; } size |= 0x80000000; // Deps record: set high bit. if (fwrite(&size, 4, 1, file_) < 1) return false; int id = node->id(); if (fwrite(&id, 4, 1, file_) < 1) return false; int timestamp = mtime; if (fwrite(&timestamp, 4, 1, file_) < 1) return false; for (int i = 0; i < node_count; ++i) { id = nodes[i]->id(); if (fwrite(&id, 4, 1, file_) < 1) return false; } if (fflush(file_) != 0) return false; // Update in-memory representation. Deps* deps = new Deps(mtime, node_count); for (int i = 0; i < node_count; ++i) deps->nodes[i] = nodes[i]; UpdateDeps(node->id(), deps); return true; } void DepsLog::Close() { if (file_) fclose(file_); file_ = NULL; } bool DepsLog::Load(const string& path, State* state, string* err) { METRIC_RECORD(".ninja_deps load"); char buf[kMaxRecordSize + 1]; FILE* f = fopen(path.c_str(), "rb"); if (!f) { if (errno == ENOENT) return true; *err = strerror(errno); return false; } bool valid_header = true; int version = 0; if (!fgets(buf, sizeof(buf), f) || fread(&version, 4, 1, f) < 1) valid_header = false; // Note: For version differences, this should migrate to the new format. // But the v1 format could sometimes (rarely) end up with invalid data, so // don't migrate v1 to v3 to force a rebuild. (v2 only existed for a few days, // and there was no release with it, so pretend that it never happened.) if (!valid_header || strcmp(buf, kFileSignature) != 0 || version != kCurrentVersion) { if (version == 1) *err = "deps log version change; rebuilding"; else *err = "bad deps log signature or version; starting over"; fclose(f); unlink(path.c_str()); // Don't report this as a failure. An empty deps log will cause // us to rebuild the outputs anyway. return true; } long offset; bool read_failed = false; int unique_dep_record_count = 0; int total_dep_record_count = 0; for (;;) { offset = ftell(f); unsigned size; if (fread(&size, 4, 1, f) < 1) { if (!feof(f)) read_failed = true; break; } bool is_deps = (size >> 31) != 0; size = size & 0x7FFFFFFF; if (size > kMaxRecordSize || fread(buf, size, 1, f) < 1) { read_failed = true; break; } if (is_deps) { assert(size % 4 == 0); int* deps_data = reinterpret_cast<int*>(buf); int out_id = deps_data[0]; int mtime = deps_data[1]; deps_data += 2; int deps_count = (size / 4) - 2; Deps* deps = new Deps(mtime, deps_count); for (int i = 0; i < deps_count; ++i) { assert(deps_data[i] < (int)nodes_.size()); assert(nodes_[deps_data[i]]); deps->nodes[i] = nodes_[deps_data[i]]; } total_dep_record_count++; if (!UpdateDeps(out_id, deps)) ++unique_dep_record_count; } else { int path_size = size - 4; assert(path_size > 0); // CanonicalizePath() rejects empty paths. // There can be up to 3 bytes of padding. if (buf[path_size - 1] == '\0') --path_size; if (buf[path_size - 1] == '\0') --path_size; if (buf[path_size - 1] == '\0') --path_size; StringPiece subpath(buf, path_size); // It is not necessary to pass in a correct slash_bits here. It will // either be a Node that's in the manifest (in which case it will already // have a correct slash_bits that GetNode will look up), or it is an // implicit dependency from a .d which does not affect the build command // (and so need not have its slashes maintained). Node* node = state->GetNode(subpath, 0); // Check that the expected index matches the actual index. This can only // happen if two ninja processes write to the same deps log concurrently. // (This uses unary complement to make the checksum look less like a // dependency record entry.) unsigned checksum = *reinterpret_cast<unsigned*>(buf + size - 4); int expected_id = ~checksum; int id = nodes_.size(); if (id != expected_id) { read_failed = true; break; } assert(node->id() < 0); node->set_id(id); nodes_.push_back(node); } } if (read_failed) { // An error occurred while loading; try to recover by truncating the // file to the last fully-read record. if (ferror(f)) { *err = strerror(ferror(f)); } else { *err = "premature end of file"; } fclose(f); if (!Truncate(path, offset, err)) return false; // The truncate succeeded; we'll just report the load error as a // warning because the build can proceed. *err += "; recovering"; return true; } fclose(f); // Rebuild the log if there are too many dead records. int kMinCompactionEntryCount = 1000; int kCompactionRatio = 3; if (total_dep_record_count > kMinCompactionEntryCount && total_dep_record_count > unique_dep_record_count * kCompactionRatio) { needs_recompaction_ = true; } return true; } DepsLog::Deps* DepsLog::GetDeps(Node* node) { // Abort if the node has no id (never referenced in the deps) or if // there's no deps recorded for the node. if (node->id() < 0 || node->id() >= (int)deps_.size()) return NULL; return deps_[node->id()]; } bool DepsLog::Recompact(const string& path, string* err) { METRIC_RECORD(".ninja_deps recompact"); Close(); string temp_path = path + ".recompact"; // OpenForWrite() opens for append. Make sure it's not appending to a // left-over file from a previous recompaction attempt that crashed somehow. unlink(temp_path.c_str()); DepsLog new_log; if (!new_log.OpenForWrite(temp_path, err)) return false; // Clear all known ids so that new ones can be reassigned. The new indices // will refer to the ordering in new_log, not in the current log. for (vector<Node*>::iterator i = nodes_.begin(); i != nodes_.end(); ++i) (*i)->set_id(-1); // Write out all deps again. for (int old_id = 0; old_id < (int)deps_.size(); ++old_id) { Deps* deps = deps_[old_id]; if (!deps) continue; // If nodes_[old_id] is a leaf, it has no deps. if (!IsDepsEntryLiveFor(nodes_[old_id])) continue; if (!new_log.RecordDeps(nodes_[old_id], deps->mtime, deps->node_count, deps->nodes)) { new_log.Close(); return false; } } new_log.Close(); // All nodes now have ids that refer to new_log, so steal its data. deps_.swap(new_log.deps_); nodes_.swap(new_log.nodes_); if (unlink(path.c_str()) < 0) { *err = strerror(errno); return false; } if (rename(temp_path.c_str(), path.c_str()) < 0) { *err = strerror(errno); return false; } return true; } bool DepsLog::IsDepsEntryLiveFor(Node* node) { // Skip entries that don't have in-edges or whose edges don't have a // "deps" attribute. They were in the deps log from previous builds, but // the the files they were for were removed from the build and their deps // entries are no longer needed. // (Without the check for "deps", a chain of two or more nodes that each // had deps wouldn't be collected in a single recompaction.) return node->in_edge() && !node->in_edge()->GetBinding("deps").empty(); } bool DepsLog::UpdateDeps(int out_id, Deps* deps) { if (out_id >= (int)deps_.size()) deps_.resize(out_id + 1); bool delete_old = deps_[out_id] != NULL; if (delete_old) delete deps_[out_id]; deps_[out_id] = deps; return delete_old; } bool DepsLog::RecordId(Node* node) { int path_size = node->path().size(); int padding = (4 - path_size % 4) % 4; // Pad path to 4 byte boundary. unsigned size = path_size + padding + 4; if (size > kMaxRecordSize) { errno = ERANGE; return false; } if (fwrite(&size, 4, 1, file_) < 1) return false; if (fwrite(node->path().data(), path_size, 1, file_) < 1) { assert(node->path().size() > 0); return false; } if (padding && fwrite("\0\0", padding, 1, file_) < 1) return false; int id = nodes_.size(); unsigned checksum = ~(unsigned)id; if (fwrite(&checksum, 4, 1, file_) < 1) return false; if (fflush(file_) != 0) return false; node->set_id(id); nodes_.push_back(node); return true; } <|endoftext|>
<commit_before>#include <sirius.h> using namespace sirius; void test_redistr(std::vector<int> mpi_grid_dims, int M, int N) { if (mpi_grid_dims.size() != 2) { TERMINATE("2d MPI grid is expected"); } MPI_Win win; BLACS_grid blacs_grid(mpi_comm_world(), mpi_grid_dims[0], mpi_grid_dims[1]); dmatrix<double> mtrx(M, N, blacs_grid, 16, 16); for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { mtrx.set(j, i, double((j + 1) * (i + 1))); } } splindex<block> spl_row(M, mpi_comm_world().size(), mpi_comm_world().rank()); matrix<double> mtrx2(spl_row.local_size(), N); MPI_Win_create(mtrx2.at<CPU>(), mtrx2.size(), sizeof(double), MPI_INFO_NULL, MPI_COMM_WORLD, &win); MPI_Win_fence(0, win); runtime::Timer t1("MPI_Put"); for (int icol = 0; icol < mtrx.num_cols_local(); icol++) { int icol_glob = mtrx.icol(icol); for (int irow = 0; irow < mtrx.num_rows_local(); irow++) { int irow_glob = mtrx.irow(irow); auto location = spl_row.location(irow_glob); MPI_Put(&mtrx(irow, icol), 1, mpi_type_wrapper<double>::kind(), location.second, icol_glob * spl_row.local_size(location.second) + location.first , 1, mpi_type_wrapper<double>::kind(), win); } } MPI_Win_fence(0, win); MPI_Win_free(&win); double tval = t1.stop(); for (int i = 0; i < N; i++) { for (int j = 0; j < spl_row.local_size(); j++) { int jglob = spl_row[j]; if (std::abs(mtrx2(j, i) - double((jglob + 1) * (i + 1))) > 1e-14) { TERMINATE("error"); } //pout.printf("%4i ", mtrx2(j, i)); } //pout.printf("\n"); } printf("time: %f\n", tval); } int main(int argn, char** argv) { cmd_args args; args.register_key("--mpi_grid_dims=", "{int int} dimensions of MPI grid"); args.register_key("--M=", "{int} global number of matrix rows"); args.register_key("--N=", "{int} global number of matrix columns"); args.parse_args(argn, argv); if (args.exist("help")) { printf("Usage: %s [options]\n", argv[0]); args.print_help(); return 0; } auto mpi_grid_dims = args.value< std::vector<int> >("mpi_grid_dims", {1, 1}); auto M = args.value<int>("M", 10000); auto N = args.value<int>("N", 1000); sirius::initialize(1); test_redistr(mpi_grid_dims, M, N); sirius::finalize(); } <commit_msg>data redistribution test<commit_after>#include <sirius.h> using namespace sirius; void test_redistr(std::vector<int> mpi_grid_dims, int M, int N) { if (mpi_grid_dims.size() != 2) { TERMINATE("2d MPI grid is expected"); } MPI_Win win; BLACS_grid blacs_grid(mpi_comm_world(), mpi_grid_dims[0], mpi_grid_dims[1]); dmatrix<double> mtrx(M, N, blacs_grid, 16, 16); for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { mtrx.set(j, i, double((j + 1) * (i + 1))); } } splindex<block> spl_row(M, mpi_comm_world().size(), mpi_comm_world().rank()); matrix<double> mtrx2(spl_row.local_size(), N); MPI_Win_create(mtrx2.at<CPU>(), mtrx2.size(), sizeof(double), MPI_INFO_NULL, MPI_COMM_WORLD, &win); MPI_Win_fence(0, win); runtime::Timer t1("MPI_Put"); for (int icol = 0; icol < mtrx.num_cols_local(); icol++) { int icol_glob = mtrx.icol(icol); for (int irow = 0; irow < mtrx.num_rows_local(); irow++) { int irow_glob = mtrx.irow(irow); auto location = spl_row.location(irow_glob); MPI_Put(&mtrx(irow, icol), 1, mpi_type_wrapper<double>::kind(), location.second, icol_glob * spl_row.local_size(location.second) + location.first , 1, mpi_type_wrapper<double>::kind(), win); } } MPI_Win_fence(0, win); MPI_Win_free(&win); double tval = t1.stop(); for (int i = 0; i < N; i++) { for (int j = 0; j < spl_row.local_size(); j++) { int jglob = spl_row[j]; if (std::abs(mtrx2(j, i) - double((jglob + 1) * (i + 1))) > 1e-14) { TERMINATE("error"); } //pout.printf("%4i ", mtrx2(j, i)); } //pout.printf("\n"); } printf("time: %f\n", tval); } struct element_pack { int data; int idx; }; void test_redistr2() { int N = 12; splindex<block_cyclic> spl1(N, mpi_comm_world().size(), mpi_comm_world().rank(), 2); splindex<block> spl2(N, mpi_comm_world().size(), mpi_comm_world().rank()); std::vector<int> data1(spl1.local_size()); std::vector<int> data2(spl2.local_size()); for (int i = 0; i < spl1.local_size(); i++) { data1[i] = spl1[i]; } block_data_descriptor sd(mpi_comm_world().size()); std::vector<std::vector<element_pack>> sbuf(mpi_comm_world().size()); /* local set of sending elements */ for (int i = 0; i < spl1.local_size(); i++) { /* location on the receiving side */ auto loc = spl2.location(spl1[i]); sd.counts[loc.second] += static_cast<int>(sizeof(element_pack)); element_pack p; p.data = data1[i]; p.idx = loc.first; sbuf[loc.second].push_back(p); } sd.calc_offsets(); std::vector<element_pack> sbuf_tot; for (int r = 0; r < mpi_comm_world().size(); r++) { sbuf_tot.insert(sbuf_tot.end(), sbuf[r].begin(), sbuf[r].end()); } block_data_descriptor rd(mpi_comm_world().size()); for (int i = 0; i < spl2.local_size(); i++) { auto loc = spl1.location(spl2[i]); rd.counts[loc.second] += static_cast<int>(sizeof(element_pack)); } rd.calc_offsets(); std::vector<element_pack> rbuf_tot(spl2.local_size()); mpi_comm_world().alltoall((char*)sbuf_tot.data(), sd.counts.data(), sd.offsets.data(), (char*)rbuf_tot.data(), rd.counts.data(), rd.offsets.data()); runtime::pstdout pout(mpi_comm_world()); pout.printf("rank: %i\n", mpi_comm_world().rank()); for (int i = 0; i < spl2.local_size(); i++) { //int j = spl2[i]; //auto loc = spl1.location(j); //data2[i] = rbuf_tot[rd.offsets[loc.secod] + loc.first //data2[rbuf_tot[i].idx] = rbuf_tot[i].data; pout.printf("data: %i idx: %i\n", rbuf_tot[i].data, rbuf_tot[i].idx); data2[rbuf_tot[i].idx] = rbuf_tot[i].data; pout.printf("%i\n", data2[i]); } pout.flush(); for (int i = 0; i < spl2.local_size(); i++) { pout.printf("%i\n", data2[i]); } //for (int i = 0; i < spl2.local_size(); i++) { // auto loc = spl1.location(spl2[i]); // data1[i] = rbuf_tot[rd.offsets[loc.secod] + loc.irst //} // } void test_redistr3() { int N = 12; splindex<block_cyclic> spl1(N, mpi_comm_world().size(), mpi_comm_world().rank(), 2); splindex<block> spl2(N, mpi_comm_world().size(), mpi_comm_world().rank()); std::vector<int> data1(spl1.local_size()); std::vector<int> data2(spl2.local_size()); for (int i = 0; i < spl1.local_size(); i++) { data1[i] = spl1[i]; } block_data_descriptor sd(mpi_comm_world().size()); std::vector<std::vector<int>> sbuf(mpi_comm_world().size()); /* local set of sending elements */ for (int i = 0; i < spl1.local_size(); i++) { /* location on the receiving side */ auto loc = spl2.location(spl1[i]); sd.counts[loc.second]++; sbuf[loc.second].push_back(data1[i]); } sd.calc_offsets(); std::vector<int> sbuf_tot; for (int r = 0; r < mpi_comm_world().size(); r++) { sbuf_tot.insert(sbuf_tot.end(), sbuf[r].begin(), sbuf[r].end()); } block_data_descriptor rd(mpi_comm_world().size()); for (int i = 0; i < spl2.local_size(); i++) { auto loc = spl1.location(spl2[i]); rd.counts[loc.second]++; } rd.calc_offsets(); std::vector<int> rbuf_tot(spl2.local_size()); mpi_comm_world().alltoall(sbuf_tot.data(), sd.counts.data(), sd.offsets.data(), rbuf_tot.data(), rd.counts.data(), rd.offsets.data()); rd.counts = std::vector<int>(mpi_comm_world().size(), 0); runtime::pstdout pout(mpi_comm_world()); pout.printf("rank: %i\n", mpi_comm_world().rank()); for (int i = 0; i < spl2.local_size(); i++) { int j = spl2[i]; auto loc = spl1.location(j); data2[i] = rbuf_tot[rd.offsets[loc.second] + rd.counts[loc.second]]; rd.counts[loc.second]++; //data2[i] = rbuf_tot[rd.offsets[loc.secod] + loc.first //data2[rbuf_tot[i].idx] = rbuf_tot[i].data; //pout.printf("data: %i idx: %i\n", rbuf_tot[i].data, rbuf_tot[i].idx); //data2[rbuf_tot[i].idx] = rbuf_tot[i].data; //pout.printf("%i\n", data2[i]); } pout.flush(); for (int i = 0; i < spl2.local_size(); i++) { pout.printf("%i\n", data2[i]); } //for (int i = 0; i < spl2.local_size(); i++) { // auto loc = spl1.location(spl2[i]); // data1[i] = rbuf_tot[rd.offsets[loc.secod] + loc.irst //} // } void test_redistr4(std::vector<int> mpi_grid_dims, int M, int N) { if (mpi_grid_dims.size() != 2) { TERMINATE("2d MPI grid is expected"); } BLACS_grid blacs_grid(mpi_comm_world(), mpi_grid_dims[0], mpi_grid_dims[1]); dmatrix<double> mtrx(M, N, blacs_grid, 16, 16); for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { mtrx.set(j, i, double((j + 1) * (i + 1))); } } /* cache cartesian ranks */ mdarray<int, 2> cart_rank(mtrx.blacs_grid()->num_ranks_row(), mtrx.blacs_grid()->num_ranks_col()); for (int i = 0; i < mtrx.blacs_grid()->num_ranks_col(); i++) { for (int j = 0; j < mtrx.blacs_grid()->num_ranks_row(); j++) { cart_rank(j, i) = mtrx.blacs_grid()->cart_rank(j, i); } } splindex<block> spl_row(M, mpi_comm_world().size(), mpi_comm_world().rank()); matrix<double> mtrx2(spl_row.local_size(), N); block_data_descriptor sd(mpi_comm_world().size()); block_data_descriptor rd(mpi_comm_world().size()); std::vector<double> sbuf(mtrx.size()); std::vector<double> rbuf(mtrx2.size()); std::vector<int> recv_row_rank(spl_row.local_size()); for (int irow = 0; irow < spl_row.local_size(); irow++) { recv_row_rank[irow] = mtrx.spl_row().local_rank(spl_row[irow]); } auto pack = [&mtrx, &cart_rank, &spl_row, &recv_row_rank, &sd, &rd, &sbuf]() { std::vector<int> row_rank(mtrx.num_rows_local()); /* cache receiving ranks */ for (int irow = 0; irow < mtrx.num_rows_local(); irow++) { int rank = spl_row.local_rank(mtrx.irow(irow)); row_rank[irow] = rank; sd.counts[rank] += mtrx.num_cols_local(); } sd.calc_offsets(); sd.counts = std::vector<int>(mpi_comm_world().size(), 0); /* pack for all rank */ for (int icol = 0; icol < mtrx.num_cols_local(); icol++) { for (int irow = 0; irow < mtrx.num_rows_local(); irow++) { int rank = row_rank[irow]; sbuf[sd.offsets[rank] + sd.counts[rank]] = mtrx(irow, icol); sd.counts[rank]++; } } /* compute receiving counts and offsets */ for (int icol = 0; icol < mtrx.num_cols(); icol++) { auto location_col = mtrx.spl_col().location(icol); for (int irow = 0; irow < spl_row.local_size(); irow++) { rd.counts[cart_rank(recv_row_rank[irow], location_col.second)]++; } } rd.calc_offsets(); }; runtime::Timer t1("pack"); pack(); t1.stop(); runtime::Timer t2("a2a"); mpi_comm_world().alltoall(sbuf.data(), sd.counts.data(), sd.offsets.data(), rbuf.data(), rd.counts.data(), rd.offsets.data()); t2.stop(); runtime::Timer t3("unpack"); rd.counts = std::vector<int>(mpi_comm_world().size(), 0); for (int icol = 0; icol < N; icol++) { auto location_col = mtrx.spl_col().location(icol); for (int irow = 0; irow < spl_row.local_size(); irow++) { int rank = cart_rank(recv_row_rank[irow], location_col.second); mtrx2(irow, icol) = rbuf[rd.offsets[rank] + rd.counts[rank]]; rd.counts[rank]++; } } t3.stop(); for (int i = 0; i < N; i++) { for (int j = 0; j < spl_row.local_size(); j++) { int jglob = spl_row[j]; if (std::abs(mtrx2(j, i) - double((jglob + 1) * (i + 1))) > 1e-14) { TERMINATE("error"); } //pout.printf("%4i ", mtrx2(j, i)); } //pout.printf("\n"); } } int main(int argn, char** argv) { cmd_args args; args.register_key("--mpi_grid_dims=", "{int int} dimensions of MPI grid"); args.register_key("--M=", "{int} global number of matrix rows"); args.register_key("--N=", "{int} global number of matrix columns"); args.parse_args(argn, argv); if (args.exist("help")) { printf("Usage: %s [options]\n", argv[0]); args.print_help(); return 0; } auto mpi_grid_dims = args.value< std::vector<int> >("mpi_grid_dims", {1, 1}); auto M = args.value<int>("M", 10000); auto N = args.value<int>("N", 1000); sirius::initialize(1); //test_redistr(mpi_grid_dims, M, N); //test_redistr3(); test_redistr4(mpi_grid_dims, M, N); runtime::Timer::print(); sirius::finalize(); } <|endoftext|>
<commit_before>// Copyright (c) 2012 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 "ash/accelerators/accelerator_filter.h" #include "ash/accelerators/accelerator_controller.h" #include "ash/shell.h" #include "ash/wm/window_util.h" #include "ui/aura/root_window.h" #include "ui/base/accelerators/accelerator.h" #include "ui/base/accelerators/accelerator_manager.h" #include "ui/base/events/event.h" namespace ash { namespace { const int kModifierFlagMask = (ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN | ui::EF_ALT_DOWN); // Returns true if the |accelerator| should be processed now, inside Ash's env // event filter. bool ShouldProcessAcceleratorsNow(const ui::Accelerator& accelerator, aura::Window* target) { if (!target) return true; if (target == Shell::GetPrimaryRootWindow()) return true; // A full screen window should be able to handle all key events including the // reserved ones. if (wm::IsWindowFullscreen(target)) { // TODO(yusukes): On Chrome OS, only browser and flash windows can be full // screen. Launching an app in "open full-screen" mode is not supported yet. // That makes the IsWindowFullscreen() check above almost meaningless // because a browser and flash window do handle Ash accelerators anyway // before they're passed to a page or flash content. return false; } if (Shell::GetInstance()->GetAppListTargetVisibility()) return true; // Unless |target| is in the full screen state, handle reserved accelerators // such as Alt+Tab now. return Shell::GetInstance()->accelerator_controller()->IsReservedAccelerator( accelerator); } } // namespace namespace internal { //////////////////////////////////////////////////////////////////////////////// // AcceleratorFilter, public: AcceleratorFilter::AcceleratorFilter() { } AcceleratorFilter::~AcceleratorFilter() { } //////////////////////////////////////////////////////////////////////////////// // AcceleratorFilter, EventFilter implementation: bool AcceleratorFilter::PreHandleKeyEvent(aura::Window* target, ui::KeyEvent* event) { const ui::EventType type = event->type(); if (type != ui::ET_KEY_PRESSED && type != ui::ET_KEY_RELEASED) return false; if (event->is_char()) return false; ui::Accelerator accelerator(event->key_code(), event->flags() & kModifierFlagMask); accelerator.set_type(type); if (!ShouldProcessAcceleratorsNow(accelerator, target)) return false; return Shell::GetInstance()->accelerator_controller()->Process(accelerator); } bool AcceleratorFilter::PreHandleMouseEvent(aura::Window* target, ui::MouseEvent* event) { return false; } ui::TouchStatus AcceleratorFilter::PreHandleTouchEvent( aura::Window* target, ui::TouchEvent* event) { return ui::TOUCH_STATUS_UNKNOWN; } ui::EventResult AcceleratorFilter::PreHandleGestureEvent( aura::Window* target, ui::GestureEvent* event) { return ui::ER_UNHANDLED; } } // namespace internal } // namespace ash <commit_msg>Fix ash shortcuts not working on the secondary monitor when no window is shown.<commit_after>// Copyright (c) 2012 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 "ash/accelerators/accelerator_filter.h" #include "ash/accelerators/accelerator_controller.h" #include "ash/shell.h" #include "ash/wm/window_util.h" #include "ui/aura/root_window.h" #include "ui/base/accelerators/accelerator.h" #include "ui/base/accelerators/accelerator_manager.h" #include "ui/base/events/event.h" namespace ash { namespace { const int kModifierFlagMask = (ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN | ui::EF_ALT_DOWN); // Returns true if the |accelerator| should be processed now, inside Ash's env // event filter. bool ShouldProcessAcceleratorsNow(const ui::Accelerator& accelerator, aura::Window* target) { if (!target) return true; Shell::RootWindowList root_windows = Shell::GetAllRootWindows(); if (std::find(root_windows.begin(), root_windows.end(), target) != root_windows.end()) return true; // A full screen window should be able to handle all key events including the // reserved ones. if (wm::IsWindowFullscreen(target)) { // TODO(yusukes): On Chrome OS, only browser and flash windows can be full // screen. Launching an app in "open full-screen" mode is not supported yet. // That makes the IsWindowFullscreen() check above almost meaningless // because a browser and flash window do handle Ash accelerators anyway // before they're passed to a page or flash content. return false; } if (Shell::GetInstance()->GetAppListTargetVisibility()) return true; // Unless |target| is in the full screen state, handle reserved accelerators // such as Alt+Tab now. return Shell::GetInstance()->accelerator_controller()->IsReservedAccelerator( accelerator); } } // namespace namespace internal { //////////////////////////////////////////////////////////////////////////////// // AcceleratorFilter, public: AcceleratorFilter::AcceleratorFilter() { } AcceleratorFilter::~AcceleratorFilter() { } //////////////////////////////////////////////////////////////////////////////// // AcceleratorFilter, EventFilter implementation: bool AcceleratorFilter::PreHandleKeyEvent(aura::Window* target, ui::KeyEvent* event) { const ui::EventType type = event->type(); if (type != ui::ET_KEY_PRESSED && type != ui::ET_KEY_RELEASED) return false; if (event->is_char()) return false; ui::Accelerator accelerator(event->key_code(), event->flags() & kModifierFlagMask); accelerator.set_type(type); if (!ShouldProcessAcceleratorsNow(accelerator, target)) return false; return Shell::GetInstance()->accelerator_controller()->Process(accelerator); } bool AcceleratorFilter::PreHandleMouseEvent(aura::Window* target, ui::MouseEvent* event) { return false; } ui::TouchStatus AcceleratorFilter::PreHandleTouchEvent( aura::Window* target, ui::TouchEvent* event) { return ui::TOUCH_STATUS_UNKNOWN; } ui::EventResult AcceleratorFilter::PreHandleGestureEvent( aura::Window* target, ui::GestureEvent* event) { return ui::ER_UNHANDLED; } } // namespace internal } // namespace ash <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: it_tplparam.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2006-06-19 11:53: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 ARY_IDL_IT_TPLPARAM_HXX #define ARY_IDL_IT_TPLPARAM_HXX // USED SERVICES // BASE CLASSES #include "it_named.hxx" // COMPONENTS // PARAMETERS namespace ary { namespace idl { /** @resp Represents a template type when it is used within the declaring struct. */ class TemplateParamType : public Named_Type { public: enum E_ClassId { class_id = 2205 }; // LIFECYCLE TemplateParamType( const char * i_sName ); virtual ~TemplateParamType(); // INQUIRY Ce_id StructId() const; /// The struct which declares this type. // ACCESS void Set_StructId( Ce_id i_nStruct ); private: // Interface RepositoryEntity: virtual void do_Visit( Host & io_rHost ) const; virtual RCid inq_ClassId() const; // Interface Type: virtual void inq_Get_Text( StringVector & o_module, String & o_name, Ce_id & o_nRelatedCe, int & o_nSequenceCount, const Gate & i_rGate ) const; // DATA Ce_id nStruct; /// The struct which declares this type. }; inline Ce_id TemplateParamType::StructId() const { return nStruct; } inline void TemplateParamType::Set_StructId( Ce_id i_nStruct ) { nStruct = i_nStruct; } } // namespace idl } // namespace ary #endif <commit_msg>INTEGRATION: CWS adc18 (1.4.32); FILE MERGED 2007/10/18 13:40:05 np 1.4.32.1: #i81775#<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: it_tplparam.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2007-11-02 15:58:08 $ * * 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 ARY_IDL_IT_TPLPARAM_HXX #define ARY_IDL_IT_TPLPARAM_HXX // BASE CLASSES #include "it_named.hxx" namespace ary { namespace idl { /** @resp Represents a template type when it is used within the declaring struct. */ class TemplateParamType : public Named_Type { public: enum E_ClassId { class_id = 2205 }; // LIFECYCLE TemplateParamType( const char * i_sName ); virtual ~TemplateParamType(); Ce_id StructId() const; /// The struct which declares this type. void Set_StructId( Ce_id i_nStruct ); private: // Interface csv::ConstProcessorClient: virtual void do_Accept( csv::ProcessorIfc & io_processor ) const; // Interface Object: virtual ClassId get_AryClass() const; // Interface Type: virtual void inq_Get_Text( StringVector & o_module, String & o_name, Ce_id & o_nRelatedCe, int & o_nSequenceCount, const Gate & i_rGate ) const; // DATA Ce_id nStruct; /// The struct which declares this type. }; // IMPLEMENTATION inline Ce_id TemplateParamType::StructId() const { return nStruct; } inline void TemplateParamType::Set_StructId( Ce_id i_nStruct ) { nStruct = i_nStruct; } } // namespace idl } // namespace ary #endif <|endoftext|>
<commit_before>/** @file @brief Implementation @date 2014 @author Ryan Pavlik <ryan@sensics.com>; <http://sensics.com> */ // Copyright 2014 Sensics, Inc. // // All rights reserved. // // (Final version intended to be licensed under // the Apache License, Version 2.0) // Internal Includes #include "PluginSpecificRegistrationContext.h" #include <ogvr/Util/Verbosity.h> #include "ResetPointerList.h" // Library/third-party includes #include <boost/range/adaptor/reversed.hpp> // Standard includes // - none namespace ogvr { namespace { class HardwarePollCaller { public: HardwarePollCaller(PluginSpecificRegistrationContext *ctx) : m_ctx(ctx) {} template <typename F> OGVR_PluginReturnCode operator()(F func) { return func(static_cast<void *>(m_ctx)); } private: PluginSpecificRegistrationContext *m_ctx; }; } // end of anonymous namespace PluginSpecificRegistrationContext::PluginSpecificRegistrationContext( std::string const &name) : m_name(name) { OGVR_DEV_VERBOSE("PluginSpecificRegistrationContext:\t" << "Creating a plugin registration context for " << m_name); } PluginSpecificRegistrationContext::~PluginSpecificRegistrationContext() { OGVR_DEV_VERBOSE("PluginSpecificRegistrationContext:\t" "Destroying plugin reg context for " << m_name); // Delete the data in reverse order. detail::resetPointerRange(m_dataList | boost::adaptors::reversed); } void PluginSpecificRegistrationContext::takePluginHandle( libfunc::PluginHandle &handle) { m_handle = handle; } const std::string &PluginSpecificRegistrationContext::getName() const { return m_name; } void PluginSpecificRegistrationContext::callHardwarePollCallbacks() { OGVR_DEV_VERBOSE("PluginSpecificRegistrationContext:\t" "In callHardwarePollCallbacks for " << m_name); boost::for_each(m_hardwarePollCallbacks, HardwarePollCaller(this)); } void PluginSpecificRegistrationContext::registerDataWithDeleteCallback( OGVR_PluginDataDeleteCallback deleteCallback, void *pluginData) { m_dataList.emplace_back(PluginDataPtr(pluginData, deleteCallback)); OGVR_DEV_VERBOSE("PluginSpecificRegistrationContext:\t" "Now have " << m_dataList.size() << " data delete callbacks registered for " << m_name); } void PluginSpecificRegistrationContext::registerHardwarePollCallback( OGVRHardwarePollCallback pollCallback, void *userData) { OGVR_DEV_VERBOSE("PluginSpecificRegistrationContext:\t" "In registerHardwarePollCallback"); m_hardwarePollCallbacks.emplace_back( CallbackWrapper<OGVRHardwarePollCallback>(pollCallback, userData)); OGVR_DEV_VERBOSE("PluginSpecificRegistrationContext:\t" "Now have " << m_hardwarePollCallbacks.size() << " hardware poll callbacks registered for " << m_name); } } // end of namespace ogvr <commit_msg>Use a lambda instead of a function object when calling hardware poll callbacks.<commit_after>/** @file @brief Implementation @date 2014 @author Ryan Pavlik <ryan@sensics.com>; <http://sensics.com> */ // Copyright 2014 Sensics, Inc. // // All rights reserved. // // (Final version intended to be licensed under // the Apache License, Version 2.0) // Internal Includes #include "PluginSpecificRegistrationContext.h" #include <ogvr/Util/Verbosity.h> #include "ResetPointerList.h" // Library/third-party includes #include <boost/range/adaptor/reversed.hpp> // Standard includes // - none namespace ogvr { PluginSpecificRegistrationContext::PluginSpecificRegistrationContext( std::string const &name) : m_name(name) { OGVR_DEV_VERBOSE("PluginSpecificRegistrationContext:\t" << "Creating a plugin registration context for " << m_name); } PluginSpecificRegistrationContext::~PluginSpecificRegistrationContext() { OGVR_DEV_VERBOSE("PluginSpecificRegistrationContext:\t" "Destroying plugin reg context for " << m_name); // Delete the data in reverse order. detail::resetPointerRange(m_dataList | boost::adaptors::reversed); } void PluginSpecificRegistrationContext::takePluginHandle( libfunc::PluginHandle &handle) { m_handle = handle; } const std::string &PluginSpecificRegistrationContext::getName() const { return m_name; } void PluginSpecificRegistrationContext::callHardwarePollCallbacks() { OGVR_DEV_VERBOSE("PluginSpecificRegistrationContext:\t" "In callHardwarePollCallbacks for " << m_name); boost::for_each(m_hardwarePollCallbacks, [this](HardwarePollCallback const &f) { f(this); }); } void PluginSpecificRegistrationContext::registerDataWithDeleteCallback( OGVR_PluginDataDeleteCallback deleteCallback, void *pluginData) { m_dataList.emplace_back(PluginDataPtr(pluginData, deleteCallback)); OGVR_DEV_VERBOSE("PluginSpecificRegistrationContext:\t" "Now have " << m_dataList.size() << " data delete callbacks registered for " << m_name); } void PluginSpecificRegistrationContext::registerHardwarePollCallback( OGVRHardwarePollCallback pollCallback, void *userData) { OGVR_DEV_VERBOSE("PluginSpecificRegistrationContext:\t" "In registerHardwarePollCallback"); m_hardwarePollCallbacks.emplace_back( CallbackWrapper<OGVRHardwarePollCallback>(pollCallback, userData)); OGVR_DEV_VERBOSE("PluginSpecificRegistrationContext:\t" "Now have " << m_hardwarePollCallbacks.size() << " hardware poll callbacks registered for " << m_name); } } // end of namespace ogvr <|endoftext|>
<commit_before>#include <crypto/crypto_encryption.h> #include <event/event_callback.h> #include <event/event_main.h> #include <event/event_system.h> #include <io/net/tcp_server.h> #include <io/pipe/pipe.h> #include <io/pipe/pipe_producer.h> #include <io/pipe/splice.h> #include <io/socket/simple_server.h> #include <ssh/ssh_algorithm_negotiation.h> #include <ssh/ssh_protocol.h> #include <ssh/ssh_server_host_key.h> #include <ssh/ssh_session.h> #include <ssh/ssh_transport_pipe.h> /* * XXX Create an SSH chat program. Let only one of each user be connected at a time. Send lines of data to all others. */ class SSHConnection { struct SSHChannel { uint32_t local_channel_; uint32_t local_window_size_; uint32_t local_packet_size_; uint32_t remote_channel_; uint32_t remote_window_size_; uint32_t remote_packet_size_; SSHChannel(uint32_t local_channel, uint32_t remote_channel, uint32_t local_window_size, uint32_t local_packet_size, uint32_t remote_window_size, uint32_t remote_packet_size) : local_channel_(local_channel), local_window_size_(local_window_size), local_packet_size_(local_packet_size), remote_channel_(remote_channel), remote_window_size_(remote_window_size), remote_packet_size_(remote_packet_size) { } }; LogHandle log_; Socket *peer_; SSH::Session session_; SSH::TransportPipe *pipe_; Action *receive_action_; Splice *splice_; Action *splice_action_; Action *close_action_; uint32_t channel_next_; std::map<uint32_t, SSHChannel *> channel_map_; std::map<uint32_t, uint32_t> remote_channel_map_; public: SSHConnection(Socket *peer) : log_("/ssh/connection"), peer_(peer), session_(SSH::ServerRole), pipe_(NULL), splice_(NULL), splice_action_(NULL), close_action_(NULL), channel_next_(0), channel_map_() { session_.algorithm_negotiation_ = new SSH::AlgorithmNegotiation(&session_); if (session_.role_ == SSH::ServerRole) { SSH::ServerHostKey *server_host_key = SSH::ServerHostKey::server(&session_, "ssh-server1.pem"); session_.algorithm_negotiation_->add_algorithm(server_host_key); } session_.algorithm_negotiation_->add_algorithms(); pipe_ = new SSH::TransportPipe(&session_); EventCallback *rcb = callback(this, &SSHConnection::receive_complete); receive_action_ = pipe_->receive(rcb); splice_ = new Splice(log_ + "/splice", peer_, pipe_, peer_); EventCallback *cb = callback(this, &SSHConnection::splice_complete); splice_action_ = splice_->start(cb); } ~SSHConnection() { ASSERT(log_, close_action_ == NULL); ASSERT(log_, splice_action_ == NULL); ASSERT(log_, splice_ == NULL); ASSERT(log_, receive_action_ == NULL); ASSERT(log_, pipe_ == NULL); ASSERT(log_, peer_ == NULL); } private: void receive_complete(Event e) { receive_action_->cancel(); receive_action_ = NULL; switch (e.type_) { case Event::Done: break; default: ERROR(log_) << "Unexpected event while waiting for a packet: " << e; return; } ASSERT(log_, !e.buffer_.empty()); Buffer service; Buffer type; Buffer msg; SSHChannel *channel; uint32_t recipient_channel, sender_channel, window_size, packet_size; bool want_reply; std::map<uint32_t, uint32_t>::const_iterator rchit; std::map<uint32_t, SSHChannel *>::const_iterator chit; switch (e.buffer_.peek()) { case SSH::Message::TransportDisconnectMessage: break; case SSH::Message::TransportServiceRequestMessage: /* Claim to support any kind of service the client requests. */ e.buffer_.skip(1); if (e.buffer_.empty()) { ERROR(log_) << "No service name after transport request."; return; } if (!SSH::String::decode(&service, &e.buffer_)) { ERROR(log_) << "Could not decode service name."; return; } if (!e.buffer_.empty()) { ERROR(log_) << "Extraneous data after service name."; return; } msg.append(SSH::Message::TransportServiceAcceptMessage); SSH::String::encode(&msg, service); pipe_->send(&msg); if (service.equal("ssh-userauth")) { msg.append(SSH::Message::UserAuthenticationBannerMessage); SSH::String::encode(&msg, std::string(" *\r\n\007 * This is a test server. Sessions, including authentication, may be logged.\r\n *\r\n")); SSH::String::encode(&msg, std::string("en-CA")); pipe_->send(&msg); } break; case SSH::Message::UserAuthenticationRequestMessage: /* Any authentication request succeeds. */ e.buffer_.skip(1); msg.append(SSH::Message::UserAuthenticationSuccessMessage); pipe_->send(&msg); break; case SSH::Message::ConnectionChannelOpen: /* Opening a channel. */ e.buffer_.skip(1); if (e.buffer_.empty()) { ERROR(log_) << "No channel type after channel open."; return; } if (!SSH::String::decode(&type, &e.buffer_)) { ERROR(log_) << "Could not decode channel type."; return; } if (!SSH::UInt32::decode(&sender_channel, &e.buffer_)) { ERROR(log_) << "Could not decode sender channel."; return; } if (!SSH::UInt32::decode(&window_size, &e.buffer_)) { ERROR(log_) << "Could not decode window size."; return; } if (!SSH::UInt32::decode(&packet_size, &e.buffer_)) { ERROR(log_) << "Could not decode packet size."; return; } /* Only support session channels. */ if (!type.equal("session")) { msg.append(SSH::Message::ConnectionChannelOpenFailure); SSH::UInt32::encode(&msg, sender_channel); SSH::UInt32::encode(&msg, 3); SSH::String::encode(&msg, std::string("Unsupported session type.")); SSH::String::encode(&msg, std::string("en-CA")); pipe_->send(&msg); return; } recipient_channel = sender_channel; sender_channel = channel_setup(recipient_channel, window_size, packet_size); /* Set up session. */ msg.append(SSH::Message::ConnectionChannelOpenConfirmation); SSH::UInt32::encode(&msg, recipient_channel); SSH::UInt32::encode(&msg, sender_channel); SSH::UInt32::encode(&msg, window_size); SSH::UInt32::encode(&msg, packet_size); pipe_->send(&msg); break; case SSH::Message::ConnectionChannelRequest: /* For now just fail any channel request. */ e.buffer_.skip(1); if (e.buffer_.empty()) { ERROR(log_) << "No channel after channel request."; return; } if (!SSH::UInt32::decode(&recipient_channel, &e.buffer_)) { ERROR(log_) << "Could not decode recipient channel."; return; } if (!SSH::String::decode(&type, &e.buffer_)) { ERROR(log_) << "Could not decode channel request type."; return; } if (e.buffer_.empty()) { ERROR(log_) << "Missing want_reply field."; return; } want_reply = e.buffer_.pop(); chit = channel_map_.find(recipient_channel); if (chit == channel_map_.end()) { if (want_reply) { msg.append(SSH::Message::ConnectionChannelRequestFailure); SSH::UInt32::encode(&msg, 0); /* XXX What to do for a request that fails due to unknown channel? */ pipe_->send(&msg); } break; } channel = chit->second; if (type.equal("pty-req")) { /* Fail for now. */ } else if (type.equal("env")) { /* Fail for now. */ } else if (type.equal("shell")) { if (want_reply) { msg.append(SSH::Message::ConnectionChannelRequestSuccess); SSH::UInt32::encode(&msg, channel->remote_channel_); pipe_->send(&msg); } break; } else { DEBUG(log_) << "Unhandled channel request type:" << std::endl << type.hexdump(); } if (want_reply) { msg.append(SSH::Message::ConnectionChannelRequestFailure); SSH::UInt32::encode(&msg, channel->remote_channel_); pipe_->send(&msg); } break; case SSH::Message::ConnectionChannelWindowAdjust: /* Follow our peer's lead on window adjustments. */ case SSH::Message::ConnectionChannelData: /* Just echo data back. We do not need to decode at present because channels are the same in both directions. */ pipe_->send(&e.buffer_); break; default: DEBUG(log_) << "Unhandled message:" << std::endl << e.buffer_.hexdump(); break; } EventCallback *rcb = callback(this, &SSHConnection::receive_complete); receive_action_ = pipe_->receive(rcb); } void close_complete(void) { close_action_->cancel(); close_action_ = NULL; ASSERT(log_, peer_ != NULL); delete peer_; peer_ = NULL; delete this; } void splice_complete(Event e) { splice_action_->cancel(); splice_action_ = NULL; switch (e.type_) { case Event::EOS: DEBUG(log_) << "Peer exiting normally."; break; case Event::Error: ERROR(log_) << "Peer exiting with error: " << e; break; default: ERROR(log_) << "Peer exiting with unknown event: " << e; break; } ASSERT(log_, splice_ != NULL); delete splice_; splice_ = NULL; if (receive_action_ != NULL) { INFO(log_) << "Peer exiting while waiting for a packet."; receive_action_->cancel(); receive_action_ = NULL; } ASSERT(log_, pipe_ != NULL); delete pipe_; pipe_ = NULL; ASSERT(log_, close_action_ == NULL); SimpleCallback *cb = callback(this, &SSHConnection::close_complete); close_action_ = peer_->close(cb); } uint32_t channel_setup(const uint32_t& remote_channel, const uint32_t& window_size, const uint32_t& packet_size) { std::map<uint32_t, SSHChannel *>::const_iterator it; uint32_t local_channel; uint32_t next = channel_next_; for (;;) { it = channel_map_.find(next); if (it == channel_map_.end()) break; next++; } channel_next_ = next + 1; local_channel = next; channel_map_[local_channel] = new SSHChannel(local_channel, remote_channel, 65536, 65536, window_size, packet_size); return (local_channel); } }; class SSHServer : public SimpleServer<TCPServer> { public: SSHServer(SocketAddressFamily family, const std::string& interface) : SimpleServer<TCPServer>("/ssh/server", family, interface) { } ~SSHServer() { } void client_connected(Socket *client) { new SSHConnection(client); } }; int main(void) { new SSHServer(SocketAddressFamilyIP, "[::]:2299"); event_main(); } <commit_msg>Allow setting of environment variables.<commit_after>#include <crypto/crypto_encryption.h> #include <event/event_callback.h> #include <event/event_main.h> #include <event/event_system.h> #include <io/net/tcp_server.h> #include <io/pipe/pipe.h> #include <io/pipe/pipe_producer.h> #include <io/pipe/splice.h> #include <io/socket/simple_server.h> #include <ssh/ssh_algorithm_negotiation.h> #include <ssh/ssh_protocol.h> #include <ssh/ssh_server_host_key.h> #include <ssh/ssh_session.h> #include <ssh/ssh_transport_pipe.h> /* * XXX Create an SSH chat program. Let only one of each user be connected at a time. Send lines of data to all others. */ class SSHConnection { struct SSHChannel { uint32_t local_channel_; uint32_t local_window_size_; uint32_t local_packet_size_; uint32_t remote_channel_; uint32_t remote_window_size_; uint32_t remote_packet_size_; std::map<std::string, Buffer> environment_; SSHChannel(uint32_t local_channel, uint32_t remote_channel, uint32_t local_window_size, uint32_t local_packet_size, uint32_t remote_window_size, uint32_t remote_packet_size) : local_channel_(local_channel), local_window_size_(local_window_size), local_packet_size_(local_packet_size), remote_channel_(remote_channel), remote_window_size_(remote_window_size), remote_packet_size_(remote_packet_size), environment_() { } }; LogHandle log_; Socket *peer_; SSH::Session session_; SSH::TransportPipe *pipe_; Action *receive_action_; Splice *splice_; Action *splice_action_; Action *close_action_; uint32_t channel_next_; std::map<uint32_t, SSHChannel *> channel_map_; std::map<uint32_t, uint32_t> remote_channel_map_; public: SSHConnection(Socket *peer) : log_("/ssh/connection"), peer_(peer), session_(SSH::ServerRole), pipe_(NULL), splice_(NULL), splice_action_(NULL), close_action_(NULL), channel_next_(0), channel_map_() { session_.algorithm_negotiation_ = new SSH::AlgorithmNegotiation(&session_); if (session_.role_ == SSH::ServerRole) { SSH::ServerHostKey *server_host_key = SSH::ServerHostKey::server(&session_, "ssh-server1.pem"); session_.algorithm_negotiation_->add_algorithm(server_host_key); } session_.algorithm_negotiation_->add_algorithms(); pipe_ = new SSH::TransportPipe(&session_); EventCallback *rcb = callback(this, &SSHConnection::receive_complete); receive_action_ = pipe_->receive(rcb); splice_ = new Splice(log_ + "/splice", peer_, pipe_, peer_); EventCallback *cb = callback(this, &SSHConnection::splice_complete); splice_action_ = splice_->start(cb); } ~SSHConnection() { ASSERT(log_, close_action_ == NULL); ASSERT(log_, splice_action_ == NULL); ASSERT(log_, splice_ == NULL); ASSERT(log_, receive_action_ == NULL); ASSERT(log_, pipe_ == NULL); ASSERT(log_, peer_ == NULL); } private: void receive_complete(Event e) { receive_action_->cancel(); receive_action_ = NULL; switch (e.type_) { case Event::Done: break; default: ERROR(log_) << "Unexpected event while waiting for a packet: " << e; return; } ASSERT(log_, !e.buffer_.empty()); Buffer service; Buffer type; Buffer msg; SSHChannel *channel; uint32_t recipient_channel, sender_channel, window_size, packet_size; bool want_reply; std::map<uint32_t, uint32_t>::const_iterator rchit; std::map<uint32_t, SSHChannel *>::const_iterator chit; switch (e.buffer_.peek()) { case SSH::Message::TransportDisconnectMessage: break; case SSH::Message::TransportServiceRequestMessage: /* Claim to support any kind of service the client requests. */ e.buffer_.skip(1); if (e.buffer_.empty()) { ERROR(log_) << "No service name after transport request."; return; } if (!SSH::String::decode(&service, &e.buffer_)) { ERROR(log_) << "Could not decode service name."; return; } if (!e.buffer_.empty()) { ERROR(log_) << "Extraneous data after service name."; return; } msg.append(SSH::Message::TransportServiceAcceptMessage); SSH::String::encode(&msg, service); pipe_->send(&msg); if (service.equal("ssh-userauth")) { msg.append(SSH::Message::UserAuthenticationBannerMessage); SSH::String::encode(&msg, std::string(" *\r\n\007 * This is a test server. Sessions, including authentication, may be logged.\r\n *\r\n")); SSH::String::encode(&msg, std::string("en-CA")); pipe_->send(&msg); } break; case SSH::Message::UserAuthenticationRequestMessage: /* Any authentication request succeeds. */ e.buffer_.skip(1); msg.append(SSH::Message::UserAuthenticationSuccessMessage); pipe_->send(&msg); break; case SSH::Message::ConnectionChannelOpen: /* Opening a channel. */ e.buffer_.skip(1); if (e.buffer_.empty()) { ERROR(log_) << "No channel type after channel open."; return; } if (!SSH::String::decode(&type, &e.buffer_)) { ERROR(log_) << "Could not decode channel type."; return; } if (!SSH::UInt32::decode(&sender_channel, &e.buffer_)) { ERROR(log_) << "Could not decode sender channel."; return; } if (!SSH::UInt32::decode(&window_size, &e.buffer_)) { ERROR(log_) << "Could not decode window size."; return; } if (!SSH::UInt32::decode(&packet_size, &e.buffer_)) { ERROR(log_) << "Could not decode packet size."; return; } /* Only support session channels. */ if (!type.equal("session")) { msg.append(SSH::Message::ConnectionChannelOpenFailure); SSH::UInt32::encode(&msg, sender_channel); SSH::UInt32::encode(&msg, 3); SSH::String::encode(&msg, std::string("Unsupported session type.")); SSH::String::encode(&msg, std::string("en-CA")); pipe_->send(&msg); return; } recipient_channel = sender_channel; sender_channel = channel_setup(recipient_channel, window_size, packet_size); /* Set up session. */ msg.append(SSH::Message::ConnectionChannelOpenConfirmation); SSH::UInt32::encode(&msg, recipient_channel); SSH::UInt32::encode(&msg, sender_channel); SSH::UInt32::encode(&msg, window_size); SSH::UInt32::encode(&msg, packet_size); pipe_->send(&msg); break; case SSH::Message::ConnectionChannelRequest: /* For now just fail any channel request. */ e.buffer_.skip(1); if (e.buffer_.empty()) { ERROR(log_) << "No channel after channel request."; return; } if (!SSH::UInt32::decode(&recipient_channel, &e.buffer_)) { ERROR(log_) << "Could not decode recipient channel."; return; } if (!SSH::String::decode(&type, &e.buffer_)) { ERROR(log_) << "Could not decode channel request type."; return; } if (e.buffer_.empty()) { ERROR(log_) << "Missing want_reply field."; return; } want_reply = e.buffer_.pop(); chit = channel_map_.find(recipient_channel); if (chit == channel_map_.end()) { if (want_reply) { msg.append(SSH::Message::ConnectionChannelRequestFailure); SSH::UInt32::encode(&msg, 0); /* XXX What to do for a request that fails due to unknown channel? */ pipe_->send(&msg); } break; } channel = chit->second; if (type.equal("pty-req")) { /* Fail for now. */ } else if (type.equal("env")) { Buffer keybuf; if (!SSH::String::decode(&keybuf, &e.buffer_)) { ERROR(log_) << "Could not decode environment key."; return; } Buffer value; if (!SSH::String::decode(&value, &e.buffer_)) { ERROR(log_) << "Could not decode environment value."; return; } std::string key; keybuf.extract(key); if (channel->environment_.find(key) == channel->environment_.end()) { channel->environment_[key] = value; DEBUG(log_) << "Client set environment variable."; if (want_reply) { msg.append(SSH::Message::ConnectionChannelRequestSuccess); SSH::UInt32::encode(&msg, channel->remote_channel_); pipe_->send(&msg); } break; } INFO(log_) << "Client attempted to set environment variable twice."; if (want_reply) { msg.append(SSH::Message::ConnectionChannelRequestFailure); SSH::UInt32::encode(&msg, channel->remote_channel_); pipe_->send(&msg); } break; } else if (type.equal("shell")) { if (want_reply) { msg.append(SSH::Message::ConnectionChannelRequestSuccess); SSH::UInt32::encode(&msg, channel->remote_channel_); pipe_->send(&msg); } break; } else { DEBUG(log_) << "Unhandled channel request type:" << std::endl << type.hexdump(); } if (want_reply) { msg.append(SSH::Message::ConnectionChannelRequestFailure); SSH::UInt32::encode(&msg, channel->remote_channel_); pipe_->send(&msg); } break; case SSH::Message::ConnectionChannelWindowAdjust: /* Follow our peer's lead on window adjustments. */ case SSH::Message::ConnectionChannelData: /* Just echo data back. We do not need to decode at present because channels are the same in both directions. */ pipe_->send(&e.buffer_); break; default: DEBUG(log_) << "Unhandled message:" << std::endl << e.buffer_.hexdump(); break; } EventCallback *rcb = callback(this, &SSHConnection::receive_complete); receive_action_ = pipe_->receive(rcb); } void close_complete(void) { close_action_->cancel(); close_action_ = NULL; ASSERT(log_, peer_ != NULL); delete peer_; peer_ = NULL; delete this; } void splice_complete(Event e) { splice_action_->cancel(); splice_action_ = NULL; switch (e.type_) { case Event::EOS: DEBUG(log_) << "Peer exiting normally."; break; case Event::Error: ERROR(log_) << "Peer exiting with error: " << e; break; default: ERROR(log_) << "Peer exiting with unknown event: " << e; break; } ASSERT(log_, splice_ != NULL); delete splice_; splice_ = NULL; if (receive_action_ != NULL) { INFO(log_) << "Peer exiting while waiting for a packet."; receive_action_->cancel(); receive_action_ = NULL; } ASSERT(log_, pipe_ != NULL); delete pipe_; pipe_ = NULL; ASSERT(log_, close_action_ == NULL); SimpleCallback *cb = callback(this, &SSHConnection::close_complete); close_action_ = peer_->close(cb); } uint32_t channel_setup(const uint32_t& remote_channel, const uint32_t& window_size, const uint32_t& packet_size) { std::map<uint32_t, SSHChannel *>::const_iterator it; uint32_t local_channel; uint32_t next = channel_next_; for (;;) { it = channel_map_.find(next); if (it == channel_map_.end()) break; next++; } channel_next_ = next + 1; local_channel = next; channel_map_[local_channel] = new SSHChannel(local_channel, remote_channel, 65536, 65536, window_size, packet_size); return (local_channel); } }; class SSHServer : public SimpleServer<TCPServer> { public: SSHServer(SocketAddressFamily family, const std::string& interface) : SimpleServer<TCPServer>("/ssh/server", family, interface) { } ~SSHServer() { } void client_connected(Socket *client) { new SSHConnection(client); } }; int main(void) { new SSHServer(SocketAddressFamilyIP, "[::]:2299"); event_main(); } <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <wchar.h> #include <wchar.h> #include <stdarg.h> #include <type_traits> #ifndef NULL #error NULL not defined #endif #ifndef WCHAR_MAX #error WCHAR_MAX not defined #endif #ifndef WCHAR_MIN #error WCHAR_MIN not defined #endif #ifndef WEOF #error WEOF not defined #endif int main() { // mbstate_t comes from the underlying C library; it is defined (in C99) as: // a complete object type other than an array type that can hold the conversion // state information necessary to convert between sequences of multibyte // characters and wide characters mbstate_t mb = {}; size_t s = 0; tm *tm = 0; wint_t w = 0; ::FILE* fp = 0; ::va_list va; char* ns = 0; wchar_t* ws = 0; static_assert((std::is_same<decltype(fwprintf(fp, L"")), int>::value), ""); static_assert((std::is_same<decltype(fwscanf(fp, L"")), int>::value), ""); static_assert((std::is_same<decltype(swprintf(ws, s, L"")), int>::value), ""); static_assert((std::is_same<decltype(swscanf(L"", L"")), int>::value), ""); static_assert((std::is_same<decltype(vfwprintf(fp, L"", va)), int>::value), ""); static_assert((std::is_same<decltype(vfwscanf(fp, L"", va)), int>::value), ""); static_assert((std::is_same<decltype(vswprintf(ws, s, L"", va)), int>::value), ""); static_assert((std::is_same<decltype(vswscanf(L"", L"", va)), int>::value), ""); static_assert((std::is_same<decltype(fgetwc(fp)), wint_t>::value), ""); static_assert((std::is_same<decltype(fgetws(ws, 0, fp)), wchar_t*>::value), ""); static_assert((std::is_same<decltype(fputwc(L' ', fp)), wint_t>::value), ""); static_assert((std::is_same<decltype(fputws(L"", fp)), int>::value), ""); static_assert((std::is_same<decltype(fwide(fp, 0)), int>::value), ""); static_assert((std::is_same<decltype(getwc(fp)), wint_t>::value), ""); static_assert((std::is_same<decltype(putwc(L' ', fp)), wint_t>::value), ""); static_assert((std::is_same<decltype(ungetwc(L' ', fp)), wint_t>::value), ""); static_assert((std::is_same<decltype(wcstod(L"", (wchar_t**)0)), double>::value), ""); static_assert((std::is_same<decltype(wcstof(L"", (wchar_t**)0)), float>::value), ""); static_assert((std::is_same<decltype(wcstold(L"", (wchar_t**)0)), long double>::value), ""); static_assert((std::is_same<decltype(wcstol(L"", (wchar_t**)0, 0)), long>::value), ""); static_assert((std::is_same<decltype(wcstoll(L"", (wchar_t**)0, 0)), long long>::value), ""); static_assert((std::is_same<decltype(wcstoul(L"", (wchar_t**)0, 0)), unsigned long>::value), ""); static_assert((std::is_same<decltype(wcstoull(L"", (wchar_t**)0, 0)), unsigned long long>::value), ""); static_assert((std::is_same<decltype(wcscpy(ws, L"")), wchar_t*>::value), ""); static_assert((std::is_same<decltype(wcsncpy(ws, L"", s)), wchar_t*>::value), ""); static_assert((std::is_same<decltype(wcscat(ws, L"")), wchar_t*>::value), ""); static_assert((std::is_same<decltype(wcsncat(ws, L"", s)), wchar_t*>::value), ""); static_assert((std::is_same<decltype(wcscmp(L"", L"")), int>::value), ""); static_assert((std::is_same<decltype(wcscoll(L"", L"")), int>::value), ""); static_assert((std::is_same<decltype(wcsncmp(L"", L"", s)), int>::value), ""); static_assert((std::is_same<decltype(wcsxfrm(ws, L"", s)), size_t>::value), ""); static_assert((std::is_same<decltype(wcschr((wchar_t*)0, L' ')), wchar_t*>::value), ""); static_assert((std::is_same<decltype(wcscspn(L"", L"")), size_t>::value), ""); static_assert((std::is_same<decltype(wcslen(L"")), size_t>::value), ""); static_assert((std::is_same<decltype(wcspbrk((wchar_t*)0, L"")), wchar_t*>::value), ""); static_assert((std::is_same<decltype(wcsrchr((wchar_t*)0, L' ')), wchar_t*>::value), ""); static_assert((std::is_same<decltype(wcsspn(L"", L"")), size_t>::value), ""); static_assert((std::is_same<decltype(wcsstr((wchar_t*)0, L"")), wchar_t*>::value), ""); static_assert((std::is_same<decltype(wcstok(ws, L"", (wchar_t**)0)), wchar_t*>::value), ""); static_assert((std::is_same<decltype(wmemchr((wchar_t*)0, L' ', s)), wchar_t*>::value), ""); static_assert((std::is_same<decltype(wmemcmp(L"", L"", s)), int>::value), ""); static_assert((std::is_same<decltype(wmemcpy(ws, L"", s)), wchar_t*>::value), ""); static_assert((std::is_same<decltype(wmemmove(ws, L"", s)), wchar_t*>::value), ""); static_assert((std::is_same<decltype(wmemset(ws, L' ', s)), wchar_t*>::value), ""); static_assert((std::is_same<decltype(wcsftime(ws, s, L"", tm)), size_t>::value), ""); static_assert((std::is_same<decltype(btowc(0)), wint_t>::value), ""); static_assert((std::is_same<decltype(wctob(w)), int>::value), ""); static_assert((std::is_same<decltype(mbsinit(&mb)), int>::value), ""); static_assert((std::is_same<decltype(mbrlen("", s, &mb)), size_t>::value), ""); static_assert((std::is_same<decltype(mbrtowc(ws, "", s, &mb)), size_t>::value), ""); static_assert((std::is_same<decltype(wcrtomb(ns, L' ', &mb)), size_t>::value), ""); static_assert((std::is_same<decltype(mbsrtowcs(ws, (const char**)0, s, &mb)), size_t>::value), ""); static_assert((std::is_same<decltype(wcsrtombs(ns, (const wchar_t**)0, s, &mb)), size_t>::value), ""); // These tests fail on systems whose C library doesn't provide a correct overload // set for wcschr, wcspbrk, wcsrchr, wcsstr, and wmemchr, unless the compiler is // a suitably recent version of Clang. #if !defined(__APPLE__) || defined(_LIBCPP_PREFERRED_OVERLOAD) static_assert((std::is_same<decltype(wcschr((const wchar_t*)0, L' ')), const wchar_t*>::value), ""); static_assert((std::is_same<decltype(wcspbrk((const wchar_t*)0, L"")), const wchar_t*>::value), ""); static_assert((std::is_same<decltype(wcsrchr((const wchar_t*)0, L' ')), const wchar_t*>::value), ""); static_assert((std::is_same<decltype(wcsstr((const wchar_t*)0, L"")), const wchar_t*>::value), ""); static_assert((std::is_same<decltype(wmemchr((const wchar_t*)0, L' ', s)), const wchar_t*>::value), ""); #endif #ifndef _LIBCPP_HAS_NO_STDIN static_assert((std::is_same<decltype(getwchar()), wint_t>::value), ""); static_assert((std::is_same<decltype(vwscanf(L"", va)), int>::value), ""); static_assert((std::is_same<decltype(wscanf(L"")), int>::value), ""); #endif #ifndef _LIBCPP_HAS_NO_STDOUT static_assert((std::is_same<decltype(putwchar(L' ')), wint_t>::value), ""); static_assert((std::is_same<decltype(vwprintf(L"", va)), int>::value), ""); static_assert((std::is_same<decltype(wprintf(L"")), int>::value), ""); #endif } <commit_msg>Silence more unused variable warnings. Patch from STL@microsoft.com<commit_after>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <wchar.h> #include <wchar.h> #include <stdarg.h> #include <type_traits> #ifndef NULL #error NULL not defined #endif #ifndef WCHAR_MAX #error WCHAR_MAX not defined #endif #ifndef WCHAR_MIN #error WCHAR_MIN not defined #endif #ifndef WEOF #error WEOF not defined #endif int main() { // mbstate_t comes from the underlying C library; it is defined (in C99) as: // a complete object type other than an array type that can hold the conversion // state information necessary to convert between sequences of multibyte // characters and wide characters mbstate_t mb = {}; size_t s = 0; tm *tm = 0; wint_t w = 0; ::FILE* fp = 0; ::va_list va; char* ns = 0; wchar_t* ws = 0; ((void)mb); // Prevent unused warning ((void)s); // Prevent unused warning ((void)tm); // Prevent unused warning ((void)w); // Prevent unused warning ((void)fp); // Prevent unused warning ((void)va); // Prevent unused warning ((void)ns); // Prevent unused warning ((void)ws); // Prevent unused warning static_assert((std::is_same<decltype(fwprintf(fp, L"")), int>::value), ""); static_assert((std::is_same<decltype(fwscanf(fp, L"")), int>::value), ""); static_assert((std::is_same<decltype(swprintf(ws, s, L"")), int>::value), ""); static_assert((std::is_same<decltype(swscanf(L"", L"")), int>::value), ""); static_assert((std::is_same<decltype(vfwprintf(fp, L"", va)), int>::value), ""); static_assert((std::is_same<decltype(vfwscanf(fp, L"", va)), int>::value), ""); static_assert((std::is_same<decltype(vswprintf(ws, s, L"", va)), int>::value), ""); static_assert((std::is_same<decltype(vswscanf(L"", L"", va)), int>::value), ""); static_assert((std::is_same<decltype(fgetwc(fp)), wint_t>::value), ""); static_assert((std::is_same<decltype(fgetws(ws, 0, fp)), wchar_t*>::value), ""); static_assert((std::is_same<decltype(fputwc(L' ', fp)), wint_t>::value), ""); static_assert((std::is_same<decltype(fputws(L"", fp)), int>::value), ""); static_assert((std::is_same<decltype(fwide(fp, 0)), int>::value), ""); static_assert((std::is_same<decltype(getwc(fp)), wint_t>::value), ""); static_assert((std::is_same<decltype(putwc(L' ', fp)), wint_t>::value), ""); static_assert((std::is_same<decltype(ungetwc(L' ', fp)), wint_t>::value), ""); static_assert((std::is_same<decltype(wcstod(L"", (wchar_t**)0)), double>::value), ""); static_assert((std::is_same<decltype(wcstof(L"", (wchar_t**)0)), float>::value), ""); static_assert((std::is_same<decltype(wcstold(L"", (wchar_t**)0)), long double>::value), ""); static_assert((std::is_same<decltype(wcstol(L"", (wchar_t**)0, 0)), long>::value), ""); static_assert((std::is_same<decltype(wcstoll(L"", (wchar_t**)0, 0)), long long>::value), ""); static_assert((std::is_same<decltype(wcstoul(L"", (wchar_t**)0, 0)), unsigned long>::value), ""); static_assert((std::is_same<decltype(wcstoull(L"", (wchar_t**)0, 0)), unsigned long long>::value), ""); static_assert((std::is_same<decltype(wcscpy(ws, L"")), wchar_t*>::value), ""); static_assert((std::is_same<decltype(wcsncpy(ws, L"", s)), wchar_t*>::value), ""); static_assert((std::is_same<decltype(wcscat(ws, L"")), wchar_t*>::value), ""); static_assert((std::is_same<decltype(wcsncat(ws, L"", s)), wchar_t*>::value), ""); static_assert((std::is_same<decltype(wcscmp(L"", L"")), int>::value), ""); static_assert((std::is_same<decltype(wcscoll(L"", L"")), int>::value), ""); static_assert((std::is_same<decltype(wcsncmp(L"", L"", s)), int>::value), ""); static_assert((std::is_same<decltype(wcsxfrm(ws, L"", s)), size_t>::value), ""); static_assert((std::is_same<decltype(wcschr((wchar_t*)0, L' ')), wchar_t*>::value), ""); static_assert((std::is_same<decltype(wcscspn(L"", L"")), size_t>::value), ""); static_assert((std::is_same<decltype(wcslen(L"")), size_t>::value), ""); static_assert((std::is_same<decltype(wcspbrk((wchar_t*)0, L"")), wchar_t*>::value), ""); static_assert((std::is_same<decltype(wcsrchr((wchar_t*)0, L' ')), wchar_t*>::value), ""); static_assert((std::is_same<decltype(wcsspn(L"", L"")), size_t>::value), ""); static_assert((std::is_same<decltype(wcsstr((wchar_t*)0, L"")), wchar_t*>::value), ""); static_assert((std::is_same<decltype(wcstok(ws, L"", (wchar_t**)0)), wchar_t*>::value), ""); static_assert((std::is_same<decltype(wmemchr((wchar_t*)0, L' ', s)), wchar_t*>::value), ""); static_assert((std::is_same<decltype(wmemcmp(L"", L"", s)), int>::value), ""); static_assert((std::is_same<decltype(wmemcpy(ws, L"", s)), wchar_t*>::value), ""); static_assert((std::is_same<decltype(wmemmove(ws, L"", s)), wchar_t*>::value), ""); static_assert((std::is_same<decltype(wmemset(ws, L' ', s)), wchar_t*>::value), ""); static_assert((std::is_same<decltype(wcsftime(ws, s, L"", tm)), size_t>::value), ""); static_assert((std::is_same<decltype(btowc(0)), wint_t>::value), ""); static_assert((std::is_same<decltype(wctob(w)), int>::value), ""); static_assert((std::is_same<decltype(mbsinit(&mb)), int>::value), ""); static_assert((std::is_same<decltype(mbrlen("", s, &mb)), size_t>::value), ""); static_assert((std::is_same<decltype(mbrtowc(ws, "", s, &mb)), size_t>::value), ""); static_assert((std::is_same<decltype(wcrtomb(ns, L' ', &mb)), size_t>::value), ""); static_assert((std::is_same<decltype(mbsrtowcs(ws, (const char**)0, s, &mb)), size_t>::value), ""); static_assert((std::is_same<decltype(wcsrtombs(ns, (const wchar_t**)0, s, &mb)), size_t>::value), ""); // These tests fail on systems whose C library doesn't provide a correct overload // set for wcschr, wcspbrk, wcsrchr, wcsstr, and wmemchr, unless the compiler is // a suitably recent version of Clang. #if !defined(__APPLE__) || defined(_LIBCPP_PREFERRED_OVERLOAD) static_assert((std::is_same<decltype(wcschr((const wchar_t*)0, L' ')), const wchar_t*>::value), ""); static_assert((std::is_same<decltype(wcspbrk((const wchar_t*)0, L"")), const wchar_t*>::value), ""); static_assert((std::is_same<decltype(wcsrchr((const wchar_t*)0, L' ')), const wchar_t*>::value), ""); static_assert((std::is_same<decltype(wcsstr((const wchar_t*)0, L"")), const wchar_t*>::value), ""); static_assert((std::is_same<decltype(wmemchr((const wchar_t*)0, L' ', s)), const wchar_t*>::value), ""); #endif #ifndef _LIBCPP_HAS_NO_STDIN static_assert((std::is_same<decltype(getwchar()), wint_t>::value), ""); static_assert((std::is_same<decltype(vwscanf(L"", va)), int>::value), ""); static_assert((std::is_same<decltype(wscanf(L"")), int>::value), ""); #endif #ifndef _LIBCPP_HAS_NO_STDOUT static_assert((std::is_same<decltype(putwchar(L' ')), wint_t>::value), ""); static_assert((std::is_same<decltype(vwprintf(L"", va)), int>::value), ""); static_assert((std::is_same<decltype(wprintf(L"")), int>::value), ""); #endif } <|endoftext|>
<commit_before>#include <btBulletDynamicsCommon.h> #include "../Physics/GlmConversion.hpp" #include "RigidBody.hpp" namespace Component { RigidBody::~RigidBody() { Destroy(); } Json::Value RigidBody::Save() const { Json::Value component; component["mass"] = mass; component["kinematic"] = kinematic; return component; } bool RigidBody::IsKinematic() const { return kinematic; } btRigidBody* RigidBody::GetBulletRigidBody() { return rigidBody; } void RigidBody::NewBulletRigidBody(float mass) { Destroy(); this->mass = mass; // Motion states inform us of movement caused by physics so that we can // deal with those changes as needed. btDefaultMotionState* motionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, 0, 0))); // Bullet treats zero mass as infinite, resulting in immovable objects. btRigidBody::btRigidBodyConstructionInfo constructionInfo(mass, motionState, nullptr, btVector3(0, 0, 0)); rigidBody = new btRigidBody(constructionInfo); rigidBody->setUserPointer(this); } void RigidBody::Destroy() { if (rigidBody) { delete rigidBody->getMotionState(); delete rigidBody; } } glm::vec3 RigidBody::GetPosition() const { btTransform trans; if (IsKinematic()) rigidBody->getMotionState()->getWorldTransform(trans); else trans = rigidBody->getWorldTransform(); return Physics::btToGlm(trans.getOrigin()); } void RigidBody::SetPosition(const glm::vec3& pos) { if (IsKinematic()) { btTransform trans; rigidBody->getMotionState()->getWorldTransform(trans); trans.setOrigin(Physics::glmToBt(pos)); rigidBody->getMotionState()->setWorldTransform(trans); } else { btTransform trans = rigidBody->getWorldTransform(); trans.setOrigin(Physics::glmToBt(pos)); rigidBody->setWorldTransform(trans); } } glm::quat RigidBody::GetOrientation() const { btTransform trans = rigidBody->getWorldTransform(); return Physics::btToGlm(trans.getRotation()); } void RigidBody::SetOrientation(const glm::quat& rotation) { btTransform trans = rigidBody->getWorldTransform(); trans.setRotation(Physics::glmToBt(rotation)); rigidBody->setWorldTransform(trans); } float RigidBody::GetMass() { return mass; } void RigidBody::SetMass(float mass) { // Bullet provides a method on the shape that we can use to calculate // inertia. btVector3 inertia; rigidBody->getCollisionShape()->calculateLocalInertia(mass, inertia); rigidBody->setMassProps(mass, inertia); this->mass = mass; } void RigidBody::MakeKinematic() { rigidBody->setCollisionFlags(rigidBody->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT); kinematic = true; } void RigidBody::MakeDynamic() { rigidBody->setCollisionFlags(rigidBody->getCollisionFlags() & ~btCollisionObject::CF_KINEMATIC_OBJECT); kinematic = false; } } <commit_msg>For kinematic rigid bodies, getting/setting rotation is done via the motion state.<commit_after>#include <btBulletDynamicsCommon.h> #include "../Physics/GlmConversion.hpp" #include "RigidBody.hpp" namespace Component { RigidBody::~RigidBody() { Destroy(); } Json::Value RigidBody::Save() const { Json::Value component; component["mass"] = mass; component["kinematic"] = kinematic; return component; } bool RigidBody::IsKinematic() const { return kinematic; } btRigidBody* RigidBody::GetBulletRigidBody() { return rigidBody; } void RigidBody::NewBulletRigidBody(float mass) { Destroy(); this->mass = mass; // Motion states inform us of movement caused by physics so that we can // deal with those changes as needed. btDefaultMotionState* motionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, 0, 0))); // Bullet treats zero mass as infinite, resulting in immovable objects. btRigidBody::btRigidBodyConstructionInfo constructionInfo(mass, motionState, nullptr, btVector3(0, 0, 0)); rigidBody = new btRigidBody(constructionInfo); rigidBody->setUserPointer(this); } void RigidBody::Destroy() { if (rigidBody) { delete rigidBody->getMotionState(); delete rigidBody; } } glm::vec3 RigidBody::GetPosition() const { btTransform trans; if (IsKinematic()) rigidBody->getMotionState()->getWorldTransform(trans); else trans = rigidBody->getWorldTransform(); return Physics::btToGlm(trans.getOrigin()); } void RigidBody::SetPosition(const glm::vec3& pos) { if (IsKinematic()) { btTransform trans; rigidBody->getMotionState()->getWorldTransform(trans); trans.setOrigin(Physics::glmToBt(pos)); rigidBody->getMotionState()->setWorldTransform(trans); } else { btTransform trans = rigidBody->getWorldTransform(); trans.setOrigin(Physics::glmToBt(pos)); rigidBody->setWorldTransform(trans); } } glm::quat RigidBody::GetOrientation() const { btTransform trans; if (IsKinematic()) rigidBody->getMotionState()->getWorldTransform(trans); else trans = rigidBody->getWorldTransform(); return Physics::btToGlm(trans.getRotation()); } void RigidBody::SetOrientation(const glm::quat& rotation) { if (IsKinematic()) { btTransform trans; rigidBody->getMotionState()->getWorldTransform(trans); trans.setRotation(Physics::glmToBt(rotation)); rigidBody->getMotionState()->setWorldTransform(trans); } else { btTransform trans = rigidBody->getWorldTransform(); trans.setRotation(Physics::glmToBt(rotation)); rigidBody->setWorldTransform(trans); } } float RigidBody::GetMass() { return mass; } void RigidBody::SetMass(float mass) { // Bullet provides a method on the shape that we can use to calculate // inertia. btVector3 inertia; rigidBody->getCollisionShape()->calculateLocalInertia(mass, inertia); rigidBody->setMassProps(mass, inertia); this->mass = mass; } void RigidBody::MakeKinematic() { rigidBody->setCollisionFlags(rigidBody->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT); kinematic = true; } void RigidBody::MakeDynamic() { rigidBody->setCollisionFlags(rigidBody->getCollisionFlags() & ~btCollisionObject::CF_KINEMATIC_OBJECT); kinematic = false; } } <|endoftext|>
<commit_before>#include <gloperate-qtwidgets/PluginWidget.h> #include "ui_PluginWidget.h" #include <gloperate/plugin/PluginManager.h> #include <gloperate/plugin/Plugin.h> #include <gloperate-qt/qt-includes-begin.h> #include <QAbstractButton> #include <QDragEnterEvent> #include <QDropEvent> #include <QMimeData> #include <QString> #include <QStringList> #include <QWindow> #include <gloperate-qt/qt-includes-end.h> #include <cassert> #ifdef WIN32 const std::string g_ext = "dll"; #elif __APPLE__ const std::string g_ext = "dylib"; #else const std::string g_ext = "so"; #endif namespace gloperate_qtwidgets { PluginWidget::PluginWidget(std::shared_ptr<gloperate::PluginManager> pluginManager, QWidget *parent) : QWidget(parent) , m_ui(new Ui_PluginWidget) , m_pluginManager(pluginManager) { m_ui->setupUi(this); initializeListView(); setAcceptDrops(true); } PluginWidget::~PluginWidget() { } void PluginWidget::dragEnterEvent(QDragEnterEvent *event) { QString uri = event->mimeData()->data("text/uri-list"); int len = uri.length(); if (uri.mid(len - g_ext.length() - 3).left(g_ext.length() + 1).toLower() == "." + QString::fromStdString(g_ext)) event->acceptProposedAction(); } void PluginWidget::initializeListView() { assert(m_pluginManager); m_ui->pluginTableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); m_ui->pluginTableWidget->setRowCount(m_pluginManager->plugins().size()); QStringList tableHeader; tableHeader << "Name" << "Version" << "Description" << "Type" << "Vendor"; m_ui->pluginTableWidget->setHorizontalHeaderLabels(tableHeader); int pluginCount = 0; for (auto plugin : m_pluginManager->plugins()) { m_ui->pluginTableWidget->setItem(pluginCount, 0, new QTableWidgetItem(plugin->name())); m_ui->pluginTableWidget->setItem(pluginCount, 1, new QTableWidgetItem(plugin->version())); m_ui->pluginTableWidget->setItem(pluginCount, 2, new QTableWidgetItem(plugin->description())); m_ui->pluginTableWidget->setItem(pluginCount, 3, new QTableWidgetItem(plugin->type())); m_ui->pluginTableWidget->setItem(pluginCount++, 4, new QTableWidgetItem(plugin->vendor())); } connect(m_ui->pluginTableWidget, &QTableWidget::cellDoubleClicked, this, &PluginWidget::cellSelected); } void PluginWidget::cellSelected(int nRow, int) { emit pluginChanged(*m_pluginManager->plugins().at(nRow)); } void PluginWidget::dropEvent(QDropEvent * dropEvent) { } } //namespace gloperate_qtwidgets <commit_msg>Fix compilation<commit_after>#include <gloperate-qtwidgets/PluginWidget.h> #include "ui_PluginWidget.h" #include <gloperate/plugin/PluginManager.h> #include <gloperate/plugin/Plugin.h> #include <gloperate-qt/qt-includes-begin.h> #include <QAbstractButton> #include <QDragEnterEvent> #include <QDropEvent> #include <QMimeData> #include <QString> #include <QStringList> #include <QWindow> #include <QDebug> #include <gloperate-qt/qt-includes-end.h> #include <cassert> #ifdef WIN32 const std::string g_ext = "dll"; #elif __APPLE__ const std::string g_ext = "dylib"; #else const std::string g_ext = "so"; #endif namespace gloperate_qtwidgets { PluginWidget::PluginWidget(std::shared_ptr<gloperate::PluginManager> pluginManager, QWidget *parent) : QWidget(parent) , m_pluginManager(pluginManager) , m_ui(new Ui_PluginWidget) { m_ui->setupUi(this); initializeListView(); setAcceptDrops(true); } PluginWidget::~PluginWidget() { } void PluginWidget::dragEnterEvent(QDragEnterEvent *event) { QString uri = event->mimeData()->data("text/uri-list"); int len = uri.length(); qDebug() << uri; if (uri.mid(len - g_ext.length() - 3).left(g_ext.length() + 1).toLower() == "." + QString::fromStdString(g_ext)) event->acceptProposedAction(); } void PluginWidget::initializeListView() { assert(m_pluginManager); m_ui->pluginTableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); m_ui->pluginTableWidget->setRowCount(m_pluginManager->plugins().size()); QStringList tableHeader; tableHeader << "Name" << "Version" << "Description" << "Type" << "Vendor"; m_ui->pluginTableWidget->setHorizontalHeaderLabels(tableHeader); int pluginCount = 0; for (auto plugin : m_pluginManager->plugins()) { m_ui->pluginTableWidget->setItem(pluginCount, 0, new QTableWidgetItem(plugin->name())); m_ui->pluginTableWidget->setItem(pluginCount, 1, new QTableWidgetItem(plugin->version())); m_ui->pluginTableWidget->setItem(pluginCount, 2, new QTableWidgetItem(plugin->description())); m_ui->pluginTableWidget->setItem(pluginCount, 3, new QTableWidgetItem(plugin->type())); m_ui->pluginTableWidget->setItem(pluginCount++, 4, new QTableWidgetItem(plugin->vendor())); } connect(m_ui->pluginTableWidget, &QTableWidget::cellDoubleClicked, this, &PluginWidget::cellSelected); } void PluginWidget::cellSelected(int nRow, int) { emit pluginChanged(*m_pluginManager->plugins().at(nRow)); } void PluginWidget::dropEvent(QDropEvent * /*dropEvent*/) { } } //namespace gloperate_qtwidgets <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2012, John Haddon. All rights reserved. // Copyright (c) 2012-2013, Image Engine Design 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 John Haddon nor the names of // any other contributors to this software 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. // ////////////////////////////////////////////////////////////////////////// #include "GafferImage/ImageProcessor.h" #include "Gaffer/Context.h" using namespace Gaffer; using namespace GafferImage; IE_CORE_DEFINERUNTIMETYPED( ImageProcessor ); size_t ImageProcessor::g_firstPlugIndex = 0; ImageProcessor::ImageProcessor( const std::string &name ) : ImageNode( name ) { storeIndexOfNextChild( g_firstPlugIndex ); addChild( new ImagePlug( "in", Gaffer::Plug::In ) ); } ImageProcessor::~ImageProcessor() { } ImagePlug *ImageProcessor::inPlug() { return getChild<ImagePlug>( g_firstPlugIndex ); } const ImagePlug *ImageProcessor::inPlug() const { return getChild<ImagePlug>( g_firstPlugIndex ); } Plug *ImageProcessor::correspondingInput( const Plug *output ) { if ( output == outPlug() ) { return inPlug(); } return ImageNode::correspondingInput( output ); } const Plug *ImageProcessor::correspondingInput( const Plug *output ) const { if ( output == outPlug() ) { return inPlug(); } return ImageNode::correspondingInput( output ); } void ImageProcessor::hash( const Gaffer::ValuePlug *output, const Gaffer::Context *context, IECore::MurmurHash &h ) const { /// \todo Can this be simplified using the same logic used in SceneProcessor::hash()? It would /// avoid calling ComputeNode::hash only to overwrite the hash if we're disabled. ComputeNode::hash( output, context, h ); h.append( enabledPlug()->hash() ); const ImagePlug *imagePlug = output->parent<ImagePlug>(); if ( imagePlug == 0 ) { return; } if ( enabled() ) { if( output == imagePlug->channelDataPlug() ) { const std::string &channel = context->get<std::string>( ImagePlug::channelNameContextName ); if ( channelEnabled( channel ) ) { hashChannelDataPlug( imagePlug, context, h ); h.append( context->get<std::string>( ImagePlug::channelNameContextName ) ); h.append( context->get<Imath::V2i>( ImagePlug::tileOriginContextName ) ); } else { h = inPlug()->channelDataPlug()->hash(); } } else if ( output == imagePlug->formatPlug() ) { hashFormatPlug( imagePlug, context, h ); } else if ( output == imagePlug->dataWindowPlug() ) { hashDataWindowPlug( imagePlug, context, h ); } else if ( output == imagePlug->channelNamesPlug() ) { hashChannelNamesPlug( imagePlug, context, h ); } } else { if( output == imagePlug->channelDataPlug() ) { h = inPlug()->channelDataPlug()->hash(); } else if ( output == imagePlug->formatPlug() ) { h = inPlug()->formatPlug()->hash(); } else if ( output == imagePlug->dataWindowPlug() ) { h = inPlug()->dataWindowPlug()->hash(); } else if ( output == imagePlug->channelNamesPlug() ) { h = inPlug()->channelNamesPlug()->hash(); } } } void ImageProcessor::compute( ValuePlug *output, const Context *context ) const { /// \todo Can this be simplified using the same logic used in SceneProcessor::compute()? /// It would remove the need for the computeImagePlugs() method. ImagePlug *imagePlug = output->ancestor<ImagePlug>(); if ( imagePlug ) { if( enabled() ) { if( output == imagePlug->channelDataPlug() ) { const std::string &channel = context->get<std::string>( ImagePlug::channelNameContextName ); if ( channelEnabled( channel ) ) { computeImagePlugs( output, context ); } else { static_cast<FloatVectorDataPlug *>( output )->setValue( inPlug()->channelDataPlug()->getValue() ); } } else { computeImagePlugs( output, context ); } } else { if( output == imagePlug->formatPlug() ) { static_cast<FormatPlug *>( output )->setValue( inPlug()->formatPlug()->getValue() ); } else if( output == imagePlug->dataWindowPlug() ) { static_cast<AtomicBox2iPlug *>( output )->setValue( inPlug()->dataWindowPlug()->getValue() ); } else if( output == imagePlug->channelNamesPlug() ) { static_cast<StringVectorDataPlug *>( output )->setValue( inPlug()->channelNamesPlug()->getValue() ); } else if( output == imagePlug->channelDataPlug() ) { static_cast<FloatVectorDataPlug *>( output )->setValue( inPlug()->channelDataPlug()->getValue() ); } } } } <commit_msg>Added a todo in ImageProcessor.<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2012, John Haddon. All rights reserved. // Copyright (c) 2012-2013, Image Engine Design 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 John Haddon nor the names of // any other contributors to this software 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. // ////////////////////////////////////////////////////////////////////////// #include "GafferImage/ImageProcessor.h" #include "Gaffer/Context.h" using namespace Gaffer; using namespace GafferImage; IE_CORE_DEFINERUNTIMETYPED( ImageProcessor ); size_t ImageProcessor::g_firstPlugIndex = 0; ImageProcessor::ImageProcessor( const std::string &name ) : ImageNode( name ) { storeIndexOfNextChild( g_firstPlugIndex ); addChild( new ImagePlug( "in", Gaffer::Plug::In ) ); } ImageProcessor::~ImageProcessor() { } ImagePlug *ImageProcessor::inPlug() { return getChild<ImagePlug>( g_firstPlugIndex ); } const ImagePlug *ImageProcessor::inPlug() const { return getChild<ImagePlug>( g_firstPlugIndex ); } Plug *ImageProcessor::correspondingInput( const Plug *output ) { if ( output == outPlug() ) { return inPlug(); } return ImageNode::correspondingInput( output ); } const Plug *ImageProcessor::correspondingInput( const Plug *output ) const { if ( output == outPlug() ) { return inPlug(); } return ImageNode::correspondingInput( output ); } void ImageProcessor::hash( const Gaffer::ValuePlug *output, const Gaffer::Context *context, IECore::MurmurHash &h ) const { /// \todo Can this be simplified using the same logic used in SceneProcessor::hash()? It would /// avoid calling ComputeNode::hash only to overwrite the hash if we're disabled. ComputeNode::hash( output, context, h ); /// \todo Should this not be done only if we're computing an ImagePlug output? /// and doesn't the fact that we call enabled() below mean that we're already /// hashing in the effect of the enabled plug anyway? h.append( enabledPlug()->hash() ); const ImagePlug *imagePlug = output->parent<ImagePlug>(); if ( imagePlug == 0 ) { return; } if ( enabled() ) { if( output == imagePlug->channelDataPlug() ) { const std::string &channel = context->get<std::string>( ImagePlug::channelNameContextName ); if ( channelEnabled( channel ) ) { hashChannelDataPlug( imagePlug, context, h ); h.append( context->get<std::string>( ImagePlug::channelNameContextName ) ); h.append( context->get<Imath::V2i>( ImagePlug::tileOriginContextName ) ); } else { h = inPlug()->channelDataPlug()->hash(); } } else if ( output == imagePlug->formatPlug() ) { hashFormatPlug( imagePlug, context, h ); } else if ( output == imagePlug->dataWindowPlug() ) { hashDataWindowPlug( imagePlug, context, h ); } else if ( output == imagePlug->channelNamesPlug() ) { hashChannelNamesPlug( imagePlug, context, h ); } } else { if( output == imagePlug->channelDataPlug() ) { h = inPlug()->channelDataPlug()->hash(); } else if ( output == imagePlug->formatPlug() ) { h = inPlug()->formatPlug()->hash(); } else if ( output == imagePlug->dataWindowPlug() ) { h = inPlug()->dataWindowPlug()->hash(); } else if ( output == imagePlug->channelNamesPlug() ) { h = inPlug()->channelNamesPlug()->hash(); } } } void ImageProcessor::compute( ValuePlug *output, const Context *context ) const { /// \todo Can this be simplified using the same logic used in SceneProcessor::compute()? /// It would remove the need for the computeImagePlugs() method. ImagePlug *imagePlug = output->ancestor<ImagePlug>(); if ( imagePlug ) { if( enabled() ) { if( output == imagePlug->channelDataPlug() ) { const std::string &channel = context->get<std::string>( ImagePlug::channelNameContextName ); if ( channelEnabled( channel ) ) { computeImagePlugs( output, context ); } else { static_cast<FloatVectorDataPlug *>( output )->setValue( inPlug()->channelDataPlug()->getValue() ); } } else { computeImagePlugs( output, context ); } } else { if( output == imagePlug->formatPlug() ) { static_cast<FormatPlug *>( output )->setValue( inPlug()->formatPlug()->getValue() ); } else if( output == imagePlug->dataWindowPlug() ) { static_cast<AtomicBox2iPlug *>( output )->setValue( inPlug()->dataWindowPlug()->getValue() ); } else if( output == imagePlug->channelNamesPlug() ) { static_cast<StringVectorDataPlug *>( output )->setValue( inPlug()->channelNamesPlug()->getValue() ); } else if( output == imagePlug->channelDataPlug() ) { static_cast<FloatVectorDataPlug *>( output )->setValue( inPlug()->channelDataPlug()->getValue() ); } } } } <|endoftext|>
<commit_before>#include "imageview.h" #include "experimentcontext.h" #include "resultspanel.h" #include "../ori/OriWidgets.h" #include "appconfig.h" #include <QBoxLayout> #include <QLabel> #include <QVariant> #include <QDebug> #include <QDateTime> #include <QPushButton> #define WORST_PREDICTED_IMAGE_W 160 #define WORST_PREDICTED_IMAGE_H 120 static QObject* spacing(int px) { return reinterpret_cast<QObject*>(px); } ResultsPanel::ResultsPanel(ExperimentContext *context, QWidget *parent) : QFrame(parent), _updateIntervalMs(AppConfig::fpsUpdateIntervalMs()) { setObjectName("resultsPanel"); _context = context; connect(_context, &ExperimentContext::experimentStarted, this, &ResultsPanel::experimentStarted); connect(_context, &ExperimentContext::newImageResult, this, &ResultsPanel::newImageResult); connect(_context, &ExperimentContext::modeChanged, this, &ResultsPanel::updateOnModeChanged); connect(_context, &ExperimentContext::zoomChanged, this, &ResultsPanel::updateOnEffectiveZoomChanged); connect(_context, &ExperimentContext::effectiveZoomChanged, this, &ResultsPanel::updateOnEffectiveZoomChanged); _infoImagesPerSec = makeInfoLabel(); _infoPrecision = makeInfoLabel(); _infoMetricTop1 = makeInfoLabel(); _infoMetricTop5 = makeInfoLabel(); _worstPredictedImage = new ImageView(WORST_PREDICTED_IMAGE_W, WORST_PREDICTED_IMAGE_H); auto panelCounters = makePanel({ Ori::Gui::makeTitle("IMAGES PER SECOND"), _infoImagesPerSec }); _panelPrecision = makePanel({ Ori::Gui::makeTitle("AVERAGE PRECISION"), _infoPrecision }); auto panelMetricTop1 = makePanel({ Ori::Gui::makeTitle("TOP-1"), _infoMetricTop1 }); auto panelMetricTop5 = makePanel({ Ori::Gui::makeTitle("TOP-5"), _infoMetricTop5 }); _panelMetrics = new QFrame; _panelMetrics->setLayout(Ori::Gui::layoutH(0, 0, { panelMetricTop1, panelMetricTop5 })); _panelWorstPrediction = makePanel({ Ori::Gui::makeTitle("WORST PREDICTION"), Ori::Gui::layoutH(0, 0, { 0, _worstPredictedImage, 0}), }); auto buttonZoomIn = new QPushButton; buttonZoomIn->setObjectName("buttonZoomIn"); buttonZoomIn->setToolTip(tr("Zoom in")); buttonZoomIn->setIcon(QIcon(":/tools/zoom-in")); connect(buttonZoomIn, SIGNAL(clicked(bool)), _context, SLOT(zoomIn())); auto buttonZoomOut = new QPushButton; buttonZoomOut->setObjectName("buttonZoomOut"); buttonZoomOut->setToolTip(tr("Zoom out")); buttonZoomOut->setIcon(QIcon(":/tools/zoom-out")); connect(buttonZoomOut, SIGNAL(clicked(bool)), _context, SLOT(zoomOut())); auto buttonZoomActual = new QPushButton; buttonZoomActual->setObjectName("buttonZoomActual"); buttonZoomActual->setToolTip(tr("Actual size")); buttonZoomActual->setIcon(QIcon(":/tools/zoom-to-actual-size")); connect(buttonZoomActual, SIGNAL(clicked(bool)), _context, SLOT(zoomActual())); auto buttonZoomToFit = new QPushButton; buttonZoomToFit->setObjectName("buttonZoomToFit"); buttonZoomToFit->setToolTip(tr("Zoom to fit")); buttonZoomToFit->setIcon(QIcon(":/tools/zoom-to-fit")); connect(buttonZoomToFit, SIGNAL(clicked(bool)), _context, SLOT(zoomToFit())); _infoZoom = new QLabel; _infoZoom->setAlignment(Qt::AlignTop | Qt::AlignRight); _infoZoom->setProperty("qss-role", "link"); auto zoomLayout = Ori::Gui::layoutH({buttonZoomActual, 0, buttonZoomOut, 0, buttonZoomIn, 0, buttonZoomToFit}); _panelZoom = makePanel({ Ori::Gui::layoutH({ Ori::Gui::makeTitle("ZOOM"), 0, _infoZoom }), zoomLayout }); setLayout(Ori::Gui::layoutV(0, 0, { panelCounters, _panelPrecision, _panelZoom, _panelMetrics, _panelWorstPrediction, 0 })); resetInfo(); updateOnModeChanged(AppConfig::currentMode().value<Mode>()); updateOnEffectiveZoomChanged(AppConfig::zoom()); } QLabel* ResultsPanel::makeInfoLabel(const QString &role) { auto label = new QLabel; label->setProperty("qss-role", role.isEmpty() ? QString("info-label") : role); return label; } QFrame* ResultsPanel::makePanel(const std::initializer_list<QObject *> &items, const QString &objectName) { auto panel = new QFrame; panel->setProperty("qss-role", "results-panel"); panel->setObjectName(objectName); panel->setLayout(Ori::Gui::layoutV(0, 0, items)); return panel; } void ResultsPanel::experimentStarted(bool resume) { if (!resume) { resetInfo(); } } void ResultsPanel::newImageResult(ImageResult ir) { qint64 curTimeMs = QDateTime::currentMSecsSinceEpoch(); if (curTimeMs - _lastUpdateMs > _updateIntervalMs) { _infoImagesPerSec->setText(QString(QStringLiteral("%1")).arg(ir.imagesPerSecond(), 0, 'f', 2)); _infoPrecision->setText(QString(QStringLiteral("%1")).arg(_context->precision().avg, 0, 'f', 2)); _infoMetricTop1->setText(QString::number(_context->top1().avg, 'f', 2)); _infoMetricTop5->setText(QString::number(_context->top5().avg, 'f', 2)); double accuracyDelta = ir.accuracyDelta(); if (accuracyDelta > _worstAccuracyDelta) { _worstAccuracyDelta = accuracyDelta; _worstPredictedImage->loadImage(ir.imageFile); _worstPredictedImage->setToolTip(QString(QStringLiteral("%1\nTop1: %2\nCorrect: %3")) .arg(ir.imageFile) .arg(ir.predictions[0].str()) .arg(ir.findCorrect()->str())); } _lastUpdateMs = curTimeMs; } } void ResultsPanel::resetInfo() { _infoImagesPerSec->setText("N/A"); _infoPrecision->setText("N/A"); _infoMetricTop1->setText("N/A"); _infoMetricTop5->setText("N/A"); _worstAccuracyDelta = 0; _worstPredictedImage->clearImage(); _worstPredictedImage->setToolTip(""); _lastUpdateMs = 0; } void ResultsPanel::updateOnModeChanged(Mode mode) { bool v = mode.type == Mode::Type::CLASSIFICATION; _panelMetrics->setVisible(v); _panelWorstPrediction->setVisible(v); _panelPrecision->setVisible(!v); _panelZoom->setVisible(!v); } void ResultsPanel::updateOnEffectiveZoomChanged(double z) { int p = z * 100; _infoZoom->setText(QString("<span style='color:#969C9E'>%1%</span>").arg(p)); } <commit_msg>Remove unused code<commit_after>#include "imageview.h" #include "experimentcontext.h" #include "resultspanel.h" #include "../ori/OriWidgets.h" #include "appconfig.h" #include <QBoxLayout> #include <QLabel> #include <QVariant> #include <QDebug> #include <QDateTime> #include <QPushButton> #define WORST_PREDICTED_IMAGE_W 160 #define WORST_PREDICTED_IMAGE_H 120 ResultsPanel::ResultsPanel(ExperimentContext *context, QWidget *parent) : QFrame(parent), _updateIntervalMs(AppConfig::fpsUpdateIntervalMs()) { setObjectName("resultsPanel"); _context = context; connect(_context, &ExperimentContext::experimentStarted, this, &ResultsPanel::experimentStarted); connect(_context, &ExperimentContext::newImageResult, this, &ResultsPanel::newImageResult); connect(_context, &ExperimentContext::modeChanged, this, &ResultsPanel::updateOnModeChanged); connect(_context, &ExperimentContext::zoomChanged, this, &ResultsPanel::updateOnEffectiveZoomChanged); connect(_context, &ExperimentContext::effectiveZoomChanged, this, &ResultsPanel::updateOnEffectiveZoomChanged); _infoImagesPerSec = makeInfoLabel(); _infoPrecision = makeInfoLabel(); _infoMetricTop1 = makeInfoLabel(); _infoMetricTop5 = makeInfoLabel(); _worstPredictedImage = new ImageView(WORST_PREDICTED_IMAGE_W, WORST_PREDICTED_IMAGE_H); auto panelCounters = makePanel({ Ori::Gui::makeTitle("IMAGES PER SECOND"), _infoImagesPerSec }); _panelPrecision = makePanel({ Ori::Gui::makeTitle("AVERAGE PRECISION"), _infoPrecision }); auto panelMetricTop1 = makePanel({ Ori::Gui::makeTitle("TOP-1"), _infoMetricTop1 }); auto panelMetricTop5 = makePanel({ Ori::Gui::makeTitle("TOP-5"), _infoMetricTop5 }); _panelMetrics = new QFrame; _panelMetrics->setLayout(Ori::Gui::layoutH(0, 0, { panelMetricTop1, panelMetricTop5 })); _panelWorstPrediction = makePanel({ Ori::Gui::makeTitle("WORST PREDICTION"), Ori::Gui::layoutH(0, 0, { 0, _worstPredictedImage, 0}), }); auto buttonZoomIn = new QPushButton; buttonZoomIn->setObjectName("buttonZoomIn"); buttonZoomIn->setToolTip(tr("Zoom in")); buttonZoomIn->setIcon(QIcon(":/tools/zoom-in")); connect(buttonZoomIn, SIGNAL(clicked(bool)), _context, SLOT(zoomIn())); auto buttonZoomOut = new QPushButton; buttonZoomOut->setObjectName("buttonZoomOut"); buttonZoomOut->setToolTip(tr("Zoom out")); buttonZoomOut->setIcon(QIcon(":/tools/zoom-out")); connect(buttonZoomOut, SIGNAL(clicked(bool)), _context, SLOT(zoomOut())); auto buttonZoomActual = new QPushButton; buttonZoomActual->setObjectName("buttonZoomActual"); buttonZoomActual->setToolTip(tr("Actual size")); buttonZoomActual->setIcon(QIcon(":/tools/zoom-to-actual-size")); connect(buttonZoomActual, SIGNAL(clicked(bool)), _context, SLOT(zoomActual())); auto buttonZoomToFit = new QPushButton; buttonZoomToFit->setObjectName("buttonZoomToFit"); buttonZoomToFit->setToolTip(tr("Zoom to fit")); buttonZoomToFit->setIcon(QIcon(":/tools/zoom-to-fit")); connect(buttonZoomToFit, SIGNAL(clicked(bool)), _context, SLOT(zoomToFit())); _infoZoom = new QLabel; _infoZoom->setAlignment(Qt::AlignTop | Qt::AlignRight); _infoZoom->setProperty("qss-role", "link"); auto zoomLayout = Ori::Gui::layoutH({buttonZoomActual, 0, buttonZoomOut, 0, buttonZoomIn, 0, buttonZoomToFit}); _panelZoom = makePanel({ Ori::Gui::layoutH({ Ori::Gui::makeTitle("ZOOM"), 0, _infoZoom }), zoomLayout }); setLayout(Ori::Gui::layoutV(0, 0, { panelCounters, _panelPrecision, _panelZoom, _panelMetrics, _panelWorstPrediction, 0 })); resetInfo(); updateOnModeChanged(AppConfig::currentMode().value<Mode>()); updateOnEffectiveZoomChanged(AppConfig::zoom()); } QLabel* ResultsPanel::makeInfoLabel(const QString &role) { auto label = new QLabel; label->setProperty("qss-role", role.isEmpty() ? QString("info-label") : role); return label; } QFrame* ResultsPanel::makePanel(const std::initializer_list<QObject *> &items, const QString &objectName) { auto panel = new QFrame; panel->setProperty("qss-role", "results-panel"); panel->setObjectName(objectName); panel->setLayout(Ori::Gui::layoutV(0, 0, items)); return panel; } void ResultsPanel::experimentStarted(bool resume) { if (!resume) { resetInfo(); } } void ResultsPanel::newImageResult(ImageResult ir) { qint64 curTimeMs = QDateTime::currentMSecsSinceEpoch(); if (curTimeMs - _lastUpdateMs > _updateIntervalMs) { _infoImagesPerSec->setText(QString(QStringLiteral("%1")).arg(ir.imagesPerSecond(), 0, 'f', 2)); _infoPrecision->setText(QString(QStringLiteral("%1")).arg(_context->precision().avg, 0, 'f', 2)); _infoMetricTop1->setText(QString::number(_context->top1().avg, 'f', 2)); _infoMetricTop5->setText(QString::number(_context->top5().avg, 'f', 2)); double accuracyDelta = ir.accuracyDelta(); if (accuracyDelta > _worstAccuracyDelta) { _worstAccuracyDelta = accuracyDelta; _worstPredictedImage->loadImage(ir.imageFile); _worstPredictedImage->setToolTip(QString(QStringLiteral("%1\nTop1: %2\nCorrect: %3")) .arg(ir.imageFile) .arg(ir.predictions[0].str()) .arg(ir.findCorrect()->str())); } _lastUpdateMs = curTimeMs; } } void ResultsPanel::resetInfo() { _infoImagesPerSec->setText("N/A"); _infoPrecision->setText("N/A"); _infoMetricTop1->setText("N/A"); _infoMetricTop5->setText("N/A"); _worstAccuracyDelta = 0; _worstPredictedImage->clearImage(); _worstPredictedImage->setToolTip(""); _lastUpdateMs = 0; } void ResultsPanel::updateOnModeChanged(Mode mode) { bool v = mode.type == Mode::Type::CLASSIFICATION; _panelMetrics->setVisible(v); _panelWorstPrediction->setVisible(v); _panelPrecision->setVisible(!v); _panelZoom->setVisible(!v); } void ResultsPanel::updateOnEffectiveZoomChanged(double z) { int p = z * 100; _infoZoom->setText(QString("<span style='color:#969C9E'>%1%</span>").arg(p)); } <|endoftext|>
<commit_before>/* Copyright (c) 2010, The Mineserver Project 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 the The Mineserver Project 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 HOLDER 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 "furnace.h" #include <iostream> //#define _DEBUG Furnace::Furnace(NBT_Value *entity) { // Setup this furnace this->x = (sint32)(*(*entity)["x"]); this->y = (sint32)(*(*entity)["y"]); this->z = (sint32)(*(*entity)["z"]); //this->fuelBurningTime = (sint16)(*(*entity)["BurnTime"]); // Clean out the slots this->slots[SLOT_INPUT].count = 0; this->slots[SLOT_INPUT].damage = 0; this->slots[SLOT_INPUT].id = 0; this->slots[SLOT_FUEL].count = 0; this->slots[SLOT_FUEL].damage = 0; this->slots[SLOT_FUEL].id = 0; this->slots[SLOT_OUTPUT].count = 0; this->slots[SLOT_OUTPUT].damage= 0; this->slots[SLOT_OUTPUT].id = 0; // Set the slots to what was passed NBT_Value *slotList = (NBT_Value *)(*entity)["Items"]; std::vector<NBT_Value*> *slotEntities = slotList->GetList(); std::vector<NBT_Value*>::iterator iter = slotEntities->begin(), end = slotEntities->end(); for( ; iter != end; iter++ ) { sint8 slotNum = (sint8)(*(**iter)["Slot"]); slots[slotNum].count = (sint8)(*(**iter)["Count"]); slots[slotNum].damage = (sint16)(*(**iter)["Damage"]); slots[slotNum].id = (sint16)(*(**iter)["id"]); } // Set the cooking time based on input type (currently all smelting takes 10 secs but this gives us flexivibility in future) sSlot inputSlot = slots[SLOT_INPUT]; cookingTime = 0; if(inputSlot.id == BLOCK_IRON_ORE) { this->cookingTime = 10; } if(inputSlot.id == BLOCK_GOLD_ORE) { this->cookingTime = 10; } if(inputSlot.id == BLOCK_SAND) { this->cookingTime = 10; } if(inputSlot.id == BLOCK_COBBLESTONE) { this->cookingTime = 10; } if(inputSlot.id == ITEM_PORK) { this->cookingTime = 10; } if(inputSlot.id == ITEM_CLAY_BALLS) { this->cookingTime = 10; } if(inputSlot.id == ITEM_RAW_FISH) { this->cookingTime = 10; } // Reset our active duration this->fuelBurningTime = 0; this->activeCookDuration = 0; this->burning = false; // Make sure we're the right kind of block based on our current status this->updateBlock(); } void Furnace::updateBlock() { // Get a pointer to this furnace's current block uint8 block; uint8 meta; // Now make sure that it's got the correct block type based on it's current status if(isBurningFuel() && !burning) { Map::get()->getBlock(this->x, this->y, this->z, &block, &meta); // Switch to burning furnace Map::get()->setBlock(this->x, this->y, this->z, BLOCK_BURNING_FURNACE, meta); Map::get()->sendBlockChange(this->x, this->y, this->z, BLOCK_BURNING_FURNACE, meta); this->sendToAllUsers(); burning = true; } else if(!isBurningFuel() && burning) { Map::get()->getBlock(this->x, this->y, this->z, &block, &meta); // Switch to regular furnace Map::get()->setBlock(this->x, this->y, this->z, BLOCK_FURNACE, meta); Map::get()->sendBlockChange(this->x, this->y, this->z, BLOCK_FURNACE, meta); this->sendToAllUsers(); burning = false; } } void Furnace::smelt() { // Check if we're cooking if(this->isCooking()) { // Convert where applicable sSlot inputSlot = slots[SLOT_INPUT]; sSlot fuelSlot = slots[SLOT_FUEL]; sSlot outputSlot = slots[SLOT_OUTPUT]; sint32 creationID = 0; if(inputSlot.id == BLOCK_IRON_ORE) { creationID = ITEM_IRON_INGOT; } if(inputSlot.id == BLOCK_GOLD_ORE) { creationID = ITEM_GOLD_INGOT; } if(inputSlot.id == BLOCK_SAND) { creationID = BLOCK_GLASS; } if(inputSlot.id == BLOCK_COBBLESTONE) { creationID = BLOCK_STONE; } if(inputSlot.id == ITEM_PORK) { creationID = ITEM_GRILLED_PORK; } if(inputSlot.id == ITEM_CLAY_BALLS) { creationID = ITEM_CLAY_BRICK; } if(inputSlot.id == ITEM_RAW_FISH) { creationID = ITEM_COOKED_FISH; } // Update other params if we actually converted if(creationID != 0) { // Ok - now check if the current output slot contains the same stuff if(outputSlot.id != creationID) { // No so overwrite it outputSlot.id = creationID; outputSlot.count = 0; } // Increment output and decrememnt the input source outputSlot.count++; inputSlot.count--; outputSlot.damage = inputSlot.damage; // Bounds check all if(outputSlot.count > 64) outputSlot.count = 64; if(inputSlot.count < 0) inputSlot.count = 0; // Update the slots this->slots[SLOT_INPUT] = inputSlot; this->slots[SLOT_FUEL] = fuelSlot; this->slots[SLOT_OUTPUT] = outputSlot; } } // Reset our active cook durations this->activeCookDuration = 0; } bool Furnace::isBurningFuel() { // Check if this furnace is currently burning if(this->fuelBurningTime > 0) { return true; } else { return false; } } bool Furnace::isCooking() { // If we're burning fuel and have valid ingredients, we're cooking! if(this->isBurningFuel() && this->hasValidIngredient()) return true; else return false; } bool Furnace::hasValidIngredient() { // Check that we have a valid input type sSlot slot = slots[SLOT_INPUT]; if((slot.count != 0) && ( (slot.id == BLOCK_IRON_ORE) || (slot.id == BLOCK_GOLD_ORE) || (slot.id == BLOCK_SAND) || (slot.id == BLOCK_COBBLESTONE) || (slot.id == ITEM_PORK) || (slot.id == ITEM_CLAY_BALLS) || (slot.id == ITEM_RAW_FISH)) ){ return true; } else { return false; } } void Furnace::consumeFuel() { // Check that we have fuel if(slots[SLOT_FUEL].count == 0) return; // Increment the fuel burning time based on fuel type // http://www.minecraftwiki.net/wiki/Furnace#Fuel_efficiency sSlot fuelSlot = slots[SLOT_FUEL]; this->initialBurningTime = 0; if(fuelSlot.id == ITEM_COAL) { this->initialBurningTime += 80; } if(fuelSlot.id == BLOCK_WOOD) { this->initialBurningTime += 15; } if(fuelSlot.id == ITEM_STICK) { this->initialBurningTime += 5; } if(fuelSlot.id == BLOCK_LOG) { this->initialBurningTime += 15; } if(fuelSlot.id == BLOCK_WORKBENCH) { this->initialBurningTime += 15; } if(fuelSlot.id == BLOCK_CHEST) { this->initialBurningTime += 15; } if(fuelSlot.id == BLOCK_BOOKSHELF) { this->initialBurningTime += 15; } if(fuelSlot.id == BLOCK_JUKEBOX) { this->initialBurningTime += 15; } if(fuelSlot.id == BLOCK_FENCE) { this->initialBurningTime += 15; } if(fuelSlot.id == BLOCK_WOODEN_STAIRS) { this->initialBurningTime += 15; } if(fuelSlot.id == ITEM_LAVA_BUCKET) { this->initialBurningTime += 1000; } this->fuelBurningTime += this->initialBurningTime; // Now decrement the fuel & reset slots[SLOT_FUEL].count--; if(slots[SLOT_FUEL].count < 0) slots[SLOT_FUEL].count = 0; // Update our block type if need be this->updateBlock(); } sint16 Furnace::burnTime() { sint16 fuelBurningTime = (sint16)((200.0f / this->initialBurningTime) * this->fuelBurningTime); if(fuelBurningTime < 0) fuelBurningTime = 0; return fuelBurningTime; // Just return the number of secs we're burning for //return (sint16)this->fuelBurningTime; } sint16 Furnace::cookTime() { // Express cook time as a fraction of total cooking time sint16 tempCookTime = (sint16)((200.0f / this->cookingTime) * this->activeCookDuration); if(tempCookTime < 0) tempCookTime = 0; return tempCookTime; } NBT_Value* Furnace::getSlotEntity(sint8 slotNumber) { // Return null of we don't have anything in this slot if(slots[slotNumber].count == 0) return NULL; // Create a new slot NBT entity and add it's data NBT_Value* slot = new NBT_Value(NBT_Value::TAG_COMPOUND); slot->Insert("Count", new NBT_Value(slots[slotNumber].count)); slot->Insert("Damage", new NBT_Value(slots[slotNumber].damage)); slot->Insert("Slot", new NBT_Value(slotNumber)); slot->Insert("id", new NBT_Value(slots[slotNumber].id)); return slot; } void Furnace::sendToAllUsers() { // Create a new compound tag and set it's direct properties NBT_Value* newEntity = new NBT_Value(NBT_Value::TAG_COMPOUND); newEntity->Insert("BurnTime", new NBT_Value(this->burnTime())); newEntity->Insert("CookTime", new NBT_Value(this->cookTime())); newEntity->Insert("id", new NBT_Value("Furnace")); newEntity->Insert("x", new NBT_Value(this->x)); newEntity->Insert("y", new NBT_Value(this->y)); newEntity->Insert("z", new NBT_Value(this->z)); // Add our 3 child compounds for each slot that contains something NBT_Value *slotList = new NBT_Value(NBT_Value::TAG_LIST, NBT_Value::TAG_COMPOUND); for(int i = 0; i <= 2; i++) { NBT_Value *slot = getSlotEntity(i); if(slot != NULL) slotList->GetList()->push_back(slot); } newEntity->Insert("Items", slotList); // Write the entity data into a parent Compound std::vector<uint8> buffer; buffer.push_back(NBT_Value::TAG_COMPOUND); buffer.push_back(0); buffer.push_back(0); newEntity->Write(buffer); buffer.push_back(0); buffer.push_back(0); // Compress the data uint8 *compressedData = new uint8[ALLOCATE_NBTFILE]; z_stream zstream; zstream.zalloc = Z_NULL; zstream.zfree = Z_NULL; zstream.opaque = Z_NULL; zstream.next_out = compressedData; zstream.next_in = &buffer[0]; zstream.avail_in = buffer.size(); zstream.avail_out = ALLOCATE_NBTFILE; zstream.total_out = 0; zstream.total_in = 0; deflateInit2(&zstream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 15+MAX_WBITS, 8, Z_DEFAULT_STRATEGY); // Gzip the data if(int state=deflate(&zstream, Z_FULL_FLUSH)!=Z_OK) { std::cout << "Error in deflate: " << state << std::endl; } deflateEnd(&zstream); // Create a new packet to send back to client Packet pkt; pkt << (sint8)PACKET_COMPLEX_ENTITIES << this->x << (sint16)this->y << this->z << (sint16)zstream.total_out; pkt.addToWrite(compressedData, zstream.total_out); delete [] compressedData; // Tell all users about this guy User::sendAll((uint8*)pkt.getWrite(), pkt.getWriteLen()); #ifdef _DEBUG std::cout << "Furnace entity data: " << std::endl; newEntity->Print(); #endif // Update our map with this guy Map::get()->setComplexEntity(x, y, z, newEntity); } <commit_msg>Removed commented code<commit_after>/* Copyright (c) 2010, The Mineserver Project 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 the The Mineserver Project 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 HOLDER 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 "furnace.h" #include <iostream> //#define _DEBUG Furnace::Furnace(NBT_Value *entity) { // Setup this furnace this->x = (sint32)(*(*entity)["x"]); this->y = (sint32)(*(*entity)["y"]); this->z = (sint32)(*(*entity)["z"]); //this->fuelBurningTime = (sint16)(*(*entity)["BurnTime"]); // Clean out the slots this->slots[SLOT_INPUT].count = 0; this->slots[SLOT_INPUT].damage = 0; this->slots[SLOT_INPUT].id = 0; this->slots[SLOT_FUEL].count = 0; this->slots[SLOT_FUEL].damage = 0; this->slots[SLOT_FUEL].id = 0; this->slots[SLOT_OUTPUT].count = 0; this->slots[SLOT_OUTPUT].damage= 0; this->slots[SLOT_OUTPUT].id = 0; // Set the slots to what was passed NBT_Value *slotList = (NBT_Value *)(*entity)["Items"]; std::vector<NBT_Value*> *slotEntities = slotList->GetList(); std::vector<NBT_Value*>::iterator iter = slotEntities->begin(), end = slotEntities->end(); for( ; iter != end; iter++ ) { sint8 slotNum = (sint8)(*(**iter)["Slot"]); slots[slotNum].count = (sint8)(*(**iter)["Count"]); slots[slotNum].damage = (sint16)(*(**iter)["Damage"]); slots[slotNum].id = (sint16)(*(**iter)["id"]); } // Set the cooking time based on input type (currently all smelting takes 10 secs but this gives us flexivibility in future) sSlot inputSlot = slots[SLOT_INPUT]; cookingTime = 0; if(inputSlot.id == BLOCK_IRON_ORE) { this->cookingTime = 10; } if(inputSlot.id == BLOCK_GOLD_ORE) { this->cookingTime = 10; } if(inputSlot.id == BLOCK_SAND) { this->cookingTime = 10; } if(inputSlot.id == BLOCK_COBBLESTONE) { this->cookingTime = 10; } if(inputSlot.id == ITEM_PORK) { this->cookingTime = 10; } if(inputSlot.id == ITEM_CLAY_BALLS) { this->cookingTime = 10; } if(inputSlot.id == ITEM_RAW_FISH) { this->cookingTime = 10; } // Reset our active duration this->fuelBurningTime = 0; this->activeCookDuration = 0; this->burning = false; // Make sure we're the right kind of block based on our current status this->updateBlock(); } void Furnace::updateBlock() { // Get a pointer to this furnace's current block uint8 block; uint8 meta; // Now make sure that it's got the correct block type based on it's current status if(isBurningFuel() && !burning) { Map::get()->getBlock(this->x, this->y, this->z, &block, &meta); // Switch to burning furnace Map::get()->setBlock(this->x, this->y, this->z, BLOCK_BURNING_FURNACE, meta); Map::get()->sendBlockChange(this->x, this->y, this->z, BLOCK_BURNING_FURNACE, meta); this->sendToAllUsers(); burning = true; } else if(!isBurningFuel() && burning) { Map::get()->getBlock(this->x, this->y, this->z, &block, &meta); // Switch to regular furnace Map::get()->setBlock(this->x, this->y, this->z, BLOCK_FURNACE, meta); Map::get()->sendBlockChange(this->x, this->y, this->z, BLOCK_FURNACE, meta); this->sendToAllUsers(); burning = false; } } void Furnace::smelt() { // Check if we're cooking if(this->isCooking()) { // Convert where applicable sSlot inputSlot = slots[SLOT_INPUT]; sSlot fuelSlot = slots[SLOT_FUEL]; sSlot outputSlot = slots[SLOT_OUTPUT]; sint32 creationID = 0; if(inputSlot.id == BLOCK_IRON_ORE) { creationID = ITEM_IRON_INGOT; } if(inputSlot.id == BLOCK_GOLD_ORE) { creationID = ITEM_GOLD_INGOT; } if(inputSlot.id == BLOCK_SAND) { creationID = BLOCK_GLASS; } if(inputSlot.id == BLOCK_COBBLESTONE) { creationID = BLOCK_STONE; } if(inputSlot.id == ITEM_PORK) { creationID = ITEM_GRILLED_PORK; } if(inputSlot.id == ITEM_CLAY_BALLS) { creationID = ITEM_CLAY_BRICK; } if(inputSlot.id == ITEM_RAW_FISH) { creationID = ITEM_COOKED_FISH; } // Update other params if we actually converted if(creationID != 0) { // Ok - now check if the current output slot contains the same stuff if(outputSlot.id != creationID) { // No so overwrite it outputSlot.id = creationID; outputSlot.count = 0; } // Increment output and decrememnt the input source outputSlot.count++; inputSlot.count--; outputSlot.damage = inputSlot.damage; // Bounds check all if(outputSlot.count > 64) outputSlot.count = 64; if(inputSlot.count < 0) inputSlot.count = 0; // Update the slots this->slots[SLOT_INPUT] = inputSlot; this->slots[SLOT_FUEL] = fuelSlot; this->slots[SLOT_OUTPUT] = outputSlot; } } // Reset our active cook durations this->activeCookDuration = 0; } bool Furnace::isBurningFuel() { // Check if this furnace is currently burning if(this->fuelBurningTime > 0) { return true; } else { return false; } } bool Furnace::isCooking() { // If we're burning fuel and have valid ingredients, we're cooking! if(this->isBurningFuel() && this->hasValidIngredient()) return true; else return false; } bool Furnace::hasValidIngredient() { // Check that we have a valid input type sSlot slot = slots[SLOT_INPUT]; if((slot.count != 0) && ( (slot.id == BLOCK_IRON_ORE) || (slot.id == BLOCK_GOLD_ORE) || (slot.id == BLOCK_SAND) || (slot.id == BLOCK_COBBLESTONE) || (slot.id == ITEM_PORK) || (slot.id == ITEM_CLAY_BALLS) || (slot.id == ITEM_RAW_FISH)) ){ return true; } else { return false; } } void Furnace::consumeFuel() { // Check that we have fuel if(slots[SLOT_FUEL].count == 0) return; // Increment the fuel burning time based on fuel type // http://www.minecraftwiki.net/wiki/Furnace#Fuel_efficiency sSlot fuelSlot = slots[SLOT_FUEL]; this->initialBurningTime = 0; if(fuelSlot.id == ITEM_COAL) { this->initialBurningTime += 80; } if(fuelSlot.id == BLOCK_WOOD) { this->initialBurningTime += 15; } if(fuelSlot.id == ITEM_STICK) { this->initialBurningTime += 5; } if(fuelSlot.id == BLOCK_LOG) { this->initialBurningTime += 15; } if(fuelSlot.id == BLOCK_WORKBENCH) { this->initialBurningTime += 15; } if(fuelSlot.id == BLOCK_CHEST) { this->initialBurningTime += 15; } if(fuelSlot.id == BLOCK_BOOKSHELF) { this->initialBurningTime += 15; } if(fuelSlot.id == BLOCK_JUKEBOX) { this->initialBurningTime += 15; } if(fuelSlot.id == BLOCK_FENCE) { this->initialBurningTime += 15; } if(fuelSlot.id == BLOCK_WOODEN_STAIRS) { this->initialBurningTime += 15; } if(fuelSlot.id == ITEM_LAVA_BUCKET) { this->initialBurningTime += 1000; } this->fuelBurningTime += this->initialBurningTime; // Now decrement the fuel & reset slots[SLOT_FUEL].count--; if(slots[SLOT_FUEL].count < 0) slots[SLOT_FUEL].count = 0; // Update our block type if need be this->updateBlock(); } sint16 Furnace::burnTime() { sint16 fuelBurningTime = (sint16)((200.0f / this->initialBurningTime) * this->fuelBurningTime); if(fuelBurningTime < 0) fuelBurningTime = 0; return fuelBurningTime; } sint16 Furnace::cookTime() { // Express cook time as a fraction of total cooking time sint16 tempCookTime = (sint16)((200.0f / this->cookingTime) * this->activeCookDuration); if(tempCookTime < 0) tempCookTime = 0; return tempCookTime; } NBT_Value* Furnace::getSlotEntity(sint8 slotNumber) { // Return null of we don't have anything in this slot if(slots[slotNumber].count == 0) return NULL; // Create a new slot NBT entity and add it's data NBT_Value* slot = new NBT_Value(NBT_Value::TAG_COMPOUND); slot->Insert("Count", new NBT_Value(slots[slotNumber].count)); slot->Insert("Damage", new NBT_Value(slots[slotNumber].damage)); slot->Insert("Slot", new NBT_Value(slotNumber)); slot->Insert("id", new NBT_Value(slots[slotNumber].id)); return slot; } void Furnace::sendToAllUsers() { // Create a new compound tag and set it's direct properties NBT_Value* newEntity = new NBT_Value(NBT_Value::TAG_COMPOUND); newEntity->Insert("BurnTime", new NBT_Value(this->burnTime())); newEntity->Insert("CookTime", new NBT_Value(this->cookTime())); newEntity->Insert("id", new NBT_Value("Furnace")); newEntity->Insert("x", new NBT_Value(this->x)); newEntity->Insert("y", new NBT_Value(this->y)); newEntity->Insert("z", new NBT_Value(this->z)); // Add our 3 child compounds for each slot that contains something NBT_Value *slotList = new NBT_Value(NBT_Value::TAG_LIST, NBT_Value::TAG_COMPOUND); for(int i = 0; i <= 2; i++) { NBT_Value *slot = getSlotEntity(i); if(slot != NULL) slotList->GetList()->push_back(slot); } newEntity->Insert("Items", slotList); // Write the entity data into a parent Compound std::vector<uint8> buffer; buffer.push_back(NBT_Value::TAG_COMPOUND); buffer.push_back(0); buffer.push_back(0); newEntity->Write(buffer); buffer.push_back(0); buffer.push_back(0); // Compress the data uint8 *compressedData = new uint8[ALLOCATE_NBTFILE]; z_stream zstream; zstream.zalloc = Z_NULL; zstream.zfree = Z_NULL; zstream.opaque = Z_NULL; zstream.next_out = compressedData; zstream.next_in = &buffer[0]; zstream.avail_in = buffer.size(); zstream.avail_out = ALLOCATE_NBTFILE; zstream.total_out = 0; zstream.total_in = 0; deflateInit2(&zstream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 15+MAX_WBITS, 8, Z_DEFAULT_STRATEGY); // Gzip the data if(int state=deflate(&zstream, Z_FULL_FLUSH)!=Z_OK) { std::cout << "Error in deflate: " << state << std::endl; } deflateEnd(&zstream); // Create a new packet to send back to client Packet pkt; pkt << (sint8)PACKET_COMPLEX_ENTITIES << this->x << (sint16)this->y << this->z << (sint16)zstream.total_out; pkt.addToWrite(compressedData, zstream.total_out); delete [] compressedData; // Tell all users about this guy User::sendAll((uint8*)pkt.getWrite(), pkt.getWriteLen()); #ifdef _DEBUG std::cout << "Furnace entity data: " << std::endl; newEntity->Print(); #endif // Update our map with this guy Map::get()->setComplexEntity(x, y, z, newEntity); } <|endoftext|>
<commit_before>/* * gameMgr.cpp * * Created on: Mar 11, 2017 * Author: sushil */ #include <gameMgr.h> #include <engine.h> #include <OgreMeshManager.h> GameMgr::GameMgr(Engine *engine): Mgr(engine), entitySceneNodes(){ floor = Ogre::Plane(Ogre::Vector3::UNIT_Y, 0); ceiling = new Ogre::MovablePlane("ceiling"); ceiling->d = 0; ceiling->normal = -1 * Ogre::Vector3::UNIT_Y; gameplayTime = 0; entityCount = 0; } GameMgr::~GameMgr(){ } void GameMgr::init(){ } void GameMgr::loadLevel(){ this->loadLevel("level001.txt"); } void GameMgr::stop(){ } void GameMgr::tick(float dt){ //engine->gfxMgr->ogreAnimationState->addTime(dt); if(engine->theState == STATE::GAMEPLAY) { gameplayTime += dt; std::cout << "Gameplay time: " << gameplayTime << std::endl; } } void GameMgr::createGround(int width, int heigth, std::string &material) { // Create Plane ////////////////////////////////////////////////////////////////////////////////////////// Ogre::MeshManager::getSingleton().createPlane( "ground", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, floor, width, heigth, 20, 20, true, 1, 5, 5, Ogre::Vector3::UNIT_Z); ////////////////////////////////////////////////////////////////////////////////////////////////////////// // Create Ground Entity ////////////////////////////////////////////////////////////////////////////////// Ogre::Entity* groundEntity = engine->gfxMgr->ogreSceneManager->createEntity("ground"); engine->gfxMgr->ogreSceneManager->getRootSceneNode()->createChildSceneNode()->attachObject(groundEntity); groundEntity->setCastShadows(false); groundEntity->setMaterialName(material); ////////////////////////////////////////////////////////////////////////////////////////////////////////// // Create Separated Water Ground //////////////////////////////////////////////////////////////////////// Ogre::Entity* groundEntity2 = engine->gfxMgr->ogreSceneManager->createEntity("ground"); engine->gfxMgr->ogreSceneManager->getRootSceneNode()->createChildSceneNode()->attachObject(groundEntity2); groundEntity2->setCastShadows(false); groundEntity2->setMaterialName("Examples/WaterStream"); ////////////////////////////////////////////////////////////////////////////////////////////////////////// } void GameMgr::createCeiling() { Ogre::MovablePlane plane(-1 * Ogre::Vector3::UNIT_Y, 50); // Create Ceiling /////////////////////////////////////////////////////////////////////////////////////// Ogre::MeshManager::getSingleton().createPlane( "ceiling", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, plane, 4000, 3400, 20, 20, true, 1, 5, 5, -Ogre::Vector3::UNIT_Z); ////////////////////////////////////////////////////////////////////////////////////////////////////////// // Create Ceiling Entity ////////////////////////////////////////////////////////////////////////////////// Ogre::Entity* ceiling = engine->gfxMgr->ogreSceneManager->createEntity("ceiling"); engine->gfxMgr->ogreSceneManager->getRootSceneNode()->createChildSceneNode()->attachObject(ceiling); ceiling->setCastShadows(false); ceiling->setMaterialName("Examples/Rockwall"); } void GameMgr::createSky(){ engine->gfxMgr->ogreSceneManager->setSkyBox(true, "Examples/SpaceSkyBox"); } void GameMgr::loadLevel(std::string levelFilename) { // Load the environment, objects, and characters this->loadEnvironment(levelFilename); this->setupEnvironment(); this->setupSounds(); this->loadObjects(); this->loadCharacters(); } void GameMgr::loadEnvironment(std::string levelFilename) { // Variables std::ifstream fin; int x, z; float x_offset, y_offset, z_offset; float scale, orientation; std::string groundMaterial, objectMesh, characterMesh; std::string buffer, buff; char objectChar; std::map<std::string, readFromFile*> objects; // Open File fin.open(levelFilename); // Check for bad file if(!fin.is_open()) { std::cerr << "ERROR, FILE CANNOT BE OPENED" << std::endl; return; } // First block is world dimensions and material name fin >> x >> z; fin >> groundMaterial; // TESTING FILE READ //////////////////////////////////////////// std::cerr << "Ground Dimensions: " << x << " x " << z << std::endl; std::cerr << "Ground Material: " << groundMaterial << std::endl; ///////////////////////////////////////////////////////////////// // Create floor mesh with read in dimensions createGround( x*100, z*100, groundMaterial); // Create Ceiling createCeiling(); //DEBUG THIS LATER // Setup the grid this->grid = new Grid( engine->gfxMgr->ogreSceneManager, x, z, engine); // Second block reads in location of you and enemies // Check for Objects line fin >> buffer; if( buffer != "Objects" ) { std::cerr << "FILE NOT FORMATTED CORRECTLY" << std::endl; } // Read Objects and positions readFromFile* readEnt = new readFromFile(); fin >> buff; // read single char fin >> readEnt->mesh; fin >> x_offset >> y_offset >> z_offset; fin >> readEnt->entityOrientation >> readEnt->entityScale; // Set entity info readEnt->positionOffset = Ogre::Vector3(x_offset, y_offset, z_offset); readEnt->entity = false; objects[buff] = readEnt; readEnt = new readFromFile(); // read in next if any // Testing Second Box Readin /////////////////////////////////// std::cerr << "Objects" << std::endl; std::cerr << objectChar << " " << objectMesh << std::endl; std::cerr << "Located at: " << x_offset << ", " << y_offset << ", " << z_offset << std::endl; std::cerr << "Scaled at: " << orientation << " " << scale << std::endl; /////////////////////////////////////////////////////////////// // Check for Characters line ///////////////////////////////////////////////////////////////// fin >> buffer; if( buffer != "Characters" ) { std::cerr << "FILE NOT FORMATTED CORRECTLY" << std::endl; } // Read in Characters fin >> buff; // read next char fin >> readEnt->mesh; fin >> x_offset >> y_offset >> z_offset; fin >> readEnt->entityOrientation >> readEnt->entityScale; // set entity info readEnt->positionOffset = Ogre::Vector3(x_offset, y_offset, z_offset); readEnt->entity = true; objects[buff] = readEnt; // read next if any readEnt = new readFromFile(); // Testing Third Box Readin /////////////////////////////////// std::cerr << "Characters" << std::endl; std::cerr << objectChar << " " << characterMesh << std::endl; std::cerr << "Located at: " << x_offset << ", " << y_offset << ", " << z_offset << std::endl; std::cerr << "Scaled at: " << orientation << " " << scale << std::endl; /////////////////////////////////////////////////////////////// // Read the World Placement ////////////////////////////////////////////////////////////////// char c; // Start to see if world is in file fin >> buffer; if( buffer != "World" ) { std::cerr << "FILE NOT FORMATTED CORRECTLY" << std::endl; } // Pre Conditions for World setup Ogre::Vector3 wallPosition; wallPosition = Ogre::Vector3(-1850, 50, 1200); Ogre::Vector3 archPosition; archPosition = Ogre::Vector3(0, 0, 0); Ogre::Vector3 enemyPosition; enemyPosition = Ogre::Vector3(-1200, 0, 1000); /* Ogre::ManualObject test; test.convertToMesh(objectMesh, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); */ // Loop through map dimensions for( int row = 0; row < ROW_SIZE - 3; row++ ) { for( int col = 0; col < COL_SIZE - 3; col++ ) { fin >> c; //buff = x + '\0'; // convert to string //readEnt = objects[buff]; // Check for walls (Not player or enemy nodes) if( c == 'W' ) { //std::cerr << "Creating Wall" << std::endl; //engine->entityMgr->CreateEntity(EntityType::WALL, wallPosition, 0); //std::cerr << "Wall Created" << std::endl; //engine->entityMgr-> // Create a Wall /* Ogre::Entity* wallEntity = engine->gfxMgr->ogreSceneManager->createEntity(getNewName(), objectMesh); wallEntity->setMaterialName("Examples/RustySteel"); engine->gfxMgr->wallNode = engine->gfxMgr->ogreSceneManager->getRootSceneNode()->createChildSceneNode(wallPosition); engine->gfxMgr->wallNode->attachObject(wallEntity); */ ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Jake edits // // Grab the "objects" config stuff from the object map that Hadi built readFromFile * objectEntData = objects["D"]; GridParams * gridParam = this->grid->getGrid(row, col); if(gridParam) gridParam->notWalkable(); Ogre::Vector3 position(this->grid->getPosition(row, col).x, 10.0f, this->grid->getPosition(row, col).z); engine->entityMgr->CreateEntity(EntityType::WALL, position, 0); // Create ogre entity Ogre::Entity * wallEntity = engine->gfxMgr->ogreSceneManager->createEntity(getNewName(), objectEntData->mesh); wallEntity->setMaterialName("Examples/RustySteel"); Ogre::SceneNode * newWallNode = engine->gfxMgr->ogreSceneManager->getRootSceneNode()->createChildSceneNode(position); newWallNode->attachObject(wallEntity); entitySceneNodes.push_back(newWallNode); objectEntData = NULL; // // End Jake edits ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Set Scale and position //engine->gfxMgr->ogreSceneManager->getRootSceneNode()->setScale(0.1f, 1.0f, 0.1f); //engine->gfxMgr->ogreSceneManager->getRootSceneNode()->setPosition(wallPosition); // Placement in world SHALL NOT PASS // this->grid->getGrid(row, col)->notWalkable(); // engine->gfxMgr->wallNode->setPosition(this->grid->getPosition(row, col).x, 10.0f, this->grid->getPosition(row, col).z); /* // Check wall position to prevent going outside of map if( wallPosition.x < 1800 || wallPosition.x > -1800 || wallPosition.z > -2500 || wallPosition.z < 2500 ) { // reset position //wallPosition.x = 0; //wallPosition.z = 0; // Increment Positions to prevent overlap from reset wallPosition.x += 25; //wallPosition.z += 50; } */ //wallPosition.z += 50; // Set blocked area } // Check for Arch else if( c == 'A' ) { // std::cerr << "Spawning Arch" << std::endl; // engine->entityMgr->CreateEntity(EntityType::ARCH, archPosition, 0); // archPosition.x += 50; } else if( c == 'C' ) { // Spawn Enemy // std::cerr << "Spawning Enemy" << std::endl; // // loadCharacters(); /* // Create Test Enemy Ogre::Entity* enemyEntity = engine->gfxMgr->ogreSceneManager->createEntity(getNewName(), characterMesh); // enemyEntity->setMaterialName("Examples/RustySteel"); engine->gfxMgr->ogreSceneManager->getRootSceneNode()->createChildSceneNode(enemyPosition)->attachObject(enemyEntity); // Set Scale and position engine->gfxMgr->ogreSceneManager->getRootSceneNode()->setScale(0.1f, 0.02f, 0.1f); //engine->gfxMgr->ogreSceneManager->getRootSceneNode()->setPosition(position); enemyPosition.x += 10; // Increment Positions to prevent overlap //enemyPosition.z += 50; */ } } } // Create the Entities // Create Skybox for the hell of it createSky(); // delete readEnt; } void GameMgr::setupEnvironment() { //We know graphicsMgr is ready and initialized engine->gfxMgr->ogreSceneManager->setAmbientLight(Ogre::ColourValue(0.5, 0.5, 0.5)); Ogre::Light* light = engine->gfxMgr->ogreSceneManager->createLight("MainLight"); light->setType(Ogre::Light::LT_POINT); light->setPosition(100.0, 800.0, 100.0); light->setDiffuseColour(Ogre::ColourValue::White); light->setSpecularColour(Ogre::ColourValue::White); } /* * * Basic Setup for pre-alpha testing * Will be more complex in later phases * */ void GameMgr::setupSounds() { // Load Song from file engine->soundMgr->load_song("Layer 1", "/home/hrumjahn/git/Cries/resources/ss.wav"); //load_sound(std::string soundName, std::string filePath); //play_sound(std::string soundName); engine->soundMgr->play_song("Layer 1", true); // Play song (.wav) } void GameMgr::loadObjects() { // Create Entity Ogre::Entity *splash = engine->gfxMgr->ogreSceneManager->createEntity("Splash.mesh"); // Create scene node for this entity engine->gfxMgr->splashNode = engine->gfxMgr->ogreSceneManager->getRootSceneNode()->createChildSceneNode(); engine->gfxMgr->splashNode->attachObject(splash); splash->setMaterialName("Material"); engine->gfxMgr->splashNode->setScale(10.f, 10.0f, 10.0f); engine->gfxMgr->splashNode->setPosition( 0.0f, 400, -3500); engine->gfxMgr->splashNode->roll(Ogre::Degree(-360)); engine->gfxMgr->splashNode->pitch(Ogre::Degree(90)); } void GameMgr::loadCharacters() { //Creating the entities engine->entityMgr->CreateEntity(EntityType::HEARNO, Ogre::Vector3(0, 10, -1000), 0); engine->entityMgr->CreateEntity(EntityType::SEENO, Ogre::Vector3(500, 0, -500), Ogre::Math::HALF_PI / 2); engine->entityMgr->CreateEntity(EntityType::SPEAKNO, Ogre::Vector3(-500, 20, -500), Ogre::Math::HALF_PI / -2); /* // Set Animation States //engine->gfxMgr->ogreAnimationState = splash->getAnimationState("Test"); engine->gfxMgr->ogreAnimationState->setWeight(1); engine->gfxMgr->ogreAnimationState->setLoop(true); engine->gfxMgr->ogreAnimationState->setEnabled(true); */ } std::string GameMgr:: getNewName() { return std::string("object_" + std::to_string(entityCount++)); } <commit_msg>Entities spawn in correct locations on grid text<commit_after>/* * gameMgr.cpp * * Created on: Mar 11, 2017 * Author: sushil */ #include <gameMgr.h> #include <engine.h> #include <OgreMeshManager.h> GameMgr::GameMgr(Engine *engine): Mgr(engine), entitySceneNodes(){ floor = Ogre::Plane(Ogre::Vector3::UNIT_Y, 0); ceiling = new Ogre::MovablePlane("ceiling"); ceiling->d = 0; ceiling->normal = -1 * Ogre::Vector3::UNIT_Y; gameplayTime = 0; entityCount = 0; } GameMgr::~GameMgr(){ } void GameMgr::init(){ } void GameMgr::loadLevel(){ this->loadLevel("level001.txt"); } void GameMgr::stop(){ } void GameMgr::tick(float dt){ //engine->gfxMgr->ogreAnimationState->addTime(dt); if(engine->theState == STATE::GAMEPLAY) { gameplayTime += dt; std::cout << "Gameplay time: " << gameplayTime << std::endl; } } void GameMgr::createGround(int width, int heigth, std::string &material) { // Create Plane ////////////////////////////////////////////////////////////////////////////////////////// Ogre::MeshManager::getSingleton().createPlane( "ground", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, floor, width, heigth, 20, 20, true, 1, 5, 5, Ogre::Vector3::UNIT_Z); ////////////////////////////////////////////////////////////////////////////////////////////////////////// // Create Ground Entity ////////////////////////////////////////////////////////////////////////////////// Ogre::Entity* groundEntity = engine->gfxMgr->ogreSceneManager->createEntity("ground"); engine->gfxMgr->ogreSceneManager->getRootSceneNode()->createChildSceneNode()->attachObject(groundEntity); groundEntity->setCastShadows(false); groundEntity->setMaterialName(material); ////////////////////////////////////////////////////////////////////////////////////////////////////////// // Create Separated Water Ground //////////////////////////////////////////////////////////////////////// Ogre::Entity* groundEntity2 = engine->gfxMgr->ogreSceneManager->createEntity("ground"); engine->gfxMgr->ogreSceneManager->getRootSceneNode()->createChildSceneNode()->attachObject(groundEntity2); groundEntity2->setCastShadows(false); groundEntity2->setMaterialName("Examples/WaterStream"); ////////////////////////////////////////////////////////////////////////////////////////////////////////// } void GameMgr::createCeiling() { Ogre::MovablePlane plane(-1 * Ogre::Vector3::UNIT_Y, 50); // Create Ceiling /////////////////////////////////////////////////////////////////////////////////////// Ogre::MeshManager::getSingleton().createPlane( "ceiling", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, plane, 4000, 3400, 20, 20, true, 1, 5, 5, -Ogre::Vector3::UNIT_Z); ////////////////////////////////////////////////////////////////////////////////////////////////////////// // Create Ceiling Entity ////////////////////////////////////////////////////////////////////////////////// Ogre::Entity* ceiling = engine->gfxMgr->ogreSceneManager->createEntity("ceiling"); engine->gfxMgr->ogreSceneManager->getRootSceneNode()->createChildSceneNode()->attachObject(ceiling); ceiling->setCastShadows(false); ceiling->setMaterialName("Examples/Rockwall"); } void GameMgr::createSky(){ engine->gfxMgr->ogreSceneManager->setSkyBox(true, "Examples/SpaceSkyBox"); } void GameMgr::loadLevel(std::string levelFilename) { // Load the environment, objects, and characters this->loadEnvironment(levelFilename); this->setupEnvironment(); this->setupSounds(); this->loadObjects(); this->loadCharacters(); } void GameMgr::loadEnvironment(std::string levelFilename) { // Variables std::ifstream fin; int x, z; float x_offset, y_offset, z_offset; float scale, orientation; std::string groundMaterial, objectMesh, characterMesh; std::string buffer, buff; char objectChar; std::map<std::string, readFromFile*> objects; // Open File fin.open(levelFilename); // Check for bad file if(!fin.is_open()) { std::cerr << "ERROR, FILE CANNOT BE OPENED" << std::endl; return; } // First block is world dimensions and material name fin >> x >> z; fin >> groundMaterial; // TESTING FILE READ //////////////////////////////////////////// std::cerr << "Ground Dimensions: " << x << " x " << z << std::endl; std::cerr << "Ground Material: " << groundMaterial << std::endl; ///////////////////////////////////////////////////////////////// // Create floor mesh with read in dimensions createGround( x*100, z*100, groundMaterial); // Create Ceiling createCeiling(); //DEBUG THIS LATER // Setup the grid this->grid = new Grid( engine->gfxMgr->ogreSceneManager, x, z, engine); // Second block reads in location of you and enemies // Check for Objects line fin >> buffer; if( buffer != "Objects" ) { std::cerr << "FILE NOT FORMATTED CORRECTLY" << std::endl; } // Read Objects and positions readFromFile* readEnt = new readFromFile(); fin >> buff; // read single char fin >> readEnt->mesh; fin >> x_offset >> y_offset >> z_offset; fin >> readEnt->entityOrientation >> readEnt->entityScale; // Set entity info readEnt->positionOffset = Ogre::Vector3(x_offset, y_offset, z_offset); readEnt->entity = false; objects[buff] = readEnt; readEnt = new readFromFile(); // read in next if any // Testing Second Box Readin /////////////////////////////////// std::cerr << "Objects" << std::endl; std::cerr << objectChar << " " << objectMesh << std::endl; std::cerr << "Located at: " << x_offset << ", " << y_offset << ", " << z_offset << std::endl; std::cerr << "Scaled at: " << orientation << " " << scale << std::endl; /////////////////////////////////////////////////////////////// // Check for Characters line ///////////////////////////////////////////////////////////////// fin >> buffer; if( buffer != "Characters" ) { std::cerr << "FILE NOT FORMATTED CORRECTLY" << std::endl; } // Read in Characters fin >> buff; // read next char fin >> readEnt->mesh; fin >> x_offset >> y_offset >> z_offset; fin >> readEnt->entityOrientation >> readEnt->entityScale; // set entity info readEnt->positionOffset = Ogre::Vector3(x_offset, y_offset, z_offset); readEnt->entity = true; objects[buff] = readEnt; // read next if any readEnt = new readFromFile(); // Testing Third Box Readin /////////////////////////////////// std::cerr << "Characters" << std::endl; std::cerr << objectChar << " " << characterMesh << std::endl; std::cerr << "Located at: " << x_offset << ", " << y_offset << ", " << z_offset << std::endl; std::cerr << "Scaled at: " << orientation << " " << scale << std::endl; /////////////////////////////////////////////////////////////// // Read the World Placement ////////////////////////////////////////////////////////////////// char c; // Start to see if world is in file fin >> buffer; if( buffer != "World" ) { std::cerr << "FILE NOT FORMATTED CORRECTLY" << std::endl; } // Pre Conditions for World setup Ogre::Vector3 wallPosition; wallPosition = Ogre::Vector3(-1850, 50, 1200); Ogre::Vector3 archPosition; archPosition = Ogre::Vector3(0, 0, 0); Ogre::Vector3 enemyPosition; enemyPosition = Ogre::Vector3(-1200, 0, 1000); /* Ogre::ManualObject test; test.convertToMesh(objectMesh, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); */ // Loop through map dimensions for( int row = 0; row < ROW_SIZE - 3; row++ ) { for( int col = 0; col < COL_SIZE - 3; col++ ) { fin >> c; Ogre::Vector3 gridPositionInWorld = this->grid->getPosition(row, col); // Check for walls (Not player or enemy nodes) if( c == 'W' ) { // Grab the "objects" config stuff from the object map that Hadi built readFromFile * objectEntData = objects["D"]; // Currently not used lmao GridParams * gridParam = this->grid->getGrid(row, col); if(gridParam) gridParam->notWalkable(); engine->entityMgr->CreateEntity(EntityType::WALL, gridPositionInWorld, 0); objectEntData = NULL; gridParam = NULL; } // Check for Arch else if( c == 'A' ) { // std::cerr << "Spawning Arch" << std::endl; // engine->entityMgr->CreateEntity(EntityType::ARCH, archPosition, 0); // archPosition.x += 50; } // See no evil else if( c == 'C' ) { engine->entityMgr->CreateEntity(EntityType::SEENO, gridPositionInWorld, 0); } else if(c == 'S') { engine->entityMgr->CreateEntity(EntityType::SPEAKNO, gridPositionInWorld, 0); } else if(c == 'H') { engine->entityMgr->CreateEntity(EntityType::HEARNO, gridPositionInWorld, 0); } } } // Create the Entities // Create Skybox for the hell of it createSky(); // delete readEnt; } void GameMgr::setupEnvironment() { //We know graphicsMgr is ready and initialized engine->gfxMgr->ogreSceneManager->setAmbientLight(Ogre::ColourValue(0.5, 0.5, 0.5)); Ogre::Light* light = engine->gfxMgr->ogreSceneManager->createLight("MainLight"); light->setType(Ogre::Light::LT_POINT); light->setPosition(100.0, 800.0, 100.0); light->setDiffuseColour(Ogre::ColourValue::White); light->setSpecularColour(Ogre::ColourValue::White); } /* * * Basic Setup for pre-alpha testing * Will be more complex in later phases * */ void GameMgr::setupSounds() { // Load Song from file engine->soundMgr->load_song("Layer 1", "/home/hrumjahn/git/Cries/resources/ss.wav"); //load_sound(std::string soundName, std::string filePath); //play_sound(std::string soundName); engine->soundMgr->play_song("Layer 1", true); // Play song (.wav) } void GameMgr::loadObjects() { // Create Entity Ogre::Entity *splash = engine->gfxMgr->ogreSceneManager->createEntity("Splash.mesh"); // Create scene node for this entity engine->gfxMgr->splashNode = engine->gfxMgr->ogreSceneManager->getRootSceneNode()->createChildSceneNode(); engine->gfxMgr->splashNode->attachObject(splash); splash->setMaterialName("Material"); engine->gfxMgr->splashNode->setScale(10.f, 10.0f, 10.0f); engine->gfxMgr->splashNode->setPosition( 0.0f, 400, -3500); engine->gfxMgr->splashNode->roll(Ogre::Degree(-360)); engine->gfxMgr->splashNode->pitch(Ogre::Degree(90)); } void GameMgr::loadCharacters() { //Creating the entities // engine->entityMgr->CreateEntity(EntityType::HEARNO, Ogre::Vector3(0, 10, -1000), 0); // engine->entityMgr->CreateEntity(EntityType::SEENO, Ogre::Vector3(500, 0, -500), Ogre::Math::HALF_PI / 2); // engine->entityMgr->CreateEntity(EntityType::SPEAKNO, Ogre::Vector3(-500, 20, -500), Ogre::Math::HALF_PI / -2); /* // Set Animation States //engine->gfxMgr->ogreAnimationState = splash->getAnimationState("Test"); engine->gfxMgr->ogreAnimationState->setWeight(1); engine->gfxMgr->ogreAnimationState->setLoop(true); engine->gfxMgr->ogreAnimationState->setEnabled(true); */ } std::string GameMgr:: getNewName() { return std::string("object_" + std::to_string(entityCount++)); } <|endoftext|>
<commit_before>/* * Copyright (c) 2019, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * 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 "mbed.h" #include "TLSSocket.h" #include "greentea-client/test_env.h" #include "unity/unity.h" #include "utest.h" #include "tls_tests.h" using namespace utest::v1; #if defined(MBEDTLS_SSL_CLI_C) void TLSSOCKET_HANDSHAKE_INVALID() { TLSSocket sock; TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock.open(NetworkInterface::get_default_instance())); TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock.set_root_ca_cert(tls_global::cert)); TEST_ASSERT_EQUAL(NSAPI_ERROR_NO_CONNECTION, sock.connect("google.com", MBED_CONF_APP_ECHO_SERVER_DISCARD_PORT_TLS)); TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock.close()); } #endif // defined(MBEDTLS_SSL_CLI_C) <commit_msg>Greentea tests: set correct port to test against google.com<commit_after>/* * Copyright (c) 2019, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * 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 "mbed.h" #include "TLSSocket.h" #include "greentea-client/test_env.h" #include "unity/unity.h" #include "utest.h" #include "tls_tests.h" using namespace utest::v1; #if defined(MBEDTLS_SSL_CLI_C) void TLSSOCKET_HANDSHAKE_INVALID() { TLSSocket sock; TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock.open(NetworkInterface::get_default_instance())); TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock.set_root_ca_cert(tls_global::cert)); TEST_ASSERT_EQUAL(NSAPI_ERROR_AUTH_FAILURE, sock.connect("google.com", 443)); // 443 is https port. TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock.close()); } #endif // defined(MBEDTLS_SSL_CLI_C) <|endoftext|>
<commit_before>/* * Copyright (c) 2003-2009 Rony Shapiro <ronys@users.sourceforge.net>. * All rights reserved. Use of the code is allowed under the * Artistic License 2.0 terms, as specified in the LICENSE file * distributed with this code, or available from * http://www.opensource.org/licenses/artistic-license-2.0.php */ // OptionsShortcuts.cpp : implementation file // #include "stdafx.h" #if defined(POCKET_PC) #include "pocketpc/resource.h" #else #include "resource.h" #include "resource2.h" // Menu resources #include "resource3.h" // String resources #endif #include "OptionsShortcuts.h" // COptionsShortcuts dialog IMPLEMENT_DYNAMIC(COptionsShortcuts, CPropertyPage) COptionsShortcuts::COptionsShortcuts(): CPWPropertyPage(COptionsShortcuts::IDD), m_bChanged(false) { //{{AFX_DATA_INIT(COptionsShortcuts) //}}AFX_DATA_INIT } COptionsShortcuts::~COptionsShortcuts() { } void COptionsShortcuts::DoDataExchange(CDataExchange* pDX) { CPropertyPage::DoDataExchange(pDX); DDX_Control(pDX, IDC_SHORTCUTLIST, m_ShortcutLC); DDX_Control(pDX, IDC_STATIC_SHCTWARNING, m_stc_warning); } BEGIN_MESSAGE_MAP(COptionsShortcuts, CPropertyPage) ON_BN_CLICKED(IDC_RESETALLSHORTCUTS, OnBnClickedResetAll) ON_WM_MEASUREITEM() END_MESSAGE_MAP() void COptionsShortcuts::InitialSetup(const MapMenuShortcuts MapMenuShortcuts, const MapKeyNameID MapKeyNameID, const std::vector<UINT> ExcludedMenuItems, const std::vector<st_MenuShortcut> ReservedShortcuts) { m_MapMenuShortcuts = MapMenuShortcuts; m_MapKeyNameID = MapKeyNameID; m_ExcludedMenuItems = ExcludedMenuItems; m_ReservedShortcuts = ReservedShortcuts; } BOOL COptionsShortcuts::OnInitDialog() { CPropertyPage::OnInitDialog(); m_ShortcutLC.Init(this); DWORD dwExtendedStyle = m_ShortcutLC.GetExtendedStyle() | LVS_EX_GRIDLINES; m_ShortcutLC.SetExtendedStyle(dwExtendedStyle); CString cs_colname; cs_colname.LoadString(IDS_COL_MENUITEM); m_ShortcutLC.InsertColumn(0, cs_colname); cs_colname.LoadString(IDS_COL_SHORTCUT); m_ShortcutLC.InsertColumn(1, cs_colname); MapMenuShortcutsIter iter, iter_parent; MapKeyNameIDConstIter citer; CString str; int iItem(-1); for (iter = m_MapMenuShortcuts.begin(); iter != m_MapMenuShortcuts.end(); iter++) { // We don't allow change of certain menu items // Just don't put in the list that the user sees. if (iter->second.uiParentID == 0) continue; if (std::find(m_ExcludedMenuItems.begin(), m_ExcludedMenuItems.end(), iter->first) != m_ExcludedMenuItems.end()) continue; if (iter->second.cVirtKey != 0) { st_KeyIDExt st_KIDEx; st_KIDEx.id = iter->second.cVirtKey; st_KIDEx.bExtended = (iter->second.cModifier & HOTKEYF_EXT) == HOTKEYF_EXT; citer = m_MapKeyNameID.find(st_KIDEx); str = CMenuShortcut::FormatShortcut(iter, citer); } else { str = _T(""); } // Remove the ampersand from the menu item the user sees here iter_parent = m_MapMenuShortcuts.find(iter->second.uiParentID); CString sMenuItemtext = CString(iter_parent->second.name) + CString(_T(" \xbb ")) + CString(iter->second.name); sMenuItemtext.Remove(TCHAR('&')); iItem = m_ShortcutLC.InsertItem(++iItem, sMenuItemtext); m_ShortcutLC.SetItemText(iItem, 1, str); DWORD dwData = MAKELONG(iter->first, iter->second.iMenuPosition); m_ShortcutLC.SetItemData(iItem, dwData); } // Now sort via Menu item position m_ShortcutLC.SortItems(CompareFunc, NULL); m_ShortcutLC.SetColumnWidth(0, LVSCW_AUTOSIZE_USEHEADER); m_ShortcutLC.SetColumnWidth(1, LVSCW_AUTOSIZE_USEHEADER); m_ShortcutLC.ModifyStyle(LVS_OWNERDRAWFIXED, 0, 0); CHeaderCtrl* pHCtrl; pHCtrl = m_ShortcutLC.GetHeaderCtrl(); ASSERT(pHCtrl != NULL); pHCtrl->SetDlgCtrlID(IDC_SHORTCUTLC_HEADER); m_SHCTHeader.SubclassWindow(pHCtrl->GetSafeHwnd()); m_SHCTHeader.SetStopChangeFlag(true); m_stc_warning.SetColour(RGB(255, 0, 0)); m_stc_warning.ShowWindow(SW_HIDE); return TRUE; } void COptionsShortcuts::OnMeasureItem(int nIDCtl, LPMEASUREITEMSTRUCT lpMIS) { // If this is our list control then increase height if (nIDCtl == IDC_SHORTCUTLIST) { lpMIS->itemHeight += 10; } } void COptionsShortcuts::OnBnClickedResetAll() { MapMenuShortcutsIter iter; MapKeyNameIDConstIter citer; CString str; UINT id; st_KeyIDExt st_KIDEx; for (int i = 0; i < m_ShortcutLC.GetItemCount(); i++) { id = (UINT)LOWORD(m_ShortcutLC.GetItemData(i)); iter = m_MapMenuShortcuts.find(id); st_KIDEx.id = iter->second.cdefVirtKey; st_KIDEx.bExtended = (iter->second.cModifier & HOTKEYF_EXT) == HOTKEYF_EXT; citer = m_MapKeyNameID.find(st_KIDEx); iter->second.cVirtKey = iter->second.cdefVirtKey; iter->second.cModifier = iter->second.cdefModifier; if (citer != m_MapKeyNameID.end() || iter->second.cdefVirtKey != 0) { str = CMenuShortcut::FormatShortcut(iter, citer); } else { str = _T(""); } m_ShortcutLC.SetItemText(i, 1, str); } ClearWarning(); m_ShortcutLC.RedrawItems(0, m_ShortcutLC.GetItemCount()); m_ShortcutLC.UpdateWindow(); m_bChanged = true; } // Functor for find_if to see if shortcut is reserved struct reserved { reserved(st_MenuShortcut& st_mst) : m_st_mst(st_mst) {} bool operator()(st_MenuShortcut const& rdata) const { return (m_st_mst.cVirtKey == rdata.cVirtKey && m_st_mst.cModifier == rdata.cModifier); } st_MenuShortcut m_st_mst; }; // Functor for find_if to see if shortcut is already in use struct already_inuse { already_inuse(st_MenuShortcut& st_mst) : m_st_mst(st_mst) {} bool operator()(MapMenuShortcutsPair const & p) const { return (p.second.cVirtKey == m_st_mst.cVirtKey && p.second.cModifier == m_st_mst.cModifier); } st_MenuShortcut m_st_mst; }; // Tortuous route to get here! // m_HotKey looses focus and calls parent (CListCtrl) that calls here void COptionsShortcuts::OnHotKeyKillFocus(const int item, const UINT id, const WORD wVirtualKeyCode, const WORD wModifiers) { CString str(_T("")), mst_str(_T("")); CString cs_warning; MapMenuShortcutsIter iter, inuse_iter; MapKeyNameIDConstIter citer; st_MenuShortcut st_mst; st_KeyIDExt st_KIDEx; st_KIDEx.id = (unsigned char)wVirtualKeyCode; st_KIDEx.bExtended = (wModifiers & HOTKEYF_EXT) == HOTKEYF_EXT; citer = m_MapKeyNameID.find(st_KIDEx); // Stop compiler complaining - put this here even if not needed already_inuse inuse(st_mst); if (citer == m_MapKeyNameID.end()) { // Invalid shortcut cs_warning.LoadString(IDS_SHCT_WARNING1); goto set_warning; } st_mst.cVirtKey = (unsigned char)wVirtualKeyCode; st_mst.cModifier = (unsigned char)wModifiers; if (st_mst.cVirtKey != 0) { mst_str = CMenuShortcut::FormatShortcut(st_mst, citer); } if (std::find_if(m_ReservedShortcuts.begin(), m_ReservedShortcuts.end(), reserved(st_mst)) != m_ReservedShortcuts.end()) { // Reserved shortcut ignored cs_warning.Format(IDS_SHCT_WARNING2, mst_str); goto set_warning; } // Check not already in use (ignore if deleting current shortcut) if (st_mst.cVirtKey != (unsigned char)0) { inuse_iter = std::find_if(m_MapMenuShortcuts.begin(), m_MapMenuShortcuts.end(), inuse); if (inuse_iter != m_MapMenuShortcuts.end() && inuse_iter->first != iter->first) { // Shortcut in use cs_warning.Format(IDS_SHCT_WARNING3, mst_str, inuse_iter->second.name); goto set_warning; } } iter = m_MapMenuShortcuts.find(id); if (iter->second.cVirtKey != 0) { str = CMenuShortcut::FormatShortcut(iter, citer); } // Not reserved and not already in use - implement iter->second.cVirtKey = st_mst.cVirtKey; iter->second.cModifier = st_mst.cModifier; m_ShortcutLC.SetItemText(item, 1, str); m_ShortcutLC.RedrawItems(item, item); m_ShortcutLC.UpdateWindow(); m_bChanged = true; return; set_warning: m_stc_warning.SetWindowText(cs_warning); m_stc_warning.ShowWindow(SW_SHOW); } BOOL COptionsShortcuts::PreTranslateMessage(MSG* pMsg) { // If HotKey active, allow Enter key to set instead of close // Property Page (OK button) if (pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_RETURN && m_ShortcutLC.IsHotKeyActive()) { m_ShortcutLC.SaveHotKey(); return TRUE; } return CPWPropertyPage::PreTranslateMessage(pMsg); } int CALLBACK COptionsShortcuts::CompareFunc(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort) { UNREFERENCED_PARAMETER(lParamSort); return (int)(HIWORD(lParam1) - HIWORD(lParam2)); } <commit_msg>Fix error introduced in last commit<commit_after>/* * Copyright (c) 2003-2009 Rony Shapiro <ronys@users.sourceforge.net>. * All rights reserved. Use of the code is allowed under the * Artistic License 2.0 terms, as specified in the LICENSE file * distributed with this code, or available from * http://www.opensource.org/licenses/artistic-license-2.0.php */ // OptionsShortcuts.cpp : implementation file // #include "stdafx.h" #if defined(POCKET_PC) #include "pocketpc/resource.h" #else #include "resource.h" #include "resource2.h" // Menu resources #include "resource3.h" // String resources #endif #include "OptionsShortcuts.h" // COptionsShortcuts dialog IMPLEMENT_DYNAMIC(COptionsShortcuts, CPropertyPage) COptionsShortcuts::COptionsShortcuts(): CPWPropertyPage(COptionsShortcuts::IDD), m_bChanged(false) { //{{AFX_DATA_INIT(COptionsShortcuts) //}}AFX_DATA_INIT } COptionsShortcuts::~COptionsShortcuts() { } void COptionsShortcuts::DoDataExchange(CDataExchange* pDX) { CPropertyPage::DoDataExchange(pDX); DDX_Control(pDX, IDC_SHORTCUTLIST, m_ShortcutLC); DDX_Control(pDX, IDC_STATIC_SHCTWARNING, m_stc_warning); } BEGIN_MESSAGE_MAP(COptionsShortcuts, CPropertyPage) ON_BN_CLICKED(IDC_RESETALLSHORTCUTS, OnBnClickedResetAll) ON_WM_MEASUREITEM() END_MESSAGE_MAP() void COptionsShortcuts::InitialSetup(const MapMenuShortcuts MapMenuShortcuts, const MapKeyNameID MapKeyNameID, const std::vector<UINT> ExcludedMenuItems, const std::vector<st_MenuShortcut> ReservedShortcuts) { m_MapMenuShortcuts = MapMenuShortcuts; m_MapKeyNameID = MapKeyNameID; m_ExcludedMenuItems = ExcludedMenuItems; m_ReservedShortcuts = ReservedShortcuts; } BOOL COptionsShortcuts::OnInitDialog() { CPropertyPage::OnInitDialog(); m_ShortcutLC.Init(this); DWORD dwExtendedStyle = m_ShortcutLC.GetExtendedStyle() | LVS_EX_GRIDLINES; m_ShortcutLC.SetExtendedStyle(dwExtendedStyle); CString cs_colname; cs_colname.LoadString(IDS_COL_MENUITEM); m_ShortcutLC.InsertColumn(0, cs_colname); cs_colname.LoadString(IDS_COL_SHORTCUT); m_ShortcutLC.InsertColumn(1, cs_colname); MapMenuShortcutsIter iter, iter_parent; MapKeyNameIDConstIter citer; CString str; int iItem(-1); for (iter = m_MapMenuShortcuts.begin(); iter != m_MapMenuShortcuts.end(); iter++) { // We don't allow change of certain menu items // Just don't put in the list that the user sees. if (iter->second.uiParentID == 0) continue; if (std::find(m_ExcludedMenuItems.begin(), m_ExcludedMenuItems.end(), iter->first) != m_ExcludedMenuItems.end()) continue; if (iter->second.cVirtKey != 0) { st_KeyIDExt st_KIDEx; st_KIDEx.id = iter->second.cVirtKey; st_KIDEx.bExtended = (iter->second.cModifier & HOTKEYF_EXT) == HOTKEYF_EXT; citer = m_MapKeyNameID.find(st_KIDEx); str = CMenuShortcut::FormatShortcut(iter, citer); } else { str = _T(""); } // Remove the ampersand from the menu item the user sees here iter_parent = m_MapMenuShortcuts.find(iter->second.uiParentID); CString sMenuItemtext = CString(iter_parent->second.name) + CString(_T(" \xbb ")) + CString(iter->second.name); sMenuItemtext.Remove(TCHAR('&')); iItem = m_ShortcutLC.InsertItem(++iItem, sMenuItemtext); m_ShortcutLC.SetItemText(iItem, 1, str); DWORD dwData = MAKELONG(iter->first, iter->second.iMenuPosition); m_ShortcutLC.SetItemData(iItem, dwData); } // Now sort via Menu item position m_ShortcutLC.SortItems(CompareFunc, NULL); m_ShortcutLC.SetColumnWidth(0, LVSCW_AUTOSIZE_USEHEADER); m_ShortcutLC.SetColumnWidth(1, LVSCW_AUTOSIZE_USEHEADER); m_ShortcutLC.ModifyStyle(LVS_OWNERDRAWFIXED, 0, 0); CHeaderCtrl* pHCtrl; pHCtrl = m_ShortcutLC.GetHeaderCtrl(); ASSERT(pHCtrl != NULL); pHCtrl->SetDlgCtrlID(IDC_SHORTCUTLC_HEADER); m_SHCTHeader.SubclassWindow(pHCtrl->GetSafeHwnd()); m_SHCTHeader.SetStopChangeFlag(true); m_stc_warning.SetColour(RGB(255, 0, 0)); m_stc_warning.ShowWindow(SW_HIDE); return TRUE; } void COptionsShortcuts::OnMeasureItem(int nIDCtl, LPMEASUREITEMSTRUCT lpMIS) { // If this is our list control then increase height if (nIDCtl == IDC_SHORTCUTLIST) { lpMIS->itemHeight += 10; } } void COptionsShortcuts::OnBnClickedResetAll() { MapMenuShortcutsIter iter; MapKeyNameIDConstIter citer; CString str; UINT id; st_KeyIDExt st_KIDEx; for (int i = 0; i < m_ShortcutLC.GetItemCount(); i++) { id = (UINT)LOWORD(m_ShortcutLC.GetItemData(i)); iter = m_MapMenuShortcuts.find(id); st_KIDEx.id = iter->second.cdefVirtKey; st_KIDEx.bExtended = (iter->second.cModifier & HOTKEYF_EXT) == HOTKEYF_EXT; citer = m_MapKeyNameID.find(st_KIDEx); iter->second.cVirtKey = iter->second.cdefVirtKey; iter->second.cModifier = iter->second.cdefModifier; if (citer != m_MapKeyNameID.end() || iter->second.cdefVirtKey != 0) { str = CMenuShortcut::FormatShortcut(iter, citer); } else { str = _T(""); } m_ShortcutLC.SetItemText(i, 1, str); } ClearWarning(); m_ShortcutLC.RedrawItems(0, m_ShortcutLC.GetItemCount()); m_ShortcutLC.UpdateWindow(); m_bChanged = true; } // Functor for find_if to see if shortcut is reserved struct reserved { reserved(st_MenuShortcut& st_mst) : m_st_mst(st_mst) {} bool operator()(st_MenuShortcut const& rdata) const { return (m_st_mst.cVirtKey == rdata.cVirtKey && m_st_mst.cModifier == rdata.cModifier); } st_MenuShortcut m_st_mst; }; // Functor for find_if to see if shortcut is already in use struct already_inuse { already_inuse(st_MenuShortcut& st_mst) : m_st_mst(st_mst) {} bool operator()(MapMenuShortcutsPair const & p) const { return (p.second.cVirtKey == m_st_mst.cVirtKey && p.second.cModifier == m_st_mst.cModifier); } st_MenuShortcut m_st_mst; }; // Tortuous route to get here! // m_HotKey looses focus and calls parent (CListCtrl) that calls here void COptionsShortcuts::OnHotKeyKillFocus(const int item, const UINT id, const WORD wVirtualKeyCode, const WORD wModifiers) { CString str(_T("")), mst_str(_T("")); CString cs_warning; MapMenuShortcutsIter iter, inuse_iter; MapKeyNameIDConstIter citer; st_MenuShortcut st_mst; st_KeyIDExt st_KIDEx; st_KIDEx.id = (unsigned char)wVirtualKeyCode; st_KIDEx.bExtended = (wModifiers & HOTKEYF_EXT) == HOTKEYF_EXT; citer = m_MapKeyNameID.find(st_KIDEx); // Stop compiler complaining - put this here even if not needed st_mst.cVirtKey = (unsigned char)wVirtualKeyCode; st_mst.cModifier = (unsigned char)wModifiers; already_inuse inuse(st_mst); if (citer == m_MapKeyNameID.end()) { // Invalid shortcut cs_warning.LoadString(IDS_SHCT_WARNING1); goto set_warning; } if (st_mst.cVirtKey != 0) { mst_str = CMenuShortcut::FormatShortcut(st_mst, citer); } if (std::find_if(m_ReservedShortcuts.begin(), m_ReservedShortcuts.end(), reserved(st_mst)) != m_ReservedShortcuts.end()) { // Reserved shortcut ignored cs_warning.Format(IDS_SHCT_WARNING2, mst_str); goto set_warning; } // Check not already in use (ignore if deleting current shortcut) iter = m_MapMenuShortcuts.find(id); if (st_mst.cVirtKey != (unsigned char)0) { inuse_iter = std::find_if(m_MapMenuShortcuts.begin(), m_MapMenuShortcuts.end(), inuse); if (inuse_iter != m_MapMenuShortcuts.end() && inuse_iter->first != iter->first) { // Shortcut in use cs_warning.Format(IDS_SHCT_WARNING3, mst_str, inuse_iter->second.name); goto set_warning; } } if (iter->second.cVirtKey != 0) { str = CMenuShortcut::FormatShortcut(iter, citer); } // Not reserved and not already in use - implement iter->second.cVirtKey = st_mst.cVirtKey; iter->second.cModifier = st_mst.cModifier; m_ShortcutLC.SetItemText(item, 1, str); m_ShortcutLC.RedrawItems(item, item); m_ShortcutLC.UpdateWindow(); m_bChanged = true; return; set_warning: m_stc_warning.SetWindowText(cs_warning); m_stc_warning.ShowWindow(SW_SHOW); } BOOL COptionsShortcuts::PreTranslateMessage(MSG* pMsg) { // If HotKey active, allow Enter key to set instead of close // Property Page (OK button) if (pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_RETURN && m_ShortcutLC.IsHotKeyActive()) { m_ShortcutLC.SaveHotKey(); return TRUE; } return CPWPropertyPage::PreTranslateMessage(pMsg); } int CALLBACK COptionsShortcuts::CompareFunc(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort) { UNREFERENCED_PARAMETER(lParamSort); return (int)(HIWORD(lParam1) - HIWORD(lParam2)); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: SwAppletImpl.cxx,v $ * * $Revision: 1.13 $ * * last change: $Author: hr $ $Date: 2006-08-14 17:01:53 $ * * 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 _SW_APPLET_IMPL_HXX #include <SwAppletImpl.hxx> #endif #ifndef SVTOOLS_URIHELPER_HXX #include <svtools/urihelper.hxx> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_EMBED_EMBEDSTATES_HPP_ #include <com/sun/star/embed/EmbedStates.hpp> #endif #include <comphelper/embeddedobjectcontainer.hxx> #include <sot/clsids.hxx> #include <com/sun/star/uno/Any.hxx> #include <svtools/embedhlp.hxx> using namespace com::sun::star; /* Some MIB magic...*/ sal_Char const SVTOOLS_CONSTASCII_DEF( sHTML_O_hidden, "HIDDEN" ); sal_Char const SVTOOLS_CONSTASCII_DEF( sHTML_HIDDEN_false, "FALSE" ); sal_Char const SVTOOLS_CONSTASCII_DEF( sHTML_O_archives, "ARCHIVES" ); sal_Char const SVTOOLS_CONSTASCII_DEF( sHTML_O_object, "OBJECT" ); USHORT SwApplet_Impl::GetOptionType( const String& rName, BOOL bApplet ) { USHORT nType = bApplet ? SWHTML_OPTTYPE_PARAM : SWHTML_OPTTYPE_TAG; switch( rName.GetChar(0) ) { case 'A': case 'a': if( rName.EqualsIgnoreCaseAscii( sHTML_O_align ) || rName.EqualsIgnoreCaseAscii( sHTML_O_alt ) ) nType = SWHTML_OPTTYPE_IGNORE; else if( bApplet && (rName.EqualsIgnoreCaseAscii( sHTML_O_archive ) || rName.EqualsIgnoreCaseAscii( sHTML_O_archives )) ) nType = SWHTML_OPTTYPE_TAG; break; case 'C': case 'c': if( rName.EqualsIgnoreCaseAscii( sHTML_O_class ) || (bApplet && (rName.EqualsIgnoreCaseAscii( sHTML_O_code ) || rName.EqualsIgnoreCaseAscii( sHTML_O_codebase ))) ) nType = SWHTML_OPTTYPE_IGNORE; break; case 'H': case 'h': if( rName.EqualsIgnoreCaseAscii( sHTML_O_height ) ) nType = SWHTML_OPTTYPE_SIZE; else if( rName.EqualsIgnoreCaseAscii( sHTML_O_hspace ) || (!bApplet && rName.EqualsIgnoreCaseAscii( sHTML_O_hidden )) ) nType = SWHTML_OPTTYPE_IGNORE; break; case 'I': case 'i': if( rName.EqualsIgnoreCaseAscii( sHTML_O_id ) ) nType = SWHTML_OPTTYPE_IGNORE; break; case 'M': case 'm': if( bApplet && rName.EqualsIgnoreCaseAscii( sHTML_O_mayscript ) ) nType = SWHTML_OPTTYPE_IGNORE; break; case 'N': case 'n': if( rName.EqualsIgnoreCaseAscii( sHTML_O_name ) ) nType = SWHTML_OPTTYPE_IGNORE; break; case 'O': case 'o': if( bApplet && rName.EqualsIgnoreCaseAscii( sHTML_O_object ) ) nType = SWHTML_OPTTYPE_TAG; break; case 'S': case 's': if( rName.EqualsIgnoreCaseAscii( sHTML_O_style ) || (!bApplet && rName.EqualsIgnoreCaseAscii( sHTML_O_src )) ) nType = SWHTML_OPTTYPE_IGNORE; break; case 'T': case 't': if( !bApplet && rName.EqualsIgnoreCaseAscii( sHTML_O_type ) ) nType = SWHTML_OPTTYPE_IGNORE; break; case 'V': case 'v': if( rName.EqualsIgnoreCaseAscii( sHTML_O_vspace ) ) nType = SWHTML_OPTTYPE_IGNORE; break; case 'W': case 'w': if( rName.EqualsIgnoreCaseAscii( sHTML_O_width ) ) nType = SWHTML_OPTTYPE_SIZE; break; } return nType; } SwApplet_Impl::SwApplet_Impl( SfxItemPool& rPool, USHORT nWhich1, USHORT nWhich2 ) : aItemSet( rPool, nWhich1, nWhich2 ) { } void SwApplet_Impl::CreateApplet( const String& rCode, const String& rName, BOOL bMayScript, const String& rCodeBase, const String& rDocumentBaseURL ) { comphelper::EmbeddedObjectContainer aCnt; ::rtl::OUString aName; // create Applet; it will be in running state xApplet = aCnt.CreateEmbeddedObject( SvGlobalName( SO3_APPLET_CLASSID ).GetByteSequence(), aName ); ::svt::EmbeddedObjectRef::TryRunningState( xApplet ); INetURLObject aUrlBase(rDocumentBaseURL); aUrlBase.removeSegment(); String sDocBase = aUrlBase.GetMainURL(INetURLObject::NO_DECODE); uno::Reference < beans::XPropertySet > xSet( xApplet->getComponent(), uno::UNO_QUERY ); if ( xSet.is() ) { xSet->setPropertyValue( ::rtl::OUString::createFromAscii("AppletCode"), uno::makeAny( ::rtl::OUString( rCode ) ) ); xSet->setPropertyValue( ::rtl::OUString::createFromAscii("AppletName"), uno::makeAny( ::rtl::OUString( rName ) ) ); xSet->setPropertyValue( ::rtl::OUString::createFromAscii("AppletIsScript"), uno::makeAny( sal_Bool(bMayScript) ) ); xSet->setPropertyValue( ::rtl::OUString::createFromAscii("AppletDocBase"), uno::makeAny( ::rtl::OUString(sDocBase) ) ); if ( rCodeBase.Len() ) xSet->setPropertyValue( ::rtl::OUString::createFromAscii("AppletCodeBase"), uno::makeAny( ::rtl::OUString( rCodeBase ) ) ); else xSet->setPropertyValue( ::rtl::OUString::createFromAscii("AppletCodeBase"), uno::makeAny( ::rtl::OUString( sDocBase ) ) ); } } #ifdef SOLAR_JAVA sal_Bool SwApplet_Impl::CreateApplet( const String& rBaseURL ) { String aCode, aName, aCodeBase; sal_Bool bMayScript = sal_False; sal_uInt32 nArgCount = aCommandList.Count(); for( sal_uInt32 i=0; i<nArgCount; i++ ) { const SvCommand& rArg = aCommandList[i]; const String& rName = rArg.GetCommand(); if( rName.EqualsIgnoreCaseAscii( sHTML_O_code ) ) aCode = rArg.GetArgument(); else if( rName.EqualsIgnoreCaseAscii( sHTML_O_codebase ) ) aCodeBase = INetURLObject::GetAbsURL( rBaseURL, rArg.GetArgument() ); else if( rName.EqualsIgnoreCaseAscii( sHTML_O_name ) ) aName = rArg.GetArgument(); else if( rName.EqualsIgnoreCaseAscii( sHTML_O_mayscript ) ) bMayScript = sal_True; } if( !aCode.Len() ) return sal_False; CreateApplet( aCode, aName, bMayScript, aCodeBase, rBaseURL ); return sal_True; } #endif SwApplet_Impl::~SwApplet_Impl() { } void SwApplet_Impl::FinishApplet() { //xApplet->EnableSetModified( TRUE ); uno::Reference < beans::XPropertySet > xSet( xApplet->getComponent(), uno::UNO_QUERY ); if ( xSet.is() ) { uno::Sequence < beans::PropertyValue > aProps; aCommandList.FillSequence( aProps ); xSet->setPropertyValue( ::rtl::OUString::createFromAscii("AppletCommands"), uno::makeAny( aProps ) ); } } #ifdef SOLAR_JAVA void SwApplet_Impl::AppendParam( const String& rName, const String& rValue ) { aCommandList.Append( rName, rValue ); } #endif <commit_msg>INTEGRATION: CWS pchfix02 (1.13.2); FILE MERGED 2006/09/01 17:52:28 kaib 1.13.2.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: SwAppletImpl.cxx,v $ * * $Revision: 1.14 $ * * last change: $Author: obo $ $Date: 2006-09-16 22:06:59 $ * * 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 * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #ifndef _SW_APPLET_IMPL_HXX #include <SwAppletImpl.hxx> #endif #ifndef SVTOOLS_URIHELPER_HXX #include <svtools/urihelper.hxx> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_EMBED_EMBEDSTATES_HPP_ #include <com/sun/star/embed/EmbedStates.hpp> #endif #include <comphelper/embeddedobjectcontainer.hxx> #include <sot/clsids.hxx> #include <com/sun/star/uno/Any.hxx> #include <svtools/embedhlp.hxx> using namespace com::sun::star; /* Some MIB magic...*/ sal_Char const SVTOOLS_CONSTASCII_DEF( sHTML_O_hidden, "HIDDEN" ); sal_Char const SVTOOLS_CONSTASCII_DEF( sHTML_HIDDEN_false, "FALSE" ); sal_Char const SVTOOLS_CONSTASCII_DEF( sHTML_O_archives, "ARCHIVES" ); sal_Char const SVTOOLS_CONSTASCII_DEF( sHTML_O_object, "OBJECT" ); USHORT SwApplet_Impl::GetOptionType( const String& rName, BOOL bApplet ) { USHORT nType = bApplet ? SWHTML_OPTTYPE_PARAM : SWHTML_OPTTYPE_TAG; switch( rName.GetChar(0) ) { case 'A': case 'a': if( rName.EqualsIgnoreCaseAscii( sHTML_O_align ) || rName.EqualsIgnoreCaseAscii( sHTML_O_alt ) ) nType = SWHTML_OPTTYPE_IGNORE; else if( bApplet && (rName.EqualsIgnoreCaseAscii( sHTML_O_archive ) || rName.EqualsIgnoreCaseAscii( sHTML_O_archives )) ) nType = SWHTML_OPTTYPE_TAG; break; case 'C': case 'c': if( rName.EqualsIgnoreCaseAscii( sHTML_O_class ) || (bApplet && (rName.EqualsIgnoreCaseAscii( sHTML_O_code ) || rName.EqualsIgnoreCaseAscii( sHTML_O_codebase ))) ) nType = SWHTML_OPTTYPE_IGNORE; break; case 'H': case 'h': if( rName.EqualsIgnoreCaseAscii( sHTML_O_height ) ) nType = SWHTML_OPTTYPE_SIZE; else if( rName.EqualsIgnoreCaseAscii( sHTML_O_hspace ) || (!bApplet && rName.EqualsIgnoreCaseAscii( sHTML_O_hidden )) ) nType = SWHTML_OPTTYPE_IGNORE; break; case 'I': case 'i': if( rName.EqualsIgnoreCaseAscii( sHTML_O_id ) ) nType = SWHTML_OPTTYPE_IGNORE; break; case 'M': case 'm': if( bApplet && rName.EqualsIgnoreCaseAscii( sHTML_O_mayscript ) ) nType = SWHTML_OPTTYPE_IGNORE; break; case 'N': case 'n': if( rName.EqualsIgnoreCaseAscii( sHTML_O_name ) ) nType = SWHTML_OPTTYPE_IGNORE; break; case 'O': case 'o': if( bApplet && rName.EqualsIgnoreCaseAscii( sHTML_O_object ) ) nType = SWHTML_OPTTYPE_TAG; break; case 'S': case 's': if( rName.EqualsIgnoreCaseAscii( sHTML_O_style ) || (!bApplet && rName.EqualsIgnoreCaseAscii( sHTML_O_src )) ) nType = SWHTML_OPTTYPE_IGNORE; break; case 'T': case 't': if( !bApplet && rName.EqualsIgnoreCaseAscii( sHTML_O_type ) ) nType = SWHTML_OPTTYPE_IGNORE; break; case 'V': case 'v': if( rName.EqualsIgnoreCaseAscii( sHTML_O_vspace ) ) nType = SWHTML_OPTTYPE_IGNORE; break; case 'W': case 'w': if( rName.EqualsIgnoreCaseAscii( sHTML_O_width ) ) nType = SWHTML_OPTTYPE_SIZE; break; } return nType; } SwApplet_Impl::SwApplet_Impl( SfxItemPool& rPool, USHORT nWhich1, USHORT nWhich2 ) : aItemSet( rPool, nWhich1, nWhich2 ) { } void SwApplet_Impl::CreateApplet( const String& rCode, const String& rName, BOOL bMayScript, const String& rCodeBase, const String& rDocumentBaseURL ) { comphelper::EmbeddedObjectContainer aCnt; ::rtl::OUString aName; // create Applet; it will be in running state xApplet = aCnt.CreateEmbeddedObject( SvGlobalName( SO3_APPLET_CLASSID ).GetByteSequence(), aName ); ::svt::EmbeddedObjectRef::TryRunningState( xApplet ); INetURLObject aUrlBase(rDocumentBaseURL); aUrlBase.removeSegment(); String sDocBase = aUrlBase.GetMainURL(INetURLObject::NO_DECODE); uno::Reference < beans::XPropertySet > xSet( xApplet->getComponent(), uno::UNO_QUERY ); if ( xSet.is() ) { xSet->setPropertyValue( ::rtl::OUString::createFromAscii("AppletCode"), uno::makeAny( ::rtl::OUString( rCode ) ) ); xSet->setPropertyValue( ::rtl::OUString::createFromAscii("AppletName"), uno::makeAny( ::rtl::OUString( rName ) ) ); xSet->setPropertyValue( ::rtl::OUString::createFromAscii("AppletIsScript"), uno::makeAny( sal_Bool(bMayScript) ) ); xSet->setPropertyValue( ::rtl::OUString::createFromAscii("AppletDocBase"), uno::makeAny( ::rtl::OUString(sDocBase) ) ); if ( rCodeBase.Len() ) xSet->setPropertyValue( ::rtl::OUString::createFromAscii("AppletCodeBase"), uno::makeAny( ::rtl::OUString( rCodeBase ) ) ); else xSet->setPropertyValue( ::rtl::OUString::createFromAscii("AppletCodeBase"), uno::makeAny( ::rtl::OUString( sDocBase ) ) ); } } #ifdef SOLAR_JAVA sal_Bool SwApplet_Impl::CreateApplet( const String& rBaseURL ) { String aCode, aName, aCodeBase; sal_Bool bMayScript = sal_False; sal_uInt32 nArgCount = aCommandList.Count(); for( sal_uInt32 i=0; i<nArgCount; i++ ) { const SvCommand& rArg = aCommandList[i]; const String& rName = rArg.GetCommand(); if( rName.EqualsIgnoreCaseAscii( sHTML_O_code ) ) aCode = rArg.GetArgument(); else if( rName.EqualsIgnoreCaseAscii( sHTML_O_codebase ) ) aCodeBase = INetURLObject::GetAbsURL( rBaseURL, rArg.GetArgument() ); else if( rName.EqualsIgnoreCaseAscii( sHTML_O_name ) ) aName = rArg.GetArgument(); else if( rName.EqualsIgnoreCaseAscii( sHTML_O_mayscript ) ) bMayScript = sal_True; } if( !aCode.Len() ) return sal_False; CreateApplet( aCode, aName, bMayScript, aCodeBase, rBaseURL ); return sal_True; } #endif SwApplet_Impl::~SwApplet_Impl() { } void SwApplet_Impl::FinishApplet() { //xApplet->EnableSetModified( TRUE ); uno::Reference < beans::XPropertySet > xSet( xApplet->getComponent(), uno::UNO_QUERY ); if ( xSet.is() ) { uno::Sequence < beans::PropertyValue > aProps; aCommandList.FillSequence( aProps ); xSet->setPropertyValue( ::rtl::OUString::createFromAscii("AppletCommands"), uno::makeAny( aProps ) ); } } #ifdef SOLAR_JAVA void SwApplet_Impl::AppendParam( const String& rName, const String& rValue ) { aCommandList.Append( rName, rValue ); } #endif <|endoftext|>
<commit_before>#ifndef MJOLNIR_PARTICLE #define MJOLNIR_PARTICLE namespace mjolnir { template<typename realT, typename coordT> struct Particle { typedef realT real_type; typedef coordT coordinate_type; realT mass; coordT position; coordT velocity; coordT force; }; template<typename realT, typename coordT> constexpr inline Particle<realT, coordT> make_particle(const realT mass, const coordT& pos, const coordT& vel, const coordT& f) { return Particle<realT, coordT>{mass, pos, vel, f}; } } // mjolnir #endif /* MJOLNIR_PARTICLE */ <commit_msg>remove needless function<commit_after>#ifndef MJOLNIR_PARTICLE #define MJOLNIR_PARTICLE namespace mjolnir { template<typename realT, typename coordT> struct Particle { typedef realT real_type; typedef coordT coordinate_type; realT mass; coordT position; coordT velocity; coordT force; }; } // mjolnir #endif /* MJOLNIR_PARTICLE */ <|endoftext|>