text
stringlengths
54
60.6k
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkPowellOptimizer.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef _itkPowellOptimizer_cxx #define _itkPowellOptimizer_cxx #include "itkPowellOptimizer.h" namespace itk { const double POWELL_BRACKET_GOLD = 1.618034; const double POWELL_BRENT_GOLD = 0.3819660; const double POWELL_GLIMIT = 100.0; const double POWELL_TINY = 1.0e-20; PowellOptimizer ::PowellOptimizer() { m_Maximize = false; m_StepLength = 1.0; m_StepTolerance = 0.00001; m_ValueTolerance = 0.00001; m_Stop = false ; m_CurrentCost = 0; m_CurrentIteration = 0; m_CurrentLineIteration = 0; m_MaximumIteration = 100 ; m_MaximumLineIteration = 100 ; m_SpaceDimension = 0; } PowellOptimizer ::~PowellOptimizer() { } void PowellOptimizer ::SetLine(const PowellOptimizer::ParametersType & origin, const vnl_vector<double> & direction) { m_LineOrigin = origin; m_LineDirection = direction; for(unsigned int i=0; i<m_SpaceDimension; i++) { m_LineDirection[i] = m_LineDirection[i] / this->GetScales()[i]; } } double PowellOptimizer ::GetLineValue(double x) const { PowellOptimizer::ParametersType xCoord( m_SpaceDimension ); for(unsigned int i=0; i<m_SpaceDimension; i++) { xCoord[i] = this->m_LineOrigin[i] + x * this->m_LineDirection[i]; } if(m_Maximize) { return -(this->m_CostFunction->GetValue(xCoord)); } else { return this->m_CostFunction->GetValue(xCoord); } } void PowellOptimizer ::SetCurrentLinePoint(double x, double fx) { PowellOptimizer::ParametersType xCoord( m_SpaceDimension ); for(unsigned int i=0; i<m_SpaceDimension; i++) { xCoord[i] = this->m_LineOrigin[i] + x * this->m_LineDirection[i]; } this->SetCurrentPosition(xCoord); if(m_Maximize) { this->SetCurrentCost(-fx); } else { this->SetCurrentCost(fx); } } void PowellOptimizer ::Swap(double * a, double * b) const { double tf; tf = *a; *a = *b; *b = tf; } void PowellOptimizer ::Shift(double *a, double *b, double *c, double d) const { *a = *b; *b = *c; *c = d; } void PowellOptimizer ::LineBracket(double * ax, double * bx, double * cx, double * fa, double * fb, double * fc) { double ulim,u,r,q,fu,dq; //*fa = this->GetLineValue(*ax); *fb = this->GetLineValue(*bx); if (*fb > *fa) { this->Swap(ax, bx); this->Swap(fa, fb); } *cx = (*bx) + POWELL_BRACKET_GOLD * (*bx - *ax); *fc = this->GetLineValue(*cx); while (*fb > *fc) { r = (*bx - *ax) * (*fb - *fc); q = (*bx - *cx) * (*fb - *fa); dq = q - r; if (vcl_abs(dq) < POWELL_TINY) { dq = vnl_math_sgn(dq) * POWELL_TINY; } u = (*bx) - ( (*bx - *cx) * q - (*bx - *ax) * r ) / (2.0 * dq); ulim = (*bx) + POWELL_GLIMIT * (*cx - *bx); if ( (*bx - u) * (u - *cx) > 0.0 ) { fu = this->GetLineValue(u); if (fu < *fc) { *ax = (*bx); *bx = u; *fa = (*fb); *fb = fu; return; } else if (fu > *fb) { *cx=u; *fc=fu; return; } u = (*cx) + POWELL_BRACKET_GOLD * (*cx - *bx); fu = this->GetLineValue(u); } else if ( (*cx - u) * (u - ulim) > 0.0 ) { fu = this->GetLineValue(u); if (fu < *fc) { //SHFT(bx,cx,&u,*cx+GOLD*(*cx-*bx)); awf dumped -- c is useless this->Shift(bx, cx, &u, u + POWELL_BRACKET_GOLD * (u - *cx)); this->Shift(fb, fc, &fu, this->GetLineValue(u)); } } else if ( (u - ulim) * (ulim - *cx) >= 0.0) { u = ulim; fu = this->GetLineValue(u); } else { u = (*cx) + POWELL_BRACKET_GOLD * (*cx - *bx); fu = this->GetLineValue(u); } this->Shift(ax, bx, cx, u); this->Shift(fa, fb, fc, fu); } this->SetCurrentLinePoint(*bx, *fb); } void PowellOptimizer ::BracketedLineOptimize(double ax, double bx, double cx, double itkNotUsed(fa), double fb, double itkNotUsed(fc), double * extX, double * extVal) { itkWarningMacro("This code has been identified to be covered by the Numerical Recipes copyright. The code will be removed/replaced as soon as possible"); // For details, please look at: // // http://www.pit.physik.uni-tuebingen.de/~hehl/CP/brent.c // // and the discussions on the ITK Wiki: // // http://www.itk.org/Wiki/Agenda%26Status_022307 // // double a, b; double d=0.0; double etemp,fu,fv,fw,fx,p,q,r,tol1,tol2,u,v,w,x,xm; double e=0.0; a = (ax < cx ? ax : cx); b = (ax > cx ? ax : cx); x = w = v = bx; fw = fv = fx = fb; for (m_CurrentLineIteration = 0; m_CurrentLineIteration < m_MaximumLineIteration; m_CurrentLineIteration++) { xm = 0.5*(a+b); tol1 = m_StepTolerance * vcl_fabs(x) + POWELL_TINY; tol2 = 2.0 * tol1; if (vcl_fabs(x-xm) <= (tol2 - 0.5*(b-a)) || 0.5*(b-a) < m_StepTolerance) { *extX = x; *extVal = fx; this->SetCurrentLinePoint(x, fx); return; } if (vcl_fabs(e) > tol1) { r = (x-w) * (fx-fv); q = (x-v) * (fx-fw); p = (x-v)*q - (x-w)*r; q = 2.0 * (q-r); if (q > 0.0) { p = -p; } q = vcl_fabs(q); etemp = e; e = d; if (vcl_fabs(p) >= vcl_fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) { if(x >= xm) { e = a - x; } else { e = b - x; } d = POWELL_BRENT_GOLD * e; } else { d = p/q; u = x+d; if (u-a < tol2 || b-u < tol2) { d = tol1 * vnl_math_sgn(xm-x); } } } else { if(x >= xm) { e = a - x; } else { e = b - x; } d = POWELL_BRENT_GOLD * e; } if(vcl_fabs(d) >= tol1) { u = x + d; } else { u = x + tol1 * vnl_math_sgn(d); } fu = this->GetLineValue(u); if (fu <= fx) { if (u >= x) { a = x; } else { b = x; } this->Shift(&v, &w, &x, u); this->Shift(&fv, &fw, &fx, fu); } else { if (u < x) { a = u; } else { b = u; } if (fu <= fw || w == x) { v = w; w = u; fv = fw; fw = fu; } else if (fu <= fv || v == x || v == w) { v = u; fv = fu; } } this->SetCurrentLinePoint(x, fx); this->InvokeEvent( IterationEvent() ); } *extX = x; *extVal = fx; this->SetCurrentLinePoint(x, fx); } void PowellOptimizer ::StartOptimization() { if( m_CostFunction.IsNull() ) { return ; } this->InvokeEvent( StartEvent() ); m_Stop = false ; m_SpaceDimension = m_CostFunction->GetNumberOfParameters(); m_LineOrigin.set_size(m_SpaceDimension); m_LineDirection.set_size(m_SpaceDimension); vnl_matrix<double> xi(m_SpaceDimension, m_SpaceDimension); vnl_vector<double> xit(m_SpaceDimension); xi.set_identity(); xit.fill(0); xit[0] = 1; PowellOptimizer::ParametersType p(m_SpaceDimension); PowellOptimizer::ParametersType pt(m_SpaceDimension); PowellOptimizer::ParametersType ptt(m_SpaceDimension); p = this->GetInitialPosition(); pt = p; unsigned int ibig; double fp, del, fptt; double ax, xx, bx; double fa, fx, fb; xx = 0; this->SetLine(p, xit); fx = this->GetLineValue(0); for (m_CurrentIteration = 0; m_CurrentIteration <= m_MaximumIteration; m_CurrentIteration++) { fp = fx; ibig = 0; del = 0.0; for (unsigned int i = 0; i < m_SpaceDimension; i++) { for (unsigned int j = 0; j < m_SpaceDimension; ++j) { xit[j] = xi[j][i]; } fptt = fx; this->SetLine(p, xit); ax = 0.0; fa = fx; xx = m_StepLength; this->LineBracket(&ax, &xx, &bx, &fa, &fx, &fb); this->BracketedLineOptimize(ax, xx, bx, fa, fx, fb, &xx, &fx); this->SetCurrentLinePoint(xx, fx); p = this->GetCurrentPosition(); if (vcl_fabs(fptt-fx) > del) { del = vcl_fabs(fptt-fx); ibig = i; } } if (2.0*vcl_fabs(fp-fx) <= m_ValueTolerance*(vcl_fabs(fp)+vcl_fabs(fx))) { this->InvokeEvent( EndEvent() ); return; } for (unsigned int j = 0; j < m_SpaceDimension; ++j) { ptt[j] = 2.0*p[j] - pt[j]; xit[j] = (p[j] - pt[j]) * this->GetScales()[j]; pt[j] = p[j]; } this->SetLine(ptt, xit); fptt = this->GetLineValue(0); if (fptt < fp) { double t = 2.0 * (fp - 2.0*fx + fptt) * vnl_math_sqr(fp-fx-del) - del * vnl_math_sqr(fp-fptt); if (t < 0.0) { this->SetLine(p, xit); ax = 0.0; fa = fx; xx = 1; this->LineBracket(&ax, &xx, &bx, &fa, &fx, &fb); this->BracketedLineOptimize(ax, xx, bx, fa, fx, fb, &xx, &fx); this->SetCurrentLinePoint(xx, fx); p = this->GetCurrentPosition(); for (unsigned int j = 0; j < m_SpaceDimension; j++) { xi[j][ibig] = xx * xit[j]; } } } this->InvokeEvent( IterationEvent() ); } this->InvokeEvent( EndEvent() ); } /** * */ void PowellOptimizer ::PrintSelf(std::ostream& os, Indent indent) const { Superclass::PrintSelf(os,indent); os << indent << "Space Dimension " << m_SpaceDimension << std::endl; os << indent << "Maximum Iteration " << m_MaximumIteration << std::endl; os << indent << "Current Iteration " << m_CurrentIteration << std::endl; os << indent << "Maximize On/Off " << m_Maximize << std::endl; os << indent << "StepLength " << m_StepLength << std::endl; os << indent << "StepTolerance " << m_StepTolerance << std::endl; os << indent << "ValueTolerance " << m_ValueTolerance << std::endl; os << indent << "LineOrigin " << m_LineOrigin << std::endl; os << indent << "LineDirection " << m_LineDirection << std::endl; os << indent << "Current Cost " << m_CurrentCost << std::endl; os << indent << "Maximum Line Iteration " << m_MaximumLineIteration << std::endl; os << indent << "Current Line Iteration " << m_CurrentLineIteration << std::endl; os << indent << "Stop " << m_Stop << std::endl; } } // end of namespace itk #endif <commit_msg>BUG: 4546: Replacing Numerical Recipies code from method BracketedLineOptimize with code from netlib.org. Code adaptation provided by Andinet Enquobahrie.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkPowellOptimizer.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef _itkPowellOptimizer_cxx #define _itkPowellOptimizer_cxx #include "itkPowellOptimizer.h" namespace itk { const double POWELL_BRACKET_GOLD = 1.618034; const double POWELL_BRENT_GOLD = 0.3819660; const double POWELL_GLIMIT = 100.0; const double POWELL_TINY = 1.0e-20; PowellOptimizer ::PowellOptimizer() { m_Maximize = false; m_StepLength = 1.0; m_StepTolerance = 0.00001; m_ValueTolerance = 0.00001; m_Stop = false ; m_CurrentCost = 0; m_CurrentIteration = 0; m_CurrentLineIteration = 0; m_MaximumIteration = 100 ; m_MaximumLineIteration = 100 ; m_SpaceDimension = 0; } PowellOptimizer ::~PowellOptimizer() { } void PowellOptimizer ::SetLine(const PowellOptimizer::ParametersType & origin, const vnl_vector<double> & direction) { m_LineOrigin = origin; m_LineDirection = direction; for(unsigned int i=0; i<m_SpaceDimension; i++) { m_LineDirection[i] = m_LineDirection[i] / this->GetScales()[i]; } } double PowellOptimizer ::GetLineValue(double x) const { PowellOptimizer::ParametersType xCoord( m_SpaceDimension ); for(unsigned int i=0; i<m_SpaceDimension; i++) { xCoord[i] = this->m_LineOrigin[i] + x * this->m_LineDirection[i]; } if(m_Maximize) { return -(this->m_CostFunction->GetValue(xCoord)); } else { return this->m_CostFunction->GetValue(xCoord); } } void PowellOptimizer ::SetCurrentLinePoint(double x, double fx) { PowellOptimizer::ParametersType xCoord( m_SpaceDimension ); for(unsigned int i=0; i<m_SpaceDimension; i++) { xCoord[i] = this->m_LineOrigin[i] + x * this->m_LineDirection[i]; } this->SetCurrentPosition(xCoord); if(m_Maximize) { this->SetCurrentCost(-fx); } else { this->SetCurrentCost(fx); } } void PowellOptimizer ::Swap(double * a, double * b) const { double tf; tf = *a; *a = *b; *b = tf; } void PowellOptimizer ::Shift(double *a, double *b, double *c, double d) const { *a = *b; *b = *c; *c = d; } void PowellOptimizer ::LineBracket(double * ax, double * bx, double * cx, double * fa, double * fb, double * fc) { double ulim,u,r,q,fu,dq; //*fa = this->GetLineValue(*ax); *fb = this->GetLineValue(*bx); if (*fb > *fa) { this->Swap(ax, bx); this->Swap(fa, fb); } *cx = (*bx) + POWELL_BRACKET_GOLD * (*bx - *ax); *fc = this->GetLineValue(*cx); while (*fb > *fc) { r = (*bx - *ax) * (*fb - *fc); q = (*bx - *cx) * (*fb - *fa); dq = q - r; if (vcl_abs(dq) < POWELL_TINY) { dq = vnl_math_sgn(dq) * POWELL_TINY; } u = (*bx) - ( (*bx - *cx) * q - (*bx - *ax) * r ) / (2.0 * dq); ulim = (*bx) + POWELL_GLIMIT * (*cx - *bx); if ( (*bx - u) * (u - *cx) > 0.0 ) { fu = this->GetLineValue(u); if (fu < *fc) { *ax = (*bx); *bx = u; *fa = (*fb); *fb = fu; return; } else if (fu > *fb) { *cx=u; *fc=fu; return; } u = (*cx) + POWELL_BRACKET_GOLD * (*cx - *bx); fu = this->GetLineValue(u); } else if ( (*cx - u) * (u - ulim) > 0.0 ) { fu = this->GetLineValue(u); if (fu < *fc) { //SHFT(bx,cx,&u,*cx+GOLD*(*cx-*bx)); awf dumped -- c is useless this->Shift(bx, cx, &u, u + POWELL_BRACKET_GOLD * (u - *cx)); this->Shift(fb, fc, &fu, this->GetLineValue(u)); } } else if ( (u - ulim) * (ulim - *cx) >= 0.0) { u = ulim; fu = this->GetLineValue(u); } else { u = (*cx) + POWELL_BRACKET_GOLD * (*cx - *bx); fu = this->GetLineValue(u); } this->Shift(ax, bx, cx, u); this->Shift(fa, fb, fc, fu); } this->SetCurrentLinePoint(*bx, *fb); } void PowellOptimizer ::BracketedLineOptimize(double ax, double bx, double cx, double itkNotUsed(fa), double functionValueOfb, double itkNotUsed(fc), double * extX, double * extVal) { double x; double v; double w; /* Abscissae, descr. see above */ double a; double b; a = (ax < cx ? ax : cx); b = (ax > cx ? ax : cx); x = bx; w = bx; const double goldenSectionRatio = (3.0-sqrt(5.0))/2; /* Gold section ratio */ double functionValueOfX; /* f(x) */ double functionValueOfV; /* f(v) */ double functionValueOfW; /* f(w) */ functionValueOfV = functionValueOfb; functionValueOfX = functionValueOfV; functionValueOfW = functionValueOfV; for (m_CurrentLineIteration = 0; m_CurrentLineIteration < m_MaximumLineIteration; m_CurrentLineIteration++) { double range = b-a; /* Range over which the minimum */ double middle_range = (a+b)/2; double new_step; /* Step at this iteration */ double tolerance1; double tolerance2; tolerance1 = m_StepTolerance * vcl_fabs(x) + POWELL_TINY; tolerance2 = 2.0 * tolerance1; if (vcl_fabs(x-middle_range) <= (tolerance2 - 0.5*(b-a)) || 0.5*(b-a) < m_StepTolerance) { *extX = x; *extVal = functionValueOfX; this->SetCurrentLinePoint(x, functionValueOfX); return ; /* Acceptable approx. is found */ } /* Obtain the gold section step */ new_step = goldenSectionRatio * ( x<middle_range ? b-x : a-x ); /* Decide if the interpolation can be tried */ if( fabs(x-w) >= tolerance1 ) /* If x and w are distinct */ { double t; t = (x-w) * (functionValueOfX-functionValueOfV); double q; /* ted as p/q; division operation*/ q = (x-v) * (functionValueOfX-functionValueOfW); double p; /* Interpolation step is calcula-*/ p = (x-v)*q - (x-w)*t; q = 2*(q-t); if( q>(double)0 ) /* q was calculated with the op-*/ { p = -p; /* posite sign; make q positive */ } else /* and assign possible minus to */ { q = -q; /* p */ } /* Chec if x+p/q falls in [a,b] and not too close to a and b and isn't too large */ if( fabs(p) < fabs(new_step*q) && p > q*(a-x+2*tolerance1) && p < q*(b-x-2*tolerance1) ) { new_step = p/q; /* it is accepted */ } /* If p/q is too large then the gold section procedure can reduce [a,b] range to more extent */ } /* Adjust the step to be not less than tolerance*/ if( fabs(new_step) < tolerance1 ) { if ( new_step > 0.0 ) { new_step = tolerance1; } else { new_step = -tolerance1; } } /* Obtain the next approximation to min */ /* and reduce the enveloping range */ double t = x + new_step; /* Tentative point for the min */ double functionValueOft; functionValueOft = this->GetLineValue(t); if( functionValueOft <= functionValueOfX ) { if( t < x ) /* Reduce the range so that */ { b = x; /* t would fall within it */ } else { a = x; } /* assing the best approximation to x */ v = w; w = x; x = t; functionValueOfV = functionValueOfW; functionValueOfW = functionValueOfX; functionValueOfX = functionValueOft; } else /* x remains the better approx */ { if( t < x ) /* Reduce the range enclosing x */ { a = t; } else { b = t; } if( functionValueOft <= functionValueOfW || w==x ) { v = w; w = t; functionValueOfV = functionValueOfW; functionValueOfW = functionValueOft; } else if( functionValueOft<=functionValueOfV || v==x || v==w ) { v = t; functionValueOfV=functionValueOft; } } } *extX = x; *extVal = functionValueOfX; this->SetCurrentLinePoint(x, functionValueOfX); } void PowellOptimizer ::StartOptimization() { if( m_CostFunction.IsNull() ) { return ; } this->InvokeEvent( StartEvent() ); m_Stop = false ; m_SpaceDimension = m_CostFunction->GetNumberOfParameters(); m_LineOrigin.set_size(m_SpaceDimension); m_LineDirection.set_size(m_SpaceDimension); vnl_matrix<double> xi(m_SpaceDimension, m_SpaceDimension); vnl_vector<double> xit(m_SpaceDimension); xi.set_identity(); xit.fill(0); xit[0] = 1; PowellOptimizer::ParametersType p(m_SpaceDimension); PowellOptimizer::ParametersType pt(m_SpaceDimension); PowellOptimizer::ParametersType ptt(m_SpaceDimension); p = this->GetInitialPosition(); pt = p; unsigned int ibig; double fp, del, fptt; double ax, xx, bx; double fa, fx, fb; xx = 0; this->SetLine(p, xit); fx = this->GetLineValue(0); for (m_CurrentIteration = 0; m_CurrentIteration <= m_MaximumIteration; m_CurrentIteration++) { fp = fx; ibig = 0; del = 0.0; for (unsigned int i = 0; i < m_SpaceDimension; i++) { for (unsigned int j = 0; j < m_SpaceDimension; ++j) { xit[j] = xi[j][i]; } fptt = fx; this->SetLine(p, xit); ax = 0.0; fa = fx; xx = m_StepLength; this->LineBracket(&ax, &xx, &bx, &fa, &fx, &fb); this->BracketedLineOptimize(ax, xx, bx, fa, fx, fb, &xx, &fx); this->SetCurrentLinePoint(xx, fx); p = this->GetCurrentPosition(); if (vcl_fabs(fptt-fx) > del) { del = vcl_fabs(fptt-fx); ibig = i; } } if (2.0*vcl_fabs(fp-fx) <= m_ValueTolerance*(vcl_fabs(fp)+vcl_fabs(fx))) { this->InvokeEvent( EndEvent() ); return; } for (unsigned int j = 0; j < m_SpaceDimension; ++j) { ptt[j] = 2.0*p[j] - pt[j]; xit[j] = (p[j] - pt[j]) * this->GetScales()[j]; pt[j] = p[j]; } this->SetLine(ptt, xit); fptt = this->GetLineValue(0); if (fptt < fp) { double t = 2.0 * (fp - 2.0*fx + fptt) * vnl_math_sqr(fp-fx-del) - del * vnl_math_sqr(fp-fptt); if (t < 0.0) { this->SetLine(p, xit); ax = 0.0; fa = fx; xx = 1; this->LineBracket(&ax, &xx, &bx, &fa, &fx, &fb); this->BracketedLineOptimize(ax, xx, bx, fa, fx, fb, &xx, &fx); this->SetCurrentLinePoint(xx, fx); p = this->GetCurrentPosition(); for (unsigned int j = 0; j < m_SpaceDimension; j++) { xi[j][ibig] = xx * xit[j]; } } } this->InvokeEvent( IterationEvent() ); } this->InvokeEvent( EndEvent() ); } /** * */ void PowellOptimizer ::PrintSelf(std::ostream& os, Indent indent) const { Superclass::PrintSelf(os,indent); os << indent << "Space Dimension " << m_SpaceDimension << std::endl; os << indent << "Maximum Iteration " << m_MaximumIteration << std::endl; os << indent << "Current Iteration " << m_CurrentIteration << std::endl; os << indent << "Maximize On/Off " << m_Maximize << std::endl; os << indent << "StepLength " << m_StepLength << std::endl; os << indent << "StepTolerance " << m_StepTolerance << std::endl; os << indent << "ValueTolerance " << m_ValueTolerance << std::endl; os << indent << "LineOrigin " << m_LineOrigin << std::endl; os << indent << "LineDirection " << m_LineDirection << std::endl; os << indent << "Current Cost " << m_CurrentCost << std::endl; os << indent << "Maximum Line Iteration " << m_MaximumLineIteration << std::endl; os << indent << "Current Line Iteration " << m_CurrentLineIteration << std::endl; os << indent << "Stop " << m_Stop << std::endl; } } // end of namespace itk #endif <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2009, 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 Image Engine Design 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. // ////////////////////////////////////////////////////////////////////////// // This include needs to be the very first to prevent problems with warnings // regarding redefinition of _POSIX_C_SOURCE #include "boost/python.hpp" #include "IECore/Renderer.h" #include "IECore/CompoundObject.h" #include "IECore/CompoundParameter.h" #include "IECore/MessageHandler.h" #include "IECore/ParameterisedProcedural.h" #include "IECore/bindings/ParameterisedProceduralBinding.h" #include "IECore/bindings/RunTimeTypedBinding.h" #include "IECore/bindings/Wrapper.h" using namespace boost::python; namespace IECore { class ParameterisedProceduralWrap : public ParameterisedProcedural, public Wrapper<ParameterisedProcedural> { public : /* ParameterisedProceduralWrap( PyObject *self ) : ParameterisedProcedural(), Wrapper<ParameterisedProcedural>( self, this ) { } */ ParameterisedProceduralWrap( PyObject *self, const std::string &description="" ) : ParameterisedProcedural( description ), Wrapper<ParameterisedProcedural>( self, this ) { } virtual void doRenderState( RendererPtr renderer, ConstCompoundObjectPtr args ) const { try { override o = this->get_override( "doRenderState" ); if( o ) { o( renderer, boost::const_pointer_cast<CompoundObject>( args ) ); } else { ParameterisedProcedural::doRenderState( renderer, args ); } } catch( error_already_set ) { PyErr_Print(); } catch( const std::exception &e ) { msg( Msg::Error, "ParameterisedProceduralWrap::doRenderState", e.what() ); } catch( ... ) { msg( Msg::Error, "ParameterisedProceduralWrap::doRenderState", "Caught unknown exception" ); } } virtual Imath::Box3f doBound( ConstCompoundObjectPtr args ) const { try { override o = this->get_override( "doBound" ); if( o ) { return o( boost::const_pointer_cast<CompoundObject>( args ) ); } else { msg( Msg::Error, "ParameterisedProceduralWrap::doBound", "doBound() python method not defined" ); } } catch( error_already_set ) { PyErr_Print(); } catch( const std::exception &e ) { msg( Msg::Error, "ParameterisedProceduralWrap::doBound", e.what() ); } catch( ... ) { msg( Msg::Error, "ParameterisedProceduralWrap::doBound", "Caught unknown exception" ); } return Imath::Box3f(); // empty } virtual void doRender( RendererPtr r, ConstCompoundObjectPtr args ) const { // ideally we might not do any exception handling here, and always leave it to the host. // but in our case the host is mainly 3delight and that does no exception handling at all. try { override o = this->get_override( "doRender" ); if( o ) { o( r, boost::const_pointer_cast<CompoundObject>( args ) ); } else { msg( Msg::Error, "ParameterisedProceduralWrap::doRender", "doRender() python method not defined" ); } } catch( error_already_set ) { PyErr_Print(); } catch( const std::exception &e ) { msg( Msg::Error, "ParameterisedProceduralWrap::doRender", e.what() ); } catch( ... ) { msg( Msg::Error, "ParameterisedProceduralWrap::doRender", "Caught unknown exception" ); } } IE_COREPYTHON_RUNTIMETYPEDWRAPPERFNS( ParameterisedProcedural ); }; IE_CORE_DECLAREPTR( ParameterisedProceduralWrap ); static ParameterPtr parameterisedProceduralGetItem( ParameterisedProcedural &o, const std::string &n ) { ParameterPtr p = o.parameters()->parameter<Parameter>( n ); if( !p ) { throw Exception( std::string("Parameter ") + n + " doesn't exist" ); } return p; } void bindParameterisedProcedural() { RunTimeTypedClass<ParameterisedProcedural, ParameterisedProceduralWrapPtr>() .def( init<>() ) .def( init< const std::string >( arg( "description") ) ) .add_property( "description", make_function( &ParameterisedProcedural::description, return_value_policy<copy_const_reference>() ) ) .def( "parameters", (CompoundParameterPtr (ParameterisedProcedural::*)())&ParameterisedProcedural::parameters ) .def( "render", (void (ParameterisedProcedural::*)( RendererPtr ) const )&ParameterisedProcedural::render ) .def( "render", (void (ParameterisedProcedural::*)( RendererPtr, bool, bool, bool, bool ) const )&ParameterisedProcedural::render, ( arg( "renderer" ), arg( "inAttributeBlock" ) = true, arg( "withState" ) = true, arg( "withGeometry" ) = true, arg( "immediateGeometry" ) = false ) ) .def( "__getitem__", &parameterisedProceduralGetItem ) ; } } // namespace IECore <commit_msg>removed old code<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2009, 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 Image Engine Design 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. // ////////////////////////////////////////////////////////////////////////// // This include needs to be the very first to prevent problems with warnings // regarding redefinition of _POSIX_C_SOURCE #include "boost/python.hpp" #include "IECore/Renderer.h" #include "IECore/CompoundObject.h" #include "IECore/CompoundParameter.h" #include "IECore/MessageHandler.h" #include "IECore/ParameterisedProcedural.h" #include "IECore/bindings/ParameterisedProceduralBinding.h" #include "IECore/bindings/RunTimeTypedBinding.h" #include "IECore/bindings/Wrapper.h" using namespace boost::python; namespace IECore { class ParameterisedProceduralWrap : public ParameterisedProcedural, public Wrapper<ParameterisedProcedural> { public : ParameterisedProceduralWrap( PyObject *self, const std::string &description="" ) : ParameterisedProcedural( description ), Wrapper<ParameterisedProcedural>( self, this ) { } virtual void doRenderState( RendererPtr renderer, ConstCompoundObjectPtr args ) const { try { override o = this->get_override( "doRenderState" ); if( o ) { o( renderer, boost::const_pointer_cast<CompoundObject>( args ) ); } else { ParameterisedProcedural::doRenderState( renderer, args ); } } catch( error_already_set ) { PyErr_Print(); } catch( const std::exception &e ) { msg( Msg::Error, "ParameterisedProceduralWrap::doRenderState", e.what() ); } catch( ... ) { msg( Msg::Error, "ParameterisedProceduralWrap::doRenderState", "Caught unknown exception" ); } } virtual Imath::Box3f doBound( ConstCompoundObjectPtr args ) const { try { override o = this->get_override( "doBound" ); if( o ) { return o( boost::const_pointer_cast<CompoundObject>( args ) ); } else { msg( Msg::Error, "ParameterisedProceduralWrap::doBound", "doBound() python method not defined" ); } } catch( error_already_set ) { PyErr_Print(); } catch( const std::exception &e ) { msg( Msg::Error, "ParameterisedProceduralWrap::doBound", e.what() ); } catch( ... ) { msg( Msg::Error, "ParameterisedProceduralWrap::doBound", "Caught unknown exception" ); } return Imath::Box3f(); // empty } virtual void doRender( RendererPtr r, ConstCompoundObjectPtr args ) const { // ideally we might not do any exception handling here, and always leave it to the host. // but in our case the host is mainly 3delight and that does no exception handling at all. try { override o = this->get_override( "doRender" ); if( o ) { o( r, boost::const_pointer_cast<CompoundObject>( args ) ); } else { msg( Msg::Error, "ParameterisedProceduralWrap::doRender", "doRender() python method not defined" ); } } catch( error_already_set ) { PyErr_Print(); } catch( const std::exception &e ) { msg( Msg::Error, "ParameterisedProceduralWrap::doRender", e.what() ); } catch( ... ) { msg( Msg::Error, "ParameterisedProceduralWrap::doRender", "Caught unknown exception" ); } } IE_COREPYTHON_RUNTIMETYPEDWRAPPERFNS( ParameterisedProcedural ); }; IE_CORE_DECLAREPTR( ParameterisedProceduralWrap ); static ParameterPtr parameterisedProceduralGetItem( ParameterisedProcedural &o, const std::string &n ) { ParameterPtr p = o.parameters()->parameter<Parameter>( n ); if( !p ) { throw Exception( std::string("Parameter ") + n + " doesn't exist" ); } return p; } void bindParameterisedProcedural() { RunTimeTypedClass<ParameterisedProcedural, ParameterisedProceduralWrapPtr>() .def( init<>() ) .def( init< const std::string >( arg( "description") ) ) .add_property( "description", make_function( &ParameterisedProcedural::description, return_value_policy<copy_const_reference>() ) ) .def( "parameters", (CompoundParameterPtr (ParameterisedProcedural::*)())&ParameterisedProcedural::parameters ) .def( "render", (void (ParameterisedProcedural::*)( RendererPtr ) const )&ParameterisedProcedural::render ) .def( "render", (void (ParameterisedProcedural::*)( RendererPtr, bool, bool, bool, bool ) const )&ParameterisedProcedural::render, ( arg( "renderer" ), arg( "inAttributeBlock" ) = true, arg( "withState" ) = true, arg( "withGeometry" ) = true, arg( "immediateGeometry" ) = false ) ) .def( "__getitem__", &parameterisedProceduralGetItem ) ; } } // namespace IECore <|endoftext|>
<commit_before>#include <iostream> #include <string> using std::cout; using std::endl; using std::string; bool hasUppercase(const string& str) { for (auto c : str) if (isupper(c)) return true; return false; } void makeLowercase(string& str) { for (auto& c : str) if (isupper(c)) c = tolower(c); } int main() { string str("Hello World!"); cout << hasUppercase(str) << endl; makeLowercase(str); cout << str << endl; return 0; } <commit_msg>improving #82<commit_after>#include <iostream> #include <string> using std::string; bool hasUppercase(const string& str) { for (auto c : str) if (isupper(c)) return true; return false; } const string& makeLowercase(string& str) { for (auto& c : str) if (isupper(c)) c = tolower(c); return str; } int main() { string str("Hello World!"); std::cout << std::boolalpha << hasUppercase(str) << std::endl; std::cout << makeLowercase(str) << std::endl; } <|endoftext|>
<commit_before>//---------------------------------------------------------------------------// //! //! \file tstGeneralEstimatorDimensionDiscretization.cpp //! \author Alex Robinson //! \brief General estimator dimension discretization unit tests //! //---------------------------------------------------------------------------// // Std Lib Includes #include <iostream> // Trilinos Includes #include <Teuchos_UnitTestHarness.hpp> #include <Teuchos_Array.hpp> #include <Teuchos_RCP.hpp> // FRENSIE Includes #include "MonteCarlo_GeneralEstimatorDimensionDiscretization.hpp" #include "MonteCarlo_PhaseSpaceDimensionTraits.hpp" #include "MonteCarlo_UnitTestHarnessExtensions.hpp" //---------------------------------------------------------------------------// // Instantiation Macros. //---------------------------------------------------------------------------// #define UNIT_TEST_INSTANTIATION( type, name ) \ using namespace MonteCarlo; \ TEUCHOS_UNIT_TEST_TEMPLATE_1_INSTANT( type, name, ENERGY_DIMENSION ) \ TEUCHOS_UNIT_TEST_TEMPLATE_1_INSTANT( type, name, COSINE_DIMENSION ) \ TEUCHOS_UNIT_TEST_TEMPLATE_1_INSTANT( type, name, TIME_DIMENSION ) \ TEUCHOS_UNIT_TEST_TEMPLATE_1_INSTANT( type, name, COLLISION_NUMBER_DIMENSION ) \ //---------------------------------------------------------------------------// // Testing Functions. //---------------------------------------------------------------------------// // Initialize an estimator dimension discretization pointer template<MonteCarlo::PhaseSpaceDimension dimension> void initialize( Teuchos::RCP<MonteCarlo::EstimatorDimensionDiscretization>& dimension_discretization, const bool add_discrete_lines ) { typedef MonteCarlo::PhaseSpaceDimensionTraits<dimension> EPSDT; Teuchos::Array<typename EPSDT::dimensionType> discretization( 4 ); if( add_discrete_lines ) discretization.resize( 9 ); discretization[0] = 0.0; discretization[1] = 1e-5; discretization[2] = 1e-4; discretization[3] = 1e-3; if( add_discrete_lines ) { discretization[4] = 1e-3; discretization[5] = 1e-2; discretization[6] = 1e-1; discretization[7] = 1e-1; discretization[8] = 1.0; } dimension_discretization.reset( new MonteCarlo::GeneralEstimatorDimensionDiscretization<dimension>( discretization ) ); } // Initialize an estimator dimension discretization point template<> void initialize<MonteCarlo::COLLISION_NUMBER_DIMENSION>( Teuchos::RCP<MonteCarlo::EstimatorDimensionDiscretization>& dimension_discretization, const bool ) { typedef MonteCarlo::PhaseSpaceDimensionTraits<MonteCarlo::COLLISION_NUMBER_DIMENSION> EPSDT; Teuchos::Array<typename EPSDT::dimensionType> discretization( 3 ); discretization[0] = 0; discretization[1] = 1; discretization[2] = std::numeric_limits<unsigned>::max(); dimension_discretization.reset( new MonteCarlo::GeneralEstimatorDimensionDiscretization<MonteCarlo::COLLISION_NUMBER_DIMENSION>( discretization ) ); } //---------------------------------------------------------------------------// // Tests. //---------------------------------------------------------------------------// // Check that the discretized dimension can be returned MC_UNIT_TEST_EPSD_TEMPLATE_1_DECL( GeneralEstimatorDimensionDiscretization, getDimension, dimension ) { Teuchos::RCP<MonteCarlo::EstimatorDimensionDiscretization> discretized_dimension; initialize<dimension>( discretized_dimension, false ); TEST_EQUALITY_CONST( discretized_dimension->getDimension(), dimension ); } UNIT_TEST_INSTANTIATION( GeneralEstimatorDimensionDiscretization, getDimension ); //---------------------------------------------------------------------------// // Check that the number of bins can be returned MC_UNIT_TEST_EPSD_TEMPLATE_1_DECL( GeneralEstimatorDimensionDiscretization, getNumberOfBins, dimension ) { Teuchos::RCP<MonteCarlo::EstimatorDimensionDiscretization> discretized_dimension; initialize<dimension>( discretized_dimension, false ); TEST_EQUALITY_CONST( discretized_dimension->getNumberOfBins(), 3u ); } UNIT_TEST_INSTANTIATION( GeneralEstimatorDimensionDiscretization, getNumberOfBins ); //---------------------------------------------------------------------------// // Check if a value is contained in the discretization MC_UNIT_TEST_EPSD_TEMPLATE_1_DECL( GeneralEstimatorDimensionDiscretization, isValueInDiscretization, dimension ) { Teuchos::RCP<MonteCarlo::EstimatorDimensionDiscretization> discretized_dimension; initialize<dimension>( discretized_dimension, false ); typedef MonteCarlo::PhaseSpaceDimensionTraits<dimension> EPSDT; typename EPSDT::dimensionType value_1, value_2, value_3, value_4; if( dimension != MonteCarlo::COLLISION_NUMBER_DIMENSION ) { value_1 = -1; value_2 = 0; value_3 = 1e-3; value_4 = 1e-2; TEST_ASSERT( !discretized_dimension->isValueInDiscretization( Teuchos::any( value_1 ) ) ); TEST_ASSERT( discretized_dimension->isValueInDiscretization( Teuchos::any( value_2 ) ) ); TEST_ASSERT( discretized_dimension->isValueInDiscretization( Teuchos::any( value_3 ) ) ); TEST_ASSERT( !discretized_dimension->isValueInDiscretization( Teuchos::any( value_4 ) ) ); } else { value_1 = 0; value_2 = 1; value_3 = 2; value_3 = -1; // max value TEST_ASSERT( discretized_dimension->isValueInDiscretization( Teuchos::any( value_1 ) ) ); TEST_ASSERT( discretized_dimension->isValueInDiscretization( Teuchos::any( value_2 ) ) ); TEST_ASSERT( discretized_dimension->isValueInDiscretization( Teuchos::any( value_3 ) ) ); TEST_ASSERT( discretized_dimension->isValueInDiscretization( Teuchos::any( value_4 ) ) ); } } UNIT_TEST_INSTANTIATION( GeneralEstimatorDimensionDiscretization, isValueInDiscretization ); //---------------------------------------------------------------------------// // Check that a bin index can be calculated MC_UNIT_TEST_EPSD_TEMPLATE_1_DECL( GeneralEstimatorDimensionDiscretization, calculateBinIndex, dimension ) { Teuchos::RCP<MonteCarlo::EstimatorDimensionDiscretization> discretized_dimension; initialize<dimension>( discretized_dimension, true ); typedef MonteCarlo::PhaseSpaceDimensionTraits<dimension> EPSDT; typename EPSDT::dimensionType value_1, value_2, value_3, value_4, value_5, value_6, value_7, value_8, value_9, value_10, value_11, value_12, value_13, value_14, value_15, value_16, value_17; if( dimension != MonteCarlo::COLLISION_NUMBER_DIMENSION ) { value_1 = 0.0; value_2 = 5e-6; value_3 = 1e-5; value_4 = 5e-5; value_5 = 1e-4; value_6 = 5e-4; value_7 = 9.9999999999999e-4; value_8 = 1e-3; value_9 = 1.0000000000001e-3; value_10 = 5e-3; value_11 = 1e-2; value_12 = 5e-2; value_13 = 9.999999999999e-2; value_14 = 1e-1; value_15 = 1.000000000001e-1; value_16 = 5e-1; value_17 = 1.0; TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_1 ) ), 0u ); TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_2 ) ), 0u ); TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_3 ) ), 0u ); TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_4 ) ), 1u ); TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_5 ) ), 1u ); TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_6 ) ), 2u ); TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_7 ) ), 2u ); TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_8 ) ), 3u ); TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_9 ) ), 4u ); TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_10 ) ), 4u ); TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_11 ) ), 4u ); TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_12 ) ), 5u ); TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_13 ) ), 5u ); TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_14 ) ), 6u ); TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_15 ) ), 7u ); TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_16 ) ), 7u ); TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_17 ) ), 7u ); } else { value_1 = 0; value_2 = 1; value_3 = 2; value_4 = -1; // max value TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_1 ) ), 0u ); TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_2 ) ), 1u ); TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_3 ) ), 2u ); TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_4 ) ), 2u ); } discretized_dimension->print( std::cout ); } UNIT_TEST_INSTANTIATION( GeneralEstimatorDimensionDiscretization, calculateBinIndex ); //---------------------------------------------------------------------------// // end tstGeneralEstimatorDimensionDiscretization.cpp //---------------------------------------------------------------------------// <commit_msg>Finished test the exportData member function in the estimator dimension discretization classes.<commit_after>//---------------------------------------------------------------------------// //! //! \file tstGeneralEstimatorDimensionDiscretization.cpp //! \author Alex Robinson //! \brief General estimator dimension discretization unit tests //! //---------------------------------------------------------------------------// // Std Lib Includes #include <iostream> #include <sstream> // Trilinos Includes #include <Teuchos_UnitTestHarness.hpp> #include <Teuchos_Array.hpp> #include <Teuchos_RCP.hpp> // FRENSIE Includes #include "MonteCarlo_GeneralEstimatorDimensionDiscretization.hpp" #include "MonteCarlo_PhaseSpaceDimensionTraits.hpp" #include "MonteCarlo_EstimatorHDF5FileHandler.hpp" #include "MonteCarlo_UnitTestHarnessExtensions.hpp" //---------------------------------------------------------------------------// // Instantiation Macros. //---------------------------------------------------------------------------// #define UNIT_TEST_INSTANTIATION( type, name ) \ using namespace MonteCarlo; \ TEUCHOS_UNIT_TEST_TEMPLATE_1_INSTANT( type, name, ENERGY_DIMENSION ) \ TEUCHOS_UNIT_TEST_TEMPLATE_1_INSTANT( type, name, COSINE_DIMENSION ) \ TEUCHOS_UNIT_TEST_TEMPLATE_1_INSTANT( type, name, TIME_DIMENSION ) \ TEUCHOS_UNIT_TEST_TEMPLATE_1_INSTANT( type, name, COLLISION_NUMBER_DIMENSION ) \ //---------------------------------------------------------------------------// // Testing Functions. //---------------------------------------------------------------------------// // Initialize an estimator dimension discretization pointer template<MonteCarlo::PhaseSpaceDimension dimension> void initialize( Teuchos::RCP<MonteCarlo::EstimatorDimensionDiscretization>& dimension_discretization, const bool add_discrete_lines ) { typedef MonteCarlo::PhaseSpaceDimensionTraits<dimension> EPSDT; Teuchos::Array<typename EPSDT::dimensionType> discretization( 4 ); if( add_discrete_lines ) discretization.resize( 9 ); discretization[0] = 0.0; discretization[1] = 1e-5; discretization[2] = 1e-4; discretization[3] = 1e-3; if( add_discrete_lines ) { discretization[4] = 1e-3; discretization[5] = 1e-2; discretization[6] = 1e-1; discretization[7] = 1e-1; discretization[8] = 1.0; } dimension_discretization.reset( new MonteCarlo::GeneralEstimatorDimensionDiscretization<dimension>( discretization ) ); } // Initialize an estimator dimension discretization point template<> void initialize<MonteCarlo::COLLISION_NUMBER_DIMENSION>( Teuchos::RCP<MonteCarlo::EstimatorDimensionDiscretization>& dimension_discretization, const bool ) { typedef MonteCarlo::PhaseSpaceDimensionTraits<MonteCarlo::COLLISION_NUMBER_DIMENSION> EPSDT; Teuchos::Array<typename EPSDT::dimensionType> discretization( 3 ); discretization[0] = 0; discretization[1] = 1; discretization[2] = std::numeric_limits<unsigned>::max(); dimension_discretization.reset( new MonteCarlo::GeneralEstimatorDimensionDiscretization<MonteCarlo::COLLISION_NUMBER_DIMENSION>( discretization ) ); } //---------------------------------------------------------------------------// // Tests. //---------------------------------------------------------------------------// // Check that the discretized dimension can be returned MC_UNIT_TEST_EPSD_TEMPLATE_1_DECL( GeneralEstimatorDimensionDiscretization, getDimension, dimension ) { Teuchos::RCP<MonteCarlo::EstimatorDimensionDiscretization> discretized_dimension; initialize<dimension>( discretized_dimension, false ); TEST_EQUALITY_CONST( discretized_dimension->getDimension(), dimension ); } UNIT_TEST_INSTANTIATION( GeneralEstimatorDimensionDiscretization, getDimension ); //---------------------------------------------------------------------------// // Check that the number of bins can be returned MC_UNIT_TEST_EPSD_TEMPLATE_1_DECL( GeneralEstimatorDimensionDiscretization, getNumberOfBins, dimension ) { Teuchos::RCP<MonteCarlo::EstimatorDimensionDiscretization> discretized_dimension; initialize<dimension>( discretized_dimension, false ); TEST_EQUALITY_CONST( discretized_dimension->getNumberOfBins(), 3u ); } UNIT_TEST_INSTANTIATION( GeneralEstimatorDimensionDiscretization, getNumberOfBins ); //---------------------------------------------------------------------------// // Check if a value is contained in the discretization MC_UNIT_TEST_EPSD_TEMPLATE_1_DECL( GeneralEstimatorDimensionDiscretization, isValueInDiscretization, dimension ) { Teuchos::RCP<MonteCarlo::EstimatorDimensionDiscretization> discretized_dimension; initialize<dimension>( discretized_dimension, false ); typedef MonteCarlo::PhaseSpaceDimensionTraits<dimension> EPSDT; typename EPSDT::dimensionType value_1, value_2, value_3, value_4; if( dimension != MonteCarlo::COLLISION_NUMBER_DIMENSION ) { value_1 = -1; value_2 = 0; value_3 = 1e-3; value_4 = 1e-2; TEST_ASSERT( !discretized_dimension->isValueInDiscretization( Teuchos::any( value_1 ) ) ); TEST_ASSERT( discretized_dimension->isValueInDiscretization( Teuchos::any( value_2 ) ) ); TEST_ASSERT( discretized_dimension->isValueInDiscretization( Teuchos::any( value_3 ) ) ); TEST_ASSERT( !discretized_dimension->isValueInDiscretization( Teuchos::any( value_4 ) ) ); } else { value_1 = 0; value_2 = 1; value_3 = 2; value_3 = -1; // max value TEST_ASSERT( discretized_dimension->isValueInDiscretization( Teuchos::any( value_1 ) ) ); TEST_ASSERT( discretized_dimension->isValueInDiscretization( Teuchos::any( value_2 ) ) ); TEST_ASSERT( discretized_dimension->isValueInDiscretization( Teuchos::any( value_3 ) ) ); TEST_ASSERT( discretized_dimension->isValueInDiscretization( Teuchos::any( value_4 ) ) ); } } UNIT_TEST_INSTANTIATION( GeneralEstimatorDimensionDiscretization, isValueInDiscretization ); //---------------------------------------------------------------------------// // Check that a bin index can be calculated MC_UNIT_TEST_EPSD_TEMPLATE_1_DECL( GeneralEstimatorDimensionDiscretization, calculateBinIndex, dimension ) { Teuchos::RCP<MonteCarlo::EstimatorDimensionDiscretization> discretized_dimension; initialize<dimension>( discretized_dimension, true ); typedef MonteCarlo::PhaseSpaceDimensionTraits<dimension> EPSDT; typename EPSDT::dimensionType value_1, value_2, value_3, value_4, value_5, value_6, value_7, value_8, value_9, value_10, value_11, value_12, value_13, value_14, value_15, value_16, value_17; if( dimension != MonteCarlo::COLLISION_NUMBER_DIMENSION ) { value_1 = 0.0; value_2 = 5e-6; value_3 = 1e-5; value_4 = 5e-5; value_5 = 1e-4; value_6 = 5e-4; value_7 = 9.9999999999999e-4; value_8 = 1e-3; value_9 = 1.0000000000001e-3; value_10 = 5e-3; value_11 = 1e-2; value_12 = 5e-2; value_13 = 9.999999999999e-2; value_14 = 1e-1; value_15 = 1.000000000001e-1; value_16 = 5e-1; value_17 = 1.0; TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_1 ) ), 0u ); TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_2 ) ), 0u ); TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_3 ) ), 0u ); TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_4 ) ), 1u ); TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_5 ) ), 1u ); TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_6 ) ), 2u ); TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_7 ) ), 2u ); TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_8 ) ), 3u ); TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_9 ) ), 4u ); TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_10 ) ), 4u ); TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_11 ) ), 4u ); TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_12 ) ), 5u ); TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_13 ) ), 5u ); TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_14 ) ), 6u ); TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_15 ) ), 7u ); TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_16 ) ), 7u ); TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_17 ) ), 7u ); } else { value_1 = 0; value_2 = 1; value_3 = 2; value_4 = -1; // max value TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_1 ) ), 0u ); TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_2 ) ), 1u ); TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_3 ) ), 2u ); TEST_EQUALITY_CONST( discretized_dimension->calculateBinIndex( Teuchos::any( value_4 ) ), 2u ); } discretized_dimension->print( std::cout ); } UNIT_TEST_INSTANTIATION( GeneralEstimatorDimensionDiscretization, calculateBinIndex ); //---------------------------------------------------------------------------// // Check that the bin boundaries can be exported MC_UNIT_TEST_EPSD_TEMPLATE_1_DECL( GeneralEstimatorDimensionDiscretization, exportData, dimension ) { // Set up the discretization typedef MonteCarlo::PhaseSpaceDimensionTraits<dimension> EPSDT; Teuchos::Array<typename EPSDT::dimensionType> discretization; if( dimension != MonteCarlo::COLLISION_NUMBER_DIMENSION ) { discretization.resize( 9 ); discretization[0] = 0.0; discretization[1] = 1e-5; discretization[2] = 1e-4; discretization[3] = 1e-3; discretization[4] = 1e-3; discretization[5] = 1e-2; discretization[6] = 1e-1; discretization[7] = 1e-1; discretization[8] = 1.0; } else { discretization.resize( 4 ); discretization[0] = 0u; discretization[1] = 1u; discretization[2] = 2u; discretization[3] = std::numeric_limits<unsigned>::max(); } Teuchos::RCP<MonteCarlo::EstimatorDimensionDiscretization> discretized_dimension( new MonteCarlo::GeneralEstimatorDimensionDiscretization<dimension>( discretization ) ); // Set up the EstimatorHDF5FileHandler std::ostringstream oss; oss << dimension << ".h5"; MonteCarlo::EstimatorHDF5FileHandler hdf5_file_handler( oss.str() ); discretized_dimension->exportData( 0u, hdf5_file_handler ); discretized_dimension->exportData( 10u, hdf5_file_handler ); // Make sure the data was written to the correct estimators Teuchos::Array<typename EPSDT::dimensionType> discretization_copy; hdf5_file_handler.getEstimatorBinBoundaries<dimension>( 0u, discretization_copy); TEST_COMPARE_ARRAYS( discretization, discretization_copy ); hdf5_file_handler.getEstimatorBinBoundaries<dimension>( 10u, discretization_copy); TEST_COMPARE_ARRAYS( discretization, discretization_copy ); TEST_THROW( hdf5_file_handler.getEstimatorBinBoundaries<dimension>( 1u, discretization_copy ), std::runtime_error ); } UNIT_TEST_INSTANTIATION( GeneralEstimatorDimensionDiscretization, exportData ); //---------------------------------------------------------------------------// // end tstGeneralEstimatorDimensionDiscretization.cpp //---------------------------------------------------------------------------// <|endoftext|>
<commit_before>//! @Alan @pezy //! //! Exercise 9.14: //! Write a program to assign the elements from a list of char* pointers //! to C-style character strings //! //! @Notice C-style character strings should use const char*, otherwise warning. //! #include <iostream> #include <string> #include <vector> #include <list> int main() { std::list<const char*> l{"Mooophy", "pezy", "Queeuqueg"}; std::vector<std::string> v; v.assign(l.cbegin(), l.cend()); for (const auto& ch : v) std::cout << ch << std::endl; return 0; } <commit_msg>Update ex9_14.cpp<commit_after>//! @Alan @pezy //! //! Exercise 9.14: //! Write a program to assign the elements from a list of char* (pointer //! to C-style character strings) to a vector of string. //! //! @Notice C-style character strings should use const char*, otherwise warning. //! #include <iostream> #include <string> #include <vector> #include <list> using namespace std; int main() { list<const char*> lst{"zhang", "zhi", "zhong"}; vector<string> svec; svec.assign(lst.cbegin(), lst.cend()); for(const auto &s : svec) cout<<s<<" "; cout<<endl; } <|endoftext|>
<commit_before>// // ex9_41.cpp // Exercise 9.41 // // Created by pezy on 12/4/14. // // @Brief Write a program that initializes a string from a vector<char>. #include <iostream> #include <vector> #include <string> using std::vector; using std::cout; using std::endl; using std::string; int main() { vector<char> vec{ 'p', 'e', 'z', 'y' }; string str(vec.begin(), vec.end()); cout << str << endl; return 0; } <commit_msg>Update ex9_41.cpp<commit_after>// // ex9_41.cpp // Exercise 9.41 // // Created by pezy on 12/4/14. // // @Brief Write a program that initializes a string from a vector<char>. #include <iostream> #include <vector> #include <string> using std::vector; using std::cout; using std::endl; using std::string; int main() { vector<char> v{ 'p', 'e', 'z', 'y' }; string str(v.cbegin(), v.cend()); cout << str << endl; return 0; } <|endoftext|>
<commit_before>#include "Engine.h" #include "Game.h" #include "ObjectDummy.h" #include "BodyRigid.h" #include "BodyDummy.h" #include "Physics.h" #include "ShapeCapsule.h" #include "ActorBase.h" #include "Visualizer.h" #include "sys/SysControl.h" using namespace MathLib; #ifdef MEMORY_INFO #define new new(__FILE__, __LINE__) #endif // MEMORY_INFO /* */ #define ACTOR_BASE_IFPS (1.0f / 60.0f) #define ACTOR_BASE_CLAMP 89.9f #define ACTOR_BASE_COLLISIONS 4 /* */ CActorBase::CActorBase() { m_vUp = vec3(0.0f, 0.0f, 1.0f); m_pObject = new CObjectDummy(); m_pDummy = new CBodyDummy(); m_pShape = new CShapeCapsule(1.0f, 1.0f); m_nFlush = 0; m_vPosition = Vec3_zero; m_vVelocity = Vec3_zero; m_fPhiAngle = 0.0f; //倾斜角 二维平面坐标系中,直线向Y周延伸的方向与X轴正向之间的夹角 m_fThetaAngle = 0.0f; //方位角,正北方那条线与当前线条按照顺时针走过的角度 for (int i = 0; i < NUM_STATES; i++) { m_pStates[i] = 0; m_pTimes[i] = 0.0f; } m_pDummy->SetEnabled(1); m_pObject->SetBody(NULL); m_pObject->SetBody(m_pDummy); m_pShape->SetBody(NULL); m_pShape->SetBody(m_pDummy); m_pObject->SetWorldTransform(Get_Body_Transform()); m_pShape->SetRestitution(0.0f); m_pShape->SetCollisionMask(2); SetEnabled(1); SetViewDirection(vec3(0.0f, 1.0f, 0.0f)); SetCollision(1); SetCollisionRadius(0.3f); SetCollisionHeight(1.0f); SetFriction(2.0f); SetMinVelocity(2.0f); SetMaxVelocity(4.0f); SetAcceleration(8.0f); SetDamping(8.0f); SetJumping(1.5f); SetGround(0); SetCeiling(0); } CActorBase::~CActorBase() { m_pDummy->SetObject(NULL); delete m_pObject; delete m_pDummy; } void CActorBase::SetEnabled(int enable) { m_nEnable = enable; m_pDummy->SetEnabled(m_nEnable); } int CActorBase::IsEnabled() const { return m_nEnable; } void CActorBase::Update(float ifps) { if (!m_nEnable) { return; } // impulse vec3 impulse = vec3_zero; // ortho basis vec3 tangent, binormal; OrthoBasis(m_vUp, tangent, binormal); // current basis vec3 x = quat(m_vUp, -m_fPhiAngle) * binormal; vec3 y = Normalize(Cross(m_vUp, x)); vec3 z = Normalize(Cross(x, y)); handle states Update_States(1, ifps); // old velocity float x_velocity = Dot(x, m_vVelocity); float y_velocity = Dot(y, m_vVelocity); float z_velocity = Dot(z, m_vVelocity); // movement if (m_pStates[STATE_FORWARD]) impulse += x; if (m_pStates[STATE_BACKWARD]) impulse -= x; if (m_pStates[STATE_MOVE_LEFT]) impulse += y; if (m_pStates[STATE_MOVE_RIGHT]) impulse -= y; impulse.normalize(); //velocity if (m_pStates[STATE_RUN]) impulse *= m_fMaxVelocity; else impulse *= m_fMinVelocity; // jump if (m_pStates[STATE_JUMP] == STATE_BEGIN) { impulse += z * CMathCore::Sqrt(2.0f * 9.8f * m_fJumping) / (m_fAcceleration * ifps); } // rotate velocity if (GetGround()) { m_vVelocity = x * x_velocity + y * y_velocity + z * z_velocity; } // time float time = ifps * g_Engine.pPhysics->GetScale(); // target velocity float target_velocity = Length(vec2(Dot(x, impulse), Dot(y, impulse))); // penetration tolerance float penetration = g_Engine.pPhysics->GetPenetrationTolerance(); float penetration_2 = penetration * 2.0f; // frozen linear velocity float frozen_velocity = g_Engine.pPhysics->GetFrozenLinearVelocity(); // friction float friction = 0.0f; if (target_velocity < EPSILON) { friction = m_fFriction; } //clear collision flags if (GetCollision()) { m_nGround = 0; m_nCeiling = 0; } // movement do { // adaptive time step float ifps = Min(time, ACTOR_BASE_IFPS); time -= ifps; // save old velocity float old_velocity = Length(vec2(Dot(x, m_vVelocity), Dot(y, m_vVelocity))); // integrate velocity m_vVelocity += impulse * (m_fAcceleration * ifps); m_vVelocity += g_Engine.pPhysics->GetGravity() * ifps; // damping float current_velocity = Length(vec2(Dot(x, m_vVelocity), Dot(y, m_vVelocity))); if (target_velocity < EPSILON || current_velocity > target_velocity) { m_vVelocity = (x * Dot(x, m_vVelocity) + y * Dot(y, m_vVelocity)) * CMathCore::Exp(-m_fDamping * ifps) + z * Dot(z, m_vVelocity); } // clamp maximum velocity current_velocity = Length(vec2(Dot(x, m_vVelocity), Dot(y, m_vVelocity))); if (current_velocity > old_velocity) { if (current_velocity > target_velocity) { m_vVelocity = (x * Dot(x, m_vVelocity) + y * Dot(y, m_vVelocity)) * target_velocity / current_velocity + z * Dot(z, m_vVelocity); } } // frozen velocity int is_frozen = 0; if (current_velocity < frozen_velocity) { m_vVelocity = z * Dot(z, m_vVelocity); is_frozen = 1; } // integrate position //m_vPosition += Vec3(m_vVelocity * ifps); // world collision if (GetCollision()) { // get collision vec3 tangent, binormal; const Vec3 *caps = m_pShape->GetCaps(); for (int i = 0; i < ACTOR_BASE_COLLISIONS; i++) { m_pDummy->SetTransform(Get_Body_Transform()); m_pShape->GetCollision(m_vecContacts, 0.0f); if (m_vecContacts.Size() == 0) break; float inum_contacts = 1.0f / CMathCore::Itof(m_vecContacts.Size()); for (int j = 0; j < m_vecContacts.Size(); j++) { const CShape::Contact &c = m_vecContacts[j]; vec3 normalCollision = c.normal; if (is_frozen && c.depth < penetration_2) { m_vPosition += Vec3(z * (Max(c.depth - penetration, 0.0f) * inum_contacts * Dot(z, normalCollision))); } else { m_vPosition += Vec3(normalCollision * (Max(c.depth - penetration, 0.0f) * inum_contacts)); is_frozen = 0; } float normal_velocity = Dot(normalCollision, m_vVelocity); if (normal_velocity < 0.0f) { m_vVelocity -= normalCollision * normal_velocity; } if (friction > EPSILON) { OrthoBasis(c.normal, tangent, binormal); float tangent_velocity = Dot(tangent, m_vVelocity); float binormal_velocity = Dot(binormal, m_vVelocity); if (CMathCore::Abs(tangent_velocity) > EPSILON || CMathCore::Abs(binormal_velocity) > EPSILON) { float friction_velocity = Clamp(Max(-normal_velocity, 0.0f) * friction * CMathCore::RSqrt(tangent_velocity * tangent_velocity + binormal_velocity * binormal_velocity), -1.0f, 1.0f); m_vVelocity -= tangent * tangent_velocity * friction_velocity; m_vVelocity -= binormal * binormal_velocity * friction_velocity; } } if (Dot(c.normal, m_vUp) > 0.5f && Dot(vec3(c.point - caps[0]), m_vUp) < 0.0f) m_nGround = 1; if (Dot(c.normal, m_vUp) < -0.5f && Dot(vec3(c.point - caps[1]), m_vUp) > 0.0f) m_nCeiling = 1; } } m_vPosition += Vec3(m_vVelocity * ifps); } while (time > EPSILON); // current position m_pObject->SetWorldTransform(Get_Body_Transform()); m_WorldBoundBox.Set(m_BoundBox, Translate(m_vPosition)); m_WorldBoundSphere.Set(m_BoundSphere, Translate(m_vPosition)); } } /* */ void CActorBase::Update_Bounds() { float radius = m_pShape->GetRadius(); float hheight = m_pShape->GetHHeight(); m_BoundBox.Set(vec3(-radius, -radius, 0.0f), vec3(radius, radius, (radius + hheight) * 2.0f)); m_BoundSphere.Set(vec3(0.0f, 0.0f, radius + hheight), radius + hheight); m_WorldBoundBox.Set(m_BoundBox, Translate(m_vPosition)); m_WorldBoundSphere.Set(m_BoundSphere, Translate(m_vPosition)); } /* */ void CActorBase::SetIntersectionMask(int mask) { m_pShape->SetIntersectionMask(mask); } int CActorBase::GetIntersectionMask() const { return m_pShape->GetIntersectionMask(); } /* */ void CActorBase::SetCollision(int c) { m_nCollision = c; } int CActorBase::GetCollision() const { return m_nCollision; } void CActorBase::SetCollisionMask(int mask) { m_pShape->SetCollisionMask(mask); } int CActorBase::GetCollisionMask() const { return m_pShape->GetCollisionMask(); } void CActorBase::SetCollisionRadius(float radius) { if (!Compare(m_pShape->GetRadius(), radius)) { m_pDummy->SetPreserveTransform(Mat4(Translate(m_vUp * (radius - m_pShape->GetRadius()))) * m_pDummy->GetTransform()); m_pShape->SetRadius(radius); } Update_Bounds(); } float CActorBase::GetCollisionRadius() const { return m_pShape->GetRadius(); } /* */ void CActorBase::SetCollisionHeight(float height) { if (!Compare(m_pShape->GetHeight(), height)) { m_pDummy->SetPreserveTransform(Mat4(Translate(m_vUp * (height - m_pShape->GetHeight()) * 0.5f)) * m_pDummy->GetTransform()); m_pShape->SetHeight(height); } Update_Bounds(); } float CActorBase::GetCollisionHeight() const { return m_pShape->GetHeight(); } void CActorBase::SetMinVelocity(float velocity) { m_fMinVelocity = Max(velocity, 0.0f); } float CActorBase::GetMinVelocity() const { return m_fMinVelocity; }<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "Engine.h" #include "Game.h" #include "ObjectDummy.h" #include "BodyRigid.h" #include "BodyDummy.h" #include "Physics.h" #include "ShapeCapsule.h" #include "ActorBase.h" #include "Visualizer.h" #include "sys/SysControl.h" using namespace MathLib; #ifdef MEMORY_INFO #define new new(__FILE__, __LINE__) #endif // MEMORY_INFO /* */ #define ACTOR_BASE_IFPS (1.0f / 60.0f) #define ACTOR_BASE_CLAMP 89.9f #define ACTOR_BASE_COLLISIONS 4 /* */ CActorBase::CActorBase() { m_vUp = vec3(0.0f, 0.0f, 1.0f); m_pObject = new CObjectDummy(); m_pDummy = new CBodyDummy(); m_pShape = new CShapeCapsule(1.0f, 1.0f); m_nFlush = 0; m_vPosition = Vec3_zero; m_vVelocity = Vec3_zero; m_fPhiAngle = 0.0f; //倾斜角 二维平面坐标系中,直线向Y周延伸的方向与X轴正向之间的夹角 m_fThetaAngle = 0.0f; //方位角,正北方那条线与当前线条按照顺时针走过的角度 for (int i = 0; i < NUM_STATES; i++) { m_pStates[i] = 0; m_pTimes[i] = 0.0f; } m_pDummy->SetEnabled(1); m_pObject->SetBody(NULL); m_pObject->SetBody(m_pDummy); m_pShape->SetBody(NULL); m_pShape->SetBody(m_pDummy); m_pObject->SetWorldTransform(Get_Body_Transform()); m_pShape->SetRestitution(0.0f); m_pShape->SetCollisionMask(2); SetEnabled(1); SetViewDirection(vec3(0.0f, 1.0f, 0.0f)); SetCollision(1); SetCollisionRadius(0.3f); SetCollisionHeight(1.0f); SetFriction(2.0f); SetMinVelocity(2.0f); SetMaxVelocity(4.0f); SetAcceleration(8.0f); SetDamping(8.0f); SetJumping(1.5f); SetGround(0); SetCeiling(0); } CActorBase::~CActorBase() { m_pDummy->SetObject(NULL); delete m_pObject; delete m_pDummy; } void CActorBase::SetEnabled(int enable) { m_nEnable = enable; m_pDummy->SetEnabled(m_nEnable); } int CActorBase::IsEnabled() const { return m_nEnable; } void CActorBase::Update(float ifps) { if (!m_nEnable) { return; } // impulse vec3 impulse = vec3_zero; // ortho basis vec3 tangent, binormal; OrthoBasis(m_vUp, tangent, binormal); // current basis vec3 x = quat(m_vUp, -m_fPhiAngle) * binormal; vec3 y = Normalize(Cross(m_vUp, x)); vec3 z = Normalize(Cross(x, y)); handle states Update_States(1, ifps); // old velocity float x_velocity = Dot(x, m_vVelocity); float y_velocity = Dot(y, m_vVelocity); float z_velocity = Dot(z, m_vVelocity); // movement if (m_pStates[STATE_FORWARD]) impulse += x; if (m_pStates[STATE_BACKWARD]) impulse -= x; if (m_pStates[STATE_MOVE_LEFT]) impulse += y; if (m_pStates[STATE_MOVE_RIGHT]) impulse -= y; impulse.normalize(); //velocity if (m_pStates[STATE_RUN]) impulse *= m_fMaxVelocity; else impulse *= m_fMinVelocity; // jump if (m_pStates[STATE_JUMP] == STATE_BEGIN) { impulse += z * CMathCore::Sqrt(2.0f * 9.8f * m_fJumping) / (m_fAcceleration * ifps); } // rotate velocity if (GetGround()) { m_vVelocity = x * x_velocity + y * y_velocity + z * z_velocity; } // time float time = ifps * g_Engine.pPhysics->GetScale(); // target velocity float target_velocity = Length(vec2(Dot(x, impulse), Dot(y, impulse))); // penetration tolerance float penetration = g_Engine.pPhysics->GetPenetrationTolerance(); float penetration_2 = penetration * 2.0f; // frozen linear velocity float frozen_velocity = g_Engine.pPhysics->GetFrozenLinearVelocity(); // friction float friction = 0.0f; if (target_velocity < EPSILON) { friction = m_fFriction; } //clear collision flags if (GetCollision()) { m_nGround = 0; m_nCeiling = 0; } // movement do { // adaptive time step float ifps = Min(time, ACTOR_BASE_IFPS); time -= ifps; // save old velocity float old_velocity = Length(vec2(Dot(x, m_vVelocity), Dot(y, m_vVelocity))); // integrate velocity m_vVelocity += impulse * (m_fAcceleration * ifps); m_vVelocity += g_Engine.pPhysics->GetGravity() * ifps; // damping float current_velocity = Length(vec2(Dot(x, m_vVelocity), Dot(y, m_vVelocity))); if (target_velocity < EPSILON || current_velocity > target_velocity) { m_vVelocity = (x * Dot(x, m_vVelocity) + y * Dot(y, m_vVelocity)) * CMathCore::Exp(-m_fDamping * ifps) + z * Dot(z, m_vVelocity); } // clamp maximum velocity current_velocity = Length(vec2(Dot(x, m_vVelocity), Dot(y, m_vVelocity))); if (current_velocity > old_velocity) { if (current_velocity > target_velocity) { m_vVelocity = (x * Dot(x, m_vVelocity) + y * Dot(y, m_vVelocity)) * target_velocity / current_velocity + z * Dot(z, m_vVelocity); } } // frozen velocity int is_frozen = 0; if (current_velocity < frozen_velocity) { m_vVelocity = z * Dot(z, m_vVelocity); is_frozen = 1; } // integrate position //m_vPosition += Vec3(m_vVelocity * ifps); // world collision if (GetCollision()) { // get collision vec3 tangent, binormal; const Vec3 *caps = m_pShape->GetCaps(); for (int i = 0; i < ACTOR_BASE_COLLISIONS; i++) { m_pDummy->SetTransform(Get_Body_Transform()); m_pShape->GetCollision(m_vecContacts, 0.0f); if (m_vecContacts.Size() == 0) break; float inum_contacts = 1.0f / CMathCore::Itof(m_vecContacts.Size()); for (int j = 0; j < m_vecContacts.Size(); j++) { const CShape::Contact &c = m_vecContacts[j]; vec3 normalCollision = c.normal; if (is_frozen && c.depth < penetration_2) { m_vPosition += Vec3(z * (Max(c.depth - penetration, 0.0f) * inum_contacts * Dot(z, normalCollision))); } else { m_vPosition += Vec3(normalCollision * (Max(c.depth - penetration, 0.0f) * inum_contacts)); is_frozen = 0; } float normal_velocity = Dot(normalCollision, m_vVelocity); if (normal_velocity < 0.0f) { m_vVelocity -= normalCollision * normal_velocity; } if (friction > EPSILON) { OrthoBasis(c.normal, tangent, binormal); float tangent_velocity = Dot(tangent, m_vVelocity); float binormal_velocity = Dot(binormal, m_vVelocity); if (CMathCore::Abs(tangent_velocity) > EPSILON || CMathCore::Abs(binormal_velocity) > EPSILON) { float friction_velocity = Clamp(Max(-normal_velocity, 0.0f) * friction * CMathCore::RSqrt(tangent_velocity * tangent_velocity + binormal_velocity * binormal_velocity), -1.0f, 1.0f); m_vVelocity -= tangent * tangent_velocity * friction_velocity; m_vVelocity -= binormal * binormal_velocity * friction_velocity; } } if (Dot(c.normal, m_vUp) > 0.5f && Dot(vec3(c.point - caps[0]), m_vUp) < 0.0f) m_nGround = 1; if (Dot(c.normal, m_vUp) < -0.5f && Dot(vec3(c.point - caps[1]), m_vUp) > 0.0f) m_nCeiling = 1; } } m_vPosition += Vec3(m_vVelocity * ifps); } while (time > EPSILON); // current position m_pObject->SetWorldTransform(Get_Body_Transform()); m_WorldBoundBox.Set(m_BoundBox, Translate(m_vPosition)); m_WorldBoundSphere.Set(m_BoundSphere, Translate(m_vPosition)); } } /* */ void CActorBase::Update_Bounds() { float radius = m_pShape->GetRadius(); float hheight = m_pShape->GetHHeight(); m_BoundBox.Set(vec3(-radius, -radius, 0.0f), vec3(radius, radius, (radius + hheight) * 2.0f)); m_BoundSphere.Set(vec3(0.0f, 0.0f, radius + hheight), radius + hheight); m_WorldBoundBox.Set(m_BoundBox, Translate(m_vPosition)); m_WorldBoundSphere.Set(m_BoundSphere, Translate(m_vPosition)); } /* */ void CActorBase::SetIntersectionMask(int mask) { m_pShape->SetIntersectionMask(mask); } int CActorBase::GetIntersectionMask() const { return m_pShape->GetIntersectionMask(); } /* */ void CActorBase::SetCollision(int c) { m_nCollision = c; } int CActorBase::GetCollision() const { return m_nCollision; } void CActorBase::SetCollisionMask(int mask) { m_pShape->SetCollisionMask(mask); } int CActorBase::GetCollisionMask() const { return m_pShape->GetCollisionMask(); } void CActorBase::SetCollisionRadius(float radius) { if (!Compare(m_pShape->GetRadius(), radius)) { m_pDummy->SetPreserveTransform(Mat4(Translate(m_vUp * (radius - m_pShape->GetRadius()))) * m_pDummy->GetTransform()); m_pShape->SetRadius(radius); } Update_Bounds(); } float CActorBase::GetCollisionRadius() const { return m_pShape->GetRadius(); } /* */ void CActorBase::SetCollisionHeight(float height) { if (!Compare(m_pShape->GetHeight(), height)) { m_pDummy->SetPreserveTransform(Mat4(Translate(m_vUp * (height - m_pShape->GetHeight()) * 0.5f)) * m_pDummy->GetTransform()); m_pShape->SetHeight(height); } Update_Bounds(); } float CActorBase::GetCollisionHeight() const { return m_pShape->GetHeight(); } void CActorBase::SetMinVelocity(float velocity) { m_fMinVelocity = Max(velocity, 0.0f); } float CActorBase::GetMinVelocity() const { return m_fMinVelocity; } /* */ void CActorBase::SetMaxVelocity(float velocity) { m_fMaxVelocity = Max(velocity, 0.0f); }<|endoftext|>
<commit_before>/*========================================================================== Program: Module: otherTimerLog.cxx Language: C++ Date: $Date$ Version: $Revision$ ==========================================================================*/ // .NAME // .SECTION Description // this program tests the TimerLog #include <stdio.h> #include "vtkTimerLog.h" #include "vtkDebugLeaks.h" void Test(ostream& strm) { // actual test float a = 1.0, b = 2.0; int i, j; strm << "Test vtkTimerLog Start" << endl; vtkTimerLog *timer1 = vtkTimerLog::New(); timer1->SetMaxEntries (5); timer1->StartTimer(); for (j = 0; j < 10; j++) { timer1->FormatAndMarkEvent("%s%d", "start", j); for (i = 0; i < 10000000; i++) { a *= b; } #ifndef WIN32 sleep (1); #else Sleep(1000); #endif timer1->FormatAndMarkEvent("%s%d", "end", j); } timer1->StopTimer(); strm << "GetElapsedTime: " << timer1->GetElapsedTime() << endl; strm << "GetCPUTime: " << timer1->GetCPUTime() << endl; timer1->DumpLog( "timing" ); timer1->ResetLog (); unlink("timing"); timer1->Delete(); strm << "Test vtkTimerLog End" << endl; } int main(int argc, char* argv[]) { vtkDebugLeaks::PromptUserOff(); Test(cout); return 0; } <commit_msg>ENH: better coverage.<commit_after>/*========================================================================== Program: Module: otherTimerLog.cxx Language: C++ Date: $Date$ Version: $Revision$ ==========================================================================*/ // .NAME // .SECTION Description // this program tests the TimerLog #include <stdio.h> #include "vtkTimerLog.h" #include "vtkDebugLeaks.h" void Test(ostream& strm) { // actual test float a = 1.0, b = 2.0; int i, j; strm << "Test vtkTimerLog Start" << endl; vtkTimerLog *timer1 = vtkTimerLog::New(); timer1->SetMaxEntries (3); timer1->StartTimer(); for (j = 0; j < 10; j++) { timer1->FormatAndMarkEvent("%s%d", "start", j); for (i = 0; i < 10000000; i++) { a *= b; } #ifndef WIN32 sleep (1); #else Sleep(1000); #endif timer1->FormatAndMarkEvent("%s%d", "end", j); } timer1->StopTimer(); strm << *timer1; strm << "GetElapsedTime: " << timer1->GetElapsedTime() << endl; strm << "GetCPUTime: " << timer1->GetCPUTime() << endl; timer1->DumpLog( "timing" ); timer1->ResetLog (); unlink("timing"); timer1->Delete(); strm << "Test vtkTimerLog End" << endl; } int main(int argc, char* argv[]) { vtkDebugLeaks::PromptUserOff(); Test(cout); return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Bitsend developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "core.h" #include "util.h" #include "main.h" #include "uint256.h" std::string COutPoint::ToString() const { return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,64), n); } void COutPoint::print() const { LogPrintf("%s\n", ToString()); } CTxIn::CTxIn(COutPoint prevoutIn, CScript scriptSigIn, unsigned int nSequenceIn) { prevout = prevoutIn; scriptSig = scriptSigIn; nSequence = nSequenceIn; } CTxIn::CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn, unsigned int nSequenceIn) { prevout = COutPoint(hashPrevTx, nOut); scriptSig = scriptSigIn; nSequence = nSequenceIn; } std::string CTxIn::ToString() const { std::string str; str += "CTxIn("; str += prevout.ToString(); if (prevout.IsNull()) str += strprintf(", coinbase %s", HexStr(scriptSig)); else str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24)); if (nSequence != std::numeric_limits<unsigned int>::max()) str += strprintf(", nSequence=%u", nSequence); str += ")"; return str; } void CTxIn::print() const { LogPrintf("%s\n", ToString()); } CTxOut::CTxOut(int64_t nValueIn, CScript scriptPubKeyIn) { nValue = nValueIn; nRounds = -10; // an initial value, should be no way to get this by calculations scriptPubKey = scriptPubKeyIn; } uint256 CTxOut::GetHash() const { return SerializeHash(*this); } std::string CTxOut::ToString() const { return strprintf("CTxOut(nValue=%d.%08d, scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30)); } void CTxOut::print() const { LogPrintf("%s\n", ToString()); } uint256 CTransaction::GetHash() const { return SerializeHash(*this); } bool CTransaction::IsNewerThan(const CTransaction& old) const { if (vin.size() != old.vin.size()) return false; for (unsigned int i = 0; i < vin.size(); i++) if (vin[i].prevout != old.vin[i].prevout) return false; bool fNewer = false; unsigned int nLowest = std::numeric_limits<unsigned int>::max(); for (unsigned int i = 0; i < vin.size(); i++) { if (vin[i].nSequence != old.vin[i].nSequence) { if (vin[i].nSequence <= nLowest) { fNewer = false; nLowest = vin[i].nSequence; } if (old.vin[i].nSequence < nLowest) { fNewer = true; nLowest = old.vin[i].nSequence; } } } return fNewer; } int64_t CTransaction::GetValueOut() const { int64_t nValueOut = 0; BOOST_FOREACH(const CTxOut& txout, vout) { nValueOut += txout.nValue; if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut)) throw std::runtime_error("CTransaction::GetValueOut() : value out of range"); } return nValueOut; } double CTransaction::ComputePriority(double dPriorityInputs, unsigned int nTxSize) const { // In order to avoid disincentivizing cleaning up the UTXO set we don't count // the constant overhead for each txin and up to 110 bytes of scriptSig (which // is enough to cover a compressed pubkey p2sh redemption) for priority. // Providing any more cleanup incentive than making additional inputs free would // risk encouraging people to create junk outputs to redeem later. if (nTxSize == 0) nTxSize = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION); BOOST_FOREACH(const CTxIn& txin, vin) { unsigned int offset = 41U + std::min(110U, (unsigned int)txin.scriptSig.size()); if (nTxSize > offset) nTxSize -= offset; } if (nTxSize == 0) return 0.0; return dPriorityInputs / nTxSize; } std::string CTransaction::ToString() const { std::string str; str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%u, vout.size=%u, nLockTime=%u)\n", GetHash().ToString().substr(0,10), nVersion, vin.size(), vout.size(), nLockTime); for (unsigned int i = 0; i < vin.size(); i++) str += " " + vin[i].ToString() + "\n"; for (unsigned int i = 0; i < vout.size(); i++) str += " " + vout[i].ToString() + "\n"; return str; } void CTransaction::print() const { LogPrintf("%s", ToString()); } // Amount compression: // * If the amount is 0, output 0 // * first, divide the amount (in base units) by the largest power of 10 possible; call the exponent e (e is max 9) // * if e<9, the last digit of the resulting number cannot be 0; store it as d, and drop it (divide by 10) // * call the result n // * output 1 + 10*(9*n + d - 1) + e // * if e==9, we only know the resulting number is not zero, so output 1 + 10*(n - 1) + 9 // (this is decodable, as d is in [1-9] and e is in [0-9]) uint64_t CTxOutCompressor::CompressAmount(uint64_t n) { if (n == 0) return 0; int e = 0; while (((n % 10) == 0) && e < 9) { n /= 10; e++; } if (e < 9) { int d = (n % 10); assert(d >= 1 && d <= 9); n /= 10; return 1 + (n*9 + d - 1)*10 + e; } else { return 1 + (n - 1)*10 + 9; } } uint64_t CTxOutCompressor::DecompressAmount(uint64_t x) { // x = 0 OR x = 1+10*(9*n + d - 1) + e OR x = 1+10*(n - 1) + 9 if (x == 0) return 0; x--; // x = 10*(9*n + d - 1) + e int e = x % 10; x /= 10; uint64_t n = 0; if (e < 9) { // x = 9*n + d - 1 int d = (x % 9) + 1; x /= 9; // x = n n = x*10 + d; } else { n = x+1; } while (e) { n *= 10; e--; } return n; } //BitSend Algoswitch 1 uint256 CBlockHeader::GetHash() const { CChain var1; int nHeight= var1.Height(); if (nHeight <= FORKX17_Main_Net){ //Debugline BitSendDev if(nHeight > 0) LogPrintf("%d nHeigt We use X11\n", nHeight); return HashX11(BEGIN(nVersion), END(nNonce)); } else { if(nHeight > 0 ) LogPrintf("%d nHeigt We use X17\n", nHeight); return HashX17(BEGIN(nVersion), END(nNonce)); } } /* uint256 CBlockHeader::GetHash() const { return HashX11(BEGIN(nVersion), END(nNonce)); } */ uint256 CBlock::BuildMerkleTree() const { vMerkleTree.clear(); BOOST_FOREACH(const CTransaction& tx, vtx) vMerkleTree.push_back(tx.GetHash()); int j = 0; for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2) { for (int i = 0; i < nSize; i += 2) { int i2 = std::min(i+1, nSize-1); vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]), BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2]))); } j += nSize; } return (vMerkleTree.empty() ? 0 : vMerkleTree.back()); } std::vector<uint256> CBlock::GetMerkleBranch(int nIndex) const { if (vMerkleTree.empty()) BuildMerkleTree(); std::vector<uint256> vMerkleBranch; int j = 0; for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2) { int i = std::min(nIndex^1, nSize-1); vMerkleBranch.push_back(vMerkleTree[j+i]); nIndex >>= 1; j += nSize; } return vMerkleBranch; } uint256 CBlock::CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex) { if (nIndex == -1) return 0; BOOST_FOREACH(const uint256& otherside, vMerkleBranch) { if (nIndex & 1) hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash)); else hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside)); nIndex >>= 1; } return hash; } void CBlock::print() const { //GetHash2().ToString(), LogPrintf("CBlock(hash=disable, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%u)\n", nVersion, hashPrevBlock.ToString(), hashMerkleRoot.ToString(), nTime, nBits, nNonce, vtx.size()); for (unsigned int i = 0; i < vtx.size(); i++) { LogPrintf(" "); vtx[i].print(); } LogPrintf(" vMerkleTree: "); for (unsigned int i = 0; i < vMerkleTree.size(); i++) LogPrintf("%s ", vMerkleTree[i].ToString()); LogPrintf("\n"); } <commit_msg>Revert "Commit"<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Bitsend developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "core.h" #include "util.h" #include "main.h" #include "uint256.h" std::string COutPoint::ToString() const { return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,64), n); } void COutPoint::print() const { LogPrintf("%s\n", ToString()); } CTxIn::CTxIn(COutPoint prevoutIn, CScript scriptSigIn, unsigned int nSequenceIn) { prevout = prevoutIn; scriptSig = scriptSigIn; nSequence = nSequenceIn; } CTxIn::CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn, unsigned int nSequenceIn) { prevout = COutPoint(hashPrevTx, nOut); scriptSig = scriptSigIn; nSequence = nSequenceIn; } std::string CTxIn::ToString() const { std::string str; str += "CTxIn("; str += prevout.ToString(); if (prevout.IsNull()) str += strprintf(", coinbase %s", HexStr(scriptSig)); else str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24)); if (nSequence != std::numeric_limits<unsigned int>::max()) str += strprintf(", nSequence=%u", nSequence); str += ")"; return str; } void CTxIn::print() const { LogPrintf("%s\n", ToString()); } CTxOut::CTxOut(int64_t nValueIn, CScript scriptPubKeyIn) { nValue = nValueIn; nRounds = -10; // an initial value, should be no way to get this by calculations scriptPubKey = scriptPubKeyIn; } uint256 CTxOut::GetHash() const { return SerializeHash(*this); } std::string CTxOut::ToString() const { return strprintf("CTxOut(nValue=%d.%08d, scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30)); } void CTxOut::print() const { LogPrintf("%s\n", ToString()); } uint256 CTransaction::GetHash() const { return SerializeHash(*this); } bool CTransaction::IsNewerThan(const CTransaction& old) const { if (vin.size() != old.vin.size()) return false; for (unsigned int i = 0; i < vin.size(); i++) if (vin[i].prevout != old.vin[i].prevout) return false; bool fNewer = false; unsigned int nLowest = std::numeric_limits<unsigned int>::max(); for (unsigned int i = 0; i < vin.size(); i++) { if (vin[i].nSequence != old.vin[i].nSequence) { if (vin[i].nSequence <= nLowest) { fNewer = false; nLowest = vin[i].nSequence; } if (old.vin[i].nSequence < nLowest) { fNewer = true; nLowest = old.vin[i].nSequence; } } } return fNewer; } int64_t CTransaction::GetValueOut() const { int64_t nValueOut = 0; BOOST_FOREACH(const CTxOut& txout, vout) { nValueOut += txout.nValue; if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut)) throw std::runtime_error("CTransaction::GetValueOut() : value out of range"); } return nValueOut; } double CTransaction::ComputePriority(double dPriorityInputs, unsigned int nTxSize) const { // In order to avoid disincentivizing cleaning up the UTXO set we don't count // the constant overhead for each txin and up to 110 bytes of scriptSig (which // is enough to cover a compressed pubkey p2sh redemption) for priority. // Providing any more cleanup incentive than making additional inputs free would // risk encouraging people to create junk outputs to redeem later. if (nTxSize == 0) nTxSize = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION); BOOST_FOREACH(const CTxIn& txin, vin) { unsigned int offset = 41U + std::min(110U, (unsigned int)txin.scriptSig.size()); if (nTxSize > offset) nTxSize -= offset; } if (nTxSize == 0) return 0.0; return dPriorityInputs / nTxSize; } std::string CTransaction::ToString() const { std::string str; str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%u, vout.size=%u, nLockTime=%u)\n", GetHash().ToString().substr(0,10), nVersion, vin.size(), vout.size(), nLockTime); for (unsigned int i = 0; i < vin.size(); i++) str += " " + vin[i].ToString() + "\n"; for (unsigned int i = 0; i < vout.size(); i++) str += " " + vout[i].ToString() + "\n"; return str; } void CTransaction::print() const { LogPrintf("%s", ToString()); } // Amount compression: // * If the amount is 0, output 0 // * first, divide the amount (in base units) by the largest power of 10 possible; call the exponent e (e is max 9) // * if e<9, the last digit of the resulting number cannot be 0; store it as d, and drop it (divide by 10) // * call the result n // * output 1 + 10*(9*n + d - 1) + e // * if e==9, we only know the resulting number is not zero, so output 1 + 10*(n - 1) + 9 // (this is decodable, as d is in [1-9] and e is in [0-9]) uint64_t CTxOutCompressor::CompressAmount(uint64_t n) { if (n == 0) return 0; int e = 0; while (((n % 10) == 0) && e < 9) { n /= 10; e++; } if (e < 9) { int d = (n % 10); assert(d >= 1 && d <= 9); n /= 10; return 1 + (n*9 + d - 1)*10 + e; } else { return 1 + (n - 1)*10 + 9; } } uint64_t CTxOutCompressor::DecompressAmount(uint64_t x) { // x = 0 OR x = 1+10*(9*n + d - 1) + e OR x = 1+10*(n - 1) + 9 if (x == 0) return 0; x--; // x = 10*(9*n + d - 1) + e int e = x % 10; x /= 10; uint64_t n = 0; if (e < 9) { // x = 9*n + d - 1 int d = (x % 9) + 1; x /= 9; // x = n n = x*10 + d; } else { n = x+1; } while (e) { n *= 10; e--; } return n; } //BitSend Algoswitch 1 uint256 CBlockHeader::GetHash() const { CChain var1; int nHeight= var1.Height(); if (nHeight <= FORKX17_Main_Net){ //Debugline BitSendDev if(nHeight > 0) LogPrintf("%d nHeigt We use X11\n", nHeight); return HashX11(BEGIN(nVersion), END(nNonce)); } else { if(nHeight > 0 ) LogPrintf("%d nHeigt We use X17\n", nHeight); return HashX17(BEGIN(nVersion), END(nNonce)); } } uint256 CBlockHeader::GetHash() const { return HashX11(BEGIN(nVersion), END(nNonce)); } */ uint256 CBlock::BuildMerkleTree() const { vMerkleTree.clear(); BOOST_FOREACH(const CTransaction& tx, vtx) vMerkleTree.push_back(tx.GetHash()); int j = 0; for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2) { for (int i = 0; i < nSize; i += 2) { int i2 = std::min(i+1, nSize-1); vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]), BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2]))); } j += nSize; } return (vMerkleTree.empty() ? 0 : vMerkleTree.back()); } std::vector<uint256> CBlock::GetMerkleBranch(int nIndex) const { if (vMerkleTree.empty()) BuildMerkleTree(); std::vector<uint256> vMerkleBranch; int j = 0; for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2) { int i = std::min(nIndex^1, nSize-1); vMerkleBranch.push_back(vMerkleTree[j+i]); nIndex >>= 1; j += nSize; } return vMerkleBranch; } uint256 CBlock::CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex) { if (nIndex == -1) return 0; BOOST_FOREACH(const uint256& otherside, vMerkleBranch) { if (nIndex & 1) hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash)); else hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside)); nIndex >>= 1; } return hash; } void CBlock::print() const { //GetHash2().ToString(), LogPrintf("CBlock(hash=disable, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%u)\n", nVersion, hashPrevBlock.ToString(), hashMerkleRoot.ToString(), nTime, nBits, nNonce, vtx.size()); for (unsigned int i = 0; i < vtx.size(); i++) { LogPrintf(" "); vtx[i].print(); } LogPrintf(" vMerkleTree: "); for (unsigned int i = 0; i < vMerkleTree.size(); i++) LogPrintf("%s ", vMerkleTree[i].ToString()); LogPrintf("\n"); } <|endoftext|>
<commit_before>/* BSD 2-Clause License Copyright (c) 2016, Doi Yusuke All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <cstring> // for memset #include <sstream> // for error massage #include <stdexcept> #include <unordered_map> // for cashe #include <fcntl.h> // for open FLAGS #include <unistd.h> // for tty checks #include "core.hpp" template<typename T, typename... Args> inline std::unique_ptr<T> make_unique(Args&&... args) { return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); } ics::Core::Core(const std::string& path, speed_t baudrate) : fd {open(path.c_str(), O_RDWR | O_NOCTTY)}, oldTio {} { if (fd < 0) throw std::runtime_error {"Cannot open deveice"}; try { if (!isatty(fd)) throw std::invalid_argument {"Not tty device"}; if (tcgetattr(fd, &oldTio) < 0) throw std::runtime_error {"Cannot setup tty"}; auto newTio = getTermios(); // forward reference if (cfsetispeed(&newTio, baudrate) < 0) throw std::runtime_error {"Cannot set baudrate"}; if (cfsetospeed(&newTio, baudrate) < 0) throw std::runtime_error {"Cannot set baudrate"}; if (tcsetattr(fd, TCSANOW, &newTio) < 0) throw std::runtime_error {"Cannot setup tty"}; } catch (...) { close(fd); throw; } } ics::Core::~Core() noexcept { if (fd < 0) return; closeThis(); } ics::Core::Core(Core&& rhs) noexcept : fd {rhs.fd}, oldTio(rhs.oldTio) // for Ubuntu14.04 compiler { rhs.fd = -1; } ics::Core& ics::Core::operator=(Core&& rhs) noexcept { if (fd != rhs.fd) { closeThis(); fd = rhs.fd; oldTio = rhs.oldTio; rhs.fd = -1; } return *this; } std::unique_ptr<ics::Core> ics::Core::getCore(const std::string& path, speed_t baudrate) { return make_unique<Core>(path, baudrate); } void ics::Core::communicate(const Container& tx, Container& rx) { write(fd, tx.data(), tx.size()); // send for (auto& receive : rx) read(fd, &receive, 1); // receive // check section auto receive = rx.cbegin(); for (const auto& send : tx) { if (send != *receive) { std::stringstream ss; ss << "Receive falied(loopback):" << receive - rx.cbegin() << ':' << static_cast<int>(send) << "<->" << static_cast<int>(*receive); throw std::runtime_error {ss.str()}; } ++receive; } } void ics::Core::communicateID(const IDContainerTx& tx, IDContainerRx& rx) { write(fd, tx.data(), tx.size()); // send for (auto& receive : rx) read(fd, &receive, 1); // receive // check section auto receive = rx.cbegin(); for (const auto& send : tx) { if (send != *receive) { std::stringstream ss; ss << "Receive falied(loopback):" << receive - rx.cbegin() << ':' << static_cast<int>(send) << "<->" << static_cast<int>(*receive); throw std::runtime_error {ss.str()}; } ++receive; } if ((tx[0] & 0xE0) != (*receive & 0xE0)) throw std::runtime_error {"Receive failed: invalid target data"}; } void ics::Core::closeThis() const noexcept { tcsetattr(fd, TCSANOW, &oldTio); close(fd); } termios ics::Core::getTermios() noexcept { termios newTio; std::memset(&newTio, 0, sizeof(newTio)); newTio.c_iflag = 0; newTio.c_oflag = 0; newTio.c_cflag = CS8 | CREAD | CLOCAL | PARENB; newTio.c_lflag = 0; newTio.c_cc[VMIN] = 1; newTio.c_cc[VTIME] = 1; return newTio; } <commit_msg>Remove my make_unique function<commit_after>/* BSD 2-Clause License Copyright (c) 2016, Doi Yusuke All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <cstring> // for memset #include <sstream> // for error massage #include <stdexcept> #include <unordered_map> // for cashe #include <fcntl.h> // for open FLAGS #include <unistd.h> // for tty checks #include "core.hpp" ics::Core::Core(const std::string& path, speed_t baudrate) : fd {open(path.c_str(), O_RDWR | O_NOCTTY)}, oldTio {} { if (fd < 0) throw std::runtime_error {"Cannot open deveice"}; try { if (!isatty(fd)) throw std::invalid_argument {"Not tty device"}; if (tcgetattr(fd, &oldTio) < 0) throw std::runtime_error {"Cannot setup tty"}; auto newTio = getTermios(); // forward reference if (cfsetispeed(&newTio, baudrate) < 0) throw std::runtime_error {"Cannot set baudrate"}; if (cfsetospeed(&newTio, baudrate) < 0) throw std::runtime_error {"Cannot set baudrate"}; if (tcsetattr(fd, TCSANOW, &newTio) < 0) throw std::runtime_error {"Cannot setup tty"}; } catch (...) { close(fd); throw; } } ics::Core::~Core() noexcept { if (fd < 0) return; closeThis(); } ics::Core::Core(Core&& rhs) noexcept : fd {rhs.fd}, oldTio(rhs.oldTio) // for Ubuntu14.04 compiler { rhs.fd = -1; } ics::Core& ics::Core::operator=(Core&& rhs) noexcept { if (fd != rhs.fd) { closeThis(); fd = rhs.fd; oldTio = rhs.oldTio; rhs.fd = -1; } return *this; } std::unique_ptr<ics::Core> ics::Core::getCore(const std::string& path, speed_t baudrate) { return std::unique_ptr<Core>(path, baudrate); } void ics::Core::communicate(const Container& tx, Container& rx) { write(fd, tx.data(), tx.size()); // send for (auto& receive : rx) read(fd, &receive, 1); // receive // check section auto receive = rx.cbegin(); for (const auto& send : tx) { if (send != *receive) { std::stringstream ss; ss << "Receive falied(loopback):" << receive - rx.cbegin() << ':' << static_cast<int>(send) << "<->" << static_cast<int>(*receive); throw std::runtime_error {ss.str()}; } ++receive; } } void ics::Core::communicateID(const IDContainerTx& tx, IDContainerRx& rx) { write(fd, tx.data(), tx.size()); // send for (auto& receive : rx) read(fd, &receive, 1); // receive // check section auto receive = rx.cbegin(); for (const auto& send : tx) { if (send != *receive) { std::stringstream ss; ss << "Receive falied(loopback):" << receive - rx.cbegin() << ':' << static_cast<int>(send) << "<->" << static_cast<int>(*receive); throw std::runtime_error {ss.str()}; } ++receive; } if ((tx[0] & 0xE0) != (*receive & 0xE0)) throw std::runtime_error {"Receive failed: invalid target data"}; } void ics::Core::closeThis() const noexcept { tcsetattr(fd, TCSANOW, &oldTio); close(fd); } termios ics::Core::getTermios() noexcept { termios newTio; std::memset(&newTio, 0, sizeof(newTio)); newTio.c_iflag = 0; newTio.c_oflag = 0; newTio.c_cflag = CS8 | CREAD | CLOCAL | PARENB; newTio.c_lflag = 0; newTio.c_cc[VMIN] = 1; newTio.c_cc[VTIME] = 1; return newTio; } <|endoftext|>
<commit_before>// // Copyright (C) 2015 Clifford Wolf <clifford@clifford.at> // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <math.h> const char *binstr(int v, int n) { static char buffer[16]; char *p = buffer; for (int i = n-1; i >= 0; i--) *(p++) = ((v >> i) & 1) ? '1' : '0'; *(p++) = 0; return buffer; } void help(const char *cmd) { printf("\n"); printf("Usage: %s [options]\n", cmd); printf("\n"); printf(" -i <input_freq_mhz>\n"); printf(" PLL Input Frequency (default: 12 MHz)\n"); printf("\n"); printf(" -o <output_freq_mhz>\n"); printf(" PLL Output Frequency (default: 60 MHz)\n"); printf("\n"); printf(" -S\n"); printf(" Disable SIMPLE feedback path mode\n"); printf("\n"); printf(" -f <filename.v>\n"); printf(" Save PLL configuration as Verilog module\n"); printf("\n"); printf(" -q\n"); printf(" Do not print PLL configuration to stdout\n"); printf("\n"); exit(1); } int main(int argc, char **argv) { double f_pllin = 12; double f_pllout = 60; bool simple_feedback = true; char* verilog_filename = NULL; bool quiet = false; int opt; while ((opt = getopt(argc, argv, "i:o:S:f:q")) != -1) { switch (opt) { case 'i': f_pllin = atof(optarg); break; case 'o': f_pllout = atof(optarg); break; case 'S': simple_feedback = false; break; case 'f': verilog_filename = optarg; break; case 'q': quiet = true; break; default: help(argv[0]); } } if (optind != argc) help(argv[0]); bool found_something = false; double best_fout = 0; int best_divr = 0; int best_divf = 0; int best_divq = 0; if (f_pllin < 10 || f_pllin > 133) { fprintf(stderr, "Error: PLL input frequency %.3f MHz is outside range 10 MHz - 133 MHz!\n", f_pllin); exit(1); } if (f_pllout < 16 || f_pllout > 275) { fprintf(stderr, "Error: PLL output frequency %.3f MHz is outside range 16 MHz - 275 MHz!\n", f_pllout); exit(1); } for (int divr = 0; divr <= 15; divr++) { double f_pfd = f_pllin / (divr + 1); if (f_pfd < 10 || f_pfd > 133) continue; for (int divf = 0; divf <= 63; divf++) { if (simple_feedback) { double f_vco = f_pfd * (divf + 1); if (f_vco < 533 || f_vco > 1066) continue; for (int divq = 1; divq <= 6; divq++) { double fout = f_vco * exp2(-divq); if (fabs(fout - f_pllout) < fabs(best_fout - f_pllout) || !found_something) { best_fout = fout; best_divr = divr; best_divf = divf; best_divq = divq; found_something = true; } } } else { for (int divq = 1; divq <= 6; divq++) { double f_vco = f_pfd * (divf + 1) * exp2(divq); if (f_vco < 533 || f_vco > 1066) continue; double fout = f_vco * exp2(-divq); if (fabs(fout - f_pllout) < fabs(best_fout - f_pllout) || !found_something) { best_fout = fout; best_divr = divr; best_divf = divf; best_divq = divq; found_something = true; } } } } } double f_pfd = f_pllin / (best_divr + 1);; double f_vco = f_pfd * (best_divf + 1); int filter_range = f_pfd < 17 ? 1 : f_pfd < 26 ? 2 : f_pfd < 44 ? 3 : f_pfd < 66 ? 4 : f_pfd < 101 ? 5 : 6; if (!simple_feedback) f_vco *= exp2(best_divq); if (!found_something) { fprintf(stderr, "Error: No valid configuration found!\n"); exit(1); } if (!quiet) { printf("\n"); printf("F_PLLIN: %8.3f MHz (given)\n", f_pllin); printf("F_PLLOUT: %8.3f MHz (requested)\n", f_pllout); printf("F_PLLOUT: %8.3f MHz (achieved)\n", best_fout); printf("\n"); printf("FEEDBACK: %s\n", simple_feedback ? "SIMPLE" : "NON_SIMPLE"); printf("F_PFD: %8.3f MHz\n", f_pfd); printf("F_VCO: %8.3f MHz\n", f_vco); printf("\n"); printf("DIVR: %2d (4'b%s)\n", best_divr, binstr(best_divr, 4)); printf("DIVF: %2d (7'b%s)\n", best_divf, binstr(best_divf, 7)); printf("DIVQ: %2d (3'b%s)\n", best_divq, binstr(best_divq, 3)); printf("\n"); printf("FILTER_RANGE: %d (3'b%s)\n", filter_range, binstr(filter_range, 3)); printf("\n"); } if (verilog_filename != NULL) { // open file for writing FILE *f; f = fopen(verilog_filename, "w"); // header fprintf(f, "/**\n * PLL configuration\n *\n" " * This Verilog source file was generated automatically\n" " * using the icepll tool from the IceStorm project.\n" " * Use at your own risk.\n" " *\n" " * Given input frequency: %8.3f MHz\n" " * Requested output frequency: %8.3f MHz\n" " * Achieved output frequency: %8.3f MHz\n" " */\n\n", f_pllin, f_pllout, best_fout); // generate Verilog module fprintf(f, "module pll(\n" "\tinput clock_in,\n" "\toutput clock_out,\n" "\toutput locked\n" "\t)\n\n" ); // save iCE40 PLL tile configuration fprintf(f, "SB_PLL40_CORE #(\n"); fprintf(f, "\t\t.FEEDBACK_PATH(\"%s\"),\n", (simple_feedback ? "SIMPLE" : "NON_SIMPLE")); fprintf(f, "\t\t.PLLOUT_SELECT(\"GENCLK\"),\n"); fprintf(f, "\t\t.DIVR(4'b%s),\n", binstr(best_divr, 4)); fprintf(f, "\t\t.DIVF(7'b%s),\n", binstr(best_divf, 7)); fprintf(f, "\t\t.DIVQ(3'b%s),\n", binstr(best_divq, 3)); fprintf(f, "\t\t.FILTER_RANGE(3'b%s),\n", binstr(filter_range, 3)); fprintf(f, "\t) uut (\n" "\t\t.LOCK(locked),\n" "\t\t.RESETB(1'b1),\n" "\t\t.BYPASS(1'b0),\n" "\t\t.REFERENCECLK(clock_in),\n" "\t\t.PLLOUTCORE(clock_out),\n" "\t\t);\n\n" ); fprintf(f, "endmodule\n"); fclose(f); printf("PLL configuration written to: %s\n", verilog_filename); } return 0; } <commit_msg>icepll: added -m option to choose between saving Verilog header or module<commit_after>// // Copyright (C) 2015 Clifford Wolf <clifford@clifford.at> // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <math.h> const char *binstr(int v, int n) { static char buffer[16]; char *p = buffer; for (int i = n-1; i >= 0; i--) *(p++) = ((v >> i) & 1) ? '1' : '0'; *(p++) = 0; return buffer; } void help(const char *cmd) { printf("\n"); printf("Usage: %s [options]\n", cmd); printf("\n"); printf(" -i <input_freq_mhz>\n"); printf(" PLL Input Frequency (default: 12 MHz)\n"); printf("\n"); printf(" -o <output_freq_mhz>\n"); printf(" PLL Output Frequency (default: 60 MHz)\n"); printf("\n"); printf(" -S\n"); printf(" Disable SIMPLE feedback path mode\n"); printf("\n"); printf(" -f <filename>\n"); printf(" Save PLL configuration as Verilog to file\n"); printf("\n"); printf(" -m\n"); printf(" Save PLL configuration as Verilog module (use with -f)\n"); printf("\n"); printf(" -q\n"); printf(" Do not print PLL configuration to stdout\n"); printf("\n"); exit(1); } int main(int argc, char **argv) { double f_pllin = 12; double f_pllout = 60; bool simple_feedback = true; char* filename = NULL; bool save_as_module = false; bool quiet = false; int opt; while ((opt = getopt(argc, argv, "i:o:S:mf:q")) != -1) { switch (opt) { case 'i': f_pllin = atof(optarg); break; case 'o': f_pllout = atof(optarg); break; case 'S': simple_feedback = false; break; case 'm': save_as_module = true; break; case 'f': filename = optarg; break; case 'q': quiet = true; break; default: help(argv[0]); } } if (optind != argc) help(argv[0]); // error: shall save as module, but no filename was given if (save_as_module && filename == NULL) help(argv[0]); bool found_something = false; double best_fout = 0; int best_divr = 0; int best_divf = 0; int best_divq = 0; if (f_pllin < 10 || f_pllin > 133) { fprintf(stderr, "Error: PLL input frequency %.3f MHz is outside range 10 MHz - 133 MHz!\n", f_pllin); exit(1); } if (f_pllout < 16 || f_pllout > 275) { fprintf(stderr, "Error: PLL output frequency %.3f MHz is outside range 16 MHz - 275 MHz!\n", f_pllout); exit(1); } for (int divr = 0; divr <= 15; divr++) { double f_pfd = f_pllin / (divr + 1); if (f_pfd < 10 || f_pfd > 133) continue; for (int divf = 0; divf <= 63; divf++) { if (simple_feedback) { double f_vco = f_pfd * (divf + 1); if (f_vco < 533 || f_vco > 1066) continue; for (int divq = 1; divq <= 6; divq++) { double fout = f_vco * exp2(-divq); if (fabs(fout - f_pllout) < fabs(best_fout - f_pllout) || !found_something) { best_fout = fout; best_divr = divr; best_divf = divf; best_divq = divq; found_something = true; } } } else { for (int divq = 1; divq <= 6; divq++) { double f_vco = f_pfd * (divf + 1) * exp2(divq); if (f_vco < 533 || f_vco > 1066) continue; double fout = f_vco * exp2(-divq); if (fabs(fout - f_pllout) < fabs(best_fout - f_pllout) || !found_something) { best_fout = fout; best_divr = divr; best_divf = divf; best_divq = divq; found_something = true; } } } } } double f_pfd = f_pllin / (best_divr + 1);; double f_vco = f_pfd * (best_divf + 1); int filter_range = f_pfd < 17 ? 1 : f_pfd < 26 ? 2 : f_pfd < 44 ? 3 : f_pfd < 66 ? 4 : f_pfd < 101 ? 5 : 6; if (!simple_feedback) f_vco *= exp2(best_divq); if (!found_something) { fprintf(stderr, "Error: No valid configuration found!\n"); exit(1); } if (!quiet) { printf("\n"); printf("F_PLLIN: %8.3f MHz (given)\n", f_pllin); printf("F_PLLOUT: %8.3f MHz (requested)\n", f_pllout); printf("F_PLLOUT: %8.3f MHz (achieved)\n", best_fout); printf("\n"); printf("FEEDBACK: %s\n", simple_feedback ? "SIMPLE" : "NON_SIMPLE"); printf("F_PFD: %8.3f MHz\n", f_pfd); printf("F_VCO: %8.3f MHz\n", f_vco); printf("\n"); printf("DIVR: %2d (4'b%s)\n", best_divr, binstr(best_divr, 4)); printf("DIVF: %2d (7'b%s)\n", best_divf, binstr(best_divf, 7)); printf("DIVQ: %2d (3'b%s)\n", best_divq, binstr(best_divq, 3)); printf("\n"); printf("FILTER_RANGE: %d (3'b%s)\n", filter_range, binstr(filter_range, 3)); printf("\n"); } // save PLL configuration as file if (filename != NULL) { // open file for writing FILE *f; f = fopen(filename, "w"); if (save_as_module) { // save PLL configuration as Verilog module // header fprintf(f, "/**\n * PLL configuration\n *\n" " * This Verilog module was generated automatically\n" " * using the icepll tool from the IceStorm project.\n" " * Use at your own risk.\n" " *\n" " * Given input frequency: %8.3f MHz\n" " * Requested output frequency: %8.3f MHz\n" " * Achieved output frequency: %8.3f MHz\n" " */\n\n", f_pllin, f_pllout, best_fout); // generate Verilog module fprintf(f, "module pll(\n" "\tinput clock_in,\n" "\toutput clock_out,\n" "\toutput locked\n" "\t);\n\n" ); // save iCE40 PLL tile configuration fprintf(f, "SB_PLL40_CORE #(\n"); fprintf(f, "\t\t.FEEDBACK_PATH(\"%s\"),\n", (simple_feedback ? "SIMPLE" : "NON_SIMPLE")); fprintf(f, "\t\t.PLLOUT_SELECT(\"GENCLK\"),\n"); fprintf(f, "\t\t.DIVR(4'b%s),\t\t" "// DIVR = %2d\n", binstr(best_divr, 4), best_divr); fprintf(f, "\t\t.DIVF(7'b%s),\t" "// DIVF = %2d\n", binstr(best_divf, 7), best_divf); fprintf(f, "\t\t.DIVQ(3'b%s),\t\t" "// DIVQ = %2d\n", binstr(best_divq, 3), best_divq); fprintf(f, "\t\t.FILTER_RANGE(3'b%s)\t" "// FILTER_RANGE = %d\n", binstr(filter_range, 3), filter_range); fprintf(f, "\t) uut (\n" "\t\t.LOCK(locked),\n" "\t\t.RESETB(1'b1),\n" "\t\t.BYPASS(1'b0),\n" "\t\t.REFERENCECLK(clock_in),\n" "\t\t.PLLOUTCORE(clock_out),\n" "\t\t);\n\n" ); fprintf(f, "endmodule\n"); } else { // only save PLL configuration values // header fprintf(f, "/**\n * PLL configuration\n *\n" " * This Verilog header file was generated automatically\n" " * using the icepll tool from the IceStorm project.\n" " * It is intended for use with FPGA primitives SB_PLL40_CORE,\n" " * SB_PLL40_PAD, SB_PLL40_2_PAD, SB_PLL40_2F_CORE or SB_PLL40_2F_PAD.\n" " * Use at your own risk.\n" " *\n" " * Given input frequency: %8.3f MHz\n" " * Requested output frequency: %8.3f MHz\n" " * Achieved output frequency: %8.3f MHz\n" " */\n\n", f_pllin, f_pllout, best_fout); // PLL configuration fprintf(f, ".FEEDBACK_PATH(\"%s\"),\n", (simple_feedback ? "SIMPLE" : "NON_SIMPLE")); fprintf(f, ".PLLOUT_SELECT(\"GENCLK\"),\n"); fprintf(f, ".DIVR(4'b%s),\t\t" "// DIVR = %2d\n", binstr(best_divr, 4), best_divr); fprintf(f, ".DIVF(7'b%s),\t" "// DIVF = %2d\n", binstr(best_divf, 7), best_divf); fprintf(f, ".DIVQ(3'b%s),\t\t" "// DIVQ = %2d\n", binstr(best_divq, 3), best_divq); fprintf(f, ".FILTER_RANGE(3'b%s)\t" "// FILTER_RANGE = %d\n", binstr(filter_range, 3), filter_range); } fclose(f); printf("PLL configuration written to: %s\n", filename); } return 0; } <|endoftext|>
<commit_before>#include <stdio.h> #include <queue> #include <mutex> #include <thread> #include <chrono> #include <condition_variable> template <class T> class Channel { std::mutex mutex; std::queue<T> queue; std::condition_variable not_full, not_empty; size_t capacity; public: explicit Channel(size_t capacity = 1) : capacity(capacity) {} T read() { T t; std::unique_lock<std::mutex> ul(mutex); // lock and wait when empty // wait means release lock and sleep thread // wakeup and re-lock when notified not_empty.wait(ul, [this]() { return !queue.empty(); }); t = queue.front(); queue.pop(); ul.unlock(); not_full.notify_one(); return t; } void write(const T &t) { std::unique_lock<std::mutex> ul(mutex); // wait when full not_full.wait(ul, [this]() { return capacity != queue.size(); }); queue.push(t); ul.unlock(); not_empty.notify_one(); } }; class Producer { Channel<int> &c; public: explicit Producer(Channel<int> &c) : c(c) {} void operator()() { for (int i = 0; i < 10; i++) { printf("%ld: try to write %d\n", std::this_thread::get_id(), i); c.write(i); printf("%ld: write %d done\n", std::this_thread::get_id(), i); std::this_thread::sleep_for(std::chrono::seconds(1)); } } }; class Consumer { Channel<int> &c; public: explicit Consumer(Channel<int> &c) : c(c) {} void operator()() { std::this_thread::sleep_for(std::chrono::seconds(5)); while (true) { printf("%ld: try to read\n", std::this_thread::get_id()); int x = c.read(); printf("%ld: read %d done\n", std::this_thread::get_id(), x); } } }; int main() { Channel<int> c(2); Producer p(c); Consumer s(c); std::thread t1(p), t2(s), t3(p), t4(s); t1.join(); t2.join(); t3.join(); t4.join(); return 0; } <commit_msg>update<commit_after>#include <iostream> #include <sstream> #include <queue> #include <mutex> #include <thread> #include <chrono> #include <condition_variable> #include <cstdio> template <class T> class Channel { std::mutex mutex; std::queue<T> queue; std::condition_variable not_full, not_empty; size_t capacity; public: explicit Channel(size_t capacity = 1) : capacity(capacity) {} T read() { T t; { std::unique_lock<std::mutex> ul(mutex); // lock and wait when empty // wait means release lock and sleep thread // wakeup and re-lock when notified not_empty.wait(ul, [this]() { return !queue.empty(); }); t = queue.front(); queue.pop(); } // unlock before notify not_full.notify_one(); return t; } void write(const T &t) { { std::unique_lock<std::mutex> ul(mutex); // wait when full not_full.wait(ul, [this]() { return capacity != queue.size(); }); queue.push(t); } // unlock before notify not_empty.notify_one(); } }; class Producer { Channel<int> &c; public: explicit Producer(Channel<int> &c) : c(c) {} void operator()() { for (int i = 0; i < 10; i++) { std::stringstream ss; ss << std::this_thread::get_id() << ": try to write " << i << "\n"; fputs(ss.str().c_str(), stderr); c.write(i); ss.clear(); ss << std::this_thread::get_id() << ": write " << i << " done\n"; fputs(ss.str().c_str(), stderr); std::this_thread::sleep_for(std::chrono::seconds(1)); } } }; class Consumer { Channel<int> &c; public: explicit Consumer(Channel<int> &c) : c(c) {} void operator()() { std::this_thread::sleep_for(std::chrono::seconds(5)); while (true) { std::stringstream ss; ss << std::this_thread::get_id() << ": try to read\n"; fputs(ss.str().c_str(), stderr); int x = c.read(); ss.clear(); ss << std::this_thread::get_id() << ": read " << x << " done\n"; fputs(ss.str().c_str(), stderr); } } }; int main() { Channel<int> c(2); Producer p(c); Consumer s(c); std::thread t1(p), t2(s), t3(p), t4(s); t1.join(); t2.join(); t3.join(); t4.join(); return 0; } <|endoftext|>
<commit_before>#include <stdio.h> #include <queue> #include <mutex> #include <thread> #include <chrono> #include <condition_variable> template<class T> class Channel { std::mutex mutex; std::queue<T> queue; std::condition_variable not_full, not_empty; size_t capacity; public: explicit Channel(size_t capacity = 1): capacity(capacity) {} T read() { T t; std::unique_lock<std::mutex> ul(mutex); // lock and wait when empty // wait means release lock and sleep thread // wakeup and re-lock when notified not_empty.wait(ul, [this](){return !queue.empty();}); t = queue.front(); queue.pop(); ul.unlock(); not_full.notify_one(); return t; } void write(const T& t) { std::unique_lock<std::mutex> ul(mutex); // wait when full not_full.wait(ul, [this](){return capacity != queue.size();}); queue.push(t); ul.unlock(); not_empty.notify_one(); } }; class Producer { Channel<int>& c; public: explicit Producer(Channel<int>& c): c(c) {} void operator()() { for(int i = 0; i < 10; i++) { printf("%ld: try to write %d\n", std::this_thread::get_id(), i); c.write(i); printf("%ld: write %d done\n", std::this_thread::get_id(), i); std::this_thread::sleep_for(std::chrono::seconds(1)); } } }; class Consumer { Channel<int>& c; public: explicit Consumer(Channel<int>& c): c(c) {} void operator()() { std::this_thread::sleep_for(std::chrono::seconds(5)); while(true) { printf("%ld: try to read\n", std::this_thread::get_id()); int x = c.read(); printf("%ld: read %d done\n", std::this_thread::get_id(), x); } } }; int main() { Channel<int> c(2); Producer p(c); Consumer s(c); std::thread t1(p), t2(s), t3(p), t4(s); t1.join(); t2.join(); return 0; } <commit_msg>update<commit_after>#include <stdio.h> #include <queue> #include <mutex> #include <thread> #include <chrono> #include <condition_variable> template <class T> class Channel { std::mutex mutex; std::queue<T> queue; std::condition_variable not_full, not_empty; size_t capacity; public: explicit Channel(size_t capacity = 1) : capacity(capacity) {} T read() { T t; std::unique_lock<std::mutex> ul(mutex); // lock and wait when empty // wait means release lock and sleep thread // wakeup and re-lock when notified not_empty.wait(ul, [this]() { return !queue.empty(); }); t = queue.front(); queue.pop(); ul.unlock(); not_full.notify_one(); return t; } void write(const T &t) { std::unique_lock<std::mutex> ul(mutex); // wait when full not_full.wait(ul, [this]() { return capacity != queue.size(); }); queue.push(t); ul.unlock(); not_empty.notify_one(); } }; class Producer { Channel<int> &c; public: explicit Producer(Channel<int> &c) : c(c) {} void operator()() { for (int i = 0; i < 10; i++) { printf("%ld: try to write %d\n", std::this_thread::get_id(), i); c.write(i); printf("%ld: write %d done\n", std::this_thread::get_id(), i); std::this_thread::sleep_for(std::chrono::seconds(1)); } } }; class Consumer { Channel<int> &c; public: explicit Consumer(Channel<int> &c) : c(c) {} void operator()() { std::this_thread::sleep_for(std::chrono::seconds(5)); while (true) { printf("%ld: try to read\n", std::this_thread::get_id()); int x = c.read(); printf("%ld: read %d done\n", std::this_thread::get_id(), x); } } }; int main() { Channel<int> c(2); Producer p(c); Consumer s(c); std::thread t1(p), t2(s), t3(p), t4(s); t1.join(); t2.join(); return 0; } <|endoftext|>
<commit_before>/* * cube.cpp * * Created on: Nov 25, 2013 * Author: leo */ #include "cube.h" #include <iostream> using namespace std; GLfloat cube::side_vertices[] = { // front base cube -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, // back base cube -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5, }; GLfloat cube::side_colors[] = { // front base cube 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, // back base cube 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, // // any mixture for debugging // // front base cube // 0.0, 1.0, 0.0, //green // 1.0, 1.0, 0.0, //yellow // 1.0, 0.5, 0.0, //orange // 1.0, 0.0, 0.0, //red // // back base cube // 0.0, 1.0, 0.0, //green // 0.0, 0.0, 1.0, //blue // 1.0, 0.5, 0.0, //orange // 0.0, 0.0, 0.0, //black }; GLfloat cube::tex_coords[] ={ // front base cube 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, // back base cube 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, }; GLushort cube::base_elements[] = { // front 0, 1, 2, 2, 3, 0, // top 3, 2, 6, 6, 7, 3, // back 7, 6, 5, 5, 4, 7, // bottom 4, 5, 1, 1, 0, 4, // left 4, 0, 3, 3, 7, 4, // right 1, 5, 6, 6, 2, 1, }; cube::cube(GLuint program, int offset_index) { translation = mat4(1.0); rotation = mat4(1.0); // base cube elements glGenBuffers(1, &base_elements_ibo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, base_elements_ibo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(base_elements), base_elements, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); // side vertices glGenBuffers(1, &pos_vbo); glBindBuffer(GL_ARRAY_BUFFER, pos_vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(side_vertices), side_vertices, GL_STATIC_DRAW); // based on the shader variable name GLint pos_attrib = glGetAttribLocation(program, "vPosition"); glEnableVertexAttribArray(pos_attrib); glVertexAttribPointer(pos_attrib, 3, GL_FLOAT, GL_FALSE, 0, 0); // side colors glGenBuffers(1, &col_vbo); glBindBuffer(GL_ARRAY_BUFFER, col_vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(side_colors), side_colors, GL_STATIC_DRAW); // based on the shader variable name GLint col_attrib = glGetAttribLocation(program, "in_Color"); glEnableVertexAttribArray(col_attrib); glVertexAttribPointer(col_attrib, 4, GL_FLOAT, GL_FALSE, 0, 0); // textures glGenBuffers(1, &tex_coord); glBindBuffer(GL_ARRAY_BUFFER, tex_coord); glBufferData(GL_ARRAY_BUFFER, sizeof(tex_coords), tex_coords, GL_STATIC_DRAW); GLint tex_attrib = glGetAttribLocation(program, "in_texcoord"); glEnableVertexAttribArray(tex_attrib); glVertexAttribPointer(tex_attrib, 2, GL_FLOAT, GL_FALSE, 0, 0); glGenTextures(1, &texture_id); glBindTexture(GL_TEXTURE_2D, texture_id); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, wood_image.width, wood_image.height, 0, GL_RGB, GL_UNSIGNED_BYTE, wood_image.pixel_data); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); } cube::cube() { col_vbo = pos_vbo = base_elements_ibo = texture_id = tex_coord = -1; } cube::~cube() { glDeleteBuffers(1, &pos_vbo); glDeleteBuffers(1, &col_vbo); glDeleteBuffers(1, &base_elements_ibo); glDeleteTextures(1, &texture_id); } void cube::draw(){ // draw base using buffer element glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, base_elements_ibo); GLint size; glGetBufferParameteriv(GL_ELEMENT_ARRAY_BUFFER, GL_BUFFER_SIZE, &size); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture_id); glDrawElements(GL_TRIANGLES, size/sizeof(GLushort), GL_UNSIGNED_SHORT, 0); // glDrawArrays(GL_TRIANGLES, 0,36); } <commit_msg>fixing textures<commit_after>/* * cube.cpp * * Created on: Nov 25, 2013 * Author: leo */ #include "cube.h" #include <iostream> using namespace std; GLfloat cube::side_vertices[] = { // // front base cube // -0.5, -0.5, 0.5, // 0.5, -0.5, 0.5, // 0.5, 0.5, 0.5, // -0.5, 0.5, 0.5, // // back base cube // -0.5, -0.5, -0.5, // 0.5, -0.5, -0.5, // 0.5, 0.5, -0.5, // -0.5, 0.5, -0.5, // starting the side vertices -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5, -0.5, }; GLfloat cube::side_colors[] = { // // front base cube // 1.0, 1.0, 1.0, 0.0, // 1.0, 1.0, 1.0, 0.0, // 1.0, 1.0, 1.0, 0.0, // 1.0, 1.0, 1.0, 0.0, // // back base cube // 1.0, 1.0, 1.0, 0.0, // 1.0, 1.0, 1.0, 0.0, // 1.0, 1.0, 1.0, 0.0, // 1.0, 1.0, 1.0, 0.0, // // any mixture for debugging // // front base cube // 0.0, 1.0, 0.0, //green // 1.0, 1.0, 0.0, //yellow // 1.0, 0.5, 0.0, //orange // 1.0, 0.0, 0.0, //red // // back base cube // 0.0, 1.0, 0.0, //green // 0.0, 0.0, 1.0, //blue // 1.0, 0.5, 0.0, //orange // 0.0, 0.0, 0.0, //black 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, }; GLfloat cube::tex_coords[] ={ // front base cube 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, // back base cube 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, }; GLushort cube::base_elements[] = { // front 0, 1, 2, 2, 3, 0, // top 3, 2, 6, 6, 7, 3, // back 7, 6, 5, 5, 4, 7, // bottom 4, 5, 1, 1, 0, 4, // left 4, 0, 3, 3, 7, 4, // right 1, 5, 6, 6, 2, 1, }; cube::cube(GLuint program, int offset_index) { translation = mat4(1.0); rotation = mat4(1.0); // base cube elements glGenBuffers(1, &base_elements_ibo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, base_elements_ibo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(base_elements), base_elements, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); // side vertices glGenBuffers(1, &pos_vbo); glBindBuffer(GL_ARRAY_BUFFER, pos_vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(side_vertices), side_vertices, GL_STATIC_DRAW); // based on the shader variable name GLint pos_attrib = glGetAttribLocation(program, "vPosition"); glEnableVertexAttribArray(pos_attrib); glVertexAttribPointer(pos_attrib, 3, GL_FLOAT, GL_FALSE, 0, 0); // side colors glGenBuffers(1, &col_vbo); glBindBuffer(GL_ARRAY_BUFFER, col_vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(side_colors), side_colors, GL_STATIC_DRAW); // based on the shader variable name GLint col_attrib = glGetAttribLocation(program, "in_Color"); glEnableVertexAttribArray(col_attrib); glVertexAttribPointer(col_attrib, 4, GL_FLOAT, GL_FALSE, 0, 0); // textures glGenBuffers(1, &tex_coord); glBindBuffer(GL_ARRAY_BUFFER, tex_coord); glBufferData(GL_ARRAY_BUFFER, sizeof(tex_coords), tex_coords, GL_STATIC_DRAW); GLint tex_attrib = glGetAttribLocation(program, "in_texcoord"); glEnableVertexAttribArray(tex_attrib); glVertexAttribPointer(tex_attrib, 2, GL_FLOAT, GL_FALSE, 0, 0); glGenTextures(1, &texture_id); glBindTexture(GL_TEXTURE_2D, texture_id); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, wood_image.width, wood_image.height, 0, GL_RGB, GL_UNSIGNED_BYTE, wood_image.pixel_data); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); } cube::cube() { col_vbo = pos_vbo = base_elements_ibo = texture_id = tex_coord = -1; } cube::~cube() { glDeleteBuffers(1, &pos_vbo); glDeleteBuffers(1, &col_vbo); glDeleteBuffers(1, &base_elements_ibo); glDeleteTextures(1, &texture_id); } void cube::draw(){ // draw base using buffer element glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, base_elements_ibo); GLint size; glGetBufferParameteriv(GL_ELEMENT_ARRAY_BUFFER, GL_BUFFER_SIZE, &size); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture_id); // glDrawElements(GL_TRIANGLES, size/sizeof(GLushort), GL_UNSIGNED_SHORT, 0); glDrawArrays(GL_TRIANGLES, 0,36); } <|endoftext|>
<commit_before>// Copyright (c) 2018 The COLX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "curl.h" #include "util.h" #include "clientversion.h" #include <stdlib.h> #include <curl/curl.h> using namespace std; // // private section // static void CurlGlobalInit() { static bool initialized = false; if (!initialized) { curl_global_init(CURL_GLOBAL_DEFAULT); initialized = true; } } struct CurlScopeInit { CurlScopeInit() { CurlGlobalInit(); curl_ = curl_easy_init(); } ~CurlScopeInit() { if (curl_) curl_easy_cleanup(curl_); } inline CURL* instance() { return curl_; } inline operator CURL*() { return curl_; } private: CurlScopeInit(const CurlScopeInit&); CurlScopeInit& operator=(const CurlScopeInit&); private: CURL *curl_; }; struct MemoryBuffer { char* memory; size_t size; }; static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) { size_t realsize = size * nmemb; struct MemoryBuffer *mem = (struct MemoryBuffer*)userp; mem->memory = (char*)realloc(mem->memory, mem->size + realsize + 1); if (mem->memory == NULL) { /* out of memory! */ error("%s: not enough memory (realloc returned NULL)\n", __func__); return 0; } else { memcpy(&(mem->memory[mem->size]), contents, realsize); mem->size += realsize; mem->memory[mem->size] = 0; return realsize; } } // // public API // bool CURLGetRedirect(const CUrl& url, CUrl& redirect, string& error) { CurlScopeInit curl; CURLcode res; char *location; long response_code; redirect.clear(); error.clear(); if (url.empty()) { error = "url is empty"; return false; } if (!curl.instance()) { error = "curl init failed"; return false; } curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); res = curl_easy_perform(curl); if (res != CURLE_OK) { error = strprintf("curl_easy_perform failed: %s", curl_easy_strerror(res)); return false; } res = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code); if ((res == CURLE_OK) && ((response_code / 100) != 3)) { /* a redirect implies a 3xx response code */ error = "Not a redirect"; return false; } else { res = curl_easy_getinfo(curl, CURLINFO_REDIRECT_URL, &location); if ((res == CURLE_OK) && location) { /* This is the new absolute URL that you could redirect to, even if * the Location: response header may have been a relative URL. */ redirect = location; return true; } else { error = strprintf("curl_easy_getinfo failed: %s", curl_easy_strerror(res)); return false; } } } bool CURLDownloadToMem(const CUrl& url, string& buff, string& error) { CurlScopeInit curl; CURLcode res; struct MemoryBuffer chunk; buff.clear(); error.clear(); if (url.empty()) { error = "url is empty"; return false; } if (!curl.instance()) { error = "curl init failed"; return false; } chunk.memory = (char*)malloc(1); /* will be grown as needed by the realloc above */ chunk.size = 0; /* no data at this point */ /* specify URL to get */ curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); /* send all data to this function */ curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); /* we pass our 'chunk' struct to the callback function */ curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk); /* some servers don't like requests that are made without a user-agent */ const string agent = FormatFullVersion(); curl_easy_setopt(curl, CURLOPT_USERAGENT, agent.c_str()); /* get it! */ res = curl_easy_perform(curl); /* check for errors */ if (res != CURLE_OK) { error = strprintf("curl_easy_perform failed: %s", curl_easy_strerror(res)); } else { long response_code = 0; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code); if (response_code / 100 != 2) { error = strprintf("response code is not OK: %d", response_code); DebugPrintf("%s: response code=%d, response content=%s", __func__, response_code, string(chunk.memory, chunk.size)); } else { /* * Now, our chunk.memory points to a memory block that is chunk.size * bytes big and contains the remote file. */ DebugPrintf("%s: %lu bytes retrieved\n", __func__, (long)chunk.size); buff.assign(chunk.memory, chunk.size); } } free(chunk.memory); return !buff.empty(); } bool CURLDownloadToFile(const CUrl& url, const string& path, ProgressReport callback, string& error) { error = "not implemented"; return false; } <commit_msg>autoupdate: peer and host verification disabled due to issues on Mac and Win<commit_after>// Copyright (c) 2018 The COLX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "curl.h" #include "util.h" #include "clientversion.h" #include <stdlib.h> #include <curl/curl.h> using namespace std; // // private section // static void CurlGlobalInit() { static bool initialized = false; if (!initialized) { curl_global_init(CURL_GLOBAL_DEFAULT); initialized = true; } } struct CurlScopeInit { CurlScopeInit() { CurlGlobalInit(); curl_ = curl_easy_init(); } ~CurlScopeInit() { if (curl_) curl_easy_cleanup(curl_); } inline CURL* instance() { return curl_; } inline operator CURL*() { return curl_; } private: CurlScopeInit(const CurlScopeInit&); CurlScopeInit& operator=(const CurlScopeInit&); private: CURL *curl_; }; struct MemoryBuffer { char* memory; size_t size; }; static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) { size_t realsize = size * nmemb; struct MemoryBuffer *mem = (struct MemoryBuffer*)userp; mem->memory = (char*)realloc(mem->memory, mem->size + realsize + 1); if (mem->memory == NULL) { /* out of memory! */ error("%s: not enough memory (realloc returned NULL)\n", __func__); return 0; } else { memcpy(&(mem->memory[mem->size]), contents, realsize); mem->size += realsize; mem->memory[mem->size] = 0; return realsize; } } // // public API // bool CURLGetRedirect(const CUrl& url, CUrl& redirect, string& error) { CurlScopeInit curl; CURLcode res; char *location; long response_code; redirect.clear(); error.clear(); if (url.empty()) { error = "url is empty"; return false; } if (!curl.instance()) { error = "curl init failed"; return false; } curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); /* disable peer and host verification because of issues on Mac and Win */ curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); res = curl_easy_perform(curl); if (res != CURLE_OK) { error = strprintf("curl_easy_perform failed: %s", curl_easy_strerror(res)); return false; } res = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code); if ((res == CURLE_OK) && ((response_code / 100) != 3)) { /* a redirect implies a 3xx response code */ error = "Not a redirect"; return false; } else { res = curl_easy_getinfo(curl, CURLINFO_REDIRECT_URL, &location); if ((res == CURLE_OK) && location) { /* This is the new absolute URL that you could redirect to, even if * the Location: response header may have been a relative URL. */ redirect = location; return true; } else { error = strprintf("curl_easy_getinfo failed: %s", curl_easy_strerror(res)); return false; } } } bool CURLDownloadToMem(const CUrl& url, string& buff, string& error) { CurlScopeInit curl; CURLcode res; struct MemoryBuffer chunk; buff.clear(); error.clear(); if (url.empty()) { error = "url is empty"; return false; } if (!curl.instance()) { error = "curl init failed"; return false; } chunk.memory = (char*)malloc(1); /* will be grown as needed by the realloc above */ chunk.size = 0; /* no data at this point */ /* specify URL to get */ curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); /* send all data to this function */ curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); /* we pass our 'chunk' struct to the callback function */ curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk); /* some servers don't like requests that are made without a user-agent */ const string agent = FormatFullVersion(); curl_easy_setopt(curl, CURLOPT_USERAGENT, agent.c_str()); /* disable peer and host verification because of issues on Mac and Win */ curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); /* get it! */ res = curl_easy_perform(curl); /* check for errors */ if (res != CURLE_OK) { error = strprintf("curl_easy_perform failed: %s", curl_easy_strerror(res)); } else { long response_code = 0; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code); if (response_code / 100 != 2) { error = strprintf("response code is not OK: %d", response_code); DebugPrintf("%s: response code=%d, response content=%s", __func__, response_code, string(chunk.memory, chunk.size)); } else { /* * Now, our chunk.memory points to a memory block that is chunk.size * bytes big and contains the remote file. */ DebugPrintf("%s: %lu bytes retrieved\n", __func__, (long)chunk.size); buff.assign(chunk.memory, chunk.size); } } free(chunk.memory); return !buff.empty(); } bool CURLDownloadToFile(const CUrl& url, const string& path, ProgressReport callback, string& error) { error = "not implemented"; return false; } <|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <string> #include <botan/pipe.h> #include <botan/hex.h> using namespace Botan; #include "common.h" void strip_comments(std::string& line) { if(line.find('#') != std::string::npos) line = line.erase(line.find('#'), std::string::npos); } void strip_newlines(std::string& line) { while(line.find('\n') != std::string::npos) line = line.erase(line.find('\n'), 1); } /* Strip comments, whitespace, etc */ void strip(std::string& line) { strip_comments(line); #if 0 while(line.find(' ') != std::string::npos) line = line.erase(line.find(' '), 1); #endif while(line.find('\t') != std::string::npos) line = line.erase(line.find('\t'), 1); } SecureVector<byte> decode_hex(const std::string& in) { SecureVector<byte> result; try { Botan::Pipe pipe(new Botan::Hex_Decoder); pipe.process_msg(in); result = pipe.read_all(); } catch(std::exception& e) { result.destroy(); } return result; } std::string hex_encode(const byte in[], u32bit len) { Botan::Pipe pipe(new Botan::Hex_Encoder); pipe.process_msg(in, len); return pipe.read_all_as_string(); } std::vector<std::string> parse(const std::string& line) { const char DELIMITER = ':'; std::vector<std::string> substr; std::string::size_type start = 0, end = line.find(DELIMITER); while(end != std::string::npos) { substr.push_back(line.substr(start, end-start)); start = end+1; end = line.find(DELIMITER, start); } if(line.size() > start) substr.push_back(line.substr(start)); while(substr.size() <= 4) // at least 5 substr, some possibly empty substr.push_back(""); return substr; } <commit_msg>Avoid VC++ warning<commit_after>#include <iostream> #include <vector> #include <string> #include <botan/pipe.h> #include <botan/hex.h> using namespace Botan; #include "common.h" void strip_comments(std::string& line) { if(line.find('#') != std::string::npos) line = line.erase(line.find('#'), std::string::npos); } void strip_newlines(std::string& line) { while(line.find('\n') != std::string::npos) line = line.erase(line.find('\n'), 1); } /* Strip comments, whitespace, etc */ void strip(std::string& line) { strip_comments(line); #if 0 while(line.find(' ') != std::string::npos) line = line.erase(line.find(' '), 1); #endif while(line.find('\t') != std::string::npos) line = line.erase(line.find('\t'), 1); } SecureVector<byte> decode_hex(const std::string& in) { SecureVector<byte> result; try { Botan::Pipe pipe(new Botan::Hex_Decoder); pipe.process_msg(in); result = pipe.read_all(); } catch(std::exception) { result.destroy(); } return result; } std::string hex_encode(const byte in[], u32bit len) { Botan::Pipe pipe(new Botan::Hex_Encoder); pipe.process_msg(in, len); return pipe.read_all_as_string(); } std::vector<std::string> parse(const std::string& line) { const char DELIMITER = ':'; std::vector<std::string> substr; std::string::size_type start = 0, end = line.find(DELIMITER); while(end != std::string::npos) { substr.push_back(line.substr(start, end-start)); start = end+1; end = line.find(DELIMITER, start); } if(line.size() > start) substr.push_back(line.substr(start)); while(substr.size() <= 4) // at least 5 substr, some possibly empty substr.push_back(""); return substr; } <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ // $Id$ //----------------------------------------------------------------------------- /// \class AliMUONVDigitStore /// /// Interface for a digit (or sdigit) container /// /// It offers methods to Add, Find and Remove single elements, and /// can create iterators to loop over (part of) the elements. /// /// \author Laurent Aphecetche, Subatech //----------------------------------------------------------------------------- #include "AliMUONVDigitStore.h" #include "AliLog.h" #include "AliMUONVDigit.h" #include <TClass.h> #include <TString.h> #include <TTree.h> /// \cond CLASSIMP ClassImp(AliMUONVDigitStore) /// \endcond //_____________________________________________________________________________ AliMUONVDigitStore::AliMUONVDigitStore() { /// ctor } //_____________________________________________________________________________ AliMUONVDigitStore::~AliMUONVDigitStore() { /// dtor } //_____________________________________________________________________________ Bool_t AliMUONVDigitStore::Add(TObject* object) { /// Add an object, if it is of type AliMUONVDigit if (object) { AliMUONVDigit* digit = dynamic_cast<AliMUONVDigit*>(object); if (digit) { AliMUONVDigit* added = Add(*digit,AliMUONVDigitStore::kIgnore); if (!added) { AliError("Could not add digit through Add(TObject*) method"); } else { return kTRUE; } } } return kFALSE; } //_____________________________________________________________________________ AliMUONVDigit* AliMUONVDigitStore::Add(Int_t detElemId, Int_t manuId, Int_t manuChannel, Int_t cathode, EReplacePolicy replace) { /// Add a digit and return it AliMUONVDigit* digit = CreateDigit(detElemId,manuId,manuChannel,cathode); if (digit) { AliMUONVDigit* d = Add(*digit,replace); delete digit; return d; } return 0x0; } //____________________________________________________________________________ AliMUONVDigitStore* AliMUONVDigitStore::Create(const char* digitstoreclassname) { /// Create a concrete digitStore, given its classname TClass* classPtr = TClass::GetClass(digitstoreclassname); if (!classPtr || !classPtr->InheritsFrom("AliMUONVDigitStore")) { return 0x0; } AliMUONVDigitStore* digitStore = reinterpret_cast<AliMUONVDigitStore*>(classPtr->New()); return digitStore; } //_____________________________________________________________________________ AliMUONVDigitStore* AliMUONVDigitStore::Create(TTree& tree) { /// Create store from the given tree (if possible). TString dataType = ( strcmp(tree.GetName(),"TreeD") == 0 ? "Digit" : (strcmp(tree.GetName(),"TreeS")== 9 ? "SDigit" : "") ); return static_cast<AliMUONVDigitStore*>(AliMUONVStore::Create(tree,dataType.Data())); } //_____________________________________________________________________________ AliMUONVDigit* AliMUONVDigitStore::FindObject(const TObject* object) const { /// Find an object, if of AliMUONVDigit type. const AliMUONVDigit* digit = dynamic_cast<const AliMUONVDigit*>(object); if (digit) { return FindObject(digit->GetUniqueID()); } return 0x0; } //_____________________________________________________________________________ AliMUONVDigit* AliMUONVDigitStore::FindObject(UInt_t uniqueID) const { /// Find digit by its uniqueID return FindObject(AliMUONVDigit::DetElemId(uniqueID), AliMUONVDigit::ManuId(uniqueID), AliMUONVDigit::ManuChannel(uniqueID), AliMUONVDigit::Cathode(uniqueID)); } //_____________________________________________________________________________ Int_t AliMUONVDigitStore::GetSize(Int_t detElemId, Int_t cathode) const { /// Return the number of digits we have for a given detection element TIter next(CreateIterator(detElemId,detElemId,cathode)); AliMUONVDigit* digit; Int_t n(0); while ( ( digit = static_cast<AliMUONVDigit*>(next()) ) ) { ++n; } return n; } <commit_msg>Fixing UNUSED_VALUE defect reported by Coverity<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ // $Id$ //----------------------------------------------------------------------------- /// \class AliMUONVDigitStore /// /// Interface for a digit (or sdigit) container /// /// It offers methods to Add, Find and Remove single elements, and /// can create iterators to loop over (part of) the elements. /// /// \author Laurent Aphecetche, Subatech //----------------------------------------------------------------------------- #include "AliMUONVDigitStore.h" #include "AliLog.h" #include "AliMUONVDigit.h" #include <TClass.h> #include <TString.h> #include <TTree.h> /// \cond CLASSIMP ClassImp(AliMUONVDigitStore) /// \endcond //_____________________________________________________________________________ AliMUONVDigitStore::AliMUONVDigitStore() { /// ctor } //_____________________________________________________________________________ AliMUONVDigitStore::~AliMUONVDigitStore() { /// dtor } //_____________________________________________________________________________ Bool_t AliMUONVDigitStore::Add(TObject* object) { /// Add an object, if it is of type AliMUONVDigit if (object) { AliMUONVDigit* digit = dynamic_cast<AliMUONVDigit*>(object); if (digit) { AliMUONVDigit* added = Add(*digit,AliMUONVDigitStore::kIgnore); if (!added) { AliError("Could not add digit through Add(TObject*) method"); } else { return kTRUE; } } } return kFALSE; } //_____________________________________________________________________________ AliMUONVDigit* AliMUONVDigitStore::Add(Int_t detElemId, Int_t manuId, Int_t manuChannel, Int_t cathode, EReplacePolicy replace) { /// Add a digit and return it AliMUONVDigit* digit = CreateDigit(detElemId,manuId,manuChannel,cathode); if (digit) { AliMUONVDigit* d = Add(*digit,replace); delete digit; return d; } return 0x0; } //____________________________________________________________________________ AliMUONVDigitStore* AliMUONVDigitStore::Create(const char* digitstoreclassname) { /// Create a concrete digitStore, given its classname TClass* classPtr = TClass::GetClass(digitstoreclassname); if (!classPtr || !classPtr->InheritsFrom("AliMUONVDigitStore")) { return 0x0; } AliMUONVDigitStore* digitStore = reinterpret_cast<AliMUONVDigitStore*>(classPtr->New()); return digitStore; } //_____________________________________________________________________________ AliMUONVDigitStore* AliMUONVDigitStore::Create(TTree& tree) { /// Create store from the given tree (if possible). TString dataType = ( strcmp(tree.GetName(),"TreeD") == 0 ? "Digit" : (strcmp(tree.GetName(),"TreeS")== 9 ? "SDigit" : "") ); return static_cast<AliMUONVDigitStore*>(AliMUONVStore::Create(tree,dataType.Data())); } //_____________________________________________________________________________ AliMUONVDigit* AliMUONVDigitStore::FindObject(const TObject* object) const { /// Find an object, if of AliMUONVDigit type. const AliMUONVDigit* digit = dynamic_cast<const AliMUONVDigit*>(object); if (digit) { return FindObject(digit->GetUniqueID()); } return 0x0; } //_____________________________________________________________________________ AliMUONVDigit* AliMUONVDigitStore::FindObject(UInt_t uniqueID) const { /// Find digit by its uniqueID return FindObject(AliMUONVDigit::DetElemId(uniqueID), AliMUONVDigit::ManuId(uniqueID), AliMUONVDigit::ManuChannel(uniqueID), AliMUONVDigit::Cathode(uniqueID)); } //_____________________________________________________________________________ Int_t AliMUONVDigitStore::GetSize(Int_t detElemId, Int_t cathode) const { /// Return the number of digits we have for a given detection element TIter next(CreateIterator(detElemId,detElemId,cathode)); Int_t n(0); while ( ( next() ) ) { ++n; } return n; } <|endoftext|>
<commit_before>/* This file is part of the KDE project Copyright (C) 2006-2007 Matthias Kretz <kretz@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <qtest_kde.h> #include "seekslidertest.h" #include "../seekslider.h" #include "../mediaobject.h" #include <QtGui/QSlider> #include <kurl.h> #include <cstdlib> #include <QtGui/QLabel> #include "loadfakebackend.h" using namespace Phonon; void SeekSliderTest::initTestCase() { Phonon::loadFakeBackend(); ss = new SeekSlider; QVERIFY(ss != 0); qslider = ss->findChild<QSlider *>(); qlabel = ss->findChild<QLabel *>(); QVERIFY(qslider != 0); QVERIFY(qlabel != 0); media = new MediaObject(this); } void SeekSliderTest::testEnabled() { QVERIFY(!qslider->isEnabled()); ss->setMediaObject(0); QVERIFY(!qslider->isEnabled()); } void SeekSliderTest::setMedia() { QVERIFY(media->state() == Phonon::LoadingState); KUrl url(testUrl()); media->setCurrentSource(url); ss->setMediaObject(media); QVERIFY(!qslider->isEnabled()); ss->setMediaObject(0); QVERIFY(!qslider->isEnabled()); ss->setMediaObject(media); QVERIFY(!qslider->isEnabled()); } void SeekSliderTest::playMedia() { media->play(); QSignalSpy stateSpy(media, SIGNAL(stateChanged(Phonon::State, Phonon::State))); while (media->state() != Phonon::PlayingState) { QVERIFY(QTest::kWaitForSignal(media, SIGNAL(stateChanged(Phonon::State, Phonon::State)), 4000)); QVERIFY(!stateSpy.isEmpty()); switch (qvariant_cast<Phonon::State>(stateSpy.last().first())) { case Phonon::PlayingState: case Phonon::PausedState: case Phonon::BufferingState: QVERIFY(qslider->isEnabled()); ss->setMediaObject(0); QVERIFY(!qslider->isEnabled()); ss->setMediaObject(media); QVERIFY(qslider->isEnabled()); break; case Phonon::ErrorState: case Phonon::StoppedState: case Phonon::LoadingState: QVERIFY(!qslider->isEnabled()); break; } } } void SeekSliderTest::seekWithSlider() { // click on the slider to seek } void SeekSliderTest::cleanupTestCase() { delete media; qslider = 0; delete ss; } QTEST_KDEMAIN(SeekSliderTest, GUI) #include "seekslidertest.moc" // vim: ts=4 <commit_msg>use AudioPath + AudioOutput; a MediaObject alone is not required to behave correctly<commit_after>/* This file is part of the KDE project Copyright (C) 2006-2007 Matthias Kretz <kretz@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <qtest_kde.h> #include "seekslidertest.h" #include "../seekslider.h" #include "../mediaobject.h" #include <QtGui/QSlider> #include <kurl.h> #include <cstdlib> #include <QtGui/QLabel> #include "loadfakebackend.h" #include "../audiopath.h" #include "../audiooutput.h" using namespace Phonon; void SeekSliderTest::initTestCase() { Phonon::loadFakeBackend(); ss = new SeekSlider; QVERIFY(ss != 0); qslider = ss->findChild<QSlider *>(); qlabel = ss->findChild<QLabel *>(); QVERIFY(qslider != 0); QVERIFY(qlabel != 0); media = new MediaObject(this); AudioPath *ap = new AudioPath(media); AudioOutput *ao = new AudioOutput(Phonon::MusicCategory, media); media->addAudioPath(ap); ap->addOutput(ao); } void SeekSliderTest::testEnabled() { QVERIFY(!qslider->isEnabled()); ss->setMediaObject(0); QVERIFY(!qslider->isEnabled()); } void SeekSliderTest::setMedia() { QVERIFY(media->state() == Phonon::LoadingState); KUrl url(testUrl()); media->setCurrentSource(url); ss->setMediaObject(media); QVERIFY(!qslider->isEnabled()); ss->setMediaObject(0); QVERIFY(!qslider->isEnabled()); ss->setMediaObject(media); QVERIFY(!qslider->isEnabled()); } void SeekSliderTest::playMedia() { media->play(); QSignalSpy stateSpy(media, SIGNAL(stateChanged(Phonon::State, Phonon::State))); while (media->state() != Phonon::PlayingState) { QVERIFY(QTest::kWaitForSignal(media, SIGNAL(stateChanged(Phonon::State, Phonon::State)), 4000)); QVERIFY(!stateSpy.isEmpty()); switch (qvariant_cast<Phonon::State>(stateSpy.last().first())) { case Phonon::PlayingState: case Phonon::PausedState: case Phonon::BufferingState: QVERIFY(qslider->isEnabled()); ss->setMediaObject(0); QVERIFY(!qslider->isEnabled()); ss->setMediaObject(media); QVERIFY(qslider->isEnabled()); break; case Phonon::ErrorState: case Phonon::StoppedState: case Phonon::LoadingState: QVERIFY(!qslider->isEnabled()); break; } } } void SeekSliderTest::seekWithSlider() { // click on the slider to seek } void SeekSliderTest::cleanupTestCase() { delete media; qslider = 0; delete ss; } QTEST_KDEMAIN(SeekSliderTest, GUI) #include "seekslidertest.moc" // vim: ts=4 <|endoftext|>
<commit_before>#if _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif #include <windows.h> #endif #include <chrono> #include <mutex> #include <thread> #include <unordered_map> #include <stdio.h> #include "LogVisor/LogVisor.hpp" /* ANSI sequences */ #define RED "\x1b[1;31m" #define YELLOW "\x1b[1;33m" #define GREEN "\x1b[1;32m" #define MAGENTA "\x1b[1;35m" #define CYAN "\x1b[1;36m" #define BOLD "\x1b[1m" #define NORMAL "\x1b[0m" #if _WIN32 #define FOREGROUND_WHITE FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE #endif namespace LogVisor { static std::unordered_map<std::thread::id, const char*> ThreadMap; void RegisterThreadName(const char* name) { ThreadMap[std::this_thread::get_id()] = name; #if __APPLE__ pthread_setname_np(name); #elif __linux__ pthread_setname_np(pthread_self(), name); #elif _MSC_VER struct { DWORD dwType; // Must be 0x1000. LPCSTR szName; // Pointer to name (in user addr space). DWORD dwThreadID; // Thread ID (-1=caller thread). DWORD dwFlags; // Reserved for future use, must be zero. } info = {0x1000, name, (DWORD)-1, 0}; __try { RaiseException(0x406D1388, 0, sizeof(info)/sizeof(ULONG_PTR), (ULONG_PTR*)&info); } __except(EXCEPTION_EXECUTE_HANDLER) { } #endif } std::vector<std::unique_ptr<ILogger>> MainLoggers; std::atomic_size_t ErrorCount(0); static std::chrono::steady_clock MonoClock; static std::chrono::steady_clock::time_point GlobalStart = MonoClock.now(); static inline std::chrono::steady_clock::duration CurrentUptime() {return MonoClock.now() - GlobalStart;} std::atomic_uint_fast64_t FrameIndex(0); #if _WIN32 static HANDLE Term = 0; #else static const char* Term = nullptr; #endif static bool XtermColor = false; struct ConsoleLogger : public ILogger { std::mutex m; ConsoleLogger() { #if _WIN32 if (!Term) Term = GetStdHandle(STD_ERROR_HANDLE); #else if (!Term) { Term = getenv("TERM"); if (Term && !strncmp(Term, "xterm", 5)) { XtermColor = true; putenv((char*)"TERM=xterm-16color"); } } #endif } static void _reportHead(const char* modName, const char* sourceInfo, Level severity) { std::chrono::steady_clock::duration tm = CurrentUptime(); double tmd = tm.count() * std::chrono::steady_clock::duration::period::num / (double)std::chrono::steady_clock::duration::period::den; std::thread::id thrId = std::this_thread::get_id(); const char* thrName = nullptr; if (ThreadMap.find(thrId) != ThreadMap.end()) thrName = ThreadMap[thrId]; #if _WIN32 SetConsoleTextAttribute(Term, FOREGROUND_INTENSITY | FOREGROUND_WHITE); fprintf(stderr, "["); SetConsoleTextAttribute(Term, FOREGROUND_INTENSITY | FOREGROUND_GREEN); fprintf(stderr, "%5.4f ", tmd); uint64_t fi = FrameIndex.load(); if (fi) fprintf(stderr, "(%llu) ", fi); switch (severity) { case Info: SetConsoleTextAttribute(Term, FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_BLUE); fprintf(stderr, "INFO"); break; case Warning: SetConsoleTextAttribute(Term, FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN); fprintf(stderr, "WARNING"); break; case Error: SetConsoleTextAttribute(Term, FOREGROUND_INTENSITY | FOREGROUND_RED); fprintf(stderr, "ERROR"); break; case FatalError: SetConsoleTextAttribute(Term, FOREGROUND_INTENSITY | FOREGROUND_RED); fprintf(stderr, "FATAL ERROR"); break; default: break; }; SetConsoleTextAttribute(Term, FOREGROUND_INTENSITY | FOREGROUND_WHITE); fprintf(stderr, " %s", modName); SetConsoleTextAttribute(Term, FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN); if (sourceInfo) fprintf(stderr, " {%s}", sourceInfo); SetConsoleTextAttribute(Term, FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_BLUE); if (thrName) fprintf(stderr, " (%s)", thrName); SetConsoleTextAttribute(Term, FOREGROUND_INTENSITY | FOREGROUND_WHITE); fprintf(stderr, "] "); SetConsoleTextAttribute(Term, FOREGROUND_WHITE); #else if (XtermColor) { fprintf(stderr, BOLD "["); fprintf(stderr, GREEN "%5.4f ", tmd); uint_fast64_t fIdx = FrameIndex.load(); if (fIdx) fprintf(stderr, "(%lu) ", fIdx); switch (severity) { case Info: fprintf(stderr, BOLD CYAN "INFO"); break; case Warning: fprintf(stderr, BOLD YELLOW "WARNING"); break; case Error: fprintf(stderr, RED BOLD "ERROR"); break; case FatalError: fprintf(stderr, BOLD RED "FATAL ERROR"); break; default: break; }; fprintf(stderr, NORMAL BOLD " %s", modName); if (sourceInfo) fprintf(stderr, BOLD YELLOW " {%s}", sourceInfo); if (thrName) fprintf(stderr, BOLD MAGENTA " (%s)", thrName); fprintf(stderr, NORMAL BOLD "] " NORMAL); } else { fprintf(stderr, "["); fprintf(stderr, "%5.4f ", tmd); uint_fast64_t fIdx = FrameIndex.load(); if (fIdx) fprintf(stderr, "(%lu) ", fIdx); switch (severity) { case Info: fprintf(stderr, "INFO"); break; case Warning: fprintf(stderr, "WARNING"); break; case Error: fprintf(stderr, "ERROR"); break; case FatalError: fprintf(stderr, "FATAL ERROR"); break; default: break; }; fprintf(stderr, " %s", modName); if (sourceInfo) fprintf(stderr, " {%s}", sourceInfo); if (thrName) fprintf(stderr, " (%s)", thrName); fprintf(stderr, "] "); } #endif } void report(const char* modName, Level severity, const char* format, va_list ap) { std::unique_lock<std::mutex> lk(m); _reportHead(modName, nullptr, severity); vfprintf(stderr, format, ap); fprintf(stderr, "\n"); } void report(const char* modName, Level severity, const wchar_t* format, va_list ap) { std::unique_lock<std::mutex> lk(m); _reportHead(modName, nullptr, severity); vfwprintf(stderr, format, ap); fprintf(stderr, "\n"); } void reportSource(const char* modName, Level severity, const char* file, unsigned linenum, const char* format, va_list ap) { std::unique_lock<std::mutex> lk(m); char sourceInfo[128]; snprintf(sourceInfo, 128, "%s:%u", file, linenum); _reportHead(modName, sourceInfo, severity); vfprintf(stderr, format, ap); fprintf(stderr, "\n"); } void reportSource(const char* modName, Level severity, const char* file, unsigned linenum, const wchar_t* format, va_list ap) { std::unique_lock<std::mutex> lk(m); char sourceInfo[128]; snprintf(sourceInfo, 128, "%s:%u", file, linenum); _reportHead(modName, sourceInfo, severity); vfwprintf(stderr, format, ap); fprintf(stderr, "\n"); } }; void RegisterConsoleLogger() { /* Determine if console logger already added */ for (auto& logger : MainLoggers) { if (typeid(logger.get()) == typeid(ConsoleLogger)) return; } /* Otherwise construct new console logger */ MainLoggers.emplace_back(new ConsoleLogger); } struct FileLogger : public ILogger { FILE* fp; std::mutex m; virtual void openFile()=0; virtual void closeFile() {fclose(fp);} void _reportHead(const char* modName, const char* sourceInfo, Level severity) { std::chrono::steady_clock::duration tm = CurrentUptime(); double tmd = tm.count() * std::chrono::steady_clock::duration::period::num / (double)std::chrono::steady_clock::duration::period::den; std::thread::id thrId = std::this_thread::get_id(); const char* thrName = nullptr; if (ThreadMap.find(thrId) != ThreadMap.end()) thrName = ThreadMap[thrId]; fprintf(fp, "["); switch (severity) { case Info: fprintf(fp, "INFO"); break; case Warning: fprintf(fp, "WARNING"); break; case Error: fprintf(fp, "ERROR"); break; case FatalError: fprintf(fp, "FATAL ERROR"); break; default: break; }; fprintf(fp, " %s", modName); if (sourceInfo) fprintf(stderr, " {%s}", sourceInfo); if (thrName) fprintf(fp, " (%s)", thrName); fprintf(fp, " %5.4f", tmd); uint_fast64_t fIdx = FrameIndex.load(); if (fIdx) fprintf(fp, " (%llu)", fIdx); fprintf(fp, "] "); } void report(const char* modName, Level severity, const char* format, va_list ap) { std::unique_lock<std::mutex> lk(m); openFile(); _reportHead(modName, nullptr, severity); vfprintf(fp, format, ap); fprintf(fp, "\n"); closeFile(); } void report(const char* modName, Level severity, const wchar_t* format, va_list ap) { std::unique_lock<std::mutex> lk(m); openFile(); _reportHead(modName, nullptr, severity); vfwprintf(fp, format, ap); fprintf(fp, "\n"); closeFile(); } void reportSource(const char* modName, Level severity, const char* file, unsigned linenum, const char* format, va_list ap) { std::unique_lock<std::mutex> lk(m); openFile(); char sourceInfo[128]; snprintf(sourceInfo, 128, "%s:%u", file, linenum); _reportHead(modName, sourceInfo, severity); vfprintf(fp, format, ap); fprintf(fp, "\n"); closeFile(); } void reportSource(const char* modName, Level severity, const char* file, unsigned linenum, const wchar_t* format, va_list ap) { std::unique_lock<std::mutex> lk(m); openFile(); char sourceInfo[128]; snprintf(sourceInfo, 128, "%s:%u", file, linenum); _reportHead(modName, sourceInfo, severity); vfwprintf(fp, format, ap); fprintf(fp, "\n"); closeFile(); } }; struct FileLogger8 : public FileLogger { const char* m_filepath; FileLogger8(const char* filepath) : m_filepath(filepath) {} void openFile() {fp = fopen(m_filepath, "a");} }; void RegisterFileLogger(const char* filepath) { /* Determine if file logger already added */ for (auto& logger : MainLoggers) { FileLogger8* filelogger = dynamic_cast<FileLogger8*>(logger.get()); if (filelogger) { if (!strcmp(filepath, filelogger->m_filepath)) return; } } /* Otherwise construct new file logger */ MainLoggers.emplace_back(new FileLogger8(filepath)); } #if LOG_UCS2 struct FileLogger16 : public FileLogger { const wchar_t* m_filepath; FileLogger16(const wchar_t* filepath) : m_filepath(filepath) {} void openFile() {fp = _wfopen(m_filepath, L"a");} }; void RegisterFileLogger(const wchar_t* filepath) { /* Determine if file logger already added */ for (auto& logger : MainLoggers) { FileLogger16* filelogger = dynamic_cast<FileLogger16*>(logger.get()); if (filelogger) { if (!wcscmp(filepath, filelogger->m_filepath)) return; } } /* Otherwise construct new file logger */ MainLoggers.emplace_back(new FileLogger16(filepath)); } #endif } <commit_msg>added inttypes<commit_after>#if _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif #include <windows.h> #endif #include <chrono> #include <mutex> #include <thread> #include <unordered_map> #include <stdio.h> #include <inttypes.h> #include "LogVisor/LogVisor.hpp" /* ANSI sequences */ #define RED "\x1b[1;31m" #define YELLOW "\x1b[1;33m" #define GREEN "\x1b[1;32m" #define MAGENTA "\x1b[1;35m" #define CYAN "\x1b[1;36m" #define BOLD "\x1b[1m" #define NORMAL "\x1b[0m" #if _WIN32 #define FOREGROUND_WHITE FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE #endif namespace LogVisor { static std::unordered_map<std::thread::id, const char*> ThreadMap; void RegisterThreadName(const char* name) { ThreadMap[std::this_thread::get_id()] = name; #if __APPLE__ pthread_setname_np(name); #elif __linux__ pthread_setname_np(pthread_self(), name); #elif _MSC_VER struct { DWORD dwType; // Must be 0x1000. LPCSTR szName; // Pointer to name (in user addr space). DWORD dwThreadID; // Thread ID (-1=caller thread). DWORD dwFlags; // Reserved for future use, must be zero. } info = {0x1000, name, (DWORD)-1, 0}; __try { RaiseException(0x406D1388, 0, sizeof(info)/sizeof(ULONG_PTR), (ULONG_PTR*)&info); } __except(EXCEPTION_EXECUTE_HANDLER) { } #endif } std::vector<std::unique_ptr<ILogger>> MainLoggers; std::atomic_size_t ErrorCount(0); static std::chrono::steady_clock MonoClock; static std::chrono::steady_clock::time_point GlobalStart = MonoClock.now(); static inline std::chrono::steady_clock::duration CurrentUptime() {return MonoClock.now() - GlobalStart;} std::atomic_uint_fast64_t FrameIndex(0); #if _WIN32 static HANDLE Term = 0; #else static const char* Term = nullptr; #endif static bool XtermColor = false; struct ConsoleLogger : public ILogger { std::mutex m; ConsoleLogger() { #if _WIN32 if (!Term) Term = GetStdHandle(STD_ERROR_HANDLE); #else if (!Term) { Term = getenv("TERM"); if (Term && !strncmp(Term, "xterm", 5)) { XtermColor = true; putenv((char*)"TERM=xterm-16color"); } } #endif } static void _reportHead(const char* modName, const char* sourceInfo, Level severity) { std::chrono::steady_clock::duration tm = CurrentUptime(); double tmd = tm.count() * std::chrono::steady_clock::duration::period::num / (double)std::chrono::steady_clock::duration::period::den; std::thread::id thrId = std::this_thread::get_id(); const char* thrName = nullptr; if (ThreadMap.find(thrId) != ThreadMap.end()) thrName = ThreadMap[thrId]; #if _WIN32 SetConsoleTextAttribute(Term, FOREGROUND_INTENSITY | FOREGROUND_WHITE); fprintf(stderr, "["); SetConsoleTextAttribute(Term, FOREGROUND_INTENSITY | FOREGROUND_GREEN); fprintf(stderr, "%5.4f ", tmd); uint64_t fi = FrameIndex.load(); if (fi) fprintf(stderr, "(%" PRIu64 ") ", fi); switch (severity) { case Info: SetConsoleTextAttribute(Term, FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_BLUE); fprintf(stderr, "INFO"); break; case Warning: SetConsoleTextAttribute(Term, FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN); fprintf(stderr, "WARNING"); break; case Error: SetConsoleTextAttribute(Term, FOREGROUND_INTENSITY | FOREGROUND_RED); fprintf(stderr, "ERROR"); break; case FatalError: SetConsoleTextAttribute(Term, FOREGROUND_INTENSITY | FOREGROUND_RED); fprintf(stderr, "FATAL ERROR"); break; default: break; }; SetConsoleTextAttribute(Term, FOREGROUND_INTENSITY | FOREGROUND_WHITE); fprintf(stderr, " %s", modName); SetConsoleTextAttribute(Term, FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN); if (sourceInfo) fprintf(stderr, " {%s}", sourceInfo); SetConsoleTextAttribute(Term, FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_BLUE); if (thrName) fprintf(stderr, " (%s)", thrName); SetConsoleTextAttribute(Term, FOREGROUND_INTENSITY | FOREGROUND_WHITE); fprintf(stderr, "] "); SetConsoleTextAttribute(Term, FOREGROUND_WHITE); #else if (XtermColor) { fprintf(stderr, BOLD "["); fprintf(stderr, GREEN "%5.4f ", tmd); uint_fast64_t fIdx = FrameIndex.load(); if (fIdx) fprintf(stderr, "(%lu) ", fIdx); switch (severity) { case Info: fprintf(stderr, BOLD CYAN "INFO"); break; case Warning: fprintf(stderr, BOLD YELLOW "WARNING"); break; case Error: fprintf(stderr, RED BOLD "ERROR"); break; case FatalError: fprintf(stderr, BOLD RED "FATAL ERROR"); break; default: break; }; fprintf(stderr, NORMAL BOLD " %s", modName); if (sourceInfo) fprintf(stderr, BOLD YELLOW " {%s}", sourceInfo); if (thrName) fprintf(stderr, BOLD MAGENTA " (%s)", thrName); fprintf(stderr, NORMAL BOLD "] " NORMAL); } else { fprintf(stderr, "["); fprintf(stderr, "%5.4f ", tmd); uint_fast64_t fIdx = FrameIndex.load(); if (fIdx) fprintf(stderr, "(%lu) ", fIdx); switch (severity) { case Info: fprintf(stderr, "INFO"); break; case Warning: fprintf(stderr, "WARNING"); break; case Error: fprintf(stderr, "ERROR"); break; case FatalError: fprintf(stderr, "FATAL ERROR"); break; default: break; }; fprintf(stderr, " %s", modName); if (sourceInfo) fprintf(stderr, " {%s}", sourceInfo); if (thrName) fprintf(stderr, " (%s)", thrName); fprintf(stderr, "] "); } #endif } void report(const char* modName, Level severity, const char* format, va_list ap) { std::unique_lock<std::mutex> lk(m); _reportHead(modName, nullptr, severity); vfprintf(stderr, format, ap); fprintf(stderr, "\n"); } void report(const char* modName, Level severity, const wchar_t* format, va_list ap) { std::unique_lock<std::mutex> lk(m); _reportHead(modName, nullptr, severity); vfwprintf(stderr, format, ap); fprintf(stderr, "\n"); } void reportSource(const char* modName, Level severity, const char* file, unsigned linenum, const char* format, va_list ap) { std::unique_lock<std::mutex> lk(m); char sourceInfo[128]; snprintf(sourceInfo, 128, "%s:%u", file, linenum); _reportHead(modName, sourceInfo, severity); vfprintf(stderr, format, ap); fprintf(stderr, "\n"); } void reportSource(const char* modName, Level severity, const char* file, unsigned linenum, const wchar_t* format, va_list ap) { std::unique_lock<std::mutex> lk(m); char sourceInfo[128]; snprintf(sourceInfo, 128, "%s:%u", file, linenum); _reportHead(modName, sourceInfo, severity); vfwprintf(stderr, format, ap); fprintf(stderr, "\n"); } }; void RegisterConsoleLogger() { /* Determine if console logger already added */ for (auto& logger : MainLoggers) { if (typeid(logger.get()) == typeid(ConsoleLogger)) return; } /* Otherwise construct new console logger */ MainLoggers.emplace_back(new ConsoleLogger); } struct FileLogger : public ILogger { FILE* fp; std::mutex m; virtual void openFile()=0; virtual void closeFile() {fclose(fp);} void _reportHead(const char* modName, const char* sourceInfo, Level severity) { std::chrono::steady_clock::duration tm = CurrentUptime(); double tmd = tm.count() * std::chrono::steady_clock::duration::period::num / (double)std::chrono::steady_clock::duration::period::den; std::thread::id thrId = std::this_thread::get_id(); const char* thrName = nullptr; if (ThreadMap.find(thrId) != ThreadMap.end()) thrName = ThreadMap[thrId]; fprintf(fp, "["); switch (severity) { case Info: fprintf(fp, "INFO"); break; case Warning: fprintf(fp, "WARNING"); break; case Error: fprintf(fp, "ERROR"); break; case FatalError: fprintf(fp, "FATAL ERROR"); break; default: break; }; fprintf(fp, " %s", modName); if (sourceInfo) fprintf(stderr, " {%s}", sourceInfo); if (thrName) fprintf(fp, " (%s)", thrName); fprintf(fp, " %5.4f", tmd); uint_fast64_t fIdx = FrameIndex.load(); if (fIdx) fprintf(fp, " (%" PRIu64 ")", fIdx); fprintf(fp, "] "); } void report(const char* modName, Level severity, const char* format, va_list ap) { std::unique_lock<std::mutex> lk(m); openFile(); _reportHead(modName, nullptr, severity); vfprintf(fp, format, ap); fprintf(fp, "\n"); closeFile(); } void report(const char* modName, Level severity, const wchar_t* format, va_list ap) { std::unique_lock<std::mutex> lk(m); openFile(); _reportHead(modName, nullptr, severity); vfwprintf(fp, format, ap); fprintf(fp, "\n"); closeFile(); } void reportSource(const char* modName, Level severity, const char* file, unsigned linenum, const char* format, va_list ap) { std::unique_lock<std::mutex> lk(m); openFile(); char sourceInfo[128]; snprintf(sourceInfo, 128, "%s:%u", file, linenum); _reportHead(modName, sourceInfo, severity); vfprintf(fp, format, ap); fprintf(fp, "\n"); closeFile(); } void reportSource(const char* modName, Level severity, const char* file, unsigned linenum, const wchar_t* format, va_list ap) { std::unique_lock<std::mutex> lk(m); openFile(); char sourceInfo[128]; snprintf(sourceInfo, 128, "%s:%u", file, linenum); _reportHead(modName, sourceInfo, severity); vfwprintf(fp, format, ap); fprintf(fp, "\n"); closeFile(); } }; struct FileLogger8 : public FileLogger { const char* m_filepath; FileLogger8(const char* filepath) : m_filepath(filepath) {} void openFile() {fp = fopen(m_filepath, "a");} }; void RegisterFileLogger(const char* filepath) { /* Determine if file logger already added */ for (auto& logger : MainLoggers) { FileLogger8* filelogger = dynamic_cast<FileLogger8*>(logger.get()); if (filelogger) { if (!strcmp(filepath, filelogger->m_filepath)) return; } } /* Otherwise construct new file logger */ MainLoggers.emplace_back(new FileLogger8(filepath)); } #if LOG_UCS2 struct FileLogger16 : public FileLogger { const wchar_t* m_filepath; FileLogger16(const wchar_t* filepath) : m_filepath(filepath) {} void openFile() {fp = _wfopen(m_filepath, L"a");} }; void RegisterFileLogger(const wchar_t* filepath) { /* Determine if file logger already added */ for (auto& logger : MainLoggers) { FileLogger16* filelogger = dynamic_cast<FileLogger16*>(logger.get()); if (filelogger) { if (!wcscmp(filepath, filelogger->m_filepath)) return; } } /* Otherwise construct new file logger */ MainLoggers.emplace_back(new FileLogger16(filepath)); } #endif } <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief VS1063 VLSI Audio Codec ドライバー @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include <cstdint> #include "G13/port.hpp" #include "common/csi_io.hpp" #include "common/delay.hpp" #include "common/format.hpp" #include "ff12a/src/ff.h" extern "C" { char sci_getch(void); uint16_t sci_length(); } namespace chip { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief VS1063 テンプレートクラス @param[in] CSI CSI(SPI) 制御クラス @param[in] SEL /xCS 制御クラス @param[in] DCS /xDCS 制御クラス @param[in] REQ DREQ 入力クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class CSI, class SEL, class DCS, class REQ> class VS1063 { CSI& csi_; uint8_t frame_; uint8_t buff_[256]; /// VS1063a コマンド表 enum class CMD { MODE, ///< モード制御 STATUS, ///< ステータス BASS, ///< 内臓の低音/高音強調 CLOCKF, ///< クロック周波数+逓倍器 DECODE_TIME, ///< 再生時間[秒] AUDATA, ///< 各種オーディオ・データ WRAM, ///< RAM リード/ライト WRAMADDR, ///< RAM リード/ライト・アドレス HDAT0, ///< ストリーム・ヘッダ・データ0 HDAT1, ///< ストリーム・ヘッダ・データ1 AIADDR, ///< アプリケーション開始アドレス VOL, ///< ボリューム制御 AICTRL0, ///< アプリケーション制御レジスタ0 AICTRL1, ///< アプリケーション制御レジスタ1 AICTRL2, ///< アプリケーション制御レジスタ2 AICTRL3 ///< アプリケーション制御レジスタ3 }; inline void sleep_() { asm("nop"); } inline bool get_status_() { return REQ::P(); } inline void wait_ready_() { while(REQ::P() == 0) sleep_(); } void write_(CMD cmd, uint16_t data) { wait_ready_(); SEL::P = 0; csi_.xchg(0x02); // Write command (0x02) csi_.xchg(static_cast<uint8_t>(cmd)); csi_.xchg(data >> 8); csi_.xchg(data & 0xff); SEL::P = 1; } uint16_t read_(CMD cmd) { wait_ready_(); uint16_t data; SEL::P = 0; csi_.xchg(0x03); // Read command (0x03) csi_.xchg(static_cast<uint8_t>(cmd)); data = static_cast<uint16_t>(CSI::xchg()) << 8; data |= csi_.xchg(); SEL::P = 1; return data; } bool probe_mp3_(FIL* fp) { UINT len; if(f_read(fp, buff_, 10, &len) != FR_OK) { return false; } if(len != 10) { return false; } if(buff_[0] == 'I' && buff_[1] == 'D' && buff_[2] == '3') ; else { return false; } // skip TAG uint32_t ofs = static_cast<uint32_t>(buff_[6]) << 21; ofs |= static_cast<uint32_t>(buff_[7]) << 14; ofs |= static_cast<uint32_t>(buff_[8]) << 7; ofs |= static_cast<uint32_t>(buff_[9]); f_lseek(fp, ofs); utils::format("Find ID3 tag skip: %d\n") % ofs; return true; } public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// VS1063(CSI& csi) : csi_(csi), frame_(0) { } //-----------------------------------------------------------------// /*! @brief 開始(初期化) */ //-----------------------------------------------------------------// void start() { SEL::PM = 0; SEL::PU = 0; DCS::PM = 0; DCS::PU = 0; REQ::PM = 1; REQ::PU = 0; SEL::P = 1; // /xCS = H DCS::P = 1; // /xDCS = H uint8_t intr_level = 0; if(!csi_.start(500000, CSI::PHASE::TYPE4, intr_level)) { utils::format("CSI1 Start fail ! (Clock spped over range)\n"); return; } /// write_(CMD::MODE, 0x4840); write_(CMD::MODE, 0x4800); write_(CMD::VOL, 0x4040); // volume write_(CMD::CLOCKF, 0x9800); // 12.288MHz // write_(CMD::CLOCKF, 0x8BE8); // 12MHz OSC 補正 utils::delay::milli_second(10); if(!csi_.start(8000000, CSI::PHASE::TYPE4, intr_level)) { utils::format("CSI1 Start fail ! (Clock spped over range)\n"); return; } utils::delay::milli_second(10); set_volume(255); } //----------------------------------------------------------------// /*! @brief サービス */ //----------------------------------------------------------------// bool service(FIL* fp) { UINT len; if(f_read(fp, buff_, sizeof(buff_), &len) != FR_OK) { return false; } if(len == 0) return false; const uint8_t* p = buff_; while(len > 0) { while(get_status_() == 0) ; uint16_t l = 32; if(l > len) l = len; csi_.send(p, l); p += l; len -= l; } ++frame_; if(frame_ >= 40) { device::P4.B3 = !device::P4.B3(); frame_ = 0; } if(sci_length()) { auto ch = sci_getch(); if(ch == '>') { return false; } } return true; } //----------------------------------------------------------------// /*! @brief 再生 @param[in] fp ファイル・ディスクリプタ @return エラーなら「false」 */ //----------------------------------------------------------------// bool play(FIL* fp) { if(fp == nullptr) return false; // ファイル・フォーマットを確認 if(!probe_mp3_(fp)) { f_close(fp); return false; } { frame_ = 0; DCS::P = 0; while(service(fp)) { sleep_(); } DCS::P = 1; } f_close(fp); return true; } //----------------------------------------------------------------// /*! @brief ボリュームを設定 @param[in] ボリューム(255が最大、0が最小) */ //----------------------------------------------------------------// void set_volume(uint8_t vol) { vol ^= 0xff; write_(CMD::VOL, (vol << 8) | vol); } //----------------------------------------------------------------// /*! @brief ボリュームを取得 @return ボリューム(255が最大、0が最小) */ //----------------------------------------------------------------// uint8_t get_volume() { return (read_(CMD::VOL) & 255) ^ 0xff; } }; } <commit_msg>update ctrl<commit_after>#pragma once //=====================================================================// /*! @file @brief VS1063 VLSI Audio Codec ドライバー @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include <cstdint> #include "G13/port.hpp" #include "common/csi_io.hpp" #include "common/delay.hpp" #include "common/format.hpp" #include "ff12a/src/ff.h" extern "C" { char sci_getch(void); uint16_t sci_length(); } namespace chip { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief VS1063 テンプレートクラス @param[in] CSI CSI(SPI) 制御クラス @param[in] SEL /xCS 制御クラス @param[in] DCS /xDCS 制御クラス @param[in] REQ DREQ 入力クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class CSI, class SEL, class DCS, class REQ> class VS1063 { CSI& csi_; uint8_t frame_; uint8_t buff_[256]; /// VS1063a コマンド表 enum class CMD { MODE, ///< モード制御 STATUS, ///< ステータス BASS, ///< 内臓の低音/高音強調 CLOCKF, ///< クロック周波数+逓倍器 DECODE_TIME, ///< 再生時間[秒] AUDATA, ///< 各種オーディオ・データ WRAM, ///< RAM リード/ライト WRAMADDR, ///< RAM リード/ライト・アドレス HDAT0, ///< ストリーム・ヘッダ・データ0 HDAT1, ///< ストリーム・ヘッダ・データ1 AIADDR, ///< アプリケーション開始アドレス VOL, ///< ボリューム制御 AICTRL0, ///< アプリケーション制御レジスタ0 AICTRL1, ///< アプリケーション制御レジスタ1 AICTRL2, ///< アプリケーション制御レジスタ2 AICTRL3 ///< アプリケーション制御レジスタ3 }; bool pause_; inline void sleep_() { asm("nop"); } inline bool get_status_() { return REQ::P(); } inline void wait_ready_() { while(REQ::P() == 0) sleep_(); } void write_(CMD cmd, uint16_t data) { wait_ready_(); SEL::P = 0; csi_.xchg(0x02); // Write command (0x02) csi_.xchg(static_cast<uint8_t>(cmd)); csi_.xchg(data >> 8); csi_.xchg(data & 0xff); SEL::P = 1; } uint16_t read_(CMD cmd) { wait_ready_(); uint16_t data; SEL::P = 0; csi_.xchg(0x03); // Read command (0x03) csi_.xchg(static_cast<uint8_t>(cmd)); data = static_cast<uint16_t>(CSI::xchg()) << 8; data |= csi_.xchg(); SEL::P = 1; return data; } bool probe_mp3_(FIL* fp) { UINT len; if(f_read(fp, buff_, 10, &len) != FR_OK) { return false; } if(len != 10) { return false; } if(buff_[0] == 'I' && buff_[1] == 'D' && buff_[2] == '3') ; else { return false; } // skip TAG uint32_t ofs = static_cast<uint32_t>(buff_[6]) << 21; ofs |= static_cast<uint32_t>(buff_[7]) << 14; ofs |= static_cast<uint32_t>(buff_[8]) << 7; ofs |= static_cast<uint32_t>(buff_[9]); f_lseek(fp, ofs); utils::format("Find ID3 tag skip: %d\n") % ofs; return true; } public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// VS1063(CSI& csi) : csi_(csi), frame_(0), pause_(false) { } //-----------------------------------------------------------------// /*! @brief 開始(初期化) */ //-----------------------------------------------------------------// void start() { SEL::PM = 0; SEL::PU = 0; DCS::PM = 0; DCS::PU = 0; REQ::PM = 1; REQ::PU = 0; SEL::P = 1; // /xCS = H DCS::P = 1; // /xDCS = H uint8_t intr_level = 0; if(!csi_.start(500000, CSI::PHASE::TYPE4, intr_level)) { utils::format("CSI1 Start fail ! (Clock spped over range)\n"); return; } /// write_(CMD::MODE, 0x4840); write_(CMD::MODE, 0x4800); write_(CMD::VOL, 0x4040); // volume write_(CMD::CLOCKF, 0x9800); // 12.288MHz // write_(CMD::CLOCKF, 0x8BE8); // 12MHz OSC 補正 utils::delay::milli_second(10); if(!csi_.start(8000000, CSI::PHASE::TYPE4, intr_level)) { utils::format("CSI1 Start fail ! (Clock spped over range)\n"); return; } utils::delay::milli_second(10); set_volume(255); } //----------------------------------------------------------------// /*! @brief サービス */ //----------------------------------------------------------------// bool service(FIL* fp) { UINT len; if(f_read(fp, buff_, sizeof(buff_), &len) != FR_OK) { return false; } if(len == 0) return false; const uint8_t* p = buff_; while(len > 0) { while(get_status_() == 0) ; uint16_t l = 32; if(l > len) l = len; csi_.send(p, l); p += l; len -= l; } return true; } //----------------------------------------------------------------// /*! @brief 再生 @param[in] fp ファイル・ディスクリプタ @return エラーなら「false」 */ //----------------------------------------------------------------// bool play(FIL* fp) { if(fp == nullptr) return false; // ファイル・フォーマットを確認 if(!probe_mp3_(fp)) { f_close(fp); return false; } { frame_ = 0; pause_ = false; DCS::P = 0; while(1) { if(!pause_) { if(!service(fp)) break; ++frame_; if(frame_ >= 40) { device::P4.B3 = !device::P4.B3(); frame_ = 0; } } else { if(frame_ < 192) { device::P4.B3 = (frame_ >> 5) & 1; } else { device::P4.B3 = 1; } utils::delay::milli_second(2); ++frame_; } if(sci_length()) { auto ch = sci_getch(); if(ch == '>') { break; } else if(ch == ' ') { pause_ = !pause_; } } } DCS::P = 1; } f_close(fp); return true; } //----------------------------------------------------------------// /*! @brief ボリュームを設定 @param[in] ボリューム(255が最大、0が最小) */ //----------------------------------------------------------------// void set_volume(uint8_t vol) { vol ^= 0xff; write_(CMD::VOL, (vol << 8) | vol); } //----------------------------------------------------------------// /*! @brief ボリュームを取得 @return ボリューム(255が最大、0が最小) */ //----------------------------------------------------------------// uint8_t get_volume() { return (read_(CMD::VOL) & 255) ^ 0xff; } }; } <|endoftext|>
<commit_before>/* * Copyright (C) 2008 Apple 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: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS 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 "WebKitPrefix.h" <commit_msg>Touch a file in WebKitWin to cause it to build<commit_after>/* * Copyright (C) 2008 Apple 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: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS 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 "WebKitPrefix.h" <|endoftext|>
<commit_before>#include "BetaRand.h" BetaRand::BetaRand(double shape1, double shape2) { setParameters(shape1, shape2); } std::string BetaRand::name() { return "Beta(" + toStringWithPrecision(getAlpha()) + ", " + toStringWithPrecision(getBeta()) + ")"; } void BetaRand::setParameters(double shape1, double shape2) { double alpha = std::max(shape1, MIN_POSITIVE); X.setParameters(alpha, 1); double beta = std::max(shape2, MIN_POSITIVE); Y.setParameters(beta, 1); if (alpha + beta > 30) { /// we use log(Gamma(x)) in order to avoid too big numbers double logGammaX = std::log(X.getInverseGammaFunction()); double logGammaY = std::log(Y.getInverseGammaFunction()); pdfCoef = std::lgamma(alpha + beta) + logGammaX + logGammaY; pdfCoef = std::exp(pdfCoef); } else { pdfCoef = std::tgamma(alpha + beta) * X.getInverseGammaFunction() * Y.getInverseGammaFunction(); } setVariateConstants(); } void BetaRand::setAlpha(double shape1) { double alpha = std::max(shape1, MIN_POSITIVE); X.setParameters(alpha, 1); pdfCoef = std::tgamma(alpha + Y.getShape()) * X.getInverseGammaFunction() * Y.getInverseGammaFunction(); setVariateConstants(); } void BetaRand::setBeta(double shape2) { double beta = std::max(shape2, MIN_POSITIVE); Y.setParameters(beta, 1); pdfCoef = std::tgamma(X.getShape() + beta) * X.getInverseGammaFunction() * Y.getInverseGammaFunction(); setVariateConstants(); } double BetaRand::f(double x) const { if (x < 0 || x > 1) return 0; double alpha = X.getShape(), beta = Y.getShape(); if (std::fabs(alpha - beta) < MIN_POSITIVE) return pdfCoef * std::pow(x - x * x, alpha - 1); double rv = std::pow(x, alpha - 1); rv *= std::pow(1 - x, beta - 1); return pdfCoef * rv; } double BetaRand::F(double x) const { if (x <= 0) return 0; if (x >= 1) return 1; return RandMath::integral([this] (double t) { return BetaRand::f(t); }, 0, x); } double BetaRand::variate() const { double alpha = X.getShape(), beta = Y.getShape(); if (!RandMath::areEqual(alpha, beta) || alpha < 1) return variateForDifferentParameters(); if (alpha == 1) return UniformRand::standardVariate(); if (alpha <= edgeForGenerators) return variateForSmallEqualParameters(); return variateForLargeEqualParameters(); } void BetaRand::sample(QVector<double> &outputData) { double alpha = X.getShape(), beta = Y.getShape(); if (!RandMath::areEqual(alpha, beta) || alpha < 1) { for (double &var : outputData) var = variateForDifferentParameters(); } else if (alpha == 1) { for (double &var : outputData) var = UniformRand::standardVariate(); } else if (alpha <= edgeForGenerators) { for (double &var : outputData) var = variateForSmallEqualParameters(); } else { for (double &var : outputData) var = variateForLargeEqualParameters(); } } double BetaRand::variateForSmallEqualParameters() const { double alpha = X.getShape(); int iter = 0; do { double u1 = UniformRand::standardVariate(); double u2 = UniformRand::standardVariate(); if (u2 <= std::pow(4 * u1 * (1 - u1), alpha - 1)) return u1; } while (++iter <= 1e9); /// one billion should be enough return 0; /// fail } double BetaRand::variateForLargeEqualParameters() const { int iter = 0; do { double n = N.variate(); if (n < 0 || n > 1) continue; double u = UniformRand::standardVariate(); if (u < N.f(n) / (variateCoef * f(n))) return n; } while (++iter <= 1e9); /// one billion should be enough return 0; /// fail } double BetaRand::variateForDifferentParameters() const { double x = X.variate(); return x / (x + Y.variate()); } void BetaRand::setVariateConstants() { double alpha = X.getShape(); /// We need to storage variate coefficient only if alpha = beta and large enough if (alpha > edgeForGenerators && std::fabs(alpha - Y.getShape()) < MIN_POSITIVE) { double t = 1.0 / (alpha + alpha + 1); variateCoef = M_E * std::sqrt(0.5 * M_PI * M_E * t); variateCoef *= std::pow(0.25 - 0.75 * t, alpha - 1); variateCoef *= pdfCoef; /// /= Beta(alpha, alpha) N.setMean(0.5); N.setVar(0.25 * t); } } double BetaRand::E() const { return X.getShape() / (X.getShape() + Y.getShape()); } double BetaRand::Var() const { double alpha = X.getShape(); double beta = Y.getShape(); double denominator = alpha + beta; denominator *= denominator * (denominator + 1); return alpha * beta / denominator; } double BetaRand::Quantile(double p) const { if (p < 0 || p > 1) return NAN; double root = p; if (RandMath::findRoot([this, p] (double x) { return BetaRand::F(x) - p; }, 0, 1, root)) return root; return NAN; } double BetaRand::Mode() const { double alpha = X.getShape(); double beta = Y.getShape(); return (alpha - 1) / (alpha + beta - 2); } double BetaRand::Skewness() const { double alpha = X.getShape(); double beta = Y.getShape(); double skewness = (alpha + beta + 1) / (alpha * beta); skewness = std::sqrt(skewness); skewness *= (alpha - beta); skewness /= (alpha + beta + 2); return skewness + skewness; } double BetaRand::ExcessKurtosis() const { double alpha = X.getShape(); double beta = Y.getShape(); double sum = alpha + beta; double kurtosis = alpha - beta; kurtosis *= kurtosis; kurtosis *= (sum + 1); kurtosis /= (alpha * beta * (sum + 2)); --kurtosis; kurtosis /= (sum + 3); return 6 * kurtosis; } <commit_msg>Update BetaRand.cpp<commit_after>#include "BetaRand.h" BetaRand::BetaRand(double shape1, double shape2) { setParameters(shape1, shape2); } std::string BetaRand::name() { return "Beta(" + toStringWithPrecision(getAlpha()) + ", " + toStringWithPrecision(getBeta()) + ")"; } void BetaRand::setParameters(double shape1, double shape2) { double alpha = std::max(shape1, MIN_POSITIVE); X.setParameters(alpha, 1); double beta = std::max(shape2, MIN_POSITIVE); Y.setParameters(beta, 1); if (alpha + beta > 30) { /// we use log(Gamma(x)) in order to avoid too big numbers double logGammaX = std::log(X.getInverseGammaFunction()); double logGammaY = std::log(Y.getInverseGammaFunction()); pdfCoef = std::lgamma(alpha + beta) + logGammaX + logGammaY; pdfCoef = std::exp(pdfCoef); } else { pdfCoef = std::tgamma(alpha + beta) * X.getInverseGammaFunction() * Y.getInverseGammaFunction(); } setVariateConstants(); } void BetaRand::setAlpha(double shape1) { double alpha = std::max(shape1, MIN_POSITIVE); X.setParameters(alpha, 1); pdfCoef = std::tgamma(alpha + Y.getShape()) * X.getInverseGammaFunction() * Y.getInverseGammaFunction(); setVariateConstants(); } void BetaRand::setBeta(double shape2) { double beta = std::max(shape2, MIN_POSITIVE); Y.setParameters(beta, 1); pdfCoef = std::tgamma(X.getShape() + beta) * X.getInverseGammaFunction() * Y.getInverseGammaFunction(); setVariateConstants(); } double BetaRand::f(double x) const { if (x < 0 || x > 1) return 0; double alpha = X.getShape(), beta = Y.getShape(); if (RandMath::areEqual(alpha, beta)) return pdfCoef * std::pow(x - x * x, alpha - 1); double rv = std::pow(x, alpha - 1); rv *= std::pow(1 - x, beta - 1); return pdfCoef * rv; } double BetaRand::F(double x) const { if (x <= 0) return 0; if (x >= 1) return 1; return RandMath::integral([this] (double t) { return BetaRand::f(t); }, 0, x); } double BetaRand::variate() const { double alpha = X.getShape(), beta = Y.getShape(); if (!RandMath::areEqual(alpha, beta) || alpha < 1) return variateForDifferentParameters(); if (alpha == 1) return UniformRand::standardVariate(); if (alpha <= edgeForGenerators) return variateForSmallEqualParameters(); return variateForLargeEqualParameters(); } void BetaRand::sample(QVector<double> &outputData) { double alpha = X.getShape(), beta = Y.getShape(); if (!RandMath::areEqual(alpha, beta) || alpha < 1) { for (double &var : outputData) var = variateForDifferentParameters(); } else if (alpha == 1) { for (double &var : outputData) var = UniformRand::standardVariate(); } else if (alpha <= edgeForGenerators) { for (double &var : outputData) var = variateForSmallEqualParameters(); } else { for (double &var : outputData) var = variateForLargeEqualParameters(); } } double BetaRand::variateForSmallEqualParameters() const { double alpha = X.getShape(); int iter = 0; do { double u1 = UniformRand::standardVariate(); double u2 = UniformRand::standardVariate(); if (u2 <= std::pow(4 * u1 * (1 - u1), alpha - 1)) return u1; } while (++iter <= 1e9); /// one billion should be enough return 0; /// fail } double BetaRand::variateForLargeEqualParameters() const { int iter = 0; do { double n = N.variate(); if (n < 0 || n > 1) continue; double u = UniformRand::standardVariate(); if (u < N.f(n) / (variateCoef * f(n))) return n; } while (++iter <= 1e9); /// one billion should be enough return 0; /// fail } double BetaRand::variateForDifferentParameters() const { double x = X.variate(); return x / (x + Y.variate()); } void BetaRand::setVariateConstants() { double alpha = X.getShape(); /// We need to storage variate coefficient only if alpha = beta and large enough if (alpha > edgeForGenerators && std::fabs(alpha - Y.getShape()) < MIN_POSITIVE) { double t = 1.0 / (alpha + alpha + 1); variateCoef = M_E * std::sqrt(0.5 * M_PI * M_E * t); variateCoef *= std::pow(0.25 - 0.75 * t, alpha - 1); variateCoef *= pdfCoef; /// /= Beta(alpha, alpha) N.setMean(0.5); N.setVar(0.25 * t); } } double BetaRand::E() const { return X.getShape() / (X.getShape() + Y.getShape()); } double BetaRand::Var() const { double alpha = X.getShape(); double beta = Y.getShape(); double denominator = alpha + beta; denominator *= denominator * (denominator + 1); return alpha * beta / denominator; } double BetaRand::Quantile(double p) const { if (p < 0 || p > 1) return NAN; double root = p; if (RandMath::findRoot([this, p] (double x) { return BetaRand::F(x) - p; }, 0, 1, root)) return root; return NAN; } double BetaRand::Mode() const { double alpha = X.getShape(); double beta = Y.getShape(); return (alpha - 1) / (alpha + beta - 2); } double BetaRand::Skewness() const { double alpha = X.getShape(); double beta = Y.getShape(); double skewness = (alpha + beta + 1) / (alpha * beta); skewness = std::sqrt(skewness); skewness *= (alpha - beta); skewness /= (alpha + beta + 2); return skewness + skewness; } double BetaRand::ExcessKurtosis() const { double alpha = X.getShape(); double beta = Y.getShape(); double sum = alpha + beta; double kurtosis = alpha - beta; kurtosis *= kurtosis; kurtosis *= (sum + 1); kurtosis /= (alpha * beta * (sum + 2)); --kurtosis; kurtosis /= (sum + 3); return 6 * kurtosis; } <|endoftext|>
<commit_before>// Copyright Daniel Wallin, Arvid Norberg 2006. Use, modification and distribution is // 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) #include <libtorrent/session.hpp> #include <libtorrent/torrent.hpp> #include <libtorrent/storage.hpp> #include <boost/python.hpp> #include "gil.hpp" using namespace boost::python; using namespace libtorrent; extern char const* session_status_doc; extern char const* session_status_has_incoming_connections_doc; extern char const* session_status_upload_rate_doc; extern char const* session_status_download_rate_doc; extern char const* session_status_payload_upload_rate_doc; extern char const* session_status_payload_download_rate_doc; extern char const* session_status_total_download_doc; extern char const* session_status_total_upload_doc; extern char const* session_status_total_payload_download_doc; extern char const* session_status_total_payload_upload_doc; extern char const* session_status_num_peers_doc; extern char const* session_status_dht_nodes_doc; extern char const* session_status_cache_nodes_doc; extern char const* session_status_dht_torrents_doc; extern char const* session_doc; extern char const* session_init_doc; extern char const* session_listen_on_doc; extern char const* session_is_listening_doc; extern char const* session_listen_port_doc; extern char const* session_status_m_doc; extern char const* session_start_dht_doc; extern char const* session_stop_dht_doc; extern char const* session_dht_state_doc; extern char const* session_add_torrent_doc; extern char const* session_remove_torrent_doc; extern char const* session_set_download_rate_limit_doc; extern char const* session_download_rate_limit_doc; extern char const* session_set_upload_rate_limit_doc; extern char const* session_upload_rate_limit_doc; extern char const* session_set_max_uploads_doc; extern char const* session_set_max_connections_doc; extern char const* session_set_max_half_open_connections_doc; extern char const* session_num_connections_doc; extern char const* session_set_settings_doc; extern char const* session_set_pe_settings_doc; extern char const* session_get_pe_settings_doc; extern char const* session_set_severity_level_doc; extern char const* session_pop_alert_doc; extern char const* session_start_upnp_doc; extern char const* session_stop_upnp_doc; extern char const* session_start_natpmp_doc; extern char const* session_stop_natpmp_doc; namespace { bool listen_on(session& s, int min_, int max_, char const* interface) { allow_threading_guard guard; return s.listen_on(std::make_pair(min_, max_), interface); } struct invoke_extension_factory { invoke_extension_factory(object const& callback) : cb(callback) {} boost::shared_ptr<torrent_plugin> operator()(torrent* t, void*) { lock_gil lock; return extract<boost::shared_ptr<torrent_plugin> >(cb(ptr(t)))(); } object cb; }; void add_extension(session& s, object const& e) { allow_threading_guard guard; s.add_extension(invoke_extension_factory(e)); } torrent_handle add_torrent(session& s, torrent_info const& ti , boost::filesystem::path const& save, entry const& resume , storage_mode_t storage_mode, bool paused) { allow_threading_guard guard; return s.add_torrent(ti, save, resume, storage_mode, paused, default_storage_constructor); } } // namespace unnamed void bind_session() { class_<session_status>("session_status", session_status_doc) .def_readonly( "has_incoming_connections", &session_status::has_incoming_connections , session_status_has_incoming_connections_doc ) .def_readonly( "upload_rate", &session_status::upload_rate , session_status_upload_rate_doc ) .def_readonly( "download_rate", &session_status::download_rate , session_status_download_rate_doc ) .def_readonly( "payload_upload_rate", &session_status::payload_upload_rate , session_status_payload_upload_rate_doc ) .def_readonly( "payload_download_rate", &session_status::payload_download_rate , session_status_payload_download_rate_doc ) .def_readonly( "total_download", &session_status::total_download , session_status_total_download_doc ) .def_readonly( "total_upload", &session_status::total_upload , session_status_total_upload_doc ) .def_readonly( "total_payload_download", &session_status::total_payload_download , session_status_total_payload_download_doc ) .def_readonly( "total_payload_upload", &session_status::total_payload_upload , session_status_total_payload_upload_doc ) .def_readonly( "num_peers", &session_status::num_peers , session_status_num_peers_doc ) #ifndef TORRENT_DISABLE_DHT .def_readonly( "dht_nodes", &session_status::dht_nodes , session_status_dht_nodes_doc ) .def_readonly( "dht_cache_nodes", &session_status::dht_node_cache , session_status_cache_nodes_doc ) .def_readonly( "dht_torrents", &session_status::dht_torrents , session_status_dht_torrents_doc ) #endif ; enum_<storage_mode_t>("storage_mode_t") .value("storage_mode_allocate", storage_mode_allocate) .value("storage_mode_compact", storage_mode_compact) .value("storage_mode_sparse", storage_mode_sparse) ; enum_<session::options_t>("options_t") .value("none", session::none) .value("delete_files", session::delete_files) ; class_<session, boost::noncopyable>("session", session_doc, no_init) .def( init<fingerprint>(arg("fingerprint")=fingerprint("LT",0,1,0,0), session_init_doc) ) .def( "listen_on", &listen_on , (arg("min"), "max", arg("interface") = (char const*)0) , session_listen_on_doc ) .def("is_listening", allow_threads(&session::is_listening), session_is_listening_doc) .def("listen_port", allow_threads(&session::listen_port), session_listen_port_doc) .def("status", allow_threads(&session::status), session_status_m_doc) #ifndef TORRENT_DISABLE_DHT .def("start_dht", allow_threads(&session::start_dht), session_start_dht_doc) .def("stop_dht", allow_threads(&session::stop_dht), session_stop_dht_doc) .def("dht_state", allow_threads(&session::dht_state), session_dht_state_doc) #endif .def( "add_torrent", &add_torrent , ( arg("resume_data") = entry(), arg("compact_mode") = true , arg("paused") = false ) , session_add_torrent_doc ) .def("remove_torrent", allow_threads(&session::remove_torrent), session_remove_torrent_doc) .def( "set_download_rate_limit", allow_threads(&session::set_download_rate_limit) , session_set_download_rate_limit_doc ) .def( "download_rate_limit", allow_threads(&session::download_rate_limit) , session_download_rate_limit_doc ) .def( "set_upload_rate_limit", allow_threads(&session::set_upload_rate_limit) , session_set_upload_rate_limit_doc ) .def( "upload_rate_limit", allow_threads(&session::upload_rate_limit) , session_upload_rate_limit_doc ) .def( "set_max_uploads", allow_threads(&session::set_max_uploads) , session_set_max_uploads_doc ) .def( "set_max_connections", allow_threads(&session::set_max_connections) , session_set_max_connections_doc ) .def( "set_max_half_open_connections", allow_threads(&session::set_max_half_open_connections) , session_set_max_half_open_connections_doc ) .def( "num_connections", allow_threads(&session::num_connections) , session_num_connections_doc ) .def("set_settings", allow_threads(&session::set_settings), session_set_settings_doc) .def("set_pe_settings", allow_threads(&session::set_pe_settings), session_set_pe_settings_doc) .def("get_pe_settings", allow_threads(&session::get_pe_settings), return_value_policy<copy_const_reference>()) .def( "set_severity_level", allow_threads(&session::set_severity_level) , session_set_severity_level_doc ) .def("pop_alert", allow_threads(&session::pop_alert), session_pop_alert_doc) .def("add_extension", &add_extension) .def("set_peer_proxy", allow_threads(&session::set_peer_proxy)) .def("set_tracker_proxy", allow_threads(&session::set_tracker_proxy)) .def("set_web_seed_proxy", allow_threads(&session::set_web_seed_proxy)) #ifndef TORRENT_DISABLE_DHT .def("set_dht_proxy", allow_threads(&session::set_dht_proxy)) #endif .def("start_upnp", allow_threads(&session::start_upnp), session_start_upnp_doc) .def("stop_upnp", allow_threads(&session::stop_upnp), session_stop_upnp_doc) .def("start_natpmp", allow_threads(&session::start_natpmp), session_start_natpmp_doc) .def("stop_natpmp", allow_threads(&session::stop_natpmp), session_stop_natpmp_doc) ; register_ptr_to_python<std::auto_ptr<alert> >(); } <commit_msg>python binding fix<commit_after>// Copyright Daniel Wallin, Arvid Norberg 2006. Use, modification and distribution is // 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) #include <libtorrent/session.hpp> #include <libtorrent/torrent.hpp> #include <libtorrent/storage.hpp> #include <boost/python.hpp> #include "gil.hpp" using namespace boost::python; using namespace libtorrent; extern char const* session_status_doc; extern char const* session_status_has_incoming_connections_doc; extern char const* session_status_upload_rate_doc; extern char const* session_status_download_rate_doc; extern char const* session_status_payload_upload_rate_doc; extern char const* session_status_payload_download_rate_doc; extern char const* session_status_total_download_doc; extern char const* session_status_total_upload_doc; extern char const* session_status_total_payload_download_doc; extern char const* session_status_total_payload_upload_doc; extern char const* session_status_num_peers_doc; extern char const* session_status_dht_nodes_doc; extern char const* session_status_cache_nodes_doc; extern char const* session_status_dht_torrents_doc; extern char const* session_doc; extern char const* session_init_doc; extern char const* session_listen_on_doc; extern char const* session_is_listening_doc; extern char const* session_listen_port_doc; extern char const* session_status_m_doc; extern char const* session_start_dht_doc; extern char const* session_stop_dht_doc; extern char const* session_dht_state_doc; extern char const* session_add_torrent_doc; extern char const* session_remove_torrent_doc; extern char const* session_set_download_rate_limit_doc; extern char const* session_download_rate_limit_doc; extern char const* session_set_upload_rate_limit_doc; extern char const* session_upload_rate_limit_doc; extern char const* session_set_max_uploads_doc; extern char const* session_set_max_connections_doc; extern char const* session_set_max_half_open_connections_doc; extern char const* session_num_connections_doc; extern char const* session_set_settings_doc; extern char const* session_set_pe_settings_doc; extern char const* session_get_pe_settings_doc; extern char const* session_set_severity_level_doc; extern char const* session_pop_alert_doc; extern char const* session_start_upnp_doc; extern char const* session_stop_upnp_doc; extern char const* session_start_natpmp_doc; extern char const* session_stop_natpmp_doc; namespace { bool listen_on(session& s, int min_, int max_, char const* interface) { allow_threading_guard guard; return s.listen_on(std::make_pair(min_, max_), interface); } struct invoke_extension_factory { invoke_extension_factory(object const& callback) : cb(callback) {} boost::shared_ptr<torrent_plugin> operator()(torrent* t, void*) { lock_gil lock; return extract<boost::shared_ptr<torrent_plugin> >(cb(ptr(t)))(); } object cb; }; void add_extension(session& s, object const& e) { allow_threading_guard guard; s.add_extension(invoke_extension_factory(e)); } torrent_handle add_torrent(session& s, torrent_info const& ti , boost::filesystem::path const& save, entry const& resume , storage_mode_t storage_mode, bool paused) { allow_threading_guard guard; return s.add_torrent(ti, save, resume, storage_mode, paused, default_storage_constructor); } } // namespace unnamed void bind_session() { class_<session_status>("session_status", session_status_doc) .def_readonly( "has_incoming_connections", &session_status::has_incoming_connections , session_status_has_incoming_connections_doc ) .def_readonly( "upload_rate", &session_status::upload_rate , session_status_upload_rate_doc ) .def_readonly( "download_rate", &session_status::download_rate , session_status_download_rate_doc ) .def_readonly( "payload_upload_rate", &session_status::payload_upload_rate , session_status_payload_upload_rate_doc ) .def_readonly( "payload_download_rate", &session_status::payload_download_rate , session_status_payload_download_rate_doc ) .def_readonly( "total_download", &session_status::total_download , session_status_total_download_doc ) .def_readonly( "total_upload", &session_status::total_upload , session_status_total_upload_doc ) .def_readonly( "total_payload_download", &session_status::total_payload_download , session_status_total_payload_download_doc ) .def_readonly( "total_payload_upload", &session_status::total_payload_upload , session_status_total_payload_upload_doc ) .def_readonly( "num_peers", &session_status::num_peers , session_status_num_peers_doc ) #ifndef TORRENT_DISABLE_DHT .def_readonly( "dht_nodes", &session_status::dht_nodes , session_status_dht_nodes_doc ) .def_readonly( "dht_cache_nodes", &session_status::dht_node_cache , session_status_cache_nodes_doc ) .def_readonly( "dht_torrents", &session_status::dht_torrents , session_status_dht_torrents_doc ) #endif ; enum_<storage_mode_t>("storage_mode_t") .value("storage_mode_allocate", storage_mode_allocate) .value("storage_mode_compact", storage_mode_compact) .value("storage_mode_sparse", storage_mode_sparse) ; enum_<session::options_t>("options_t") .value("none", session::none) .value("delete_files", session::delete_files) ; class_<session, boost::noncopyable>("session", session_doc, no_init) .def( init<fingerprint>(arg("fingerprint")=fingerprint("LT",0,1,0,0), session_init_doc) ) .def( "listen_on", &listen_on , (arg("min"), "max", arg("interface") = (char const*)0) , session_listen_on_doc ) .def("is_listening", allow_threads(&session::is_listening), session_is_listening_doc) .def("listen_port", allow_threads(&session::listen_port), session_listen_port_doc) .def("status", allow_threads(&session::status), session_status_m_doc) #ifndef TORRENT_DISABLE_DHT .def("start_dht", allow_threads(&session::start_dht), session_start_dht_doc) .def("stop_dht", allow_threads(&session::stop_dht), session_stop_dht_doc) .def("dht_state", allow_threads(&session::dht_state), session_dht_state_doc) #endif .def( "add_torrent", &add_torrent , ( arg("resume_data") = entry(), arg("storage_mode") = storage_mode_sparse, arg("paused") = false ) , session_add_torrent_doc ) .def("remove_torrent", allow_threads(&session::remove_torrent), session_remove_torrent_doc) .def( "set_download_rate_limit", allow_threads(&session::set_download_rate_limit) , session_set_download_rate_limit_doc ) .def( "download_rate_limit", allow_threads(&session::download_rate_limit) , session_download_rate_limit_doc ) .def( "set_upload_rate_limit", allow_threads(&session::set_upload_rate_limit) , session_set_upload_rate_limit_doc ) .def( "upload_rate_limit", allow_threads(&session::upload_rate_limit) , session_upload_rate_limit_doc ) .def( "set_max_uploads", allow_threads(&session::set_max_uploads) , session_set_max_uploads_doc ) .def( "set_max_connections", allow_threads(&session::set_max_connections) , session_set_max_connections_doc ) .def( "set_max_half_open_connections", allow_threads(&session::set_max_half_open_connections) , session_set_max_half_open_connections_doc ) .def( "num_connections", allow_threads(&session::num_connections) , session_num_connections_doc ) .def("set_settings", allow_threads(&session::set_settings), session_set_settings_doc) .def("set_pe_settings", allow_threads(&session::set_pe_settings), session_set_pe_settings_doc) .def("get_pe_settings", allow_threads(&session::get_pe_settings), return_value_policy<copy_const_reference>()) .def( "set_severity_level", allow_threads(&session::set_severity_level) , session_set_severity_level_doc ) .def("pop_alert", allow_threads(&session::pop_alert), session_pop_alert_doc) .def("add_extension", &add_extension) .def("set_peer_proxy", allow_threads(&session::set_peer_proxy)) .def("set_tracker_proxy", allow_threads(&session::set_tracker_proxy)) .def("set_web_seed_proxy", allow_threads(&session::set_web_seed_proxy)) #ifndef TORRENT_DISABLE_DHT .def("set_dht_proxy", allow_threads(&session::set_dht_proxy)) #endif .def("start_upnp", allow_threads(&session::start_upnp), session_start_upnp_doc) .def("stop_upnp", allow_threads(&session::stop_upnp), session_stop_upnp_doc) .def("start_natpmp", allow_threads(&session::start_natpmp), session_start_natpmp_doc) .def("stop_natpmp", allow_threads(&session::stop_natpmp), session_stop_natpmp_doc) ; register_ptr_to_python<std::auto_ptr<alert> >(); } <|endoftext|>
<commit_before>/*========================================================================= * * Copyright Leiden University Medical Center, Erasmus University Medical * Center and 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.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "selxSuperElastixFilter.h" #include "selxItkSmoothingRecursiveGaussianImageFilterComponent.h" #include "selxItkImageSink.h" #include "selxItkImageSource.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "selxDefaultComponents.h" #include "selxDataManager.h" #include "gtest/gtest.h" /** this test uses the following blueprint setup [SourceComponent] - [itkImageFilter] - [itkImageFilter] - [SinkComponent] - All the nodes are identified by their Class names - All Connections are identified by their Interface names The overlord finds the Source and Sink Components and connects these to it's external pipeline (internal reader and writer filters, currently). */ namespace selx { class itkImageFilterTest : public ::testing::Test { public: using BlueprintITKType = itk::SharedPointerDataObjectDecorator< Blueprint >; typedef BlueprintITKType::Pointer BlueprintITKPointer; typedef std::shared_ptr< Blueprint > BlueprintPointer; typedef Blueprint::ParameterMapType ParameterMapType; typedef Blueprint::ParameterValueType ParameterValueType; typedef DataManager DataManagerType; typedef SuperElastixFilter< TypeList< > > SuperElastixFilterType; typedef itk::Image< double, 3 > Image3DType; typedef itk::ImageFileReader< Image3DType > ImageReader3DType; typedef itk::ImageFileWriter< Image3DType > ImageWriter3DType; virtual void SetUp() { /** register all components used for this test */ // For testing the itkfilter pipeline ComponentFactory< ItkSmoothingRecursiveGaussianImageFilterComponent< 3, double >>::RegisterOneFactory(); ComponentFactory< ItkImageSinkComponent< 3, double >>::RegisterOneFactory(); ComponentFactory< ItkImageSourceComponent< 3, double >>::RegisterOneFactory(); // For testing templated components ComponentFactory< ItkSmoothingRecursiveGaussianImageFilterComponent< 2, double >>::RegisterOneFactory(); ComponentFactory< ItkSmoothingRecursiveGaussianImageFilterComponent< 3, float >>::RegisterOneFactory(); ComponentFactory< ItkSmoothingRecursiveGaussianImageFilterComponent< 2, float >>::RegisterOneFactory(); /** make example blueprint configuration */ BlueprintPointer blueprint = BlueprintPointer( new Blueprint() ); /** the 2 itkImageFilter Components are ItkSmoothingRecursiveGaussianImageFilterComponent*/ ParameterMapType componentParameters; componentParameters[ "NameOfClass" ] = { "ItkSmoothingRecursiveGaussianImageFilterComponent" }; // The parameters over which the Component is templated are criteria for the ComponentSelector too. componentParameters[ "Dimensionality" ] = { "3" }; // template parameters componentParameters[ "PixelType" ] = { "double" }; // Setting of the component are considered as criteria too. If the components can interpret the parameters, it's all good. componentParameters[ "Sigma" ] = { "2.5" }; blueprint->SetComponent( "FistStageFilter", componentParameters ); blueprint->SetComponent( "SecondStageFilter", componentParameters ); // TODO: For now, the connections to make are explicitly indicated by the Interface name. // Design consideration: connections might be indicated by higher concepts ( MetricCostConnection: value and/or derivative? DefaultPipeline? ) ParameterMapType connectionParameters; //connectionParameters["NameOfInterface"] = { "itkImageSourceInterface" }; //TODO: check direction blueprint->SetConnection( "FistStageFilter", "SecondStageFilter", connectionParameters ); /** Add a description of the SourceComponent*/ ParameterMapType sourceComponentParameters; sourceComponentParameters[ "NameOfClass" ] = { "ItkImageSourceComponent" }; blueprint->SetComponent( "Source", sourceComponentParameters ); /** Add a description of the SinkComponent*/ ParameterMapType sinkComponentParameters; sinkComponentParameters[ "NameOfClass" ] = { "ItkImageSinkComponent" }; blueprint->SetComponent( "Sink", sinkComponentParameters ); /** Connect Sink and Source to the itkImageFilter Components*/ blueprint->SetConnection( "Source", "FistStageFilter", connectionParameters ); // blueprint->SetConnection( "SecondStageFilter", "Sink", connectionParameters ); BlueprintITKPointer ITKBlueprint = BlueprintITKType::New(); ITKBlueprint->Set( blueprint ); } virtual void TearDown() { itk::ObjectFactoryBase::UnRegisterAllFactories(); } BlueprintITKPointer ITKBlueprint; }; TEST_F( itkImageFilterTest, Run ) { // Instantiate SuperElastix SuperElastixFilterType::Pointer superElastixFilter; EXPECT_NO_THROW( superElastixFilter = SuperElastixFilterType::New() ); // Data manager provides the paths to the input and output data for unit tests DataManagerType::Pointer dataManager = DataManagerType::New(); // Set up the readers and writers ImageReader3DType::Pointer inputImageReader = ImageReader3DType::New(); inputImageReader->SetFileName( dataManager->GetInputFile( "sphereA3d.mhd" ) ); ImageWriter3DType::Pointer resultImageWriter = ImageWriter3DType::New(); resultImageWriter->SetFileName( dataManager->GetOutputFile( "itkImageFilterTest.mhd" ) ); // Connect SuperElastix in an itk pipeline superElastixFilter->SetInput( "Source", inputImageReader->GetOutput() ); resultImageWriter->SetInput( superElastixFilter->GetOutput< Image3DType >( "Sink" ) ); EXPECT_NO_THROW( superElastixFilter->SetBlueprint( ITKBlueprint ) ); //Optional Update call //superElastixFilter->Update(); // Update call on the writers triggers SuperElastix to configure and execute EXPECT_NO_THROW( resultImageWriter->Update() ); } } // namespace selx <commit_msg>BUG: incorrect blueprint member assignment<commit_after>/*========================================================================= * * Copyright Leiden University Medical Center, Erasmus University Medical * Center and 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.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "selxSuperElastixFilter.h" #include "selxItkSmoothingRecursiveGaussianImageFilterComponent.h" #include "selxItkImageSink.h" #include "selxItkImageSource.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "selxDefaultComponents.h" #include "selxDataManager.h" #include "gtest/gtest.h" /** this test uses the following blueprint setup [SourceComponent] - [itkImageFilter] - [itkImageFilter] - [SinkComponent] - All the nodes are identified by their Class names - All Connections are identified by their Interface names The overlord finds the Source and Sink Components and connects these to it's external pipeline (internal reader and writer filters, currently). */ namespace selx { class itkImageFilterTest : public ::testing::Test { public: using BlueprintITKType = itk::SharedPointerDataObjectDecorator< Blueprint >; typedef BlueprintITKType::Pointer BlueprintITKPointer; typedef std::shared_ptr< Blueprint > BlueprintPointer; typedef Blueprint::ParameterMapType ParameterMapType; typedef Blueprint::ParameterValueType ParameterValueType; typedef DataManager DataManagerType; typedef SuperElastixFilter< TypeList< > > SuperElastixFilterType; typedef itk::Image< double, 3 > Image3DType; typedef itk::ImageFileReader< Image3DType > ImageReader3DType; typedef itk::ImageFileWriter< Image3DType > ImageWriter3DType; virtual void SetUp() { /** register all components used for this test */ // For testing the itkfilter pipeline ComponentFactory< ItkSmoothingRecursiveGaussianImageFilterComponent< 3, double >>::RegisterOneFactory(); ComponentFactory< ItkImageSinkComponent< 3, double >>::RegisterOneFactory(); ComponentFactory< ItkImageSourceComponent< 3, double >>::RegisterOneFactory(); // For testing templated components ComponentFactory< ItkSmoothingRecursiveGaussianImageFilterComponent< 2, double >>::RegisterOneFactory(); ComponentFactory< ItkSmoothingRecursiveGaussianImageFilterComponent< 3, float >>::RegisterOneFactory(); ComponentFactory< ItkSmoothingRecursiveGaussianImageFilterComponent< 2, float >>::RegisterOneFactory(); /** make example blueprint configuration */ BlueprintPointer blueprint = BlueprintPointer( new Blueprint() ); /** the 2 itkImageFilter Components are ItkSmoothingRecursiveGaussianImageFilterComponent*/ ParameterMapType componentParameters; componentParameters[ "NameOfClass" ] = { "ItkSmoothingRecursiveGaussianImageFilterComponent" }; // The parameters over which the Component is templated are criteria for the ComponentSelector too. componentParameters[ "Dimensionality" ] = { "3" }; // template parameters componentParameters[ "PixelType" ] = { "double" }; // Setting of the component are considered as criteria too. If the components can interpret the parameters, it's all good. componentParameters[ "Sigma" ] = { "2.5" }; blueprint->SetComponent( "FistStageFilter", componentParameters ); blueprint->SetComponent( "SecondStageFilter", componentParameters ); // TODO: For now, the connections to make are explicitly indicated by the Interface name. // Design consideration: connections might be indicated by higher concepts ( MetricCostConnection: value and/or derivative? DefaultPipeline? ) ParameterMapType connectionParameters; //connectionParameters["NameOfInterface"] = { "itkImageSourceInterface" }; //TODO: check direction blueprint->SetConnection( "FistStageFilter", "SecondStageFilter", connectionParameters ); /** Add a description of the SourceComponent*/ ParameterMapType sourceComponentParameters; sourceComponentParameters[ "NameOfClass" ] = { "ItkImageSourceComponent" }; blueprint->SetComponent( "Source", sourceComponentParameters ); /** Add a description of the SinkComponent*/ ParameterMapType sinkComponentParameters; sinkComponentParameters[ "NameOfClass" ] = { "ItkImageSinkComponent" }; blueprint->SetComponent( "Sink", sinkComponentParameters ); /** Connect Sink and Source to the itkImageFilter Components*/ blueprint->SetConnection( "Source", "FistStageFilter", connectionParameters ); // blueprint->SetConnection( "SecondStageFilter", "Sink", connectionParameters ); ITKBlueprint = BlueprintITKType::New(); ITKBlueprint->Set( blueprint ); } virtual void TearDown() { itk::ObjectFactoryBase::UnRegisterAllFactories(); } BlueprintITKPointer ITKBlueprint; }; TEST_F( itkImageFilterTest, Run ) { // Instantiate SuperElastix SuperElastixFilterType::Pointer superElastixFilter; EXPECT_NO_THROW( superElastixFilter = SuperElastixFilterType::New() ); // Data manager provides the paths to the input and output data for unit tests DataManagerType::Pointer dataManager = DataManagerType::New(); // Set up the readers and writers ImageReader3DType::Pointer inputImageReader = ImageReader3DType::New(); inputImageReader->SetFileName( dataManager->GetInputFile( "sphereA3d.mhd" ) ); ImageWriter3DType::Pointer resultImageWriter = ImageWriter3DType::New(); resultImageWriter->SetFileName( dataManager->GetOutputFile( "itkImageFilterTest.mhd" ) ); // Connect SuperElastix in an itk pipeline superElastixFilter->SetInput( "Source", inputImageReader->GetOutput() ); resultImageWriter->SetInput( superElastixFilter->GetOutput< Image3DType >( "Sink" ) ); EXPECT_NO_THROW( superElastixFilter->SetBlueprint( ITKBlueprint ) ); //Optional Update call //superElastixFilter->Update(); // Update call on the writers triggers SuperElastix to configure and execute EXPECT_NO_THROW( resultImageWriter->Update() ); } } // namespace selx <|endoftext|>
<commit_before>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at // the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights // reserved. See file COPYRIGHT for details. // // This file is part of the MFEM library. For more information and source code // availability see http://mfem.org. // // MFEM 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) version 2.1 dated February 1999. // // -------------------------------------------------------------- // Field Interp Miniapp: Transfer a GridFunction from one mesh onto another // -------------------------------------------------------------- // // This miniapp provides the capability to transfer a GridFunction // (H1, L2, H(div), and H(curl)) from one mesh onto another using FindPointsGSLIB. // Using FindPoints, we identify the nodal positions of the target mesh with // respect to the source mesh and then interpolate the source GridFunction. // The interpolated values are then projected onto the desired FiniteElementSpace // on the target mesh. Finally, the transferred solution is visualized using GLVis. // // Compile with: make field-interp // // An H(div) function file is provided in this directory for a sample run. // Other functions [H1, H(curl), and L2] can be generated using existing MFEM // example codes in the "../../examples/" directory. // // Sample run: // field-interp // field-interp -ft 3 // field-interp -m1 triple-pt-1.mesh -s1 triple-pt-1.gf -m2 triple-pt-2.mesh -ft 1 // field-interp -m2 ../meshing/amr-quad-q2.mesh -ft 0 -r 1 #include "mfem.hpp" #include <fstream> using namespace mfem; using namespace std; int main (int argc, char *argv[]) { // Set the method's default parameters. const char *src_mesh_file = "../meshing/square01.mesh"; const char *tar_mesh_file = "../../data/inline-tri.mesh"; const char *src_sltn_file = "square01_hdiv.gf"; int order = 3; int ref_levels = 0; int fieldtype = -1; bool visualization = true; // Parse command-line options. OptionsParser args(argc, argv); args.AddOption(&src_mesh_file, "-m1", "--mesh1", "Mesh file for the starting solution."); args.AddOption(&src_sltn_file, "-s1", "--solution1", "Grid function for the starting solution."); args.AddOption(&tar_mesh_file, "-m2", "--mesh2", "Mesh file for interpolation."); args.AddOption(&order, "-o", "--order", "Order of the interpolated solution."); args.AddOption(&ref_levels, "-r", "--refine", "Number of refinements of the interpolation mesh."); args.AddOption(&fieldtype, "-ft", "--field-type", "Target GridFunction type: -1 - source GridFunction type (default)," "0 - H1, 1 - L2, 2 - H(div), 3 - H(curl)."); args.AddOption(&visualization, "-vis", "--visualization", "-no-vis", "--no-visualization", "Enable or disable GLVis visualization."); args.Parse(); if (!args.Good()) { args.PrintUsage(cout); return 1; } args.PrintOptions(cout); // Input meshes. Mesh mesh_1(src_mesh_file, 1, 1, false); Mesh mesh_2(tar_mesh_file, 1, 1, false); const int dim = mesh_1.Dimension(); MFEM_ASSERT(dim == mesh_2.Dimension(), "Source and target meshes " "must be in the same dimension."); MFEM_VERIFY(dim > 1, "GSLIB requires a 2D or a 3D mesh" ); for (int lev = 0; lev < ref_levels; lev++) { mesh_2.UniformRefinement(); } if (mesh_1.GetNodes() == NULL) { mesh_1.SetCurvature(1); } if (mesh_2.GetNodes() == NULL) { mesh_2.SetCurvature(1); } const int mesh_poly_deg = mesh_2.GetNodes()->FESpace()->GetOrder(0); cout << "Source mesh curvature: " << mesh_1.GetNodes()->OwnFEC()->Name() << endl << "Target mesh curvature: " << mesh_2.GetNodes()->OwnFEC()->Name() << endl; ifstream mat_stream_1(src_sltn_file); GridFunction func_source(&mesh_1, mat_stream_1); // Display the starting mesh and the field. if (visualization) { char vishost[] = "localhost"; int visport = 19916; socketstream sout1; sout1.open(vishost, visport); if (!sout1) { cout << "Unable to connect to GLVis server at " << vishost << ':' << visport << endl; } else { sout1.precision(8); sout1 << "solution\n" << mesh_1 << func_source << "window_title 'Source mesh and solution'" << "window_geometry 0 0 600 600"; if (dim == 2) { sout1 << "keys RmjAc"; } if (dim == 3) { sout1 << "keys mA\n"; } sout1 << flush; } } const Geometry::Type gt = mesh_2.GetNodalFESpace()->GetFE(0)->GetGeomType(); MFEM_VERIFY(gt != Geometry::PRISM, "Wedge elements are not currently " "supported."); // Ensure the source GridFunction can be transferred using FindPointsGSLIB. const FiniteElementCollection *fec_in = func_source.FESpace()->FEColl(); std::cout << "Source FE collection: " << fec_in->Name() << std::endl; const int vdim_src = func_source.FESpace()->GetVDim(); int fieldtype_src = -1; { const H1_FECollection *fec_h1 = dynamic_cast<const H1_FECollection *>(fec_in); const L2_FECollection *fec_l2 = dynamic_cast<const L2_FECollection *>(fec_in); const RT_FECollection *fec_rt = dynamic_cast<const RT_FECollection *>(fec_in); const ND_FECollection *fec_nd = dynamic_cast<const ND_FECollection *>(fec_in); if (fec_h1) { fieldtype_src = 0; } else if (fec_l2) { fieldtype_src = 1; } else if (fec_rt) { fieldtype_src = 2; } else if (fec_nd) { fieldtype_src = 3; } else { MFEM_ABORT("GridFunction type not supported yet."); } if (fieldtype_src <= 1 && fec_h1->GetBasisType() != BasisType::GaussLobatto && fec_h1->GetBasisType() != BasisType::GaussLegendre) { MFEM_ABORT("Only nodal basis are currently supported in this miniapp."); } } if (fieldtype == -1) { fieldtype = fieldtype_src; } // Setup the FiniteElementSpace and GridFunction on the target mesh. FiniteElementCollection *fec = NULL; FiniteElementSpace *fes = NULL; int vdim_tar = vdim_src; if (fieldtype == 0) { fec = new H1_FECollection(order, dim); vdim_tar = (fieldtype_src > 1) ? dim : vdim_src; } else if (fieldtype == 1) { fec = new L2_FECollection(order, dim); vdim_tar = (fieldtype_src > 1) ? dim : vdim_src; } else if (fieldtype == 2) { fec = new RT_FECollection(order, dim); vdim_tar = 1; MFEM_VERIFY(fieldtype_src > 1, "Cannot interpolate a scalar " "GridFunction to a vector"); } else if (fieldtype == 3) { fec = new ND_FECollection(order, dim); vdim_tar = 1; MFEM_VERIFY(fieldtype_src > 1, "Cannot interpolate a scalar " "GridFunction to a vector"); } else { MFEM_ABORT("GridFunction type not supported."); } std::cout << "Target FE collection: " << fec->Name() << std::endl; fes = new FiniteElementSpace(&mesh_2, fec, vdim_tar); GridFunction func_target(fes); const int NE = mesh_2.GetNE(), nsp = fes->GetFE(0)->GetNodes().GetNPoints(), ncomp_tar = func_target.VectorDim(); // Generate list of points where the Gridfunction will be evaluated. Vector vxyz; if (fieldtype == 0 && order == mesh_poly_deg) { vxyz = *mesh_2.GetNodes(); } else { vxyz.SetSize(nsp*NE*dim); for (int i = 0; i < NE; i++) { const FiniteElement *fe = fes->GetFE(i); const IntegrationRule ir = fe->GetNodes(); ElementTransformation *et = fes->GetElementTransformation(i); DenseMatrix pos; et->Transform(ir, pos); Vector rowx(vxyz.GetData() + i*nsp, nsp), rowy(vxyz.GetData() + i*nsp + NE*nsp, nsp), rowz; if (dim == 3) { rowz.SetDataAndSize(vxyz.GetData() + i*nsp + 2*NE*nsp, nsp); } pos.GetRow(0, rowx); pos.GetRow(1, rowy); if (dim == 3) { pos.GetRow(2, rowz); } } } const int nodes_cnt = vxyz.Size() / dim; // Evaluate source gridfunction. Vector interp_vals(nodes_cnt*ncomp_tar); FindPointsGSLIB finder; finder.Setup(mesh_1); finder.Interpolate(vxyz, func_source, interp_vals); // Project the interpolated values to the target FiniteElementSpace. if (fieldtype <= 1) // H1 or L2 { if ((fieldtype == 0 && order == mesh_poly_deg) || fieldtype == 1) { func_target = interp_vals; } else // H1 - but mesh order != GridFunction order { Array<int> vdofs; Vector vals; const int nsp = func_target.FESpace()->GetFE(0)->GetNodes().GetNPoints(), NE = mesh_2.GetNE(); Vector elem_dof_vals(nsp*dim); for (int i = 0; i < mesh_2.GetNE(); i++) { fes->GetElementVDofs(i, vdofs); vals.SetSize(vdofs.Size()); for (int j = 0; j < nsp; j++) { for (int d = 0; d < ncomp_tar; d++) { // Arrange values byNodes elem_dof_vals(j+d*nsp) = interp_vals(d*nsp*NE + i*nsp + j); } } func_target.SetSubVector(vdofs, elem_dof_vals); } } } else // H(div) or H(curl) { Array<int> vdofs; Vector vals; const int nsp = func_target.FESpace()->GetFE(0)->GetNodes().GetNPoints(), NE = mesh_2.GetNE(); Vector elem_dof_vals(nsp*dim); for (int i = 0; i < mesh_2.GetNE(); i++) { fes->GetElementVDofs(i, vdofs); vals.SetSize(vdofs.Size()); for (int j = 0; j < nsp; j++) { for (int d = 0; d < ncomp_tar; d++) { // Arrange values byVDim elem_dof_vals(j*ncomp_tar+d) = interp_vals(d*nsp*NE + i*nsp + j); } } fes->GetFE(i)->ProjectFromNodes(elem_dof_vals, *fes->GetElementTransformation(i), vals); func_target.SetSubVector(vdofs, vals); } } // Visualize the transferred solution. if (visualization) { char vishost[] = "localhost"; int visport = 19916; socketstream sout1; sout1.open(vishost, visport); if (!sout1) { cout << "Unable to connect to GLVis server at " << vishost << ':' << visport << endl; } else { sout1.precision(8); sout1 << "solution\n" << mesh_2 << func_target << "window_title 'Target mesh and solution'" << "window_geometry 600 0 600 600"; if (dim == 2) { sout1 << "keys RmjAc"; } if (dim == 3) { sout1 << "keys mA\n"; } sout1 << flush; } } // Output the target mesh with the interpolated solution. ostringstream rho_name; rho_name << "interpolated.gf"; ofstream rho_ofs(rho_name.str().c_str()); rho_ofs.precision(8); func_target.Save(rho_ofs); rho_ofs.close(); // Free the internal gslib data. finder.FreeData(); // Delete delete fes; delete fec; return 0; } <commit_msg>Minor.<commit_after>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at // the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights // reserved. See file COPYRIGHT for details. // // This file is part of the MFEM library. For more information and source code // availability see http://mfem.org. // // MFEM 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) version 2.1 dated February 1999. // // -------------------------------------------------------------- // Field Interp Miniapp: Transfer a GridFunction from one mesh onto another // -------------------------------------------------------------- // // This miniapp provides the capability to transfer a GridFunction // (H1, L2, H(div), and H(curl)) from one mesh onto another using FindPointsGSLIB. // Using FindPoints, we identify the nodal positions of the target mesh with // respect to the source mesh and then interpolate the source GridFunction. // The interpolated values are then projected onto the desired FiniteElementSpace // on the target mesh. Finally, the transferred solution is visualized using GLVis. // // Compile with: make field-interp // // An H(div) function file is provided in this directory for a sample run. // Other functions [H1, H(curl), and L2] can be generated using existing MFEM // example codes in the "../../examples/" directory. // // Sample runs: // field-interp // field-interp -ft 3 // field-interp -m1 triple-pt-1.mesh -s1 triple-pt-1.gf -m2 triple-pt-2.mesh -ft 1 // field-interp -m2 ../meshing/amr-quad-q2.mesh -ft 0 -r 1 #include "mfem.hpp" #include <fstream> using namespace mfem; using namespace std; int main (int argc, char *argv[]) { // Set the method's default parameters. const char *src_mesh_file = "../meshing/square01.mesh"; const char *tar_mesh_file = "../../data/inline-tri.mesh"; const char *src_sltn_file = "square01_hdiv.gf"; int order = 3; int ref_levels = 0; int fieldtype = -1; bool visualization = true; // Parse command-line options. OptionsParser args(argc, argv); args.AddOption(&src_mesh_file, "-m1", "--mesh1", "Mesh file for the starting solution."); args.AddOption(&src_sltn_file, "-s1", "--solution1", "Grid function for the starting solution."); args.AddOption(&tar_mesh_file, "-m2", "--mesh2", "Mesh file for interpolation."); args.AddOption(&order, "-o", "--order", "Order of the interpolated solution."); args.AddOption(&ref_levels, "-r", "--refine", "Number of refinements of the interpolation mesh."); args.AddOption(&fieldtype, "-ft", "--field-type", "Target GridFunction type: -1 - source GridFunction type (default)," "0 - H1, 1 - L2, 2 - H(div), 3 - H(curl)."); args.AddOption(&visualization, "-vis", "--visualization", "-no-vis", "--no-visualization", "Enable or disable GLVis visualization."); args.Parse(); if (!args.Good()) { args.PrintUsage(cout); return 1; } args.PrintOptions(cout); // Input meshes. Mesh mesh_1(src_mesh_file, 1, 1, false); Mesh mesh_2(tar_mesh_file, 1, 1, false); const int dim = mesh_1.Dimension(); MFEM_ASSERT(dim == mesh_2.Dimension(), "Source and target meshes " "must be in the same dimension."); MFEM_VERIFY(dim > 1, "GSLIB requires a 2D or a 3D mesh" ); for (int lev = 0; lev < ref_levels; lev++) { mesh_2.UniformRefinement(); } if (mesh_1.GetNodes() == NULL) { mesh_1.SetCurvature(1); } if (mesh_2.GetNodes() == NULL) { mesh_2.SetCurvature(1); } const int mesh_poly_deg = mesh_2.GetNodes()->FESpace()->GetOrder(0); cout << "Source mesh curvature: " << mesh_1.GetNodes()->OwnFEC()->Name() << endl << "Target mesh curvature: " << mesh_2.GetNodes()->OwnFEC()->Name() << endl; ifstream mat_stream_1(src_sltn_file); GridFunction func_source(&mesh_1, mat_stream_1); // Display the starting mesh and the field. if (visualization) { char vishost[] = "localhost"; int visport = 19916; socketstream sout1; sout1.open(vishost, visport); if (!sout1) { cout << "Unable to connect to GLVis server at " << vishost << ':' << visport << endl; } else { sout1.precision(8); sout1 << "solution\n" << mesh_1 << func_source << "window_title 'Source mesh and solution'" << "window_geometry 0 0 600 600"; if (dim == 2) { sout1 << "keys RmjAc"; } if (dim == 3) { sout1 << "keys mA\n"; } sout1 << flush; } } const Geometry::Type gt = mesh_2.GetNodalFESpace()->GetFE(0)->GetGeomType(); MFEM_VERIFY(gt != Geometry::PRISM, "Wedge elements are not currently " "supported."); // Ensure the source GridFunction can be transferred using FindPointsGSLIB. const FiniteElementCollection *fec_in = func_source.FESpace()->FEColl(); std::cout << "Source FE collection: " << fec_in->Name() << std::endl; const int vdim_src = func_source.FESpace()->GetVDim(); int fieldtype_src = -1; { const H1_FECollection *fec_h1 = dynamic_cast<const H1_FECollection *>(fec_in); const L2_FECollection *fec_l2 = dynamic_cast<const L2_FECollection *>(fec_in); const RT_FECollection *fec_rt = dynamic_cast<const RT_FECollection *>(fec_in); const ND_FECollection *fec_nd = dynamic_cast<const ND_FECollection *>(fec_in); if (fec_h1) { fieldtype_src = 0; } else if (fec_l2) { fieldtype_src = 1; } else if (fec_rt) { fieldtype_src = 2; } else if (fec_nd) { fieldtype_src = 3; } else { MFEM_ABORT("GridFunction type not supported yet."); } if (fieldtype_src <= 1 && fec_h1->GetBasisType() != BasisType::GaussLobatto && fec_h1->GetBasisType() != BasisType::GaussLegendre) { MFEM_ABORT("Only nodal basis are currently supported in this miniapp."); } } if (fieldtype == -1) { fieldtype = fieldtype_src; } // Setup the FiniteElementSpace and GridFunction on the target mesh. FiniteElementCollection *fec = NULL; FiniteElementSpace *fes = NULL; int vdim_tar = vdim_src; if (fieldtype == 0) { fec = new H1_FECollection(order, dim); vdim_tar = (fieldtype_src > 1) ? dim : vdim_src; } else if (fieldtype == 1) { fec = new L2_FECollection(order, dim); vdim_tar = (fieldtype_src > 1) ? dim : vdim_src; } else if (fieldtype == 2) { fec = new RT_FECollection(order, dim); vdim_tar = 1; MFEM_VERIFY(fieldtype_src > 1, "Cannot interpolate a scalar " "GridFunction to a vector"); } else if (fieldtype == 3) { fec = new ND_FECollection(order, dim); vdim_tar = 1; MFEM_VERIFY(fieldtype_src > 1, "Cannot interpolate a scalar " "GridFunction to a vector"); } else { MFEM_ABORT("GridFunction type not supported."); } std::cout << "Target FE collection: " << fec->Name() << std::endl; fes = new FiniteElementSpace(&mesh_2, fec, vdim_tar); GridFunction func_target(fes); const int NE = mesh_2.GetNE(), nsp = fes->GetFE(0)->GetNodes().GetNPoints(), ncomp_tar = func_target.VectorDim(); // Generate list of points where the Gridfunction will be evaluated. Vector vxyz; if (fieldtype == 0 && order == mesh_poly_deg) { vxyz = *mesh_2.GetNodes(); } else { vxyz.SetSize(nsp*NE*dim); for (int i = 0; i < NE; i++) { const FiniteElement *fe = fes->GetFE(i); const IntegrationRule ir = fe->GetNodes(); ElementTransformation *et = fes->GetElementTransformation(i); DenseMatrix pos; et->Transform(ir, pos); Vector rowx(vxyz.GetData() + i*nsp, nsp), rowy(vxyz.GetData() + i*nsp + NE*nsp, nsp), rowz; if (dim == 3) { rowz.SetDataAndSize(vxyz.GetData() + i*nsp + 2*NE*nsp, nsp); } pos.GetRow(0, rowx); pos.GetRow(1, rowy); if (dim == 3) { pos.GetRow(2, rowz); } } } const int nodes_cnt = vxyz.Size() / dim; // Evaluate source gridfunction. Vector interp_vals(nodes_cnt*ncomp_tar); FindPointsGSLIB finder; finder.Setup(mesh_1); finder.Interpolate(vxyz, func_source, interp_vals); // Project the interpolated values to the target FiniteElementSpace. if (fieldtype <= 1) // H1 or L2 { if ((fieldtype == 0 && order == mesh_poly_deg) || fieldtype == 1) { func_target = interp_vals; } else // H1 - but mesh order != GridFunction order { Array<int> vdofs; Vector vals; const int nsp = func_target.FESpace()->GetFE(0)->GetNodes().GetNPoints(), NE = mesh_2.GetNE(); Vector elem_dof_vals(nsp*dim); for (int i = 0; i < mesh_2.GetNE(); i++) { fes->GetElementVDofs(i, vdofs); vals.SetSize(vdofs.Size()); for (int j = 0; j < nsp; j++) { for (int d = 0; d < ncomp_tar; d++) { // Arrange values byNodes elem_dof_vals(j+d*nsp) = interp_vals(d*nsp*NE + i*nsp + j); } } func_target.SetSubVector(vdofs, elem_dof_vals); } } } else // H(div) or H(curl) { Array<int> vdofs; Vector vals; const int nsp = func_target.FESpace()->GetFE(0)->GetNodes().GetNPoints(), NE = mesh_2.GetNE(); Vector elem_dof_vals(nsp*dim); for (int i = 0; i < mesh_2.GetNE(); i++) { fes->GetElementVDofs(i, vdofs); vals.SetSize(vdofs.Size()); for (int j = 0; j < nsp; j++) { for (int d = 0; d < ncomp_tar; d++) { // Arrange values byVDim elem_dof_vals(j*ncomp_tar+d) = interp_vals(d*nsp*NE + i*nsp + j); } } fes->GetFE(i)->ProjectFromNodes(elem_dof_vals, *fes->GetElementTransformation(i), vals); func_target.SetSubVector(vdofs, vals); } } // Visualize the transferred solution. if (visualization) { char vishost[] = "localhost"; int visport = 19916; socketstream sout1; sout1.open(vishost, visport); if (!sout1) { cout << "Unable to connect to GLVis server at " << vishost << ':' << visport << endl; } else { sout1.precision(8); sout1 << "solution\n" << mesh_2 << func_target << "window_title 'Target mesh and solution'" << "window_geometry 600 0 600 600"; if (dim == 2) { sout1 << "keys RmjAc"; } if (dim == 3) { sout1 << "keys mA\n"; } sout1 << flush; } } // Output the target mesh with the interpolated solution. ostringstream rho_name; rho_name << "interpolated.gf"; ofstream rho_ofs(rho_name.str().c_str()); rho_ofs.precision(8); func_target.Save(rho_ofs); rho_ofs.close(); // Free the internal gslib data. finder.FreeData(); // Delete delete fes; delete fec; return 0; } <|endoftext|>
<commit_before>/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */ #include <iostream> #include "linbox/matrix/polynomial-matrix.h" #include "linbox/randiter/random-fftprime.h" #include "linbox/randiter/random-prime.h" #include "linbox/ring/modular.h" #include "linbox/algorithms/polynomial-matrix/polynomial-matrix-domain.h" #include "linbox/algorithms/polynomial-matrix/order-basis.h" #include "linbox/algorithms/block-coppersmith-domain.h" using namespace LinBox; using namespace std; template<typename Field, typename Mat> string check_sigma(const Field& F, const Mat& sigma, Mat& serie, size_t ord){ Mat T(F,sigma.rowdim(),serie.coldim(),sigma.size()+serie.size()-1); PolynomialMatrixMulDomain<Field> PMD(F); PMD.mul(T,sigma,serie); MatrixDomain<Field> MD(F); size_t i=0; string msg("....."); bool nul_sigma=true; while(i<ord && MD.isZero(T[i])){ if (!MD.isZero(sigma[i])) nul_sigma=false; i++; } if (i<ord){ cout<<"error at degree="<<i<<endl; T[i].write(std::cout, Tag::FileFormat::Plain); cout<<"***"<<endl; cout<<serie<<endl; cout<<sigma<<endl; } if (i==ord && !nul_sigma) msg+="done"; else msg+="error"; return msg; } template<typename MatPol> bool operator==(const MatPol& A, const MatPol& B){ MatrixDomain<typename MatPol::Field> MD(A.field()); if (A.real_degree()!=B.real_degree()|| A.rowdim()!= B.rowdim() || A.coldim()!=B.coldim()){ cout<<A.size()<<"("<<A.rowdim()<<"x"<<A.coldim()<<") <> " <<B.size()<<"("<<B.rowdim()<<"x"<<B.coldim()<<") <> "<<endl; return false; } size_t i=0; while (i<=A.real_degree() && MD.areEqual(A[i],B[i])) i++; if (i<=A.real_degree() && A.rowdim()<10 && A.coldim()<10){ cout<<"first:"<<endl<<A<<endl; cout<<"second:"<<endl<<B<<endl; } return i>A.real_degree(); } template<typename Field, typename RandIter> void check_sigma(const Field& F, const RandIter& Gen, size_t m, size_t n, size_t d) { //typedef typename Field::Element Element; typedef PolynomialMatrix<PMType::matfirst,PMStorage::plain,Field> MatrixP; //typedef PolynomialMatrix<PMType::polfirst,PMStorage::plain,Field> MatrixP; MatrixP Serie(F, m, n, d); MatrixP Sigma1(F, m, m, d+1),Sigma2(F, m, m, d+1),Sigma3(F, m, m, d+1); // set the Serie at random for (size_t k=0;k<d;++k) for (size_t i=0;i<m;++i) for (size_t j=0;j<n;++j) Gen.random(Serie.ref(i,j,k)); //std::cout<<"Serie:="<<Serie<<std::endl; // define the shift vector<size_t> shift(m,0); vector<size_t> shift2(shift),shift3(shift); OrderBasis<Field> SB(F); SB.M_Basis(Sigma3, Serie, d, shift3); std::cout << "M-Basis : " <<check_sigma(F,Sigma3,Serie,d)<<endl; SB.PM_Basis2(Sigma1,Serie, d, shift); std::cout << "PM-Basis : " <<check_sigma(F,Sigma1,Serie,d)<<endl; SB.oPM_Basis(Sigma2, Serie, d, shift2); std::cout << "PM-Basis iter : " <<check_sigma(F,Sigma2,Serie,d)<<endl; // if (!(Sigma1==Sigma2)){ // cout<<"---> different basis for PM-Basis and PM-Basis iter"<<endl; // cout<<Sigma1<<endl; // cout<<Sigma2<<endl; // } cout<<endl; } int main(int argc, char** argv){ static size_t m = 64; // matrix dimension static size_t n = 32; // matrix dimension static size_t b = 20; // entries bitsize static size_t d = 32; // matrix degree static long seed = time(NULL); static Argument args[] = { { 'm', "-m M", "Set row dimension of matrix series to M.", TYPE_INT, &m }, { 'n', "-n N", "Set column dimension of matrix series to N.", TYPE_INT, &n }, { 'd', "-d D", "Set degree of matrix series to D.", TYPE_INT, &d }, { 'b', "-b B", "Set bitsize of the matrix entries", TYPE_INT, &b }, { 's', "-s s", "Set the random seed to a specific value", TYPE_INT, &seed}, END_OF_ARGUMENTS }; parseArguments (argc, argv, args); typedef Givaro::Modular<double> SmallField; typedef Givaro::Modular<Givaro::Integer> LargeField; size_t logd=integer(d).bitsize(); std::cout<<"### matrix series is of size "<<m<<" x "<<n<<" of degree "<<d<<std::endl; if (b < 26){ if (logd>b-2){ std::cout<<"degree is to large for field bitsize: "<<b<<std::endl; exit(0); } RandomFFTPrime Rd(b,seed); integer p = Rd.randomPrime(logd+1); std::cout<<"# starting sigma basis computation over Fp[x] with p="<<p<<endl;; SmallField F(p); typename SmallField::RandIter G(F,0,seed); check_sigma(F,G,m,n,d); } else { RandomPrimeIterator Rd(b,seed); integer p = Rd.randomPrime(); std::cout<<"# starting sigma basis computation over Fp[x] with p="<<p<<endl;; LargeField F(p); typename LargeField::RandIter G(F,0,seed); check_sigma(F,G,m,n,d); } return 0; } <commit_msg>remove bug with const qualifier<commit_after>/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */ #include <iostream> #include "linbox/matrix/polynomial-matrix.h" #include "linbox/randiter/random-fftprime.h" #include "linbox/randiter/random-prime.h" #include "linbox/ring/modular.h" #include "linbox/algorithms/polynomial-matrix/polynomial-matrix-domain.h" #include "linbox/algorithms/polynomial-matrix/order-basis.h" #include "linbox/algorithms/block-coppersmith-domain.h" using namespace LinBox; using namespace std; template<typename Field, typename Mat> string check_sigma(const Field& F, const Mat& sigma, Mat& serie, size_t ord){ Mat T(F,sigma.rowdim(),serie.coldim(),sigma.size()+serie.size()-1); PolynomialMatrixMulDomain<Field> PMD(F); PMD.mul(T,sigma,serie); MatrixDomain<Field> MD(F); size_t i=0; string msg("....."); bool nul_sigma=true; while(i<ord && MD.isZero(T[i])){ if (!MD.isZero(sigma[i])) nul_sigma=false; i++; } if (i<ord){ cout<<"error at degree="<<i<<endl; T[i].write(std::cout, Tag::FileFormat::Plain); cout<<"***"<<endl; cout<<serie<<endl; cout<<sigma<<endl; } if (i==ord && !nul_sigma) msg+="done"; else msg+="error"; return msg; } template<typename MatPol> bool operator==(const MatPol& A, const MatPol& B){ MatrixDomain<typename MatPol::Field> MD(A.field()); if (A.real_degree()!=B.real_degree()|| A.rowdim()!= B.rowdim() || A.coldim()!=B.coldim()){ cout<<A.size()<<"("<<A.rowdim()<<"x"<<A.coldim()<<") <> " <<B.size()<<"("<<B.rowdim()<<"x"<<B.coldim()<<") <> "<<endl; return false; } size_t i=0; while (i<=A.real_degree() && MD.areEqual(A[i],B[i])) i++; if (i<=A.real_degree() && A.rowdim()<10 && A.coldim()<10){ cout<<"first:"<<endl<<A<<endl; cout<<"second:"<<endl<<B<<endl; } return i>A.real_degree(); } template<typename Field, typename RandIter> void check_sigma(const Field& F, RandIter& Gen, size_t m, size_t n, size_t d) { //typedef typename Field::Element Element; typedef PolynomialMatrix<PMType::matfirst,PMStorage::plain,Field> MatrixP; //typedef PolynomialMatrix<PMType::polfirst,PMStorage::plain,Field> MatrixP; MatrixP Serie(F, m, n, d); MatrixP Sigma1(F, m, m, d+1),Sigma2(F, m, m, d+1),Sigma3(F, m, m, d+1); // set the Serie at random for (size_t k=0;k<d;++k) for (size_t i=0;i<m;++i) for (size_t j=0;j<n;++j) Gen.random(Serie.ref(i,j,k)); //std::cout<<"Serie:="<<Serie<<std::endl; // define the shift vector<size_t> shift(m,0); vector<size_t> shift2(shift),shift3(shift); OrderBasis<Field> SB(F); SB.M_Basis(Sigma3, Serie, d, shift3); std::cout << "M-Basis : " <<check_sigma(F,Sigma3,Serie,d)<<endl; SB.PM_Basis2(Sigma1,Serie, d, shift); std::cout << "PM-Basis : " <<check_sigma(F,Sigma1,Serie,d)<<endl; SB.oPM_Basis(Sigma2, Serie, d, shift2); std::cout << "PM-Basis iter : " <<check_sigma(F,Sigma2,Serie,d)<<endl; // if (!(Sigma1==Sigma2)){ // cout<<"---> different basis for PM-Basis and PM-Basis iter"<<endl; // cout<<Sigma1<<endl; // cout<<Sigma2<<endl; // } cout<<endl; } int main(int argc, char** argv){ static size_t m = 64; // matrix dimension static size_t n = 32; // matrix dimension static size_t b = 20; // entries bitsize static size_t d = 32; // matrix degree static long seed = time(NULL); static Argument args[] = { { 'm', "-m M", "Set row dimension of matrix series to M.", TYPE_INT, &m }, { 'n', "-n N", "Set column dimension of matrix series to N.", TYPE_INT, &n }, { 'd', "-d D", "Set degree of matrix series to D.", TYPE_INT, &d }, { 'b', "-b B", "Set bitsize of the matrix entries", TYPE_INT, &b }, { 's', "-s s", "Set the random seed to a specific value", TYPE_INT, &seed}, END_OF_ARGUMENTS }; parseArguments (argc, argv, args); typedef Givaro::Modular<double> SmallField; typedef Givaro::Modular<Givaro::Integer> LargeField; size_t logd=integer(d).bitsize(); std::cout<<"### matrix series is of size "<<m<<" x "<<n<<" of degree "<<d<<std::endl; if (b < 26){ if (logd>b-2){ std::cout<<"degree is to large for field bitsize: "<<b<<std::endl; exit(0); } RandomFFTPrime Rd(b,seed); integer p = Rd.randomPrime(logd+1); std::cout<<"# starting sigma basis computation over Fp[x] with p="<<p<<endl;; SmallField F(p); typename SmallField::RandIter G(F,0,seed); check_sigma(F,G,m,n,d); } else { RandomPrimeIterator Rd(b,seed); integer p = Rd.randomPrime(); std::cout<<"# starting sigma basis computation over Fp[x] with p="<<p<<endl;; LargeField F(p); typename LargeField::RandIter G(F,0,seed); check_sigma(F,G,m,n,d); } return 0; } <|endoftext|>
<commit_before>#include <raindance/Core/Headers.hh> #include <raindance/Core/OpenCL.hh> class GPUGraph { public: struct ParticleForce { glm::vec4 Direction; }; struct NodeParticle { glm::vec4 Origin; }; struct NodeInstance { typedef unsigned int ID; glm::vec4 Position; glm::vec4 Color; cl_float Size; ParticleForce Force; glm::vec3 __Unused; // NOTE: Memory alignment with OpenCL, reserved for later. }; struct EdgeParticle { glm::vec4 Origin; }; struct EdgeInstance { typedef unsigned int ID; glm::vec4 SourcePosition; glm::vec4 SourceColor; glm::vec4 TargetPosition; glm::vec4 TargetColor; cl_float Width; cl_uint SourceID; cl_uint TargetID; cl_float __Unused; // NOTE : Memory alignment with OpenCL, reserved for later. }; GPUGraph() { m_Icon = new Icon(); m_Icon->load("network/shapes/disk", FS::BinaryFile("Assets/NetworkView/shape_disk.png")); FS::TextFile nodes_vert("Assets/NetworkView/nodes.vert"); FS::TextFile nodes_geom("Assets/NetworkView/nodes.geom"); FS::TextFile nodes_frag("Assets/NetworkView/nodes.frag"); m_NodeShader = ResourceManager::getInstance().loadShader("NetworkView/nodes", nodes_vert.content(), nodes_frag.content(), nodes_geom.content()); // m_NodeShader->dump(); FS::TextFile edges_vert("Assets/NetworkView/edges.vert"); FS::TextFile edges_geom("Assets/NetworkView/edges.geom"); FS::TextFile edges_frag("Assets/NetworkView/edges.frag"); m_EdgeShader = ResourceManager::getInstance().loadShader("NetworkView/edges", edges_vert.content(), edges_frag.content(), edges_geom.content()); // m_EdgeShader->dump(); m_NeedsUpdate = true; } virtual ~GPUGraph() { SAFE_DELETE(m_Icon); ResourceManager::getInstance().unload(m_NodeShader); } void initialize(Context* context) { // OpenGL { // ----- Node Particle Geometry ----- m_NodeParticleBuffer << glm::vec4(0, 0, 0, 0); m_NodeParticleBuffer.describe("a_Origin", 4, GL_FLOAT, sizeof(NodeParticle), 0); m_NodeParticleBuffer.generate(Buffer::STATIC); // ----- Edge Particle Geometry ----- m_EdgeParticleBuffer << glm::vec4(0, 0, 0, 0); m_EdgeParticleBuffer.describe("a_Origin", 4, GL_FLOAT, sizeof(EdgeParticle), 0); m_EdgeParticleBuffer.generate(Buffer::STATIC); } // OpenCL { m_OpenCL.detect(); //m_OpenCL.dump(); // NOTE : We are assuming the last device is the best one. m_CL.Device = m_OpenCL.devices().back(); m_OpenCL.dump(*m_CL.Device); m_CL.Context = m_OpenCL.createContext(*m_CL.Device); m_CL.Queue = m_OpenCL.createCommandQueue(*m_CL.Context); auto source = FS::TextFile("./Assets/NetworkView/physics.cl"); m_CL.Program = m_OpenCL.loadProgram(*m_CL.Context, "physics", source.content()); m_CL.RepulsionK = m_OpenCL.createKernel(*m_CL.Program, "repulsion"); m_CL.AttractionK = m_OpenCL.createKernel(*m_CL.Program, "attraction"); m_CL.NodeAnimationK = m_OpenCL.createKernel(*m_CL.Program, "node_animation"); m_CL.EdgeAnimationK = m_OpenCL.createKernel(*m_CL.Program, "edge_animation"); clFinish(m_CL.Queue->Object); } } void updateOpenGL(Context* context) { // LOG("updateOpenGL: %u nodes, %u edges.\n", m_NodeBuffer.size() / sizeof(Node), m_EdgeBuffer.size() / sizeof(Edge)); if (m_NodeInstanceBuffer.size() == 0) // TODO: HACK: OpenGL doesn't like VBO resizing, Find a way to handle it properly. return; // --- Define Node Instances static bool m_NodeInstanceBufferFirstUpdate = true; if (!m_NodeInstanceBufferFirstUpdate) m_NodeInstanceBuffer.update(); m_NodeInstanceBuffer.describe("a_Position", 4, GL_FLOAT, sizeof(NodeInstance), 0); m_NodeInstanceBuffer.describe("a_Color", 4, GL_FLOAT, sizeof(NodeInstance), 1 * sizeof(glm::vec4)); m_NodeInstanceBuffer.describe("a_Size", 1, GL_FLOAT, sizeof(NodeInstance), 2 * sizeof(glm::vec4)); if (m_NodeInstanceBufferFirstUpdate) m_NodeInstanceBuffer.generate(Buffer::DYNAMIC); m_NodeInstanceBufferFirstUpdate = false; // --- Define Edge Instances static bool m_EdgeInstanceBufferFirstUpdate = true; if (!m_EdgeInstanceBufferFirstUpdate) m_EdgeInstanceBuffer.update(); m_EdgeInstanceBuffer.describe("a_SourcePosition", 4, GL_FLOAT, sizeof(EdgeInstance), 0); m_EdgeInstanceBuffer.describe("a_SourceColor", 4, GL_FLOAT, sizeof(EdgeInstance), 1 * sizeof(glm::vec4)); m_EdgeInstanceBuffer.describe("a_TargetPosition", 4, GL_FLOAT, sizeof(EdgeInstance), 2 * sizeof(glm::vec4)); m_EdgeInstanceBuffer.describe("a_TargetColor", 4, GL_FLOAT, sizeof(EdgeInstance), 3 * sizeof(glm::vec4)); m_EdgeInstanceBuffer.describe("a_Width", 1, GL_FLOAT, sizeof(EdgeInstance), 4 * sizeof(glm::vec4)); if (m_EdgeInstanceBufferFirstUpdate) m_EdgeInstanceBuffer.generate(Buffer::DYNAMIC); m_EdgeInstanceBufferFirstUpdate = false; } void updateOpenCL(Context* context) { size_t node_count = m_NodeInstanceBuffer.size() / sizeof(NodeInstance); size_t edge_count = m_EdgeInstanceBuffer.size() / sizeof(EdgeInstance); if (node_count == 0) // TODO: HACK: OpenGL doesn't like VBO resizing, Find a way to handle it properly. return; static bool m_OCLNeedsUpdate = true; if (m_OCLNeedsUpdate) { m_CL.NodeInstanceBuffer = m_OpenCL.createFromGLBuffer(*m_CL.Context, CL_MEM_READ_WRITE, m_NodeInstanceBuffer.vbo()); m_CL.EdgeInstanceBuffer = m_OpenCL.createFromGLBuffer(*m_CL.Context, CL_MEM_READ_WRITE, m_EdgeInstanceBuffer.vbo()); clFinish(m_CL.Queue->Object); m_OCLNeedsUpdate = false; } // ----- Parameters ----- static int Iterations = 0; if (Iterations >= 100) return; const float cube_side = 100; // NOTE : Graph should fit in this cube const float volume = cube_side * cube_side * cube_side; m_CL.K = pow(volume / node_count, 1.0 / 3.0); m_CL.Time = context->clock().seconds(); m_CL.Temperature = cube_side / (Iterations + 1); LOG("Iteration: %i, K: %f, Time: %f, Temperature: %f\n", Iterations, m_CL.K, m_CL.Time, m_CL.Temperature); // ----- Node Repulsion ----- m_OpenCL.enqueueAcquireGLObjects(*m_CL.Queue, 1, &m_CL.NodeInstanceBuffer->Object, 0, 0, NULL); { m_CL.RepulsionK->setArgument(0, *m_CL.NodeInstanceBuffer); m_CL.RepulsionK->setArgument(1, &m_CL.K, sizeof(float)); m_OpenCL.enqueueNDRangeKernel(*m_CL.Queue, *m_CL.RepulsionK, 1, NULL, &node_count, NULL, 0, NULL, NULL); } m_OpenCL.enqueueReleaseGLObjects(*m_CL.Queue, 1, &m_CL.NodeInstanceBuffer->Object, 0, 0, NULL); // ----- Edge Attraction ----- m_OpenCL.enqueueAcquireGLObjects(*m_CL.Queue, 1, &m_CL.NodeInstanceBuffer->Object, 0, 0, NULL); m_OpenCL.enqueueAcquireGLObjects(*m_CL.Queue, 1, &m_CL.EdgeInstanceBuffer->Object, 0, 0, NULL); { m_CL.AttractionK->setArgument(0, *m_CL.NodeInstanceBuffer); m_CL.AttractionK->setArgument(1, *m_CL.EdgeInstanceBuffer); m_CL.AttractionK->setArgument(2, &m_CL.K, sizeof(float)); m_OpenCL.enqueueNDRangeKernel(*m_CL.Queue, *m_CL.AttractionK, 1, NULL, &edge_count, NULL, 0, NULL, NULL); } m_OpenCL.enqueueReleaseGLObjects(*m_CL.Queue, 1, &m_CL.EdgeInstanceBuffer->Object, 0, 0, NULL); m_OpenCL.enqueueReleaseGLObjects(*m_CL.Queue, 1, &m_CL.NodeInstanceBuffer->Object, 0, 0, NULL); // ----- Node Animation ----- m_OpenCL.enqueueAcquireGLObjects(*m_CL.Queue, 1, &m_CL.NodeInstanceBuffer->Object, 0, 0, NULL); { m_CL.NodeAnimationK->setArgument(0, *m_CL.NodeInstanceBuffer); m_CL.NodeAnimationK->setArgument(1, &m_CL.Temperature, sizeof(float)); m_OpenCL.enqueueNDRangeKernel(*m_CL.Queue, *m_CL.NodeAnimationK, 1, NULL, &node_count, NULL, 0, NULL, NULL); } m_OpenCL.enqueueReleaseGLObjects(*m_CL.Queue, 1, &m_CL.NodeInstanceBuffer->Object, 0, 0, NULL); // ----- Edge Animation ----- m_OpenCL.enqueueAcquireGLObjects(*m_CL.Queue, 1, &m_CL.NodeInstanceBuffer->Object, 0, 0, NULL); m_OpenCL.enqueueAcquireGLObjects(*m_CL.Queue, 1, &m_CL.EdgeInstanceBuffer->Object, 0, 0, NULL); { m_CL.EdgeAnimationK->setArgument(0, *m_CL.NodeInstanceBuffer); m_CL.EdgeAnimationK->setArgument(1, *m_CL.EdgeInstanceBuffer); m_OpenCL.enqueueNDRangeKernel(*m_CL.Queue, *m_CL.EdgeAnimationK, 1, NULL, &edge_count, NULL, 0, NULL, NULL); } m_OpenCL.enqueueReleaseGLObjects(*m_CL.Queue, 1, &m_CL.EdgeInstanceBuffer->Object, 0, 0, NULL); m_OpenCL.enqueueReleaseGLObjects(*m_CL.Queue, 1, &m_CL.NodeInstanceBuffer->Object, 0, 0, NULL); clFinish(m_CL.Queue->Object); Iterations++; } void idle(Context* context) { if (m_NeedsUpdate) { updateOpenGL(context); m_NeedsUpdate = false; } updateOpenCL(context); } virtual void drawEdges(Context* context, Camera& camera, Transformation& transformation) { if (!m_EdgeInstanceBuffer.isGenerated() || m_EdgeInstanceBuffer.size() == 0) return; m_EdgeShader->use(); //m_EdgeShader->uniform("u_Texture").set(m_Icon->getTexture(0)); m_EdgeShader->uniform("u_ModelViewMatrix").set(camera.getViewMatrix() * transformation.state()); m_EdgeShader->uniform("u_ProjectionMatrix").set(camera.getProjectionMatrix()); context->geometry().bind(m_EdgeParticleBuffer, *m_EdgeShader); context->geometry().bind(m_EdgeInstanceBuffer, *m_EdgeShader); glVertexAttribDivisorARB(m_EdgeShader->attribute("a_Origin").location(), 0); // Same vertices per instance glVertexAttribDivisorARB(m_EdgeShader->attribute("a_SourcePosition").location(), 1); glVertexAttribDivisorARB(m_EdgeShader->attribute("a_SourceColor").location(), 1); glVertexAttribDivisorARB(m_EdgeShader->attribute("a_TargetPosition").location(), 1); glVertexAttribDivisorARB(m_EdgeShader->attribute("a_TargetColor").location(), 1); glVertexAttribDivisorARB(m_EdgeShader->attribute("a_Width").location(), 1); context->geometry().drawArraysInstanced(GL_POINTS, 0, m_EdgeParticleBuffer.size() / sizeof(EdgeParticle), m_EdgeInstanceBuffer.size() / sizeof(EdgeInstance)); context->geometry().unbind(m_EdgeParticleBuffer); context->geometry().unbind(m_EdgeInstanceBuffer); } virtual void drawNodes(Context* context, Camera& camera, Transformation& transformation) { if (!m_NodeInstanceBuffer.isGenerated() || m_NodeInstanceBuffer.size() == 0) return; m_NodeShader->use(); m_NodeShader->uniform("u_Texture").set(m_Icon->getTexture(0)); m_NodeShader->uniform("u_ModelViewMatrix").set(camera.getViewMatrix() * transformation.state()); m_NodeShader->uniform("u_ProjectionMatrix").set(camera.getProjectionMatrix()); context->geometry().bind(m_NodeParticleBuffer, *m_NodeShader); context->geometry().bind(m_NodeInstanceBuffer, *m_NodeShader); glVertexAttribDivisorARB(m_NodeShader->attribute("a_Origin").location(), 0); // Same vertices per instance glVertexAttribDivisorARB(m_NodeShader->attribute("a_Position").location(), 1); glVertexAttribDivisorARB(m_NodeShader->attribute("a_Color").location(), 1); glVertexAttribDivisorARB(m_NodeShader->attribute("a_Size").location(), 1); context->geometry().drawArraysInstanced(GL_POINTS, 0, m_NodeParticleBuffer.size() / sizeof(NodeParticle), m_NodeInstanceBuffer.size() / sizeof(NodeInstance)); context->geometry().unbind(m_NodeParticleBuffer); context->geometry().unbind(m_NodeInstanceBuffer); } virtual void draw(Context* context, Camera& camera, Transformation& transformation) { glDisable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_DST_ALPHA); drawEdges(context, camera, transformation); drawNodes(context, camera, transformation); } // ----- Nodes Accessors ----- inline Buffer& getNodes() { return m_NodeInstanceBuffer; } void addNode(const NodeInstance& node) { m_NodeInstanceBuffer.push(&node, sizeof(NodeInstance)); m_NeedsUpdate = true; } inline NodeInstance getNode(NodeInstance::ID id) { NodeInstance node; m_NodeInstanceBuffer.get(id, &node, sizeof(NodeInstance)); return node; } inline void setNode(NodeInstance::ID id, const NodeInstance& node) { m_NodeInstanceBuffer.set(id, &node, sizeof(NodeInstance)); m_NeedsUpdate = true; } // ----- Edges Accessors ----- inline Buffer& getEdges() { return m_EdgeInstanceBuffer; } void addEdge(const EdgeInstance& edge) { m_EdgeInstanceBuffer.push(&edge, sizeof(EdgeInstance)); m_NeedsUpdate = true; } inline EdgeInstance getEdge(EdgeInstance::ID id) { EdgeInstance edge; m_EdgeInstanceBuffer.get(id, &edge, sizeof(EdgeInstance)); return edge; } inline void setEdge(EdgeInstance::ID id, const EdgeInstance& edge) { m_EdgeInstanceBuffer.set(id, &edge, sizeof(EdgeInstance)); m_NeedsUpdate = true; } private: Icon* m_Icon; bool m_NeedsUpdate; Shader::Program* m_NodeShader; Buffer m_NodeParticleBuffer; Buffer m_NodeInstanceBuffer; Shader::Program* m_EdgeShader; Buffer m_EdgeParticleBuffer; Buffer m_EdgeInstanceBuffer; struct OCLData { OCLData() {} OpenCL::Device* Device; OpenCL::Context* Context; OpenCL::CommandQueue* Queue; OpenCL::Program* Program; OpenCL::Kernel* RepulsionK; OpenCL::Kernel* AttractionK; OpenCL::Kernel* NodeAnimationK; OpenCL::Kernel* EdgeAnimationK; OpenCL::Memory* NodeInstanceBuffer; OpenCL::Memory* EdgeInstanceBuffer; float Time; float K; float Temperature; }; OpenCL m_OpenCL; OCLData m_CL; }; <commit_msg>Remove unnecessary acquire/release<commit_after>#include <raindance/Core/Headers.hh> #include <raindance/Core/OpenCL.hh> class GPUGraph { public: struct ParticleForce { glm::vec4 Direction; }; struct NodeParticle { glm::vec4 Origin; }; struct NodeInstance { typedef unsigned int ID; glm::vec4 Position; glm::vec4 Color; cl_float Size; ParticleForce Force; glm::vec3 __Unused; // NOTE: Memory alignment with OpenCL, reserved for later. }; struct EdgeParticle { glm::vec4 Origin; }; struct EdgeInstance { typedef unsigned int ID; glm::vec4 SourcePosition; glm::vec4 SourceColor; glm::vec4 TargetPosition; glm::vec4 TargetColor; cl_float Width; cl_uint SourceID; cl_uint TargetID; cl_float __Unused; // NOTE : Memory alignment with OpenCL, reserved for later. }; GPUGraph() { m_Icon = new Icon(); m_Icon->load("network/shapes/disk", FS::BinaryFile("Assets/NetworkView/shape_disk.png")); FS::TextFile nodes_vert("Assets/NetworkView/nodes.vert"); FS::TextFile nodes_geom("Assets/NetworkView/nodes.geom"); FS::TextFile nodes_frag("Assets/NetworkView/nodes.frag"); m_NodeShader = ResourceManager::getInstance().loadShader("NetworkView/nodes", nodes_vert.content(), nodes_frag.content(), nodes_geom.content()); // m_NodeShader->dump(); FS::TextFile edges_vert("Assets/NetworkView/edges.vert"); FS::TextFile edges_geom("Assets/NetworkView/edges.geom"); FS::TextFile edges_frag("Assets/NetworkView/edges.frag"); m_EdgeShader = ResourceManager::getInstance().loadShader("NetworkView/edges", edges_vert.content(), edges_frag.content(), edges_geom.content()); // m_EdgeShader->dump(); m_NeedsUpdate = true; } virtual ~GPUGraph() { SAFE_DELETE(m_Icon); ResourceManager::getInstance().unload(m_NodeShader); } void initialize(Context* context) { // OpenGL { // ----- Node Particle Geometry ----- m_NodeParticleBuffer << glm::vec4(0, 0, 0, 0); m_NodeParticleBuffer.describe("a_Origin", 4, GL_FLOAT, sizeof(NodeParticle), 0); m_NodeParticleBuffer.generate(Buffer::STATIC); // ----- Edge Particle Geometry ----- m_EdgeParticleBuffer << glm::vec4(0, 0, 0, 0); m_EdgeParticleBuffer.describe("a_Origin", 4, GL_FLOAT, sizeof(EdgeParticle), 0); m_EdgeParticleBuffer.generate(Buffer::STATIC); } // OpenCL { m_OpenCL.detect(); //m_OpenCL.dump(); // NOTE : We are assuming the last device is the best one. m_CL.Device = m_OpenCL.devices().back(); m_OpenCL.dump(*m_CL.Device); m_CL.Context = m_OpenCL.createContext(*m_CL.Device); m_CL.Queue = m_OpenCL.createCommandQueue(*m_CL.Context); auto source = FS::TextFile("./Assets/NetworkView/physics.cl"); m_CL.Program = m_OpenCL.loadProgram(*m_CL.Context, "physics", source.content()); m_CL.RepulsionK = m_OpenCL.createKernel(*m_CL.Program, "repulsion"); m_CL.AttractionK = m_OpenCL.createKernel(*m_CL.Program, "attraction"); m_CL.NodeAnimationK = m_OpenCL.createKernel(*m_CL.Program, "node_animation"); m_CL.EdgeAnimationK = m_OpenCL.createKernel(*m_CL.Program, "edge_animation"); clFinish(m_CL.Queue->Object); } } void updateOpenGL(Context* context) { // LOG("updateOpenGL: %u nodes, %u edges.\n", m_NodeBuffer.size() / sizeof(Node), m_EdgeBuffer.size() / sizeof(Edge)); if (m_NodeInstanceBuffer.size() == 0) // TODO: HACK: OpenGL doesn't like VBO resizing, Find a way to handle it properly. return; // --- Define Node Instances static bool m_NodeInstanceBufferFirstUpdate = true; if (!m_NodeInstanceBufferFirstUpdate) m_NodeInstanceBuffer.update(); m_NodeInstanceBuffer.describe("a_Position", 4, GL_FLOAT, sizeof(NodeInstance), 0); m_NodeInstanceBuffer.describe("a_Color", 4, GL_FLOAT, sizeof(NodeInstance), 1 * sizeof(glm::vec4)); m_NodeInstanceBuffer.describe("a_Size", 1, GL_FLOAT, sizeof(NodeInstance), 2 * sizeof(glm::vec4)); if (m_NodeInstanceBufferFirstUpdate) m_NodeInstanceBuffer.generate(Buffer::DYNAMIC); m_NodeInstanceBufferFirstUpdate = false; // --- Define Edge Instances static bool m_EdgeInstanceBufferFirstUpdate = true; if (!m_EdgeInstanceBufferFirstUpdate) m_EdgeInstanceBuffer.update(); m_EdgeInstanceBuffer.describe("a_SourcePosition", 4, GL_FLOAT, sizeof(EdgeInstance), 0); m_EdgeInstanceBuffer.describe("a_SourceColor", 4, GL_FLOAT, sizeof(EdgeInstance), 1 * sizeof(glm::vec4)); m_EdgeInstanceBuffer.describe("a_TargetPosition", 4, GL_FLOAT, sizeof(EdgeInstance), 2 * sizeof(glm::vec4)); m_EdgeInstanceBuffer.describe("a_TargetColor", 4, GL_FLOAT, sizeof(EdgeInstance), 3 * sizeof(glm::vec4)); m_EdgeInstanceBuffer.describe("a_Width", 1, GL_FLOAT, sizeof(EdgeInstance), 4 * sizeof(glm::vec4)); if (m_EdgeInstanceBufferFirstUpdate) m_EdgeInstanceBuffer.generate(Buffer::DYNAMIC); m_EdgeInstanceBufferFirstUpdate = false; } void updateOpenCL(Context* context) { size_t node_count = m_NodeInstanceBuffer.size() / sizeof(NodeInstance); size_t edge_count = m_EdgeInstanceBuffer.size() / sizeof(EdgeInstance); if (node_count == 0) // TODO: HACK: OpenGL doesn't like VBO resizing, Find a way to handle it properly. return; static bool m_OCLNeedsUpdate = true; if (m_OCLNeedsUpdate) { m_CL.NodeInstanceBuffer = m_OpenCL.createFromGLBuffer(*m_CL.Context, CL_MEM_READ_WRITE, m_NodeInstanceBuffer.vbo()); m_CL.EdgeInstanceBuffer = m_OpenCL.createFromGLBuffer(*m_CL.Context, CL_MEM_READ_WRITE, m_EdgeInstanceBuffer.vbo()); clFinish(m_CL.Queue->Object); m_OCLNeedsUpdate = false; } // ----- Parameters ----- static int Iterations = 0; if (Iterations >= 100) return; const float cube_side = 100; // NOTE : Graph should fit in this cube const float volume = cube_side * cube_side * cube_side; m_CL.K = pow(volume / node_count, 1.0 / 3.0); m_CL.Time = context->clock().seconds(); m_CL.Temperature = cube_side / (Iterations + 1); LOG("Iteration: %i, K: %f, Time: %f, Temperature: %f\n", Iterations, m_CL.K, m_CL.Time, m_CL.Temperature); m_OpenCL.enqueueAcquireGLObjects(*m_CL.Queue, 1, &m_CL.NodeInstanceBuffer->Object, 0, 0, NULL); m_OpenCL.enqueueAcquireGLObjects(*m_CL.Queue, 1, &m_CL.EdgeInstanceBuffer->Object, 0, 0, NULL); { // ----- Node Repulsion ----- m_CL.RepulsionK->setArgument(0, *m_CL.NodeInstanceBuffer); m_CL.RepulsionK->setArgument(1, &m_CL.K, sizeof(float)); m_OpenCL.enqueueNDRangeKernel(*m_CL.Queue, *m_CL.RepulsionK, 1, NULL, &node_count, NULL, 0, NULL, NULL); // ----- Edge Attraction ----- m_CL.AttractionK->setArgument(0, *m_CL.NodeInstanceBuffer); m_CL.AttractionK->setArgument(1, *m_CL.EdgeInstanceBuffer); m_CL.AttractionK->setArgument(2, &m_CL.K, sizeof(float)); m_OpenCL.enqueueNDRangeKernel(*m_CL.Queue, *m_CL.AttractionK, 1, NULL, &edge_count, NULL, 0, NULL, NULL); // ----- Node Animation ----- m_CL.NodeAnimationK->setArgument(0, *m_CL.NodeInstanceBuffer); m_CL.NodeAnimationK->setArgument(1, &m_CL.Temperature, sizeof(float)); m_OpenCL.enqueueNDRangeKernel(*m_CL.Queue, *m_CL.NodeAnimationK, 1, NULL, &node_count, NULL, 0, NULL, NULL); // ----- Edge Animation ----- m_CL.EdgeAnimationK->setArgument(0, *m_CL.NodeInstanceBuffer); m_CL.EdgeAnimationK->setArgument(1, *m_CL.EdgeInstanceBuffer); m_OpenCL.enqueueNDRangeKernel(*m_CL.Queue, *m_CL.EdgeAnimationK, 1, NULL, &edge_count, NULL, 0, NULL, NULL); } m_OpenCL.enqueueReleaseGLObjects(*m_CL.Queue, 1, &m_CL.EdgeInstanceBuffer->Object, 0, 0, NULL); m_OpenCL.enqueueReleaseGLObjects(*m_CL.Queue, 1, &m_CL.NodeInstanceBuffer->Object, 0, 0, NULL); clFinish(m_CL.Queue->Object); Iterations++; } void idle(Context* context) { if (m_NeedsUpdate) { updateOpenGL(context); m_NeedsUpdate = false; } updateOpenCL(context); } virtual void drawEdges(Context* context, Camera& camera, Transformation& transformation) { if (!m_EdgeInstanceBuffer.isGenerated() || m_EdgeInstanceBuffer.size() == 0) return; m_EdgeShader->use(); //m_EdgeShader->uniform("u_Texture").set(m_Icon->getTexture(0)); m_EdgeShader->uniform("u_ModelViewMatrix").set(camera.getViewMatrix() * transformation.state()); m_EdgeShader->uniform("u_ProjectionMatrix").set(camera.getProjectionMatrix()); context->geometry().bind(m_EdgeParticleBuffer, *m_EdgeShader); context->geometry().bind(m_EdgeInstanceBuffer, *m_EdgeShader); glVertexAttribDivisorARB(m_EdgeShader->attribute("a_Origin").location(), 0); // Same vertices per instance glVertexAttribDivisorARB(m_EdgeShader->attribute("a_SourcePosition").location(), 1); glVertexAttribDivisorARB(m_EdgeShader->attribute("a_SourceColor").location(), 1); glVertexAttribDivisorARB(m_EdgeShader->attribute("a_TargetPosition").location(), 1); glVertexAttribDivisorARB(m_EdgeShader->attribute("a_TargetColor").location(), 1); glVertexAttribDivisorARB(m_EdgeShader->attribute("a_Width").location(), 1); context->geometry().drawArraysInstanced(GL_POINTS, 0, m_EdgeParticleBuffer.size() / sizeof(EdgeParticle), m_EdgeInstanceBuffer.size() / sizeof(EdgeInstance)); context->geometry().unbind(m_EdgeParticleBuffer); context->geometry().unbind(m_EdgeInstanceBuffer); } virtual void drawNodes(Context* context, Camera& camera, Transformation& transformation) { if (!m_NodeInstanceBuffer.isGenerated() || m_NodeInstanceBuffer.size() == 0) return; m_NodeShader->use(); m_NodeShader->uniform("u_Texture").set(m_Icon->getTexture(0)); m_NodeShader->uniform("u_ModelViewMatrix").set(camera.getViewMatrix() * transformation.state()); m_NodeShader->uniform("u_ProjectionMatrix").set(camera.getProjectionMatrix()); context->geometry().bind(m_NodeParticleBuffer, *m_NodeShader); context->geometry().bind(m_NodeInstanceBuffer, *m_NodeShader); glVertexAttribDivisorARB(m_NodeShader->attribute("a_Origin").location(), 0); // Same vertices per instance glVertexAttribDivisorARB(m_NodeShader->attribute("a_Position").location(), 1); glVertexAttribDivisorARB(m_NodeShader->attribute("a_Color").location(), 1); glVertexAttribDivisorARB(m_NodeShader->attribute("a_Size").location(), 1); context->geometry().drawArraysInstanced(GL_POINTS, 0, m_NodeParticleBuffer.size() / sizeof(NodeParticle), m_NodeInstanceBuffer.size() / sizeof(NodeInstance)); context->geometry().unbind(m_NodeParticleBuffer); context->geometry().unbind(m_NodeInstanceBuffer); } virtual void draw(Context* context, Camera& camera, Transformation& transformation) { glDisable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_DST_ALPHA); drawEdges(context, camera, transformation); drawNodes(context, camera, transformation); } // ----- Nodes Accessors ----- inline Buffer& getNodes() { return m_NodeInstanceBuffer; } void addNode(const NodeInstance& node) { m_NodeInstanceBuffer.push(&node, sizeof(NodeInstance)); m_NeedsUpdate = true; } inline NodeInstance getNode(NodeInstance::ID id) { NodeInstance node; m_NodeInstanceBuffer.get(id, &node, sizeof(NodeInstance)); return node; } inline void setNode(NodeInstance::ID id, const NodeInstance& node) { m_NodeInstanceBuffer.set(id, &node, sizeof(NodeInstance)); m_NeedsUpdate = true; } // ----- Edges Accessors ----- inline Buffer& getEdges() { return m_EdgeInstanceBuffer; } void addEdge(const EdgeInstance& edge) { m_EdgeInstanceBuffer.push(&edge, sizeof(EdgeInstance)); m_NeedsUpdate = true; } inline EdgeInstance getEdge(EdgeInstance::ID id) { EdgeInstance edge; m_EdgeInstanceBuffer.get(id, &edge, sizeof(EdgeInstance)); return edge; } inline void setEdge(EdgeInstance::ID id, const EdgeInstance& edge) { m_EdgeInstanceBuffer.set(id, &edge, sizeof(EdgeInstance)); m_NeedsUpdate = true; } private: Icon* m_Icon; bool m_NeedsUpdate; Shader::Program* m_NodeShader; Buffer m_NodeParticleBuffer; Buffer m_NodeInstanceBuffer; Shader::Program* m_EdgeShader; Buffer m_EdgeParticleBuffer; Buffer m_EdgeInstanceBuffer; struct OCLData { OCLData() {} OpenCL::Device* Device; OpenCL::Context* Context; OpenCL::CommandQueue* Queue; OpenCL::Program* Program; OpenCL::Kernel* RepulsionK; OpenCL::Kernel* AttractionK; OpenCL::Kernel* NodeAnimationK; OpenCL::Kernel* EdgeAnimationK; OpenCL::Memory* NodeInstanceBuffer; OpenCL::Memory* EdgeInstanceBuffer; float Time; float K; float Temperature; }; OpenCL m_OpenCL; OCLData m_CL; }; <|endoftext|>
<commit_before>// #include "spack.h" #include <cstdint> #include <algorithm> #include <boost/filesystem.hpp> #include <boost/algorithm/string/replace.hpp> #include "sections_packer.h" #include "import_packer.h" #include "file_utils.h" #include "tiny_logger.h" typedef std::shared_ptr<PeLib::PeFile> PeFilePtr; uint32_t rebuildMZHeader(PeFilePtr& peFile, std::vector<uint8_t>& outFileBuffer, std::vector<uint8_t>& sourceFileBuff) { std::vector<PeLib::byte> mzHeadBuffer; auto mzHead = peFile->mzHeader(); mzHead.rebuild(mzHeadBuffer); std::copy(mzHeadBuffer.cbegin(), mzHeadBuffer.cend(), std::back_inserter(outFileBuffer)); // append mzHeader with undocumented data located between MZHeader & PEHeader auto peOffset = mzHead.getAddressOfPeHeader(); auto cbMZHead = mzHead.size(); auto cbJunkData = std::max(peOffset - cbMZHead, static_cast<uint32_t>(0)); if (cbJunkData) { std::copy(&sourceFileBuff.at(cbMZHead), &sourceFileBuff.at(cbMZHead + cbJunkData), std::back_inserter(outFileBuffer)); } return cbMZHead + cbJunkData; } template<int bits> void rebuildPEHeader(PeLib::PeFile& peFile, std::vector<uint8_t>& outFileBuffer, uint32_t& offset) { const PeLib::PeHeaderT<bits>& peh = static_cast<PeLib::PeFileT<bits>&>(peFile).peHeader(); std::vector<PeLib::byte> peHeaderBuff; peh.rebuild(peHeaderBuff); PeLib::PeHeaderT<bits> pehOut; auto cbAfterHeader = peh.size(); std::copy(peHeaderBuff.cbegin(), peHeaderBuff.cend(), std::back_inserter(outFileBuffer)); offset += pehOut.size(); // append with aligned zero-bytes auto headersSize = peh.getSizeOfHeaders() - offset; if (headersSize) { //todo(azerg): strip unused data by fixing size of headers ? outFileBuffer.insert(outFileBuffer.end(), headersSize, 0); } offset += headersSize; } //------------------------------------------------------------------------ class DumpPeHeaderVisitor: public PeLib::PeFileVisitor { public: DumpPeHeaderVisitor(std::vector<uint8_t>& outFileBuffer, uint32_t& offset) : outFileBuffer_(outFileBuffer) , offset_(offset) {} virtual void callback(PeLib::PeFile32& file) { rebuildPEHeader<32>(file, outFileBuffer_, offset_); } virtual void callback(PeLib::PeFile64& file) { rebuildPEHeader<64>(file, outFileBuffer_, offset_); } private: std::vector<uint8_t>& outFileBuffer_; uint32_t& offset_; }; //------------------------------------------------------------------------ ErrorCode PackExecutable(const std::string& srcFileName, const std::string& outFileName) { try { if (!boost::filesystem::exists(srcFileName)) { return ErrorCode::FILE_NOT_FOUND; } auto sourceFileBuff = file_utils::readFile(srcFileName.c_str()); decltype(sourceFileBuff) outFileBuff; if (boost::filesystem::exists(outFileName)) { boost::filesystem::remove(outFileName); } auto pef = PeLib::openPeFile(srcFileName); if (!pef) { std::cout << "Invalid PE File" << std::endl; return ErrorCode::INVALID_PE_FILE; } std::vector<uint8_t> outFileBuffer; pef->readMzHeader(); auto offset = rebuildMZHeader(pef, outFileBuffer, sourceFileBuff); // stores data sizes required by different packers std::vector<RequiredDataBlock> additionalSizeRequest; //----------------------------------------------------- pef->readPeHeader(); DumpPeHeaderVisitor peVisitor(outFileBuffer, offset); pef->visit(peVisitor); //----------------------------------------------------- ImportPacker importPacker(pef); additionalSizeRequest.push_back({importPacker.GetRequiredSpaceSize(), PackerTypes::kImportPacker}); //----------------------------------------------------- SectionsPacker sectionsPacker(pef); auto sectionsArr = sectionsPacker.ProcessExecutable(sourceFileBuff, additionalSizeRequest); //----------------------------------------------------- auto importsArr = importPacker.ProcessExecutable(0); // new import RVA passed here //----------------------------------------------------- return ErrorCode::ERROR_SUCC; } catch (std::runtime_error& err) { std::cout << err.what(); } return ErrorCode::FATAL_ERROR; }<commit_msg>using VA from additional block for constructing new imports<commit_after>// #include "spack.h" #include <cstdint> #include <algorithm> #include <boost/filesystem.hpp> #include <boost/algorithm/string/replace.hpp> #include "sections_packer.h" #include "import_packer.h" #include "file_utils.h" #include "tiny_logger.h" typedef std::shared_ptr<PeLib::PeFile> PeFilePtr; uint32_t rebuildMZHeader(PeFilePtr& peFile, std::vector<uint8_t>& outFileBuffer, std::vector<uint8_t>& sourceFileBuff) { std::vector<PeLib::byte> mzHeadBuffer; auto mzHead = peFile->mzHeader(); mzHead.rebuild(mzHeadBuffer); std::copy(mzHeadBuffer.cbegin(), mzHeadBuffer.cend(), std::back_inserter(outFileBuffer)); // append mzHeader with undocumented data located between MZHeader & PEHeader auto peOffset = mzHead.getAddressOfPeHeader(); auto cbMZHead = mzHead.size(); auto cbJunkData = std::max(peOffset - cbMZHead, static_cast<uint32_t>(0)); if (cbJunkData) { std::copy(&sourceFileBuff.at(cbMZHead), &sourceFileBuff.at(cbMZHead + cbJunkData), std::back_inserter(outFileBuffer)); } return cbMZHead + cbJunkData; } template<int bits> void rebuildPEHeader(PeLib::PeFile& peFile, std::vector<uint8_t>& outFileBuffer, uint32_t& offset) { const PeLib::PeHeaderT<bits>& peh = static_cast<PeLib::PeFileT<bits>&>(peFile).peHeader(); std::vector<PeLib::byte> peHeaderBuff; peh.rebuild(peHeaderBuff); PeLib::PeHeaderT<bits> pehOut; auto cbAfterHeader = peh.size(); std::copy(peHeaderBuff.cbegin(), peHeaderBuff.cend(), std::back_inserter(outFileBuffer)); offset += pehOut.size(); // append with aligned zero-bytes auto headersSize = peh.getSizeOfHeaders() - offset; if (headersSize) { //todo(azerg): strip unused data by fixing size of headers ? outFileBuffer.insert(outFileBuffer.end(), headersSize, 0); } offset += headersSize; } //------------------------------------------------------------------------ class DumpPeHeaderVisitor: public PeLib::PeFileVisitor { public: DumpPeHeaderVisitor(std::vector<uint8_t>& outFileBuffer, uint32_t& offset) : outFileBuffer_(outFileBuffer) , offset_(offset) {} virtual void callback(PeLib::PeFile32& file) { rebuildPEHeader<32>(file, outFileBuffer_, offset_); } virtual void callback(PeLib::PeFile64& file) { rebuildPEHeader<64>(file, outFileBuffer_, offset_); } private: std::vector<uint8_t>& outFileBuffer_; uint32_t& offset_; }; //------------------------------------------------------------------------ ErrorCode PackExecutable(const std::string& srcFileName, const std::string& outFileName) { try { if (!boost::filesystem::exists(srcFileName)) { return ErrorCode::FILE_NOT_FOUND; } auto sourceFileBuff = file_utils::readFile(srcFileName.c_str()); decltype(sourceFileBuff) outFileBuff; if (boost::filesystem::exists(outFileName)) { boost::filesystem::remove(outFileName); } auto pef = PeLib::openPeFile(srcFileName); if (!pef) { std::cout << "Invalid PE File" << std::endl; return ErrorCode::INVALID_PE_FILE; } std::vector<uint8_t> outFileBuffer; pef->readMzHeader(); auto offset = rebuildMZHeader(pef, outFileBuffer, sourceFileBuff); // stores data sizes required by different packers std::vector<RequiredDataBlock> additionalSizeRequest; //----------------------------------------------------- pef->readPeHeader(); DumpPeHeaderVisitor peVisitor(outFileBuffer, offset); pef->visit(peVisitor); //----------------------------------------------------- ImportPacker importPacker(pef); additionalSizeRequest.push_back({importPacker.GetRequiredSpaceSize(), PackerTypes::kImportPacker}); //----------------------------------------------------- SectionsPacker sectionsPacker(pef); auto sectionsArr = sectionsPacker.ProcessExecutable(sourceFileBuff, additionalSizeRequest); //----------------------------------------------------- // pick last section VA to use it as new imports VA auto additionalImportsBlock = std::find_if( sectionsArr.additionalDataBlocks.begin() , sectionsArr.additionalDataBlocks.end() ,[&](decltype(sectionsArr.additionalDataBlocks)::value_type& valIt) { return valIt.ownerType == PackerTypes::kImportPacker; }); auto newImportsVA = 0; if (additionalImportsBlock != sectionsArr.additionalDataBlocks.end()) { newImportsVA = additionalImportsBlock->virtualOffset; } auto importsArr = importPacker.ProcessExecutable(newImportsVA); // new import RVA passed here //----------------------------------------------------- return ErrorCode::ERROR_SUCC; } catch (std::runtime_error& err) { std::cout << err.what(); } return ErrorCode::FATAL_ERROR; }<|endoftext|>
<commit_before><commit_msg>cppcheck reduce scope of var in vcl/unx/...wmadaptor.cxx<commit_after><|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbImageViewerManager.h" int main(int argc, char* argv[]) { try { typedef double PixelType; typedef otb::ImageViewerManager<PixelType> ManagerType; ManagerType::Pointer manager = ManagerType::New(); manager->Show(); std::string strTest("--Test"); bool bFlRun(true); for(int i = 1; i<argc;++i) { if( strTest.compare(argv[i])==0 ) { std::cout << "--Test option. No FL::run() call !" << std::endl; bFlRun=false; } else { manager->OpenImage(argv[i]); Fl::check(); } } if( bFlRun==true) return Fl::run(); } catch( itk::ExceptionObject & err ) { std::cout << "Following otbException catch :" << std::endl; std::cout << err << std::endl; return EXIT_FAILURE; } catch( std::bad_alloc & err ) { std::cout << "Exception bad_alloc : "<<(char*)err.what()<< std::endl; return EXIT_FAILURE; } catch( ... ) { std::cout << "Unknown Exception found !" << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>Ajout du filtre de lecture/ecriture des shapefiles (encore en cours de développement) Ajout de tests du répertoire Projections dans OTB-Applications Ajout de fichiers en Baseline d'OTB-Applications pour les tests de non-régression du répertoire Projections Ajout d'une option --OTB-Testing par défaut dans le otb::CommandLineArgumentParser (non visible par un usage()) Suppression du troisième paramètre template "bidon" dans otb::Image et otb::VectorImage<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbImageViewerManager.h" int main(int argc, char* argv[]) { try { typedef double PixelType; typedef otb::ImageViewerManager<PixelType> ManagerType; ManagerType::Pointer manager = ManagerType::New(); manager->Show(); std::string strTest("--OTBTesting"); bool bFlRun(true); for(int i = 1; i<argc;++i) { if( strTest.compare(argv[i])==0 ) { std::cout << "--OTBTesting option. No FL::run() call !" << std::endl; bFlRun=false; } else { manager->OpenImage(argv[i]); Fl::check(); } } if( bFlRun==true) return Fl::run(); } catch( itk::ExceptionObject & err ) { std::cout << "Following otbException catch :" << std::endl; std::cout << err << std::endl; return EXIT_FAILURE; } catch( std::bad_alloc & err ) { std::cout << "Exception bad_alloc : "<<(char*)err.what()<< std::endl; return EXIT_FAILURE; } catch( ... ) { std::cout << "Unknown Exception found !" << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before><commit_msg>Land additional doctype piece. toString fix of doctype.<commit_after><|endoftext|>
<commit_before>#include "logics/tagrepository.h" #include <TWebApplication> #include <QJsonObject> #include <QJsonDocument> // make symlink for `tags` to public namespace { struct TagDirMakePublicLink { TagDirMakePublicLink() { const QString sourcePath = TagRepository().baseDir().absolutePath(); const QString linkPath = QDir(Tf::app()->publicPath()).absoluteFilePath(QFileInfo(sourcePath).fileName()); QFile::link(sourcePath, linkPath); }; } TagDirMakePublicLink; }; TagRepository::TagRepository() : _baseDir(Tf::conf("settings").value("TagsDir").toString()) { } TagRepository::TagRepository(const QDir& listDir) : _baseDir(listDir) { } QList<TagGroup> TagRepository::allGroups() const { QList<TagGroup> groups; if (_baseDir.exists()) { for (const QString& name : _baseDir.entryList(QDir::Dirs|QDir::NoDotAndDotDot, QDir::Name)) { groups << TagGroup(_baseDir, name); } } return groups; } TagGroup TagRepository::createGroup(const QString& groupName) const { TagGroup created; if (! groupName.isEmpty()) { if (_baseDir.mkpath(groupName)) { created = TagGroup(_baseDir, groupName); } } return created; } bool TagRepository::destroyGroup(const QString& groupName) const { bool destroyed = false; if (findGroup(groupName).exists()) { destroyed = QDir(_baseDir.filePath(groupName)).removeRecursively(); } return destroyed; } TagGroup TagRepository::findGroup(const QString& groupName) const { TagGroup found; if (! groupName.isEmpty()) { if (_baseDir.exists(groupName)) { found = TagGroup(_baseDir, groupName); } } return found; } bool TagRepository::saveGroup(TagGroup& group) { bool created = false; const QString groupName(group.name()); if (! groupName.isEmpty()) { created = _baseDir.mkpath(groupName); if (created) { group.setDirectory(_baseDir); } } return created; } QList<Tag> TagRepository::allTags() const { QList<Tag> tags; for (const TagGroup& group : allGroups()) { tags << group.tags(); } return tags; } Tag TagRepository::createTag(const QString& groupName, const QString& tagName, const QString& tagDisplayName) { TagGroup group = findGroup(groupName); if (! group.exists()) { group = createGroup(groupName); } Tag created = group.createTag(tagName); if (created.exists()) { created.setDisplayName(tagDisplayName); QStringList alltags; for (auto& tag : TagRepository().allTags()) { alltags << tag.name(); } // Tag name is system unique. if (alltags.filter(tagName).count() > 1) { created.destroy(); } } return created; } bool TagRepository::destroyTag(const QString& groupName, const QString& tagName) { return findGroup(groupName).destroyTag(tagName); } bool TagRepository::destroyTag(const QString& tagName) { return findTag(tagName).destroy(); } Tag TagRepository::findTag(const QString& tagName) const { Tag found; if (! tagName.isEmpty()) { for (const TagGroup& group : allGroups()) { found = group.findTag(tagName); if (found.exists()) break; } } return found; } bool TagRepository::updateTag(const QString& groupName, const QString& tagName, const QVariantMap& changes) { Tag sourceTag = findGroup(groupName).findTag(tagName); if (sourceTag.exists()) { return updateTag(sourceTag, changes); } return false; } bool TagRepository::updateTag(const QString& tagName, const QVariantMap& changes) { Tag sourceTag = findTag(tagName); if (sourceTag.exists()) { return updateTag(sourceTag, changes); } return false; } bool TagRepository::updateTag(Tag& sourceTag, const QVariantMap& changes) { bool succeed = false; if (sourceTag.exists()) { const QString name = changes.value("name").toString(); if ((! name.isEmpty()) && (name != sourceTag.name())) { // tag name is system unique if (findTag(name).exists()) { return false; } succeed = sourceTag.setName(name); } const QString displayName = changes.value("displayName").toString(); if ((! displayName.isEmpty()) && (displayName != sourceTag.displayName())) { sourceTag.setDisplayName(displayName); succeed = true; } const QString groupName = changes.value("groupName").toString(); if ((! groupName.isEmpty()) && (groupName != sourceTag.groupName())) { TagGroup destinationGroup = findGroup(groupName); if (destinationGroup.exists()) { succeed = destinationGroup.saveTag(sourceTag); } } } return succeed; } void TagRepository::appendImages(const QStringList& images, const QString& groupName, const QString& tagName) { const TagGroup group = findGroup(groupName); if ((! group.exists()) || (! group.hasTag(tagName))) { createTag(groupName, tagName); } const Tag tag = group.findTag(tagName); for (const QString& path : images) { tag.appendImage(path); generateTagResolution(path); } } void TagRepository::removeImages(const QStringList& images, const QString& groupName, const QString& tagName) { const TagGroup group = findGroup(groupName); if ((! group.exists()) || (! group.hasTag(tagName))) { return; } const Tag tag = group.findTag(tagName); for (const QString& path : images) { tag.removeImage(QFileInfo(path).fileName()); generateTagResolution(path); } } void TagRepository::updateImages(const QStringList& images, const QString& groupName, const QString& tagName) { TagGroup group = findGroup(groupName); Tag tag = group.findTag(tagName); for (const QString& path : images) { if (! tagName.isEmpty()) { tag.appendImage(path); } for (const Tag& otherTag : group.tags()) { if (otherTag.name() != tagName) { otherTag.removeImage(QFileInfo(path).fileName()); } } generateTagResolution(path); } } void TagRepository::updateImages(const QStringList& images, const QVariantMap& tags) { for (const QString& groupName : tags.keys()) { const QString tagName = tags.value(groupName).toString(); updateImages(images, groupName, tagName); } } QDir TagRepository::baseDir() const { return _baseDir; } QList<Tag> TagRepository::getTags(const QString& image) const { static const auto TagResolutionDir = QDir(Tf::conf("settings").value("TagResolutionDir").toString()); QList<Tag> tags; QFileInfo fi(image); QFile resolveJson(TagResolutionDir.absoluteFilePath(fi.completeBaseName() + ".json")); if (! resolveJson.exists()) { generateTagResolution(image); } if (resolveJson.open(QIODevice::ReadOnly)) { // Read from JSON auto json = resolveJson.readAll(); resolveJson.close(); auto tagobj = QJsonDocument::fromJson(json).object().value("tags").toObject(); if (! json.isEmpty()) { bool regen = false; for (auto it = tagobj.constBegin(); it != tagobj.constEnd(); ++it) { Tag t = findGroup(it.key()).findTag(it.value().toString()); if (t.exists()) { tags << t; } else { regen = true; } } if (regen) { // Regenerates generateTagResolution(image); } return tags; } } tError() << "Tag resolution error : " << fi.fileName(); return tags; } static bool generateTagResolutionFile(const QString& image, const QList<TagGroup>& allGroups) { static const auto TagResolutionDir = QDir(Tf::conf("settings").value("TagResolutionDir").toString()); const QFileInfo fi(image); const QString filename = fi.fileName(); QJsonObject tagObj; for (const TagGroup& g : allGroups) { for (const Tag& t : g.tags()) { if (t.hasImage(filename)) { tagObj.insert(g.name(), t.name()); } } } QJsonObject json; json.insert("tags", tagObj); auto jsondata = QJsonDocument(json).toJson(QJsonDocument::Compact); if (! TagResolutionDir.exists()) { TagResolutionDir.mkpath("."); } QFile resolveJson(TagResolutionDir.absoluteFilePath(fi.completeBaseName() + ".json")); if (resolveJson.exists() && resolveJson.open(QIODevice::ReadOnly)) { auto currentJson = resolveJson.readAll(); resolveJson.close(); if (currentJson == jsondata) { // not write return true; } } if (resolveJson.open(QIODevice::WriteOnly | QIODevice::Truncate)) { resolveJson.write(jsondata); resolveJson.close(); tInfo() << "tag resolution json created: " << resolveJson.fileName(); } else { tError() << "write error tag resolution json: " << resolveJson.fileName(); return false; } return true; } bool TagRepository::generateTagResolution(const QString& image) const { return generateTagResolutionFile(image, allGroups()); } void TagRepository::regenerateTagResolution() const { static const auto OriginalImagesDir = Tf::conf("settings").value("OriginalImagesDir").toString(); const auto allgroups = allGroups(); QDirIterator it(OriginalImagesDir, {"*.jpg", "*.jpeg"}, QDir::Files | QDir::Readable, QDirIterator::Subdirectories); while (it.hasNext()) { generateTagResolutionFile(it.next(), allgroups); } } /* JSON sample { "tags": { "フォルダ(大腸炎)": "ulcerativecolitis_0630_001-420_mayo2_r", "全体病変": "ulcerativecolitis_mayo2", "照明": "normal", "部位": "e07daichorectum" } } */ <commit_msg>Fix makeshift<commit_after>#include "logics/tagrepository.h" #include <TWebApplication> #include <QJsonObject> #include <QJsonDocument> #include <QtConcurrent> // make symlink for `tags` to public namespace { struct TagDirMakePublicLink { TagDirMakePublicLink() { const QString sourcePath = TagRepository().baseDir().absolutePath(); const QString linkPath = QDir(Tf::app()->publicPath()).absoluteFilePath(QFileInfo(sourcePath).fileName()); QFile::link(sourcePath, linkPath); }; } TagDirMakePublicLink; }; TagRepository::TagRepository() : _baseDir(Tf::conf("settings").value("TagsDir").toString()) { } TagRepository::TagRepository(const QDir& listDir) : _baseDir(listDir) { } QList<TagGroup> TagRepository::allGroups() const { QList<TagGroup> groups; if (_baseDir.exists()) { for (const QString& name : _baseDir.entryList(QDir::Dirs|QDir::NoDotAndDotDot, QDir::Name)) { groups << TagGroup(_baseDir, name); } } return groups; } TagGroup TagRepository::createGroup(const QString& groupName) const { TagGroup created; if (! groupName.isEmpty()) { if (_baseDir.mkpath(groupName)) { created = TagGroup(_baseDir, groupName); } } return created; } bool TagRepository::destroyGroup(const QString& groupName) const { bool destroyed = false; if (findGroup(groupName).exists()) { destroyed = QDir(_baseDir.filePath(groupName)).removeRecursively(); } return destroyed; } TagGroup TagRepository::findGroup(const QString& groupName) const { TagGroup found; if (! groupName.isEmpty()) { if (_baseDir.exists(groupName)) { found = TagGroup(_baseDir, groupName); } } return found; } bool TagRepository::saveGroup(TagGroup& group) { bool created = false; const QString groupName(group.name()); if (! groupName.isEmpty()) { created = _baseDir.mkpath(groupName); if (created) { group.setDirectory(_baseDir); } } return created; } QList<Tag> TagRepository::allTags() const { QList<Tag> tags; for (const TagGroup& group : allGroups()) { tags << group.tags(); } return tags; } Tag TagRepository::createTag(const QString& groupName, const QString& tagName, const QString& tagDisplayName) { TagGroup group = findGroup(groupName); if (! group.exists()) { group = createGroup(groupName); } Tag created = group.createTag(tagName); if (created.exists()) { created.setDisplayName(tagDisplayName); QStringList alltags; for (auto& tag : TagRepository().allTags()) { alltags << tag.name(); } // Tag name is system unique. if (alltags.filter(tagName).count() > 1) { created.destroy(); } } return created; } bool TagRepository::destroyTag(const QString& groupName, const QString& tagName) { return findGroup(groupName).destroyTag(tagName); } bool TagRepository::destroyTag(const QString& tagName) { return findTag(tagName).destroy(); } Tag TagRepository::findTag(const QString& tagName) const { Tag found; if (! tagName.isEmpty()) { for (const TagGroup& group : allGroups()) { found = group.findTag(tagName); if (found.exists()) break; } } return found; } bool TagRepository::updateTag(const QString& groupName, const QString& tagName, const QVariantMap& changes) { Tag sourceTag = findGroup(groupName).findTag(tagName); if (sourceTag.exists()) { return updateTag(sourceTag, changes); } return false; } bool TagRepository::updateTag(const QString& tagName, const QVariantMap& changes) { Tag sourceTag = findTag(tagName); if (sourceTag.exists()) { return updateTag(sourceTag, changes); } return false; } bool TagRepository::updateTag(Tag& sourceTag, const QVariantMap& changes) { bool succeed = false; if (sourceTag.exists()) { const QString name = changes.value("name").toString(); if ((! name.isEmpty()) && (name != sourceTag.name())) { // tag name is system unique if (findTag(name).exists()) { return false; } succeed = sourceTag.setName(name); } const QString displayName = changes.value("displayName").toString(); if ((! displayName.isEmpty()) && (displayName != sourceTag.displayName())) { sourceTag.setDisplayName(displayName); succeed = true; } const QString groupName = changes.value("groupName").toString(); if ((! groupName.isEmpty()) && (groupName != sourceTag.groupName())) { TagGroup destinationGroup = findGroup(groupName); if (destinationGroup.exists()) { succeed = destinationGroup.saveTag(sourceTag); } } } return succeed; } void TagRepository::appendImages(const QStringList& images, const QString& groupName, const QString& tagName) { const TagGroup group = findGroup(groupName); if ((! group.exists()) || (! group.hasTag(tagName))) { createTag(groupName, tagName); } const Tag tag = group.findTag(tagName); for (const QString& path : images) { tag.appendImage(path); QtConcurrent::run([=]{ generateTagResolution(path); }); } } void TagRepository::removeImages(const QStringList& images, const QString& groupName, const QString& tagName) { const TagGroup group = findGroup(groupName); if ((! group.exists()) || (! group.hasTag(tagName))) { return; } const Tag tag = group.findTag(tagName); for (const QString& path : images) { tag.removeImage(QFileInfo(path).fileName()); QtConcurrent::run([=]{ generateTagResolution(path); }); } } void TagRepository::updateImages(const QStringList& images, const QString& groupName, const QString& tagName) { TagGroup group = findGroup(groupName); Tag tag = group.findTag(tagName); for (const QString& path : images) { if (! tagName.isEmpty()) { tag.appendImage(path); } for (const Tag& otherTag : group.tags()) { if (otherTag.name() != tagName) { otherTag.removeImage(QFileInfo(path).fileName()); } } QtConcurrent::run([=]{ generateTagResolution(path); }); } } void TagRepository::updateImages(const QStringList& images, const QVariantMap& tags) { for (const QString& groupName : tags.keys()) { const QString tagName = tags.value(groupName).toString(); updateImages(images, groupName, tagName); } } QDir TagRepository::baseDir() const { return _baseDir; } QList<Tag> TagRepository::getTags(const QString& image) const { static const auto TagResolutionDir = QDir(Tf::conf("settings").value("TagResolutionDir").toString()); QList<Tag> tags; QFileInfo fi(image); QFile resolveJson(TagResolutionDir.absoluteFilePath(fi.completeBaseName() + ".json")); if (! resolveJson.exists()) { generateTagResolution(image); } if (resolveJson.open(QIODevice::ReadOnly)) { // Read from JSON auto json = resolveJson.readAll(); resolveJson.close(); auto tagobj = QJsonDocument::fromJson(json).object().value("tags").toObject(); if (! json.isEmpty()) { bool regen = false; for (auto it = tagobj.constBegin(); it != tagobj.constEnd(); ++it) { Tag t = findGroup(it.key()).findTag(it.value().toString()); if (t.exists()) { tags << t; } else { regen = true; } } if (regen) { // Regenerates generateTagResolution(image); } return tags; } } tError() << "Tag resolution error : " << fi.fileName(); return tags; } static bool generateTagResolutionFile(const QString& image, const QList<TagGroup>& allGroups) { static const auto TagResolutionDir = QDir(Tf::conf("settings").value("TagResolutionDir").toString()); const QFileInfo fi(image); const QString filename = fi.fileName(); QJsonObject tagObj; for (const TagGroup& g : allGroups) { for (const Tag& t : g.tags()) { if (t.hasImage(filename)) { tagObj.insert(g.name(), t.name()); } } } QJsonObject json; json.insert("tags", tagObj); auto jsondata = QJsonDocument(json).toJson(QJsonDocument::Compact); if (! TagResolutionDir.exists()) { TagResolutionDir.mkpath("."); } QFile resolveJson(TagResolutionDir.absoluteFilePath(fi.completeBaseName() + ".json")); if (resolveJson.exists() && resolveJson.open(QIODevice::ReadOnly)) { auto currentJson = resolveJson.readAll(); resolveJson.close(); if (currentJson == jsondata) { // not write return true; } } if (resolveJson.open(QIODevice::WriteOnly | QIODevice::Truncate)) { resolveJson.write(jsondata); resolveJson.close(); tInfo() << "tag resolution json created: " << resolveJson.fileName(); } else { tError() << "write error tag resolution json: " << resolveJson.fileName(); return false; } return true; } bool TagRepository::generateTagResolution(const QString& image) const { return generateTagResolutionFile(image, allGroups()); } void TagRepository::regenerateTagResolution() const { static const auto OriginalImagesDir = Tf::conf("settings").value("OriginalImagesDir").toString(); const auto allgroups = allGroups(); QDirIterator it(OriginalImagesDir, {"*.jpg", "*.jpeg"}, QDir::Files | QDir::Readable, QDirIterator::Subdirectories); while (it.hasNext()) { generateTagResolutionFile(it.next(), allgroups); } } /* JSON sample { "tags": { "フォルダ(大腸炎)": "ulcerativecolitis_0630_001-420_mayo2_r", "全体病変": "ulcerativecolitis_mayo2", "照明": "normal", "部位": "e07daichorectum" } } */ <|endoftext|>
<commit_before>/***************************************************************************** * timer.cpp : wxWindows plugin for vlc ***************************************************************************** * Copyright (C) 2000-2003 VideoLAN * $Id$ * * Authors: Gildas Bazin <gbazin@videolan.org> * * 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., 59 Temple Place - Suite 330, Boston, MA 02111, USA. *****************************************************************************/ /***************************************************************************** * Preamble *****************************************************************************/ #include <stdlib.h> /* malloc(), free() */ #include <errno.h> /* ENOMEM */ #include <string.h> /* strerror() */ #include <stdio.h> #include <vlc/vlc.h> #include <vlc/aout.h> #include <vlc/intf.h> #include "wxwindows.h" #include <wx/timer.h> //void DisplayStreamDate( wxControl *, intf_thread_t *, int ); /* Callback prototypes */ static int PopupMenuCB( vlc_object_t *p_this, const char *psz_variable, vlc_value_t old_val, vlc_value_t new_val, void *param ); static int IntfShowCB( vlc_object_t *p_this, const char *psz_variable, vlc_value_t old_val, vlc_value_t new_val, void *param ); /***************************************************************************** * Constructor. *****************************************************************************/ Timer::Timer( intf_thread_t *_p_intf, Interface *_p_main_interface ) { p_intf = _p_intf; p_main_interface = _p_main_interface; b_init = 0; i_old_playing_status = PAUSE_S; i_old_rate = INPUT_RATE_DEFAULT; /* Register callback for the intf-popupmenu variable */ playlist_t *p_playlist = (playlist_t *)vlc_object_find( p_intf, VLC_OBJECT_PLAYLIST, FIND_ANYWHERE ); if( p_playlist != NULL ) { var_AddCallback( p_playlist, "intf-popupmenu", PopupMenuCB, p_intf ); var_AddCallback( p_playlist, "intf-show", IntfShowCB, p_intf ); vlc_object_release( p_playlist ); } Start( 100 /*milliseconds*/, wxTIMER_CONTINUOUS ); } Timer::~Timer() { /* Unregister callback */ playlist_t *p_playlist = (playlist_t *)vlc_object_find( p_intf, VLC_OBJECT_PLAYLIST, FIND_ANYWHERE ); if( p_playlist != NULL ) { var_DelCallback( p_playlist, "intf-popupmenu", PopupMenuCB, p_intf ); var_DelCallback( p_playlist, "intf-show", IntfShowCB, p_intf ); vlc_object_release( p_playlist ); } } /***************************************************************************** * Private methods. *****************************************************************************/ /***************************************************************************** * Manage: manage main thread messages ***************************************************************************** * In this function, called approx. 10 times a second, we check what the * main program wanted to tell us. *****************************************************************************/ void Timer::Notify() { input_thread_t *p_input = NULL; #if defined( __WXMSW__ ) /* Work-around a bug with accelerators */ if( !b_init ) { p_main_interface->Init(); b_init = VLC_TRUE; } #endif vlc_mutex_lock( &p_intf->change_lock ); /* Update the input */ if( p_intf->p_sys->p_input == NULL ) { playlist_t *p_playlist = (playlist_t *)vlc_object_find( p_intf, VLC_OBJECT_PLAYLIST, FIND_ANYWHERE ); if( p_playlist != NULL ) { p_intf->p_sys->p_input = p_playlist->p_input; vlc_object_release( p_playlist ); } /* Refresh interface */ if( p_intf->p_sys->p_input ) { p_main_interface->slider->SetValue( 0 ); b_old_seekable = VLC_FALSE; b_disc_shown = VLC_FALSE; p_main_interface->statusbar->SetStatusText( wxU(p_intf->p_sys->p_input->input.p_item->psz_name), 2 ); p_main_interface->TogglePlayButton( PLAYING_S ); i_old_playing_status = PLAYING_S; } } else if( p_intf->p_sys->p_input->b_dead ) { /* Hide slider and Disc Buttons */ p_main_interface->disc_frame->Hide(); p_main_interface->slider_sizer->Hide( p_main_interface->disc_frame ); p_main_interface->slider_sizer->Layout(); p_main_interface->slider_sizer->Fit( p_main_interface->slider_frame ); p_main_interface->slider_frame->Hide(); p_main_interface->frame_sizer->Hide( p_main_interface->slider_frame ); p_main_interface->frame_sizer->Layout(); p_main_interface->frame_sizer->Fit( p_main_interface ); p_main_interface->TogglePlayButton( PAUSE_S ); i_old_playing_status = PAUSE_S; p_main_interface->statusbar->SetStatusText( wxT(""), 0 ); p_main_interface->statusbar->SetStatusText( wxT(""), 2 ); p_intf->p_sys->p_input = NULL; } if( p_intf->p_sys->p_input ) { input_thread_t *p_input = p_intf->p_sys->p_input; vlc_value_t val; if( !p_input->b_die ) { vlc_value_t pos; /* New input or stream map change */ p_intf->p_sys->b_playing = 1; /* Update the item name */ p_main_interface->statusbar->SetStatusText( wxU(p_intf->p_sys->p_input->input.p_item->psz_name), 2 ); /* Manage the slider */ /* FIXME --fenrir */ /* Change the name of b_old_seekable into b_show_bar or something like that */ var_Get( p_input, "position", &pos ); vlc_value_t val; var_Change( p_input, "title", VLC_VAR_CHOICESCOUNT, &val, NULL ); if( val.i_int > 0 && !b_disc_shown ) { b_disc_shown = VLC_TRUE; vlc_value_t val; #define HELP_MENU N_("Menu") #define HELP_PCH N_("Previous chapter") #define HELP_NCH N_("Next chapter") #define HELP_PTR N_("Previous track") #define HELP_NTR N_("Next track") var_Change( p_input, "chapter", VLC_VAR_CHOICESCOUNT, &val, NULL ); if( val.i_int > 0 ) { p_main_interface->disc_menu_button->Show(); p_main_interface->disc_sizer->Show( p_main_interface->disc_menu_button ); p_main_interface->disc_sizer->Layout(); p_main_interface->disc_sizer->Fit( p_main_interface->disc_frame ); p_main_interface->disc_menu_button->SetToolTip( wxU(_( HELP_MENU ) ) ); p_main_interface->disc_prev_button->SetToolTip( wxU(_( HELP_PCH ) ) ); p_main_interface->disc_next_button->SetToolTip( wxU(_( HELP_NCH ) ) ); } else { p_main_interface->disc_menu_button->Hide(); p_main_interface->disc_sizer->Hide( p_main_interface->disc_menu_button ); p_main_interface->disc_prev_button->SetToolTip( wxU(_( HELP_PTR ) ) ); p_main_interface->disc_next_button->SetToolTip( wxU(_( HELP_NTR ) ) ); } p_main_interface->disc_frame->Show(); p_main_interface->slider_sizer->Show( p_main_interface->disc_frame ); } if( ! b_old_seekable ) { if( pos.f_float > 0.0 ) { /* Done like this, as it's the only way to know if the */ /* slider has to be displayed */ b_old_seekable = VLC_TRUE; p_main_interface->slider_frame->Show(); p_main_interface->frame_sizer->Show( p_main_interface->slider_frame ); p_main_interface->frame_sizer->Layout(); p_main_interface->frame_sizer->Fit( p_main_interface ); } } if( p_intf->p_sys->b_playing && b_old_seekable ) { /* Update the slider if the user isn't dragging it. */ if( p_intf->p_sys->b_slider_free ) { char psz_time[ MSTRTIME_MAX_SIZE ]; char psz_total[ MSTRTIME_MAX_SIZE ]; vlc_value_t time; mtime_t i_seconds; /* Update the value */ if( pos.f_float >= 0.0 ) { p_intf->p_sys->i_slider_pos = (int)(SLIDER_MAX_POS * pos.f_float); p_main_interface->slider->SetValue( p_intf->p_sys->i_slider_pos ); var_Get( p_intf->p_sys->p_input, "time", &time ); i_seconds = time.i_time / 1000000; secstotimestr ( psz_time, i_seconds ); var_Get( p_intf->p_sys->p_input, "length", &time ); i_seconds = time.i_time / 1000000; secstotimestr ( psz_total, i_seconds ); p_main_interface->statusbar->SetStatusText( wxU(psz_time) + wxString(wxT(" / ")) + wxU(psz_total), 0 ); } } } #if 0 vlc_mutex_lock( &p_input->stream.stream_lock ); if( p_intf->p_sys->p_input->stream.b_seekable && !b_old_seekable ) { /* Done like this because b_seekable is set slightly after * the new input object is available. */ b_old_seekable = VLC_TRUE; p_main_interface->slider_frame->Show(); p_main_interface->frame_sizer->Show( p_main_interface->slider_frame ); p_main_interface->frame_sizer->Layout(); p_main_interface->frame_sizer->Fit( p_main_interface ); } if( p_input->stream.b_seekable && p_intf->p_sys->b_playing ) { /* Update the slider if the user isn't dragging it. */ if( p_intf->p_sys->b_slider_free ) { vlc_value_t pos; char psz_time[ MSTRTIME_MAX_SIZE ]; char psz_total[ MSTRTIME_MAX_SIZE ]; vlc_value_t time; mtime_t i_seconds; /* Update the value */ var_Get( p_input, "position", &pos ); if( pos.f_float >= 0.0 ) { p_intf->p_sys->i_slider_pos = (int)(SLIDER_MAX_POS * pos.f_float); p_main_interface->slider->SetValue( p_intf->p_sys->i_slider_pos ); var_Get( p_intf->p_sys->p_input, "time", &time ); i_seconds = time.i_time / 1000000; secstotimestr ( psz_time, i_seconds ); var_Get( p_intf->p_sys->p_input, "length", &time ); i_seconds = time.i_time / 1000000; secstotimestr ( psz_total, i_seconds ); p_main_interface->statusbar->SetStatusText( wxU(psz_time) + wxString(wxT(" / ")) + wxU(psz_total), 0 ); } } } vlc_mutex_unlock( &p_input->stream.stream_lock ); #endif /* Take care of the volume, etc... */ p_main_interface->Update(); /* Manage Playing status */ var_Get( p_input, "state", &val ); if( i_old_playing_status != val.i_int ) { if( val.i_int == PAUSE_S ) { p_main_interface->TogglePlayButton( PAUSE_S ); } else { p_main_interface->TogglePlayButton( PLAYING_S ); } i_old_playing_status = val.i_int; } /* Manage Speed status */ var_Get( p_input, "rate", &val ); if( i_old_rate != val.i_int ) { p_main_interface->statusbar->SetStatusText( wxString::Format(wxT("x%.2f"), (float)INPUT_RATE_DEFAULT / val.i_int ), 1 ); i_old_rate = val.i_int; } } } else if( p_intf->p_sys->b_playing && !p_intf->b_die ) { p_intf->p_sys->b_playing = 0; p_main_interface->TogglePlayButton( PAUSE_S ); i_old_playing_status = PAUSE_S; } /* Show the interface, if requested */ if( p_intf->p_sys->b_intf_show ) { p_main_interface->Raise(); p_intf->p_sys->b_intf_show = VLC_FALSE; } if( p_intf->b_die ) { vlc_mutex_unlock( &p_intf->change_lock ); /* Prepare to die, young Skywalker */ p_main_interface->Close(TRUE); return; } vlc_mutex_unlock( &p_intf->change_lock ); } /***************************************************************************** * PopupMenuCB: callback triggered by the intf-popupmenu playlist variable. * We don't show the menu directly here because we don't want the * caller to block for a too long time. *****************************************************************************/ static int PopupMenuCB( vlc_object_t *p_this, const char *psz_variable, vlc_value_t old_val, vlc_value_t new_val, void *param ) { intf_thread_t *p_intf = (intf_thread_t *)param; if( p_intf->p_sys->pf_show_dialog ) { p_intf->p_sys->pf_show_dialog( p_intf, INTF_DIALOG_POPUPMENU, new_val.b_bool, 0 ); } return VLC_SUCCESS; } /***************************************************************************** * IntfShowCB: callback triggered by the intf-show playlist variable. *****************************************************************************/ static int IntfShowCB( vlc_object_t *p_this, const char *psz_variable, vlc_value_t old_val, vlc_value_t new_val, void *param ) { intf_thread_t *p_intf = (intf_thread_t *)param; p_intf->p_sys->b_intf_show = VLC_TRUE; return VLC_SUCCESS; } <commit_msg>* modules/gui/wxwindows/timer.cpp: don't forget to yield/release the input otherwise you're bound to access an invalid pointer later on.<commit_after>/***************************************************************************** * timer.cpp : wxWindows plugin for vlc ***************************************************************************** * Copyright (C) 2000-2003 VideoLAN * $Id$ * * Authors: Gildas Bazin <gbazin@videolan.org> * * 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., 59 Temple Place - Suite 330, Boston, MA 02111, USA. *****************************************************************************/ /***************************************************************************** * Preamble *****************************************************************************/ #include <stdlib.h> /* malloc(), free() */ #include <errno.h> /* ENOMEM */ #include <string.h> /* strerror() */ #include <stdio.h> #include <vlc/vlc.h> #include <vlc/aout.h> #include <vlc/intf.h> #include "wxwindows.h" #include <wx/timer.h> //void DisplayStreamDate( wxControl *, intf_thread_t *, int ); /* Callback prototypes */ static int PopupMenuCB( vlc_object_t *p_this, const char *psz_variable, vlc_value_t old_val, vlc_value_t new_val, void *param ); static int IntfShowCB( vlc_object_t *p_this, const char *psz_variable, vlc_value_t old_val, vlc_value_t new_val, void *param ); /***************************************************************************** * Constructor. *****************************************************************************/ Timer::Timer( intf_thread_t *_p_intf, Interface *_p_main_interface ) { p_intf = _p_intf; p_main_interface = _p_main_interface; b_init = 0; i_old_playing_status = PAUSE_S; i_old_rate = INPUT_RATE_DEFAULT; /* Register callback for the intf-popupmenu variable */ playlist_t *p_playlist = (playlist_t *)vlc_object_find( p_intf, VLC_OBJECT_PLAYLIST, FIND_ANYWHERE ); if( p_playlist != NULL ) { var_AddCallback( p_playlist, "intf-popupmenu", PopupMenuCB, p_intf ); var_AddCallback( p_playlist, "intf-show", IntfShowCB, p_intf ); vlc_object_release( p_playlist ); } Start( 100 /*milliseconds*/, wxTIMER_CONTINUOUS ); } Timer::~Timer() { /* Unregister callback */ playlist_t *p_playlist = (playlist_t *)vlc_object_find( p_intf, VLC_OBJECT_PLAYLIST, FIND_ANYWHERE ); if( p_playlist != NULL ) { var_DelCallback( p_playlist, "intf-popupmenu", PopupMenuCB, p_intf ); var_DelCallback( p_playlist, "intf-show", IntfShowCB, p_intf ); vlc_object_release( p_playlist ); } } /***************************************************************************** * Private methods. *****************************************************************************/ /***************************************************************************** * Manage: manage main thread messages ***************************************************************************** * In this function, called approx. 10 times a second, we check what the * main program wanted to tell us. *****************************************************************************/ void Timer::Notify() { #if defined( __WXMSW__ ) /* Work-around a bug with accelerators */ if( !b_init ) { p_main_interface->Init(); b_init = VLC_TRUE; } #endif vlc_mutex_lock( &p_intf->change_lock ); /* Update the input */ if( p_intf->p_sys->p_input == NULL ) { playlist_t *p_playlist = (playlist_t *)vlc_object_find( p_intf, VLC_OBJECT_PLAYLIST, FIND_ANYWHERE ); if( p_playlist != NULL ) { vlc_mutex_lock( &p_playlist->object_lock ); p_intf->p_sys->p_input = p_playlist->p_input; if( p_intf->p_sys->p_input ) vlc_object_yield( p_intf->p_sys->p_input ); vlc_mutex_unlock( &p_playlist->object_lock ); vlc_object_release( p_playlist ); } /* Refresh interface */ if( p_intf->p_sys->p_input ) { p_main_interface->slider->SetValue( 0 ); b_old_seekable = VLC_FALSE; b_disc_shown = VLC_FALSE; p_main_interface->statusbar->SetStatusText( wxU(p_intf->p_sys->p_input->input.p_item->psz_name), 2 ); p_main_interface->TogglePlayButton( PLAYING_S ); i_old_playing_status = PLAYING_S; } } else if( p_intf->p_sys->p_input->b_dead ) { /* Hide slider and Disc Buttons */ p_main_interface->disc_frame->Hide(); p_main_interface->slider_sizer->Hide( p_main_interface->disc_frame ); p_main_interface->slider_sizer->Layout(); p_main_interface->slider_sizer->Fit( p_main_interface->slider_frame ); p_main_interface->slider_frame->Hide(); p_main_interface->frame_sizer->Hide( p_main_interface->slider_frame ); p_main_interface->frame_sizer->Layout(); p_main_interface->frame_sizer->Fit( p_main_interface ); p_main_interface->TogglePlayButton( PAUSE_S ); i_old_playing_status = PAUSE_S; p_main_interface->statusbar->SetStatusText( wxT(""), 0 ); p_main_interface->statusbar->SetStatusText( wxT(""), 2 ); vlc_object_release( p_intf->p_sys->p_input ); p_intf->p_sys->p_input = NULL; } if( p_intf->p_sys->p_input ) { input_thread_t *p_input = p_intf->p_sys->p_input; vlc_value_t val; if( !p_input->b_die ) { vlc_value_t pos; /* New input or stream map change */ p_intf->p_sys->b_playing = 1; /* Update the item name */ p_main_interface->statusbar->SetStatusText( wxU(p_intf->p_sys->p_input->input.p_item->psz_name), 2 ); /* Manage the slider */ /* FIXME --fenrir */ /* Change the name of b_old_seekable into b_show_bar or something like that */ var_Get( p_input, "position", &pos ); var_Change( p_input, "title", VLC_VAR_CHOICESCOUNT, &val, NULL ); if( val.i_int > 0 && !b_disc_shown ) { b_disc_shown = VLC_TRUE; vlc_value_t val; #define HELP_MENU N_("Menu") #define HELP_PCH N_("Previous chapter") #define HELP_NCH N_("Next chapter") #define HELP_PTR N_("Previous track") #define HELP_NTR N_("Next track") var_Change( p_input, "chapter", VLC_VAR_CHOICESCOUNT, &val, NULL ); if( val.i_int > 0 ) { p_main_interface->disc_menu_button->Show(); p_main_interface->disc_sizer->Show( p_main_interface->disc_menu_button ); p_main_interface->disc_sizer->Layout(); p_main_interface->disc_sizer->Fit( p_main_interface->disc_frame ); p_main_interface->disc_menu_button->SetToolTip( wxU(_( HELP_MENU ) ) ); p_main_interface->disc_prev_button->SetToolTip( wxU(_( HELP_PCH ) ) ); p_main_interface->disc_next_button->SetToolTip( wxU(_( HELP_NCH ) ) ); } else { p_main_interface->disc_menu_button->Hide(); p_main_interface->disc_sizer->Hide( p_main_interface->disc_menu_button ); p_main_interface->disc_prev_button->SetToolTip( wxU(_( HELP_PTR ) ) ); p_main_interface->disc_next_button->SetToolTip( wxU(_( HELP_NTR ) ) ); } p_main_interface->disc_frame->Show(); p_main_interface->slider_sizer->Show( p_main_interface->disc_frame ); } if( ! b_old_seekable ) { if( pos.f_float > 0.0 ) { /* Done like this, as it's the only way to know if the */ /* slider has to be displayed */ b_old_seekable = VLC_TRUE; p_main_interface->slider_frame->Show(); p_main_interface->frame_sizer->Show( p_main_interface->slider_frame ); p_main_interface->frame_sizer->Layout(); p_main_interface->frame_sizer->Fit( p_main_interface ); } } if( p_intf->p_sys->b_playing && b_old_seekable ) { /* Update the slider if the user isn't dragging it. */ if( p_intf->p_sys->b_slider_free ) { char psz_time[ MSTRTIME_MAX_SIZE ]; char psz_total[ MSTRTIME_MAX_SIZE ]; vlc_value_t time; mtime_t i_seconds; /* Update the value */ if( pos.f_float >= 0.0 ) { p_intf->p_sys->i_slider_pos = (int)(SLIDER_MAX_POS * pos.f_float); p_main_interface->slider->SetValue( p_intf->p_sys->i_slider_pos ); var_Get( p_intf->p_sys->p_input, "time", &time ); i_seconds = time.i_time / 1000000; secstotimestr ( psz_time, i_seconds ); var_Get( p_intf->p_sys->p_input, "length", &time ); i_seconds = time.i_time / 1000000; secstotimestr ( psz_total, i_seconds ); p_main_interface->statusbar->SetStatusText( wxU(psz_time) + wxString(wxT(" / ")) + wxU(psz_total), 0 ); } } } #if 0 vlc_mutex_lock( &p_input->stream.stream_lock ); if( p_intf->p_sys->p_input->stream.b_seekable && !b_old_seekable ) { /* Done like this because b_seekable is set slightly after * the new input object is available. */ b_old_seekable = VLC_TRUE; p_main_interface->slider_frame->Show(); p_main_interface->frame_sizer->Show( p_main_interface->slider_frame ); p_main_interface->frame_sizer->Layout(); p_main_interface->frame_sizer->Fit( p_main_interface ); } if( p_input->stream.b_seekable && p_intf->p_sys->b_playing ) { /* Update the slider if the user isn't dragging it. */ if( p_intf->p_sys->b_slider_free ) { vlc_value_t pos; char psz_time[ MSTRTIME_MAX_SIZE ]; char psz_total[ MSTRTIME_MAX_SIZE ]; vlc_value_t time; mtime_t i_seconds; /* Update the value */ var_Get( p_input, "position", &pos ); if( pos.f_float >= 0.0 ) { p_intf->p_sys->i_slider_pos = (int)(SLIDER_MAX_POS * pos.f_float); p_main_interface->slider->SetValue( p_intf->p_sys->i_slider_pos ); var_Get( p_intf->p_sys->p_input, "time", &time ); i_seconds = time.i_time / 1000000; secstotimestr ( psz_time, i_seconds ); var_Get( p_intf->p_sys->p_input, "length", &time ); i_seconds = time.i_time / 1000000; secstotimestr ( psz_total, i_seconds ); p_main_interface->statusbar->SetStatusText( wxU(psz_time) + wxString(wxT(" / ")) + wxU(psz_total), 0 ); } } } vlc_mutex_unlock( &p_input->stream.stream_lock ); #endif /* Take care of the volume, etc... */ p_main_interface->Update(); /* Manage Playing status */ var_Get( p_input, "state", &val ); if( i_old_playing_status != val.i_int ) { if( val.i_int == PAUSE_S ) { p_main_interface->TogglePlayButton( PAUSE_S ); } else { p_main_interface->TogglePlayButton( PLAYING_S ); } i_old_playing_status = val.i_int; } /* Manage Speed status */ var_Get( p_input, "rate", &val ); if( i_old_rate != val.i_int ) { p_main_interface->statusbar->SetStatusText( wxString::Format(wxT("x%.2f"), (float)INPUT_RATE_DEFAULT / val.i_int ), 1 ); i_old_rate = val.i_int; } } } else if( p_intf->p_sys->b_playing && !p_intf->b_die ) { p_intf->p_sys->b_playing = 0; p_main_interface->TogglePlayButton( PAUSE_S ); i_old_playing_status = PAUSE_S; } /* Show the interface, if requested */ if( p_intf->p_sys->b_intf_show ) { p_main_interface->Raise(); p_intf->p_sys->b_intf_show = VLC_FALSE; } if( p_intf->b_die ) { vlc_mutex_unlock( &p_intf->change_lock ); /* Prepare to die, young Skywalker */ p_main_interface->Close(TRUE); return; } vlc_mutex_unlock( &p_intf->change_lock ); } /***************************************************************************** * PopupMenuCB: callback triggered by the intf-popupmenu playlist variable. * We don't show the menu directly here because we don't want the * caller to block for a too long time. *****************************************************************************/ static int PopupMenuCB( vlc_object_t *p_this, const char *psz_variable, vlc_value_t old_val, vlc_value_t new_val, void *param ) { intf_thread_t *p_intf = (intf_thread_t *)param; if( p_intf->p_sys->pf_show_dialog ) { p_intf->p_sys->pf_show_dialog( p_intf, INTF_DIALOG_POPUPMENU, new_val.b_bool, 0 ); } return VLC_SUCCESS; } /***************************************************************************** * IntfShowCB: callback triggered by the intf-show playlist variable. *****************************************************************************/ static int IntfShowCB( vlc_object_t *p_this, const char *psz_variable, vlc_value_t old_val, vlc_value_t new_val, void *param ) { intf_thread_t *p_intf = (intf_thread_t *)param; p_intf->p_sys->b_intf_show = VLC_TRUE; return VLC_SUCCESS; } <|endoftext|>
<commit_before>// Author: Jan Kristian Sto. Domingo [jstod001@ucr.edu] // main.cpp for rshell #include <iostream> using namespace std; int main() { return 0; } <commit_msg>edited exec.cpp header<commit_after>// Author: Jan Kristian Sto. Domingo [jstod001@ucr.edu] // exec.cpp for rshell #include <iostream> using namespace std; int main() { return 0; } <|endoftext|>
<commit_before>/* * The MIT License (MIT) * * Copyright (c) 2015 Jett * * 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. */ #ifndef HCKT_TREE_H #define HCKT_TREE_H #include <cassert> #include <iostream> #include <bitset> #include "lmemvector.hpp" #include "util.hpp" namespace hckt { template <typename T> class tree { typedef T value_type; protected: std::bitset<64> chiset; //is child set to this position std::bitset<64> inv_leaf; //opposite of leaf hckt::lmemvector<value_type> values; hckt::lmemvector<tree<value_type>*> children; public: tree() : chiset { 0x0000000000000000 } , inv_leaf { 0xFFFFFFFFFFFFFFFF } , values { } , children { } { } ~tree() { collapse(); } //counts number of set bits static inline unsigned popcount(std::uint64_t x) { #ifdef __SSE4_2__ return _popcnt64(x); #else constexpr std::uint64_t m1 { 0x5555555555555555 }; constexpr std::uint64_t m2 { 0x3333333333333333 }; constexpr std::uint64_t m4 { 0x0f0f0f0f0f0f0f0f }; constexpr std::uint64_t h01 { 0x0101010101010101 }; x -= (x >> 1) & m1; x = (x & m2) + ((x >> 2) & m2); x = (x + (x >> 4)) & m4; return (x * h01) >> 56; #endif } std::uint64_t chidist() const { return (chiset.to_ullong() & inv_leaf.to_ullong()); } unsigned children_amnt() const { return popcount(chidist()); } unsigned leaf_amnt() const { return popcount(~inv_leaf.to_ullong()); } unsigned value_amount() const { return popcount(chiset.to_ullong()); } unsigned get_children_position(const unsigned position) const { assert(position < 64); return position == 0 ? position : popcount(chidist() << (64 - position)); } /* * check if we have any children */ bool has_children() const { return chiset.any(); } bool is_set(const unsigned position) const { assert(position < 64); return chiset[position]; } bool is_leaf(const unsigned position) const { assert(position < 64); return !inv_leaf[position]; } /* * destroy children */ void collapse() { const unsigned c_amnt { children_amnt() }; for(unsigned i=0; i<c_amnt; ++i) { children[i]->collapse(); } children.clear(c_amnt); values.clear(c_amnt); chiset.reset(); } /* * insert a tree into position of tree * position should be result of get_position */ void insert(const unsigned position, const value_type value) { assert(position < 64); assert(! is_set(position)); const unsigned cpos { get_children_position(position) }; const unsigned c_amnt { children_amnt() }; children.insert(cpos, new tree<value_type>(), c_amnt); values.insert(cpos, value, c_amnt); chiset.set(position); inv_leaf.set(position); } /* * insert a leaf into position of tree * position should be result of get_position */ void insert_leaf(const unsigned position, const value_type value) { assert(position < 64); assert(! is_set(position)); const unsigned cpos { get_children_position(position) }; const unsigned c_amnt { children_amnt() }; values.insert(cpos, value, c_amnt); chiset.set(position); inv_leaf.reset(position); } /* * removes an item from tree * position should be result of get_position */ void remove(const unsigned position) { assert(position < 64); assert(is_set(position)); assert(! is_leaf(position)); const unsigned cpos { get_children_position(position) }; const unsigned c_amnt { children_amnt() }; children[cpos]->collapse(); children.erase(cpos); values.erase(cpos); chiset.reset(position); } /* * get child node * position should be result of get_position */ tree<value_type> * child(const unsigned position) const { assert(position < 64); assert(is_set(position)); assert(! is_leaf(position)); const unsigned cpos { get_children_position(position) }; return children[cpos]; } /* * sets node to specific value * note: this does not check whether a value has been inserted here yet * position should be result of get_position */ void set_value(const unsigned position, const value_type value) { assert(position < 64); assert(is_set(position)); const unsigned cpos { get_children_position(position) }; values[cpos] = value; } /* * gets value from specific position * note: this does not check whether a value has been inserted here yet * position should be result of get_position */ value_type get_value(const unsigned position) const { assert(position < 64); const unsigned cpos { get_children_position(position) }; return values[cpos]; } /************************************************ * * BENCHMARKING CODE * ***********************************************/ std::size_t calculate_memory_size() const { const unsigned c_amnt { children_amnt() }; const unsigned v_amnt { value_amount() }; std::size_t size { sizeof(chiset) + sizeof(inv_leaf) + sizeof(values) + (v_amnt * sizeof(value_type)) + sizeof(children) + (c_amnt * sizeof(tree<value_type>*)) }; for(unsigned i=0; i<c_amnt; ++i) { size += children[i]->calculate_memory_size(); } return size; } std::size_t calculate_children_amnt() const { std::size_t amount { children_amnt() }; for(unsigned i=0, c_amnt = children_amnt(); i<c_amnt; ++i) { amount += children[i]->calculate_children_amnt(); } return amount; } std::size_t calculate_leaf_amount() const { std::size_t amount { leaf_amnt() }; for(unsigned i=0, c_amnt = children_amnt(); i<c_amnt; ++i) { amount += children[i]->calculate_leaf_amount(); } return amount; } void mem_usage_info() const { const std::size_t memsize { calculate_memory_size() }; const std::size_t c_amnt { calculate_children_amnt() }; const std::size_t l_amnt { calculate_leaf_amount() }; const std::size_t v_amnt { c_amnt + l_amnt }; std::cout << "total: " << hckt::render_size(memsize) << std::endl; std::cout << "tree-size: " << hckt::render_size(sizeof(tree<value_type>)) << std::endl; std::cout << "val-size: " << hckt::render_size(sizeof(value_type)) << std::endl; std::cout << "values: " << hckt::render_number(v_amnt) << std::endl; std::cout << "children: " << hckt::render_number(c_amnt) << std::endl; std::cout << "leaves: " << hckt::render_number(l_amnt) << std::endl; std::cout << "per-val: " << (static_cast<double>(memsize) / v_amnt) << " B" << std::endl; std::cout << "overhead: " << (static_cast<double>(memsize - (v_amnt * sizeof(value_type))) / v_amnt) << " B" << std::endl; } }; }; #endif <commit_msg>use _mm_popcnt<commit_after>/* * The MIT License (MIT) * * Copyright (c) 2015 Jett * * 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. */ #ifndef HCKT_TREE_H #define HCKT_TREE_H #include <cassert> #include <iostream> #include <bitset> #include "lmemvector.hpp" #include "util.hpp" namespace hckt { template <typename T> class tree { typedef T value_type; protected: std::bitset<64> chiset; //is child set to this position std::bitset<64> inv_leaf; //opposite of leaf hckt::lmemvector<value_type> values; hckt::lmemvector<tree<value_type>*> children; public: tree() : chiset { 0x0000000000000000 } , inv_leaf { 0xFFFFFFFFFFFFFFFF } , values { } , children { } { } ~tree() { collapse(); } //counts number of set bits static inline unsigned popcount(std::uint64_t x) { #ifdef __SSE4_2__ return _mm_popcnt_u64(x); #else constexpr std::uint64_t m1 { 0x5555555555555555 }; constexpr std::uint64_t m2 { 0x3333333333333333 }; constexpr std::uint64_t m4 { 0x0f0f0f0f0f0f0f0f }; constexpr std::uint64_t h01 { 0x0101010101010101 }; x -= (x >> 1) & m1; x = (x & m2) + ((x >> 2) & m2); x = (x + (x >> 4)) & m4; return (x * h01) >> 56; #endif } std::uint64_t chidist() const { return (chiset.to_ullong() & inv_leaf.to_ullong()); } unsigned children_amnt() const { return popcount(chidist()); } unsigned leaf_amnt() const { return popcount(~inv_leaf.to_ullong()); } unsigned value_amount() const { return popcount(chiset.to_ullong()); } unsigned get_children_position(const unsigned position) const { assert(position < 64); return position == 0 ? position : popcount(chidist() << (64 - position)); } /* * check if we have any children */ bool has_children() const { return chiset.any(); } bool is_set(const unsigned position) const { assert(position < 64); return chiset[position]; } bool is_leaf(const unsigned position) const { assert(position < 64); return !inv_leaf[position]; } /* * destroy children */ void collapse() { const unsigned c_amnt { children_amnt() }; for(unsigned i=0; i<c_amnt; ++i) { children[i]->collapse(); } children.clear(c_amnt); values.clear(c_amnt); chiset.reset(); } /* * insert a tree into position of tree * position should be result of get_position */ void insert(const unsigned position, const value_type value) { assert(position < 64); assert(! is_set(position)); const unsigned cpos { get_children_position(position) }; const unsigned c_amnt { children_amnt() }; children.insert(cpos, new tree<value_type>(), c_amnt); values.insert(cpos, value, c_amnt); chiset.set(position); inv_leaf.set(position); } /* * insert a leaf into position of tree * position should be result of get_position */ void insert_leaf(const unsigned position, const value_type value) { assert(position < 64); assert(! is_set(position)); const unsigned cpos { get_children_position(position) }; const unsigned c_amnt { children_amnt() }; values.insert(cpos, value, c_amnt); chiset.set(position); inv_leaf.reset(position); } /* * removes an item from tree * position should be result of get_position */ void remove(const unsigned position) { assert(position < 64); assert(is_set(position)); assert(! is_leaf(position)); const unsigned cpos { get_children_position(position) }; const unsigned c_amnt { children_amnt() }; children[cpos]->collapse(); children.erase(cpos); values.erase(cpos); chiset.reset(position); } /* * get child node * position should be result of get_position */ tree<value_type> * child(const unsigned position) const { assert(position < 64); assert(is_set(position)); assert(! is_leaf(position)); const unsigned cpos { get_children_position(position) }; return children[cpos]; } /* * sets node to specific value * note: this does not check whether a value has been inserted here yet * position should be result of get_position */ void set_value(const unsigned position, const value_type value) { assert(position < 64); assert(is_set(position)); const unsigned cpos { get_children_position(position) }; values[cpos] = value; } /* * gets value from specific position * note: this does not check whether a value has been inserted here yet * position should be result of get_position */ value_type get_value(const unsigned position) const { assert(position < 64); const unsigned cpos { get_children_position(position) }; return values[cpos]; } /************************************************ * * BENCHMARKING CODE * ***********************************************/ std::size_t calculate_memory_size() const { const unsigned c_amnt { children_amnt() }; const unsigned v_amnt { value_amount() }; std::size_t size { sizeof(chiset) + sizeof(inv_leaf) + sizeof(values) + (v_amnt * sizeof(value_type)) + sizeof(children) + (c_amnt * sizeof(tree<value_type>*)) }; for(unsigned i=0; i<c_amnt; ++i) { size += children[i]->calculate_memory_size(); } return size; } std::size_t calculate_children_amnt() const { std::size_t amount { children_amnt() }; for(unsigned i=0, c_amnt = children_amnt(); i<c_amnt; ++i) { amount += children[i]->calculate_children_amnt(); } return amount; } std::size_t calculate_leaf_amount() const { std::size_t amount { leaf_amnt() }; for(unsigned i=0, c_amnt = children_amnt(); i<c_amnt; ++i) { amount += children[i]->calculate_leaf_amount(); } return amount; } void mem_usage_info() const { const std::size_t memsize { calculate_memory_size() }; const std::size_t c_amnt { calculate_children_amnt() }; const std::size_t l_amnt { calculate_leaf_amount() }; const std::size_t v_amnt { c_amnt + l_amnt }; std::cout << "total: " << hckt::render_size(memsize) << std::endl; std::cout << "tree-size: " << hckt::render_size(sizeof(tree<value_type>)) << std::endl; std::cout << "val-size: " << hckt::render_size(sizeof(value_type)) << std::endl; std::cout << "values: " << hckt::render_number(v_amnt) << std::endl; std::cout << "children: " << hckt::render_number(c_amnt) << std::endl; std::cout << "leaves: " << hckt::render_number(l_amnt) << std::endl; std::cout << "per-val: " << (static_cast<double>(memsize) / v_amnt) << " B" << std::endl; std::cout << "overhead: " << (static_cast<double>(memsize - (v_amnt * sizeof(value_type))) / v_amnt) << " B" << std::endl; } }; }; #endif <|endoftext|>
<commit_before>// Copyright (c) 2015, Ming Wen #ifndef _H_UTIL #define _H_UTIL #include "fys.hpp" #include "json_images.hpp" using namespace std; using namespace cv; namespace fys { int checkDigit(string str); string itoa(int idx); string ftoa(double num); string btoa(bool var); bool atob(const char* s); bool pointsCompXAscend(KeyPoint i, KeyPoint j); bool pointsCompXDescend(KeyPoint i, KeyPoint j); bool pointsCompYAscend(KeyPoint i, KeyPoint j); bool pointsCompYDescend(KeyPoint i, KeyPoint j); vector<KeyPoint> pointsInRegion(vector<KeyPoint> allPoints, ImageRegion& region); vector<KeyPoint> pointsInObject(vector<KeyPoint> allPoints, ImageObject& object); vector<KeyPoint> matchedPoints(vector<KeyPoint> allPoints, vector<DMatch> matches, int type); ImageRegion locateDenseRegion(vector<KeyPoint> points, double featherRate); } // namespce fys #endif // _H_UTIL <commit_msg>fix a typo in util.hpp<commit_after>// Copyright (c) 2015, Ming Wen #ifndef _H_UTIL #define _H_UTIL #include "fys.hpp" #include "json_images.hpp" using namespace std; using namespace cv; namespace fys { int checkDigit(string str); string itoa(int idx); string ftoa(double num); string btoa(bool var); bool atob(const char* s); bool pointsCompXAscend(KeyPoint i, KeyPoint j); bool pointsCompXDescend(KeyPoint i, KeyPoint j); bool pointsCompYAscend(KeyPoint i, KeyPoint j); bool pointsCompYDescend(KeyPoint i, KeyPoint j); vector<KeyPoint> pointsInRegion(vector<KeyPoint> allPoints, ImageRegion& region); vector<KeyPoint> pointsInObject(vector<KeyPoint> allPoints, ImageObject& object); vector<KeyPoint> matchedPoints(vector<KeyPoint> allPoints, vector<DMatch> matches, int type); ImageRegion locateDenseRegion(vector<KeyPoint> points, double featherRate); } // namespace fys #endif // _H_UTIL <|endoftext|>
<commit_before>/* This file is part of Ingen. Copyright 2007-2015 David Robillard <http://drobilla.net/> Ingen 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 any later version. Ingen 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 details. You should have received a copy of the GNU Affero General Public License along with Ingen. If not, see <http://www.gnu.org/licenses/>. */ #ifndef INGEN_MODULE_HPP #define INGEN_MODULE_HPP #include "ingen/ingen.h" namespace Glib { class Module; } namespace Ingen { class World; /** A dynamically loaded Ingen module. * * All components of Ingen reside in one of these. * @ingroup IngenShared */ class INGEN_API Module { public: Module() : library(nullptr) {} virtual ~Module() = default; virtual void load(Ingen::World* world) = 0; virtual void run(Ingen::World* world) {} /** Library implementing this module. * * This is managed by the World and not this class, since closing the library * in this destructor could possibly reference code from the library * afterwards and cause a segfault on exit. */ Glib::Module* library; private: Module(const Module& noncopyable); Module& operator=(const Module& noncopyable); }; } // namespace Ingen extern "C" { /** Prototype for the ingen_module_load() entry point in an ingen module. */ INGEN_API Ingen::Module* ingen_module_load(); } #endif // INGEN_MODULE_HPP <commit_msg>Use delete to hide constructors<commit_after>/* This file is part of Ingen. Copyright 2007-2015 David Robillard <http://drobilla.net/> Ingen 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 any later version. Ingen 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 details. You should have received a copy of the GNU Affero General Public License along with Ingen. If not, see <http://www.gnu.org/licenses/>. */ #ifndef INGEN_MODULE_HPP #define INGEN_MODULE_HPP #include "ingen/ingen.h" namespace Glib { class Module; } namespace Ingen { class World; /** A dynamically loaded Ingen module. * * All components of Ingen reside in one of these. * @ingroup IngenShared */ class INGEN_API Module { public: Module() : library(nullptr) {} virtual ~Module() = default; virtual void load(Ingen::World* world) = 0; virtual void run(Ingen::World* world) {} /** Library implementing this module. * * This is managed by the World and not this class, since closing the library * in this destructor could possibly reference code from the library * afterwards and cause a segfault on exit. */ Glib::Module* library; private: Module(const Module& noncopyable) = delete; Module& operator=(const Module& noncopyable) = delete; }; } // namespace Ingen extern "C" { /** Prototype for the ingen_module_load() entry point in an ingen module. */ INGEN_API Ingen::Module* ingen_module_load(); } #endif // INGEN_MODULE_HPP <|endoftext|>
<commit_before>#include "Atm_condition.hpp" Atm_condition & Atm_condition::begin( bool default_state /* = false */ ) { const static state_t state_table[] PROGMEM = { /* ON_ENTER ON_LOOP ON_EXIT EVT_ON EVT_OFF EVT_TOGGLE EVT_INPUT ELSE */ /* OFF */ ACT_OFF, -1, -1, ON, -1, ON, OFF, -1, /* ON */ ACT_ON, -1, -1, -1, OFF, OFF, ON, -1, }; Machine::begin( state_table, ELSE ); _last_state = -1; state( default_state ? ON : OFF ); // cycle(); Causes the condition to become true momentarily return *this; } Atm_condition & Atm_condition::onFlip( bool st, stepcb_t callback ) { short idx = st ? 0 : 1; _comm[idx]._mode = MODE_CALLBACK; _comm[idx]._callback = callback; return *this; } Atm_condition & Atm_condition::onFlip( bool st, Machine & machine, state_t event /* = 0 */ ) { short idx = st ? 0 : 1; _comm[idx]._mode = MODE_MACHINE; _comm[idx]._client_machine = &machine; _comm[idx]._client_machine_event = event; return *this; } Atm_condition & Atm_condition::onFlip( bool st, const char * label, state_t event /* = 0 */ ) { short idx = st ? 0 : 1; _comm[idx]._mode = MODE_FACTORY; _comm[idx]._client_label = label; _comm[idx]._client_label_event = event; return *this; } Atm_condition & Atm_condition::onFlip( bool st, TinyMachine & machine, state_t event /* = 0 */ ) { short idx = st ? 0 : 1; _comm[idx]._mode = MODE_TMACHINE; _comm[idx]._client_tmachine = &machine; _comm[idx]._client_tmachine_event = event; return *this; } Atm_condition & Atm_condition::onInput( bool st, stepcb_t callback ) { short idx = st ? 2 : 3; _comm[idx]._mode = MODE_CALLBACK; _comm[idx]._callback = callback; return *this; } Atm_condition & Atm_condition::onInput( bool st, Machine & machine, state_t event /* = 0 */ ) { short idx = st ? 2 : 3; _comm[idx]._mode = MODE_MACHINE; _comm[idx]._client_machine = &machine; _comm[idx]._client_machine_event = event; return *this; } Atm_condition & Atm_condition::onInput( bool st, const char * label, state_t event /* = 0 */ ) { short idx = st ? 2 : 3; _comm[idx]._mode = MODE_FACTORY; _comm[idx]._client_label = label; _comm[idx]._client_label_event = event; return *this; } Atm_condition & Atm_condition::onInput( bool st, TinyMachine & machine, state_t event /* = 0 */ ) { short idx = st ? 2 : 3; _comm[idx]._mode = MODE_TMACHINE; _comm[idx]._client_tmachine = &machine; _comm[idx]._client_tmachine_event = event; return *this; } Atm_condition & Atm_condition::IF( Machine & machine, char relOp /* = '>' */, state_t match /* = 0 */ ) { return OP( '?', machine, relOp, match ); } Atm_condition & Atm_condition::IF( TinyMachine & machine, char relOp /* = '>' */, state_t match /* = 0 */ ) { return OP( '?', machine, relOp, match ); } Atm_condition & Atm_condition::AND( Machine & machine, char relOp /* = '>' */, state_t match /* = 0 */ ) { return OP( '&', machine, relOp, match ); } Atm_condition & Atm_condition::AND( TinyMachine & machine, char relOp /* = '>' */, state_t match /* = 0 */ ) { return OP( '&', machine, relOp, match ); } Atm_condition & Atm_condition::OR( Machine & machine, char relOp /* = '>' */, state_t match /* = 0 */ ) { return OP( '|', machine, relOp, match ); } Atm_condition & Atm_condition::OR( TinyMachine & machine, char relOp /* = '>' */, state_t match /* = 0 */ ) { return OP( '|', machine, relOp, match ); } Atm_condition & Atm_condition::OP( char logOp, Machine & machine, char relOp = '>', state_t match = 0 ) { for ( uint8_t i = 0; i < ATM_CONDITION_OP_MAX; i++ ) { // Fix me off-by-one, should be <!!! if ( _op[i]._mode == MODE_NULL ) { // Pick the first free slot _op[i]._mode = MODE_MACHINE; _op[i]._logop = logOp; _op[i]._relop = relOp; _op[i]._client_machine = &machine; _op[i]._client_machine_event = match; break; } } return *this; } Atm_condition & Atm_condition::OP( char logOp, TinyMachine & machine, char relOp, state_t match ) { for ( uint8_t i = 0; i < ATM_CONDITION_OP_MAX; i++ ) { if ( _op[i]._mode == MODE_NULL ) { // Pick the first free slot _op[i]._mode = MODE_TMACHINE; _op[i]._logop = logOp; _op[i]._relop = relOp; _op[i]._client_tmachine = &machine; _op[i]._client_tmachine_event = match; break; } } return *this; } bool Atm_condition::eval_one( uint8_t idx ) { if ( _op[idx]._mode == MODE_MACHINE ) { state_t machine_state = _op[idx]._client_machine->state(); switch ( _op[idx]._relop ) { case '=' : return machine_state == _op[idx]._client_machine_event; case '!' : return machine_state != _op[idx]._client_machine_event; case '<' : return machine_state < _op[idx]._client_machine_event; case '>' : return machine_state > _op[idx]._client_machine_event; case '-' : return machine_state <= _op[idx]._client_machine_event; case '+' : return machine_state >= _op[idx]._client_machine_event; } } if ( _op[idx]._mode == MODE_TMACHINE ) { state_t machine_state = _op[idx]._client_tmachine->state(); switch ( _op[idx]._relop ) { case '=' : return machine_state == _op[idx]._client_tmachine_event; case '!' : return machine_state != _op[idx]._client_tmachine_event; case '<' : return machine_state < _op[idx]._client_tmachine_event; case '>' : return machine_state > _op[idx]._client_tmachine_event; case '-' : return machine_state <= _op[idx]._client_tmachine_event; case '+' : return machine_state >= _op[idx]._client_tmachine_event; } } return false; } bool Atm_condition::eval() { bool r = eval_one( 0 ); for ( uint8_t i = 1; i < ATM_CONDITION_OP_MAX; i++ ) { if ( _op[i]._mode ) { switch ( _op[i]._logop ) { case '&' : r = r && eval_one( i ); break; case '|' : r = r || eval_one( i ); break; } } } return r; } int Atm_condition::event( int id ) { switch (id ) { case EVT_ON : return eval(); case EVT_OFF : return !eval(); } return 0; } void Atm_condition::comm( Atm_Condition_Comm & c, state_t st ) { switch ( c._mode ) { case MODE_CALLBACK : (*c._callback)( st ); return; case MODE_MACHINE : c._client_machine->trigger( c._client_machine_event ); return; case MODE_TMACHINE : c._client_tmachine->trigger( c._client_tmachine_event ); return; case MODE_FACTORY: factory->trigger( c._client_label, c._client_label_event ); return; } } void Atm_condition::action( int id ) { switch ( id ) { case ACT_OFF : comm( _comm[ _last_state == current ? 3 : 1 ], current ); _last_state = current; return; case ACT_ON : if ( _last_state != -1 ) comm( _comm[ _last_state == current ? 2 : 0 ], current ); _last_state = current; return; } } Atm_condition & Atm_condition::trace( Stream & stream ) { Machine::setTrace( &stream, atm_serial_debug::trace, "EVT_ON\0EVT_OFF\0EVT_TOGGLE\0EVT_INPUT\0ELSE\0OFF\0ON" ); return *this; } <commit_msg>Removed comment<commit_after>#include "Atm_condition.hpp" Atm_condition & Atm_condition::begin( bool default_state /* = false */ ) { const static state_t state_table[] PROGMEM = { /* ON_ENTER ON_LOOP ON_EXIT EVT_ON EVT_OFF EVT_TOGGLE EVT_INPUT ELSE */ /* OFF */ ACT_OFF, -1, -1, ON, -1, ON, OFF, -1, /* ON */ ACT_ON, -1, -1, -1, OFF, OFF, ON, -1, }; Machine::begin( state_table, ELSE ); _last_state = -1; state( default_state ? ON : OFF ); // cycle(); Causes the condition to become true momentarily return *this; } Atm_condition & Atm_condition::onFlip( bool st, stepcb_t callback ) { short idx = st ? 0 : 1; _comm[idx]._mode = MODE_CALLBACK; _comm[idx]._callback = callback; return *this; } Atm_condition & Atm_condition::onFlip( bool st, Machine & machine, state_t event /* = 0 */ ) { short idx = st ? 0 : 1; _comm[idx]._mode = MODE_MACHINE; _comm[idx]._client_machine = &machine; _comm[idx]._client_machine_event = event; return *this; } Atm_condition & Atm_condition::onFlip( bool st, const char * label, state_t event /* = 0 */ ) { short idx = st ? 0 : 1; _comm[idx]._mode = MODE_FACTORY; _comm[idx]._client_label = label; _comm[idx]._client_label_event = event; return *this; } Atm_condition & Atm_condition::onFlip( bool st, TinyMachine & machine, state_t event /* = 0 */ ) { short idx = st ? 0 : 1; _comm[idx]._mode = MODE_TMACHINE; _comm[idx]._client_tmachine = &machine; _comm[idx]._client_tmachine_event = event; return *this; } Atm_condition & Atm_condition::onInput( bool st, stepcb_t callback ) { short idx = st ? 2 : 3; _comm[idx]._mode = MODE_CALLBACK; _comm[idx]._callback = callback; return *this; } Atm_condition & Atm_condition::onInput( bool st, Machine & machine, state_t event /* = 0 */ ) { short idx = st ? 2 : 3; _comm[idx]._mode = MODE_MACHINE; _comm[idx]._client_machine = &machine; _comm[idx]._client_machine_event = event; return *this; } Atm_condition & Atm_condition::onInput( bool st, const char * label, state_t event /* = 0 */ ) { short idx = st ? 2 : 3; _comm[idx]._mode = MODE_FACTORY; _comm[idx]._client_label = label; _comm[idx]._client_label_event = event; return *this; } Atm_condition & Atm_condition::onInput( bool st, TinyMachine & machine, state_t event /* = 0 */ ) { short idx = st ? 2 : 3; _comm[idx]._mode = MODE_TMACHINE; _comm[idx]._client_tmachine = &machine; _comm[idx]._client_tmachine_event = event; return *this; } Atm_condition & Atm_condition::IF( Machine & machine, char relOp /* = '>' */, state_t match /* = 0 */ ) { return OP( '?', machine, relOp, match ); } Atm_condition & Atm_condition::IF( TinyMachine & machine, char relOp /* = '>' */, state_t match /* = 0 */ ) { return OP( '?', machine, relOp, match ); } Atm_condition & Atm_condition::AND( Machine & machine, char relOp /* = '>' */, state_t match /* = 0 */ ) { return OP( '&', machine, relOp, match ); } Atm_condition & Atm_condition::AND( TinyMachine & machine, char relOp /* = '>' */, state_t match /* = 0 */ ) { return OP( '&', machine, relOp, match ); } Atm_condition & Atm_condition::OR( Machine & machine, char relOp /* = '>' */, state_t match /* = 0 */ ) { return OP( '|', machine, relOp, match ); } Atm_condition & Atm_condition::OR( TinyMachine & machine, char relOp /* = '>' */, state_t match /* = 0 */ ) { return OP( '|', machine, relOp, match ); } Atm_condition & Atm_condition::OP( char logOp, Machine & machine, char relOp = '>', state_t match = 0 ) { for ( uint8_t i = 0; i < ATM_CONDITION_OP_MAX; i++ ) { if ( _op[i]._mode == MODE_NULL ) { // Pick the first free slot _op[i]._mode = MODE_MACHINE; _op[i]._logop = logOp; _op[i]._relop = relOp; _op[i]._client_machine = &machine; _op[i]._client_machine_event = match; break; } } return *this; } Atm_condition & Atm_condition::OP( char logOp, TinyMachine & machine, char relOp, state_t match ) { for ( uint8_t i = 0; i < ATM_CONDITION_OP_MAX; i++ ) { if ( _op[i]._mode == MODE_NULL ) { // Pick the first free slot _op[i]._mode = MODE_TMACHINE; _op[i]._logop = logOp; _op[i]._relop = relOp; _op[i]._client_tmachine = &machine; _op[i]._client_tmachine_event = match; break; } } return *this; } bool Atm_condition::eval_one( uint8_t idx ) { if ( _op[idx]._mode == MODE_MACHINE ) { state_t machine_state = _op[idx]._client_machine->state(); switch ( _op[idx]._relop ) { case '=' : return machine_state == _op[idx]._client_machine_event; case '!' : return machine_state != _op[idx]._client_machine_event; case '<' : return machine_state < _op[idx]._client_machine_event; case '>' : return machine_state > _op[idx]._client_machine_event; case '-' : return machine_state <= _op[idx]._client_machine_event; case '+' : return machine_state >= _op[idx]._client_machine_event; } } if ( _op[idx]._mode == MODE_TMACHINE ) { state_t machine_state = _op[idx]._client_tmachine->state(); switch ( _op[idx]._relop ) { case '=' : return machine_state == _op[idx]._client_tmachine_event; case '!' : return machine_state != _op[idx]._client_tmachine_event; case '<' : return machine_state < _op[idx]._client_tmachine_event; case '>' : return machine_state > _op[idx]._client_tmachine_event; case '-' : return machine_state <= _op[idx]._client_tmachine_event; case '+' : return machine_state >= _op[idx]._client_tmachine_event; } } return false; } bool Atm_condition::eval() { bool r = eval_one( 0 ); for ( uint8_t i = 1; i < ATM_CONDITION_OP_MAX; i++ ) { if ( _op[i]._mode ) { switch ( _op[i]._logop ) { case '&' : r = r && eval_one( i ); break; case '|' : r = r || eval_one( i ); break; } } } return r; } int Atm_condition::event( int id ) { switch (id ) { case EVT_ON : return eval(); case EVT_OFF : return !eval(); } return 0; } void Atm_condition::comm( Atm_Condition_Comm & c, state_t st ) { switch ( c._mode ) { case MODE_CALLBACK : (*c._callback)( st ); return; case MODE_MACHINE : c._client_machine->trigger( c._client_machine_event ); return; case MODE_TMACHINE : c._client_tmachine->trigger( c._client_tmachine_event ); return; case MODE_FACTORY: factory->trigger( c._client_label, c._client_label_event ); return; } } void Atm_condition::action( int id ) { switch ( id ) { case ACT_OFF : comm( _comm[ _last_state == current ? 3 : 1 ], current ); _last_state = current; return; case ACT_ON : if ( _last_state != -1 ) comm( _comm[ _last_state == current ? 2 : 0 ], current ); _last_state = current; return; } } Atm_condition & Atm_condition::trace( Stream & stream ) { Machine::setTrace( &stream, atm_serial_debug::trace, "EVT_ON\0EVT_OFF\0EVT_TOGGLE\0EVT_INPUT\0ELSE\0OFF\0ON" ); return *this; } <|endoftext|>
<commit_before>#include "xchainer/numerical_gradient.h" #include <algorithm> #include <functional> #include <vector> #ifdef XCHAINER_ENABLE_CUDA #include <cuda_runtime.h> #endif // XCHAINER_ENABLE_CUDA #include "xchainer/array.h" #include "xchainer/array_repr.h" #include "xchainer/error.h" #include "xchainer/indexable_array.h" #include "xchainer/indexer.h" #ifdef XCHAINER_ENABLE_CUDA #include "xchainer/cuda/cuda_runtime.h" #endif // XCHAINER_ENABLE_CUDA #include "xchainer/device.h" namespace xchainer { namespace numerical_gradient_internal { // TODO(niboshi): These temporary implementation for primitive operations depend on that the data in arrays can be accessed directly // (e.g. with unified memory). In order for numerical gradient calculation to work corretly on general devices, They should be replaced with // full-featured operations. Array& Subtract(const Array& lhs, const Array& rhs, Array& out) { lhs.device().Synchronize(); rhs.device().Synchronize(); out.device().Synchronize(); VisitDtype(lhs.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; IndexableArray<const T> lhs_iarray{lhs}; IndexableArray<const T> rhs_iarray{rhs}; IndexableArray<T> out_iarray{out}; Indexer indexer{out.shape()}; for (int64_t i = 0; i < indexer.total_size(); ++i) { indexer.Set(i); out_iarray[indexer] = lhs_iarray[indexer] - rhs_iarray[indexer]; } }); return out; } Array& Divide(const Array& lhs, const Array& rhs, Array& out) { lhs.device().Synchronize(); rhs.device().Synchronize(); out.device().Synchronize(); VisitDtype(lhs.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; IndexableArray<const T> lhs_iarray{lhs}; IndexableArray<const T> rhs_iarray{rhs}; IndexableArray<T> out_iarray{out}; Indexer indexer{out.shape()}; for (int64_t i = 0; i < indexer.total_size(); ++i) { indexer.Set(i); out_iarray[indexer] = lhs_iarray[indexer] / rhs_iarray[indexer]; } }); return out; } Array operator/(const Array& lhs, const Array& rhs) { Array out = Array::EmptyLike(lhs); Divide(lhs, rhs, out); return out; } // TODO(niboshi): Replace this with xchainer::Sum() Scalar Sum(const Array& array) { array.device().Synchronize(); return VisitDtype(array.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; IndexableArray<const T> iarray{array}; Indexer indexer{array.shape()}; T s = 0; for (int64_t i = 0; i < indexer.total_size(); ++i) { indexer.Set(i); s += iarray[indexer]; } return Scalar{s}; }); } Scalar Norm(const Array& x) { Scalar s = Sum(x * x); return Scalar(std::sqrt(static_cast<double>(s)), x.dtype()); } Scalar VectorDot(const Array& x, const Array& y) { return Sum(x * y); } void Set(Array& out, int64_t flat_index, Scalar value) { out.device().Synchronize(); VisitDtype(out.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; IndexableArray<T> iarray{out}; Indexer indexer{out.shape()}; indexer.Set(flat_index); iarray[indexer] = static_cast<T>(value); }); } Scalar Get(const Array& out, int64_t flat_index) { out.device().Synchronize(); return VisitDtype(out.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; IndexableArray<const T> iarray{out}; Indexer indexer{out.shape()}; indexer.Set(flat_index); return Scalar{iarray[indexer]}; }); } Arrays CalculateNumericalGradient( std::function<Arrays(const Arrays&)> func, const Arrays& inputs, const Arrays& grad_outputs, const Arrays& eps, const GraphId& graph_id) { // TODO(niboshi): Currently only elementwise functions are supported. // TODO(niboshi): Implement arithmetic operations and avoid manual synchronize const int nin = inputs.size(); const int nout = grad_outputs.size(); if (eps.size() != static_cast<size_t>(nin)) { throw XchainerError( "Invalid number of eps arrays where number of inputs: " + std::to_string(nin) + ", eps: " + std::to_string(eps.size())); } for (int i = 0; i < nin; ++i) { if (inputs.at(i).shape() != eps.at(i).shape()) { throw XchainerError("Invalid eps shape"); } if (inputs.at(i).dtype() != eps.at(i).dtype()) { throw XchainerError("Invalid eps dtype"); } // TODO(niboshi): Check: eps must not contain zeros. } Dtype dtype = inputs[0].dtype(); auto eval = [&, graph_id](int i_in, int64_t in_flat_index, Scalar eps_scalar, float multiplier) -> Arrays { Arrays xs; std::transform(inputs.begin(), inputs.end(), std::back_inserter(xs), [graph_id](const Array& x) { return x.AsConstant(CopyKind::kCopy).RequireGrad(graph_id); }); Set(xs.at(i_in), in_flat_index, Get(xs.at(i_in), in_flat_index) + Scalar(static_cast<float>(eps_scalar) * multiplier, dtype)); return func(xs); }; Arrays grads; for (int i = 0; i < nin; ++i) { Array grad_i = Array::ZerosLike(inputs.at(i)); int64_t size = grad_i.GetTotalSize(); for (int64_t in_flat_index = 0; in_flat_index < size; ++in_flat_index) { Scalar eps_scalar = Get(eps.at(i), in_flat_index); Arrays ys0 = eval(i, in_flat_index, eps_scalar, -1); Arrays ys1 = eval(i, in_flat_index, eps_scalar, 1); for (int j = 0; j < nout; ++j) { Array dy = ys1.at(j) - ys0.at(j); Array denom = Array::FullLike(dy, eps_scalar) * Array::FullLike(dy, Scalar(2, dtype)); Scalar g = VectorDot((ys1.at(j) - ys0.at(j)) / denom, grad_outputs.at(j)); Scalar g_ij = Get(grad_i, in_flat_index) + g; Set(grad_i, in_flat_index, g_ij); } } grads.push_back(grad_i); } return grads; } } // namespace numerical_gradient_internal } // namespace xchainer <commit_msg>Fix rebase error<commit_after>#include "xchainer/numerical_gradient.h" #include <algorithm> #include <functional> #include <vector> #ifdef XCHAINER_ENABLE_CUDA #include <cuda_runtime.h> #endif // XCHAINER_ENABLE_CUDA #include "xchainer/array.h" #include "xchainer/array_repr.h" #include "xchainer/error.h" #include "xchainer/indexable_array.h" #include "xchainer/indexer.h" #ifdef XCHAINER_ENABLE_CUDA #include "xchainer/cuda/cuda_runtime.h" #endif // XCHAINER_ENABLE_CUDA #include "xchainer/device.h" namespace xchainer { namespace numerical_gradient_internal { // TODO(niboshi): These temporary implementation for primitive operations depend on that the data in arrays can be accessed directly // (e.g. with unified memory). In order for numerical gradient calculation to work corretly on general devices, They should be replaced with // full-featured operations. Array& Divide(const Array& lhs, const Array& rhs, Array& out) { lhs.device().Synchronize(); rhs.device().Synchronize(); out.device().Synchronize(); VisitDtype(lhs.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; IndexableArray<const T> lhs_iarray{lhs}; IndexableArray<const T> rhs_iarray{rhs}; IndexableArray<T> out_iarray{out}; Indexer indexer{out.shape()}; for (int64_t i = 0; i < indexer.total_size(); ++i) { indexer.Set(i); out_iarray[indexer] = lhs_iarray[indexer] / rhs_iarray[indexer]; } }); return out; } Array operator/(const Array& lhs, const Array& rhs) { Array out = Array::EmptyLike(lhs); Divide(lhs, rhs, out); return out; } // TODO(niboshi): Replace this with xchainer::Sum() Scalar Sum(const Array& array) { array.device().Synchronize(); return VisitDtype(array.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; IndexableArray<const T> iarray{array}; Indexer indexer{array.shape()}; T s = 0; for (int64_t i = 0; i < indexer.total_size(); ++i) { indexer.Set(i); s += iarray[indexer]; } return Scalar{s}; }); } Scalar Norm(const Array& x) { Scalar s = Sum(x * x); return Scalar(std::sqrt(static_cast<double>(s)), x.dtype()); } Scalar VectorDot(const Array& x, const Array& y) { return Sum(x * y); } void Set(Array& out, int64_t flat_index, Scalar value) { out.device().Synchronize(); VisitDtype(out.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; IndexableArray<T> iarray{out}; Indexer indexer{out.shape()}; indexer.Set(flat_index); iarray[indexer] = static_cast<T>(value); }); } Scalar Get(const Array& out, int64_t flat_index) { out.device().Synchronize(); return VisitDtype(out.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; IndexableArray<const T> iarray{out}; Indexer indexer{out.shape()}; indexer.Set(flat_index); return Scalar{iarray[indexer]}; }); } Arrays CalculateNumericalGradient( std::function<Arrays(const Arrays&)> func, const Arrays& inputs, const Arrays& grad_outputs, const Arrays& eps, const GraphId& graph_id) { // TODO(niboshi): Currently only elementwise functions are supported. // TODO(niboshi): Implement arithmetic operations and avoid manual synchronize const int nin = inputs.size(); const int nout = grad_outputs.size(); if (eps.size() != static_cast<size_t>(nin)) { throw XchainerError( "Invalid number of eps arrays where number of inputs: " + std::to_string(nin) + ", eps: " + std::to_string(eps.size())); } for (int i = 0; i < nin; ++i) { if (inputs.at(i).shape() != eps.at(i).shape()) { throw XchainerError("Invalid eps shape"); } if (inputs.at(i).dtype() != eps.at(i).dtype()) { throw XchainerError("Invalid eps dtype"); } // TODO(niboshi): Check: eps must not contain zeros. } Dtype dtype = inputs[0].dtype(); auto eval = [&, graph_id](int i_in, int64_t in_flat_index, Scalar eps_scalar, float multiplier) -> Arrays { Arrays xs; std::transform(inputs.begin(), inputs.end(), std::back_inserter(xs), [graph_id](const Array& x) { return x.AsConstant(CopyKind::kCopy).RequireGrad(graph_id); }); Set(xs.at(i_in), in_flat_index, Get(xs.at(i_in), in_flat_index) + Scalar(static_cast<float>(eps_scalar) * multiplier, dtype)); return func(xs); }; Arrays grads; for (int i = 0; i < nin; ++i) { Array grad_i = Array::ZerosLike(inputs.at(i)); int64_t size = grad_i.GetTotalSize(); for (int64_t in_flat_index = 0; in_flat_index < size; ++in_flat_index) { Scalar eps_scalar = Get(eps.at(i), in_flat_index); Arrays ys0 = eval(i, in_flat_index, eps_scalar, -1); Arrays ys1 = eval(i, in_flat_index, eps_scalar, 1); for (int j = 0; j < nout; ++j) { Array dy = ys1.at(j) - ys0.at(j); Array denom = Array::FullLike(dy, eps_scalar) * Array::FullLike(dy, Scalar(2, dtype)); Scalar g = VectorDot((ys1.at(j) - ys0.at(j)) / denom, grad_outputs.at(j)); Scalar g_ij = Get(grad_i, in_flat_index) + g; Set(grad_i, in_flat_index, g_ij); } } grads.push_back(grad_i); } return grads; } } // namespace numerical_gradient_internal } // namespace xchainer <|endoftext|>
<commit_before>/* * * kPPP: A pppd front end for the KDE project * * $Id$ * * (c) 1998 Mario Weilguni <mweilguni@kde.org> * * Copyright (C) 1997 Bernd Johannes Wuebben * wuebben@math.cornell.edu * * based on EzPPP: * Copyright (C) 1997 Jay Painter * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library 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 <qlabel.h> #include <qdir.h> #include <qpushbutton.h> //Added by qt3to4: #include <QVBoxLayout> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <unistd.h> #include <sys/stat.h> #include <qdialog.h> #include <qregexp.h> #include <q3multilineedit.h> #include <qlayout.h> #include <kbuttonbox.h> #include <kmessagebox.h> #include "pppdata.h" #include "requester.h" #include <klocale.h> int PPPL_MakeLog(QStringList &list) { int pid = -1, newpid; char buffer[1024], *p; const char *pidp; int fd; fd = Requester::rq->openSysLog(); if(fd < 0) { list.append(i18n("Cannot open any of the following logfiles:")); const char * const * logFile = &kppp_syslog[0]; while(*logFile) { list.append(*logFile); logFile++; } return 1; } FILE *f = fdopen(fd, "r"); while(fgets(buffer, sizeof(buffer), f) != 0) { // pppd line ? p = (char *)strstr(buffer, "pppd["); if(p == 0) continue; pidp = p += strlen("pppd["); while(*p && isdigit(*p)) p++; if(*p != ']') continue; /* find out pid of pppd */ sscanf(pidp, "%d", &newpid); if(newpid != pid) { pid = newpid; list.clear(); } if(buffer[strlen(buffer)-1] == '\n') buffer[strlen(buffer)-1] = '\0'; list.append(buffer); } fclose(f); if(list.isEmpty()) return 2; /* clear security related info */ const char *keyword[] = {"name = \"", "user=\"", "password=\"", 0}; for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it ) { QByteArray tmp = (*it).toLocal8Bit(); for(int j = 0; keyword[j] != 0; j++) { char *p; if( (p = (char *)strstr(tmp.data(), keyword[j])) != 0) { p += strlen(keyword[j]); while(*p && *p != '"') *p++ = 'X'; } } } return 0; } void PPPL_AnalyseLog(QStringList &list, QStringList &result) { QString msg; const char *rmsg = "Remote message: "; result.clear(); // setup the analysis database struct { const char *regexp; const char *answer; } hints[] = { {"Receive serial link is not 8-bit clean", I18N_NOOP("You have launched pppd before the remote server " \ "was ready to establish a PPP connection.\n" "Please use the terminal-based login to verify") }, {"Serial line is looped back", I18N_NOOP("You have not started the PPP software on the peer system.") }, {"AP authentication failed", I18N_NOOP("Check that you supplied the correct username and password.")} , {"is locked by pid", I18N_NOOP("You should not pass 'lock' as an argument to pppd. " "Check /etc/ppp/options and ~/.ppprc") }, {"CP: timeout sending", I18N_NOOP("The remote system does not seem to answer to\n" "configuration request. Contact your provider.") }, {"unrecognized option", I18N_NOOP("You have passed an invalid option to pppd. See 'man pppd' " "for a complete list of valid arguments.") }, // terminator {0,0} }; // scan the log for keywords and try to offer any help for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it ) { // look for remote message int pos = (*it).indexOf(rmsg); if (pos != -1) { QString str = (*it); str.remove(0, pos + strlen(rmsg)); if(!str.isEmpty()) { msg = i18n("Notice that the remote system has sent the following" " message:\n\"%1\"\nThis may give you a hint why the" " the connection has failed.", str); result.append(msg); } } // check in the hint database for(uint k = 0; hints[k].regexp != 0; k++) { QRegExp rx(hints[k].regexp); QString l(*it); if(l.contains(rx)) { result.append(i18n(hints[k].answer)); break; } } } if (result.isEmpty()) result.append(i18n("Unable to provide help.")); } void PPPL_ShowLog() { QStringList sl, result; PPPL_MakeLog(sl); bool foundConnect = false; bool foundLCP = gpppdata.getPPPDebug(); QString lcp = QLatin1String("[LCP"); QString conn = QLatin1String("Connect:"); QStringList::ConstIterator it = sl.begin(); for( ; it != sl.end(); it++) { if((*it).indexOf(lcp) >= 0) { foundLCP = true; break; } if((*it).contains(conn)) foundConnect = true; } if(foundConnect && !foundLCP) { int result = KMessageBox::warningYesNo(0, i18n("KPPP could not prepare a PPP log. It is very likely " "that pppd was started without the \"debug\" option.\n" "Without this option it's difficult to find out PPP " "problems, so you should turn on the debug option.\n" "Shall I turn it on now?"), QString::null, i18n("Restart pppd"), i18n("Do Not Restart")); if(result == KMessageBox::Yes) { gpppdata.setPPPDebug(TRUE); KMessageBox::information(0, i18n("The \"debug\" option has been added. You " "should now try to reconnect. If that fails " "again, you will get a PPP log that may help " "you to track down the connection problem.")); // return; } // return; } PPPL_AnalyseLog(sl, result); QDialog *dlg = new QDialog(0, "", TRUE); dlg->setWindowTitle(i18n("PPP Log")); QVBoxLayout *tl = new QVBoxLayout(dlg); tl->setSpacing(10); tl->setMargin(10); Q3MultiLineEdit *edit = new Q3MultiLineEdit(dlg); edit->setReadOnly(TRUE); QLabel *label = new QLabel(i18n("kppp's diagnosis (just guessing):"), dlg); Q3MultiLineEdit *diagnosis = new Q3MultiLineEdit(dlg); diagnosis->setReadOnly(TRUE); KButtonBox *bbox = new KButtonBox(dlg); bbox->addStretch(1); QPushButton *write = bbox->addButton(i18n("Write to File")); QPushButton *close = bbox->addButton(KStdGuiItem::close()); bbox->layout(); edit->setMinimumSize(600, 250); label->setMinimumSize(600, 15); diagnosis->setMinimumSize(600, 60); tl->addWidget(edit, 1); tl->addWidget(label); tl->addWidget(diagnosis, 1); tl->addWidget(bbox); dlg->setFixedSize(dlg->sizeHint()); for(int i = 0; i < sl.count(); i++) edit->append(sl.at(i)); for(int i = 0; i < result.count(); i++) diagnosis->append(result.at(i)); dlg->connect(close, SIGNAL(clicked()), dlg, SLOT(reject())); dlg->connect(write, SIGNAL(clicked()), dlg, SLOT(accept())); if(dlg->exec()) { QDir d = QDir::home(); QString s = d.absolutePath() + "/PPP-logfile"; int old_umask = umask(0077); FILE *f = fopen(QFile::encodeName(s), "w"); for(int i = 0; i < sl.count(); i++) fprintf(f, "%s\n", sl.at(i).toLocal8Bit().data()); fclose(f); umask(old_umask); QString msg = i18n("The PPP log has been saved\nas \"%1\".\n\nIf you want to send a bug report, or have\nproblems connecting to the Internet, please\nattach this file. It will help the maintainers\nto find the bug and to improve KPPP", s); KMessageBox::information(0, msg); } delete dlg; } <commit_msg>Deprecated--<commit_after>/* * * kPPP: A pppd front end for the KDE project * * $Id$ * * (c) 1998 Mario Weilguni <mweilguni@kde.org> * * Copyright (C) 1997 Bernd Johannes Wuebben * wuebben@math.cornell.edu * * based on EzPPP: * Copyright (C) 1997 Jay Painter * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library 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 <qlabel.h> #include <qdir.h> #include <qpushbutton.h> //Added by qt3to4: #include <QVBoxLayout> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <unistd.h> #include <sys/stat.h> #include <qdialog.h> #include <qregexp.h> #include <QTextEdit> #include <qlayout.h> #include <kbuttonbox.h> #include <kmessagebox.h> #include "pppdata.h" #include "requester.h" #include <klocale.h> int PPPL_MakeLog(QStringList &list) { int pid = -1, newpid; char buffer[1024], *p; const char *pidp; int fd; fd = Requester::rq->openSysLog(); if(fd < 0) { list.append(i18n("Cannot open any of the following logfiles:")); const char * const * logFile = &kppp_syslog[0]; while(*logFile) { list.append(*logFile); logFile++; } return 1; } FILE *f = fdopen(fd, "r"); while(fgets(buffer, sizeof(buffer), f) != 0) { // pppd line ? p = (char *)strstr(buffer, "pppd["); if(p == 0) continue; pidp = p += strlen("pppd["); while(*p && isdigit(*p)) p++; if(*p != ']') continue; /* find out pid of pppd */ sscanf(pidp, "%d", &newpid); if(newpid != pid) { pid = newpid; list.clear(); } if(buffer[strlen(buffer)-1] == '\n') buffer[strlen(buffer)-1] = '\0'; list.append(buffer); } fclose(f); if(list.isEmpty()) return 2; /* clear security related info */ const char *keyword[] = {"name = \"", "user=\"", "password=\"", 0}; for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it ) { QByteArray tmp = (*it).toLocal8Bit(); for(int j = 0; keyword[j] != 0; j++) { char *p; if( (p = (char *)strstr(tmp.data(), keyword[j])) != 0) { p += strlen(keyword[j]); while(*p && *p != '"') *p++ = 'X'; } } } return 0; } void PPPL_AnalyseLog(QStringList &list, QStringList &result) { QString msg; const char *rmsg = "Remote message: "; result.clear(); // setup the analysis database struct { const char *regexp; const char *answer; } hints[] = { {"Receive serial link is not 8-bit clean", I18N_NOOP("You have launched pppd before the remote server " \ "was ready to establish a PPP connection.\n" "Please use the terminal-based login to verify") }, {"Serial line is looped back", I18N_NOOP("You have not started the PPP software on the peer system.") }, {"AP authentication failed", I18N_NOOP("Check that you supplied the correct username and password.")} , {"is locked by pid", I18N_NOOP("You should not pass 'lock' as an argument to pppd. " "Check /etc/ppp/options and ~/.ppprc") }, {"CP: timeout sending", I18N_NOOP("The remote system does not seem to answer to\n" "configuration request. Contact your provider.") }, {"unrecognized option", I18N_NOOP("You have passed an invalid option to pppd. See 'man pppd' " "for a complete list of valid arguments.") }, // terminator {0,0} }; // scan the log for keywords and try to offer any help for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it ) { // look for remote message int pos = (*it).indexOf(rmsg); if (pos != -1) { QString str = (*it); str.remove(0, pos + strlen(rmsg)); if(!str.isEmpty()) { msg = i18n("Notice that the remote system has sent the following" " message:\n\"%1\"\nThis may give you a hint why the" " the connection has failed.", str); result.append(msg); } } // check in the hint database for(uint k = 0; hints[k].regexp != 0; k++) { QRegExp rx(hints[k].regexp); QString l(*it); if(l.contains(rx)) { result.append(i18n(hints[k].answer)); break; } } } if (result.isEmpty()) result.append(i18n("Unable to provide help.")); } void PPPL_ShowLog() { QStringList sl, result; PPPL_MakeLog(sl); bool foundConnect = false; bool foundLCP = gpppdata.getPPPDebug(); QString lcp = QLatin1String("[LCP"); QString conn = QLatin1String("Connect:"); QStringList::ConstIterator it = sl.begin(); for( ; it != sl.end(); it++) { if((*it).indexOf(lcp) >= 0) { foundLCP = true; break; } if((*it).contains(conn)) foundConnect = true; } if(foundConnect && !foundLCP) { int result = KMessageBox::warningYesNo(0, i18n("KPPP could not prepare a PPP log. It is very likely " "that pppd was started without the \"debug\" option.\n" "Without this option it's difficult to find out PPP " "problems, so you should turn on the debug option.\n" "Shall I turn it on now?"), QString::null, i18n("Restart pppd"), i18n("Do Not Restart")); if(result == KMessageBox::Yes) { gpppdata.setPPPDebug(TRUE); KMessageBox::information(0, i18n("The \"debug\" option has been added. You " "should now try to reconnect. If that fails " "again, you will get a PPP log that may help " "you to track down the connection problem.")); // return; } // return; } PPPL_AnalyseLog(sl, result); QDialog *dlg = new QDialog(0, "", TRUE); dlg->setWindowTitle(i18n("PPP Log")); QVBoxLayout *tl = new QVBoxLayout(dlg); tl->setSpacing(10); tl->setMargin(10); QTextEdit *edit = new QTextEdit(dlg); edit->setReadOnly(TRUE); QLabel *label = new QLabel(i18n("kppp's diagnosis (just guessing):"), dlg); QTextEdit *diagnosis = new QTextEdit(dlg); diagnosis->setReadOnly(TRUE); KButtonBox *bbox = new KButtonBox(dlg); bbox->addStretch(1); QPushButton *write = bbox->addButton(i18n("Write to File")); QPushButton *close = bbox->addButton(KStdGuiItem::close()); bbox->layout(); edit->setMinimumSize(600, 250); label->setMinimumSize(600, 15); diagnosis->setMinimumSize(600, 60); tl->addWidget(edit, 1); tl->addWidget(label); tl->addWidget(diagnosis, 1); tl->addWidget(bbox); dlg->setFixedSize(dlg->sizeHint()); for(int i = 0; i < sl.count(); i++) edit->append(sl.at(i)); for(int i = 0; i < result.count(); i++) diagnosis->append(result.at(i)); dlg->connect(close, SIGNAL(clicked()), dlg, SLOT(reject())); dlg->connect(write, SIGNAL(clicked()), dlg, SLOT(accept())); if(dlg->exec()) { QDir d = QDir::home(); QString s = d.absolutePath() + "/PPP-logfile"; int old_umask = umask(0077); FILE *f = fopen(QFile::encodeName(s), "w"); for(int i = 0; i < sl.count(); i++) fprintf(f, "%s\n", sl.at(i).toLocal8Bit().data()); fclose(f); umask(old_umask); QString msg = i18n("The PPP log has been saved\nas \"%1\".\n\nIf you want to send a bug report, or have\nproblems connecting to the Internet, please\nattach this file. It will help the maintainers\nto find the bug and to improve KPPP", s); KMessageBox::information(0, msg); } delete dlg; } <|endoftext|>
<commit_before>// // Set.h // Set // // Created by Antonio Seprano on 10/08/14. // Copyright (c) 2014 Antonio Seprano. All rights reserved. // #include <vector> #include <functional> #include <utility> #include <algorithm> #ifndef _SET_HPP #define _SET_HPP template<class _T, class _Allocator = std::allocator<_T> > class Set { public: typedef _T value_type; typedef _Allocator allocator_type; private: typedef Set<value_type,allocator_type> _SET; public: typedef typename std::vector<value_type,allocator_type>::iterator iterator; typedef typename std::vector<value_type,allocator_type>::const_iterator const_iterator; // Empty set Set() {}; // Set with initializer list Set(std::initializer_list<value_type> l) { _set.insert(_set.begin(), l); } // Copy constructor Set(const _SET& s) { _set = s._set; } // Move constructor Set(_SET&& s) { _set = std::move(s._set); } // Copy assignment _SET& operator=(const _SET& s) noexcept { _set = s._set; return *this; } // Move assignment _SET& operator=(_SET&& s) noexcept { _set = std::move(s._set); return *this; } iterator begin() noexcept { return _set.begin(); } const_iterator begin() const noexcept { return _set.begin(); } iterator end() noexcept { return _set.end(); }; const_iterator end() const noexcept { return _set.end(); } size_t size() const noexcept { return _set.size(); } bool empty() const noexcept { return _set.empty(); } void clear() noexcept { _set.clear(); } iterator find(const value_type& value) noexcept { for (auto it = _set.begin(); it != _set.end(); it++) { if (*it == value) return it; } return _set.end(); } const_iterator find(const value_type& value) const noexcept { return (const_iterator)find(value); } size_t count(const value_type& value) const noexcept { size_t ret{}; for (const auto& v : _set) { if (v == value) { ret++; } } return ret; } bool operator==(const _SET& s) const noexcept { return this->contains(s, false) && s.contains(*this, false); } bool operator!=(const _SET& s) const noexcept { return !(*this == s); }; /* bool operator<(const _SET& s) const noexcept { if (size() != s.size()) { return size() < s.size(); } auto it1=begin(), it2=s.begin(); while (it1 != end() && it2 != s.end()) { if (*it1 < *it2) { return true; } else if (*it1 > *it2) { return false; } it1++; it2++; }; return false; } */ // Insert new value // unique = true => values must be unique (no duplicate values allowed) void insert(const value_type& value, bool unique = false) noexcept { if (!unique || find(value) == _set.end()) { _set.push_back(value); } } void insert(value_type&& value, bool unique = false) noexcept { if (!unique || find(value) == _set.end()) { _set.push_back(std::move(value)); } } _SET operator+(const value_type& value) const noexcept { return _SET{*this}+_SET{value}; } _SET operator+(value_type&& value) const noexcept { return _SET{*this}+_SET{std::move(value)}; } _SET operator+(const _SET& s) const noexcept { _SET ret{*this}; for (const auto& value : s) { ret.insert(value); } return ret; } _SET operator+(_SET&& s) const noexcept { _SET ret{*this}; for (auto& value : s) { ret.insert(std::move(value)); } return ret; } _SET& operator+=(const value_type& value) noexcept { insert(value); return *this; } _SET& operator+=(value_type&& value) noexcept { insert(std::move(value)); return *this; } _SET& operator+=(const _SET& s) noexcept { for (const auto& value : s) { insert(value); } return *this; } _SET& operator+=(_SET&& s) noexcept { for (auto& value : s) { insert(std::move(value)); } return *this; } _SET operator-(const value_type& value) const noexcept { _SET ret{*this}; ret.erase(value); return ret; } _SET operator-(const _SET& s) const noexcept { _SET ret{*this}; for (const auto& v : s) { ret.erase(v); } return ret; } _SET& operator-=(const value_type& value) noexcept { _set.erase(value); return *this; } _SET& operator-=(const _SET& s) noexcept { for (const auto& value : s) { _set.erase(value); } return *this; } Set<_SET> operator*(const _SET& other) noexcept { Set<_SET> ret; if (!this->empty() && !other.empty()) { for (const auto& v1 : _set) { for (const auto& v2 : other) { ret.insert(_SET{v1,v2}); } } } return ret; } _SET intersection(const _SET& s) noexcept { _SET s1, s2; if (s.size() <= size()) { s1 = s; s2 = *this; } else { s1 = *this; s2 = s; } for (const auto &v : s1) { if (!s2.contains(v)) s1.erase(v); } return s1; } bool contains(const value_type& value) const noexcept { return contains(_SET{value}); } bool contains(const _SET& s, bool strict = false) const noexcept { for (const auto& value : s) { bool found{false}; for (const auto& v : _set) { if (v == value) { found = true; break; } } if (!found) { return false; } } return strict ? (s.size() != size()) : true; } template<class InputIterator> void insert(InputIterator first, InputIterator last) { for (auto it = first; it != last; it++) { _set.insert(*it); } }; iterator erase(const_iterator position) { return _set.erase(position); } iterator erase(const_iterator first, const_iterator last) { return _set.erase(first,last); } size_t erase(const value_type& value, bool all = true) { size_t ret{}; if (!all) { auto it = find(value); if (it != end()) { erase(it); ret++; } return ret; } for (auto it = _set.begin(); it != _set.end(); it++) { if (*it == value) { _set.erase(it); ++ret; } } return ret; } _SET& unique() noexcept { for (auto i = begin(); i != end(); i++) { auto j = i+1; while (j != end()) { if (*i == *j) { _set.erase(j); } else { j++; } } } return *this; } private: std::vector<value_type,allocator_type> _set; }; #endif /* defined(_SET_HPP) */ <commit_msg>[ref] Small refactor on Set remove<commit_after>// // Set.h // Set // // Created by Antonio Seprano on 10/08/14. // Copyright (c) 2014 Antonio Seprano. All rights reserved. // #include <vector> #include <functional> #include <utility> #include <algorithm> #ifndef _SET_HPP #define _SET_HPP template<class _T, class _Allocator = std::allocator<_T> > class Set { public: typedef _T value_type; typedef _Allocator allocator_type; private: typedef Set<value_type,allocator_type> _SET; public: typedef typename std::vector<value_type,allocator_type>::iterator iterator; typedef typename std::vector<value_type,allocator_type>::const_iterator const_iterator; // Empty set Set() {}; // Set with initializer list Set(std::initializer_list<value_type> l) { _set.insert(_set.begin(), l); } // Copy constructor Set(const _SET& s) { _set = s._set; } // Move constructor Set(_SET&& s) { _set = std::move(s._set); } // Copy assignment _SET& operator=(const _SET& s) noexcept { _set = s._set; return *this; } // Move assignment _SET& operator=(_SET&& s) noexcept { _set = std::move(s._set); return *this; } iterator begin() noexcept { return _set.begin(); } const_iterator begin() const noexcept { return _set.begin(); } iterator end() noexcept { return _set.end(); }; const_iterator end() const noexcept { return _set.end(); } size_t size() const noexcept { return _set.size(); } bool empty() const noexcept { return _set.empty(); } void clear() noexcept { _set.clear(); } iterator find(const value_type& value) noexcept { for (auto it = _set.begin(); it != _set.end(); it++) { if (*it == value) return it; } return _set.end(); } const_iterator find(const value_type& value) const noexcept { return (const_iterator)find(value); } size_t count(const value_type& value) const noexcept { size_t ret{}; for (const auto& v : _set) { if (v == value) { ret++; } } return ret; } bool operator==(const _SET& s) const noexcept { return this->contains(s, false) && s.contains(*this, false); } bool operator!=(const _SET& s) const noexcept { return !(*this == s); }; /* bool operator<(const _SET& s) const noexcept { if (size() != s.size()) { return size() < s.size(); } auto it1=begin(), it2=s.begin(); while (it1 != end() && it2 != s.end()) { if (*it1 < *it2) { return true; } else if (*it1 > *it2) { return false; } it1++; it2++; }; return false; } */ // Insert new value // unique = true => values must be unique (no duplicate values allowed) _SET& insert(const value_type& value, bool unique = false) noexcept { if (!unique || find(value) == _set.end()) { _set.push_back(value); } return *this; } _SET& insert(value_type&& value, bool unique = false) noexcept { if (!unique || find(value) == _set.end()) { _set.push_back(std::move(value)); } return *this; } _SET operator+(const value_type& value) const noexcept { return _SET{*this}+_SET{value}; } _SET operator+(value_type&& value) const noexcept { return _SET{*this}+_SET{std::move(value)}; } _SET operator+(const _SET& s) const noexcept { _SET ret{*this}; for (const auto& value : s) { ret.insert(value); } return ret; } _SET operator+(_SET&& s) const noexcept { _SET ret{*this}; for (auto& value : s) { ret.insert(std::move(value)); } return ret; } _SET& operator+=(const value_type& value) noexcept { insert(value); return *this; } _SET& operator+=(value_type&& value) noexcept { insert(std::move(value)); return *this; } _SET& operator+=(const _SET& s) noexcept { for (const auto& value : s) { insert(value); } return *this; } _SET& operator+=(_SET&& s) noexcept { for (auto& value : s) { insert(std::move(value)); } return *this; } _SET operator-(const value_type& value) const noexcept { _SET ret{*this}; ret.erase(value); return ret; } _SET operator-(const _SET& s) const noexcept { _SET ret{*this}; for (const auto& v : s) { ret.erase(v); } return ret; } _SET& operator-=(const value_type& value) noexcept { _set.erase(value); return *this; } _SET& operator-=(const _SET& s) noexcept { for (const auto& value : s) { _set.erase(value); } return *this; } Set<_SET> operator*(const _SET& other) noexcept { Set<_SET> ret; if (!this->empty() && !other.empty()) { for (const auto& v1 : _set) { for (const auto& v2 : other) { ret.insert(_SET{v1,v2}); } } } return ret; } _SET intersection(const _SET& s) noexcept { _SET s1, s2; if (s.size() <= size()) { s1 = s; s2 = *this; } else { s1 = *this; s2 = s; } for (const auto &v : s1) { if (!s2.contains(v)) s1.erase(v); } return s1; } bool contains(const value_type& value) const noexcept { return contains(_SET{value}); } bool contains(const _SET& s, bool strict = false) const noexcept { for (const auto& value : s) { bool found{false}; for (const auto& v : _set) { if (v == value) { found = true; break; } } if (!found) { return false; } } return strict ? (s.size() != size()) : true; } template<class InputIterator> void insert(InputIterator first, InputIterator last) { for (auto it = first; it != last; it++) { _set.insert(*it); } }; iterator erase(const_iterator position) { return _set.erase(position); } iterator erase(const_iterator first, const_iterator last) { return _set.erase(first,last); } size_t erase(const value_type& value, bool all = false) { size_t ret{}; if (!all) { auto it = find(value); if (it != end()) { erase(it); ret++; } return ret; } for (auto it = _set.begin(); it != _set.end(); it++) { if (*it == value) { _set.erase(it); ++ret; } } return ret; } _SET& unique() noexcept { for (auto i = begin(); i != end(); i++) { auto j = i+1; while (j != end()) { if (*i == *j) { _set.erase(j); } else { j++; } } } return *this; } private: std::vector<value_type,allocator_type> _set; }; #endif /* defined(_SET_HPP) */ <|endoftext|>
<commit_before>/* Copyright (c) 2003, Arvid Norberg 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 author 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. */ #include "libtorrent/pch.hpp" #ifdef _WIN32 // windows part #include "libtorrent/utf8.hpp" #include <io.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #ifndef _MODE_T_ typedef int mode_t; #endif #ifdef UNICODE #include "libtorrent/storage.hpp" #endif #else // unix part #define _FILE_OFFSET_BITS 64 #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <errno.h> #include <boost/static_assert.hpp> // make sure the _FILE_OFFSET_BITS define worked // on this platform BOOST_STATIC_ASSERT(sizeof(lseek(0, 0, 0)) >= 8); #endif #include <boost/filesystem/operations.hpp> #include "libtorrent/file.hpp" #include <sstream> #ifndef O_BINARY #define O_BINARY 0 #endif #ifndef O_RANDOM #define O_RANDOM 0 #endif #ifdef UNICODE #include "libtorrent/storage.hpp" #endif #include "libtorrent/assert.hpp" namespace { enum { mode_in = 1, mode_out = 2 }; mode_t map_open_mode(int m) { if (m == (mode_in | mode_out)) return O_RDWR | O_CREAT | O_BINARY | O_RANDOM; if (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM; if (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM; TORRENT_ASSERT(false); return 0; } #ifdef WIN32 std::string utf8_native(std::string const& s) { try { std::wstring ws; libtorrent::utf8_wchar(s, ws); std::size_t size = wcstombs(0, ws.c_str(), 0); if (size == std::size_t(-1)) return s; std::string ret; ret.resize(size); size = wcstombs(&ret[0], ws.c_str(), size + 1); if (size == wchar_t(-1)) return s; ret.resize(size); return ret; } catch(std::exception) { return s; } } #else std::string utf8_native(std::string const& s) { return s; } #endif } namespace libtorrent { namespace fs = boost::filesystem; const file::open_mode file::in(mode_in); const file::open_mode file::out(mode_out); const file::seek_mode file::begin(1); const file::seek_mode file::end(2); struct file::impl { impl() : m_fd(-1) , m_open_mode(0) {} impl(fs::path const& path, int mode) : m_fd(-1) , m_open_mode(0) { open(path, mode); } ~impl() { close(); } void open(fs::path const& path, int mode) { TORRENT_ASSERT(path.is_complete()); close(); #if defined(_WIN32) && defined(UNICODE) std::wstring wpath(safe_convert(path.native_file_string())); m_fd = ::_wopen( wpath.c_str() , map_open_mode(mode) , S_IREAD | S_IWRITE); #else #ifdef _WIN32 m_fd = ::_open( #else m_fd = ::open( #endif utf8_native(path.native_file_string()).c_str() , map_open_mode(mode) #ifdef _WIN32 , S_IREAD | S_IWRITE); #else , S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); #endif #endif if (m_fd == -1) { std::stringstream msg; msg << "open failed: '" << path.native_file_string() << "'. " << strerror(errno); throw file_error(msg.str()); } m_open_mode = mode; } void close() { if (m_fd == -1) return; #ifdef _WIN32 ::_close(m_fd); #else ::close(m_fd); #endif m_fd = -1; m_open_mode = 0; } size_type read(char* buf, size_type num_bytes) { TORRENT_ASSERT(m_open_mode & mode_in); TORRENT_ASSERT(m_fd != -1); #ifdef _WIN32 size_type ret = ::_read(m_fd, buf, num_bytes); #else size_type ret = ::read(m_fd, buf, num_bytes); #endif if (ret == -1) { std::stringstream msg; msg << "read failed: " << strerror(errno); throw file_error(msg.str()); } return ret; } size_type write(const char* buf, size_type num_bytes) { TORRENT_ASSERT(m_open_mode & mode_out); TORRENT_ASSERT(m_fd != -1); // TODO: Test this a bit more, what happens with random failures in // the files? // if ((rand() % 100) > 80) // throw file_error("debug"); #ifdef _WIN32 size_type ret = ::_write(m_fd, buf, num_bytes); #else size_type ret = ::write(m_fd, buf, num_bytes); #endif if (ret == -1) { std::stringstream msg; msg << "write failed: " << strerror(errno); throw file_error(msg.str()); } return ret; } void set_size(size_type s) { #ifdef _WIN32 #error file.cpp is for posix systems only. use file_win.cpp on windows #else if (ftruncate(m_fd, s) < 0) { std::stringstream msg; msg << "ftruncate failed: '" << strerror(errno); throw file_error(msg.str()); } #endif } size_type seek(size_type offset, int m = 1) { TORRENT_ASSERT(m_open_mode); TORRENT_ASSERT(m_fd != -1); int seekdir = (m == 1)?SEEK_SET:SEEK_END; #ifdef _WIN32 size_type ret = _lseeki64(m_fd, offset, seekdir); #else size_type ret = lseek(m_fd, offset, seekdir); #endif // For some strange reason this fails // on win32. Use windows specific file // wrapper instead. if (ret == -1) { std::stringstream msg; msg << "seek failed: '" << strerror(errno) << "' fd: " << m_fd << " offset: " << offset << " seekdir: " << seekdir; throw file_error(msg.str()); } return ret; } size_type tell() { TORRENT_ASSERT(m_open_mode); TORRENT_ASSERT(m_fd != -1); #ifdef _WIN32 return _telli64(m_fd); #else return lseek(m_fd, 0, SEEK_CUR); #endif } int m_fd; int m_open_mode; }; // pimpl forwardings file::file() : m_impl(new impl()) {} file::file(fs::path const& p, file::open_mode m) : m_impl(new impl(p, m.m_mask)) {} file::~file() {} void file::open(fs::path const& p, file::open_mode m) { m_impl->open(p, m.m_mask); } void file::close() { m_impl->close(); } size_type file::write(const char* buf, size_type num_bytes) { return m_impl->write(buf, num_bytes); } size_type file::read(char* buf, size_type num_bytes) { return m_impl->read(buf, num_bytes); } void file::set_size(size_type s) { m_impl->set_size(s); } size_type file::seek(size_type pos, file::seek_mode m) { return m_impl->seek(pos, m.m_val); } size_type file::tell() { return m_impl->tell(); } } <commit_msg>include fixes in file.cpp<commit_after>/* Copyright (c) 2003, Arvid Norberg 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 author 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. */ #include "libtorrent/pch.hpp" #ifdef _WIN32 // windows part #include "libtorrent/utf8.hpp" #include <io.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #ifndef _MODE_T_ typedef int mode_t; #endif #ifdef UNICODE #include "libtorrent/storage.hpp" #endif #else // unix part #define _FILE_OFFSET_BITS 64 #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <errno.h> #include <boost/static_assert.hpp> // make sure the _FILE_OFFSET_BITS define worked // on this platform BOOST_STATIC_ASSERT(sizeof(lseek(0, 0, 0)) >= 8); #endif #include <boost/filesystem/operations.hpp> #include "libtorrent/file.hpp" #include <sstream> #include <cstring> #ifndef O_BINARY #define O_BINARY 0 #endif #ifndef O_RANDOM #define O_RANDOM 0 #endif #ifdef UNICODE #include "libtorrent/storage.hpp" #endif #include "libtorrent/assert.hpp" namespace { enum { mode_in = 1, mode_out = 2 }; mode_t map_open_mode(int m) { if (m == (mode_in | mode_out)) return O_RDWR | O_CREAT | O_BINARY | O_RANDOM; if (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM; if (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM; TORRENT_ASSERT(false); return 0; } #ifdef WIN32 std::string utf8_native(std::string const& s) { try { std::wstring ws; libtorrent::utf8_wchar(s, ws); std::size_t size = wcstombs(0, ws.c_str(), 0); if (size == std::size_t(-1)) return s; std::string ret; ret.resize(size); size = wcstombs(&ret[0], ws.c_str(), size + 1); if (size == wchar_t(-1)) return s; ret.resize(size); return ret; } catch(std::exception) { return s; } } #else std::string utf8_native(std::string const& s) { return s; } #endif } namespace libtorrent { namespace fs = boost::filesystem; const file::open_mode file::in(mode_in); const file::open_mode file::out(mode_out); const file::seek_mode file::begin(1); const file::seek_mode file::end(2); struct file::impl { impl() : m_fd(-1) , m_open_mode(0) {} impl(fs::path const& path, int mode) : m_fd(-1) , m_open_mode(0) { open(path, mode); } ~impl() { close(); } void open(fs::path const& path, int mode) { TORRENT_ASSERT(path.is_complete()); close(); #if defined(_WIN32) && defined(UNICODE) std::wstring wpath(safe_convert(path.native_file_string())); m_fd = ::_wopen( wpath.c_str() , map_open_mode(mode) , S_IREAD | S_IWRITE); #else #ifdef _WIN32 m_fd = ::_open( #else m_fd = ::open( #endif utf8_native(path.native_file_string()).c_str() , map_open_mode(mode) #ifdef _WIN32 , S_IREAD | S_IWRITE); #else , S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); #endif #endif if (m_fd == -1) { std::stringstream msg; msg << "open failed: '" << path.native_file_string() << "'. " << std::strerror(errno); throw file_error(msg.str()); } m_open_mode = mode; } void close() { if (m_fd == -1) return; #ifdef _WIN32 ::_close(m_fd); #else ::close(m_fd); #endif m_fd = -1; m_open_mode = 0; } size_type read(char* buf, size_type num_bytes) { TORRENT_ASSERT(m_open_mode & mode_in); TORRENT_ASSERT(m_fd != -1); #ifdef _WIN32 size_type ret = ::_read(m_fd, buf, num_bytes); #else size_type ret = ::read(m_fd, buf, num_bytes); #endif if (ret == -1) { std::stringstream msg; msg << "read failed: " << std::strerror(errno); throw file_error(msg.str()); } return ret; } size_type write(const char* buf, size_type num_bytes) { TORRENT_ASSERT(m_open_mode & mode_out); TORRENT_ASSERT(m_fd != -1); // TODO: Test this a bit more, what happens with random failures in // the files? // if ((rand() % 100) > 80) // throw file_error("debug"); #ifdef _WIN32 size_type ret = ::_write(m_fd, buf, num_bytes); #else size_type ret = ::write(m_fd, buf, num_bytes); #endif if (ret == -1) { std::stringstream msg; msg << "write failed: " << std::strerror(errno); throw file_error(msg.str()); } return ret; } void set_size(size_type s) { #ifdef _WIN32 #error file.cpp is for posix systems only. use file_win.cpp on windows #else if (ftruncate(m_fd, s) < 0) { std::stringstream msg; msg << "ftruncate failed: '" << std::strerror(errno); throw file_error(msg.str()); } #endif } size_type seek(size_type offset, int m = 1) { TORRENT_ASSERT(m_open_mode); TORRENT_ASSERT(m_fd != -1); int seekdir = (m == 1)?SEEK_SET:SEEK_END; #ifdef _WIN32 size_type ret = _lseeki64(m_fd, offset, seekdir); #else size_type ret = lseek(m_fd, offset, seekdir); #endif // For some strange reason this fails // on win32. Use windows specific file // wrapper instead. if (ret == -1) { std::stringstream msg; msg << "seek failed: '" << std::strerror(errno) << "' fd: " << m_fd << " offset: " << offset << " seekdir: " << seekdir; throw file_error(msg.str()); } return ret; } size_type tell() { TORRENT_ASSERT(m_open_mode); TORRENT_ASSERT(m_fd != -1); #ifdef _WIN32 return _telli64(m_fd); #else return lseek(m_fd, 0, SEEK_CUR); #endif } int m_fd; int m_open_mode; }; // pimpl forwardings file::file() : m_impl(new impl()) {} file::file(fs::path const& p, file::open_mode m) : m_impl(new impl(p, m.m_mask)) {} file::~file() {} void file::open(fs::path const& p, file::open_mode m) { m_impl->open(p, m.m_mask); } void file::close() { m_impl->close(); } size_type file::write(const char* buf, size_type num_bytes) { return m_impl->write(buf, num_bytes); } size_type file::read(char* buf, size_type num_bytes) { return m_impl->read(buf, num_bytes); } void file::set_size(size_type s) { m_impl->set_size(s); } size_type file::seek(size_type pos, file::seek_mode m) { return m_impl->seek(pos, m.m_val); } size_type file::tell() { return m_impl->tell(); } } <|endoftext|>
<commit_before>#include <nan.h> #include <windows.h> using namespace v8; using namespace node; NAN_METHOD(GetFileStats) { NanScope(); Local<Object> returnObj = NanNew<Object>(); String::Utf8Value filePathV8(args[0]->ToString()); const char* filePath = std::string(*filePathV8).c_str(); int fileAttributes = GetFileAttributes(filePath); int lastError = GetLastError(); returnObj->Set(NanNew<String>("errorCode"), NanNew<Number>(lastError)); if (lastError == 0) { bool isNormal = false, isHidden = false, isReadOnly = false, isSystem = false, isDirectory = false, isArchive = false; if ((fileAttributes & FILE_ATTRIBUTE_NORMAL) != 0){ isNormal = true; } if ((fileAttributes & FILE_ATTRIBUTE_ARCHIVE) != 0){ isArchive = true; } if ((fileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0){ isHidden = true; } if ((fileAttributes & FILE_ATTRIBUTE_READONLY) != 0){ isReadOnly = true; } if ((fileAttributes & FILE_ATTRIBUTE_SYSTEM) != 0){ isSystem = true; } if ((fileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0){ isDirectory = true; } returnObj->Set(NanNew<String>("isNormal"), NanNew<Boolean>(isNormal)); returnObj->Set(NanNew<String>("isArchive"), NanNew<Boolean>(isArchive)); returnObj->Set(NanNew<String>("isHidden"), NanNew<Boolean>(isHidden)); returnObj->Set(NanNew<String>("isSystem"), NanNew<Boolean>(isSystem)); returnObj->Set(NanNew<String>("isReadOnly"), NanNew<Boolean>(isReadOnly)); returnObj->Set(NanNew<String>("isDirectory"), NanNew<Boolean>(isDirectory)); } NanReturnValue(returnObj); } void init(Handle<Object> exports) { exports->Set(NanNew<String>("getFileStats"), NanNew<FunctionTemplate>(GetFileStats)->GetFunction()); } NODE_MODULE(file, init) <commit_msg>fixed using v8<commit_after>#include <nan.h> #include <windows.h> using v8::FunctionTemplate; using v8::Handle; using v8::Object; using v8::String; using v8::Boolean; using v8::Number; using v8::Local; NAN_METHOD(GetFileStats) { NanScope(); Local<Object> returnObj = NanNew<Object>(); String::Utf8Value filePathV8(args[0]->ToString()); const char* filePath = std::string(*filePathV8).c_str(); int fileAttributes = GetFileAttributes(filePath); int lastError = GetLastError(); returnObj->Set(NanNew<String>("errorCode"), NanNew<Number>(lastError)); if (lastError == 0) { bool isNormal = false, isHidden = false, isReadOnly = false, isSystem = false, isDirectory = false, isArchive = false; if ((fileAttributes & FILE_ATTRIBUTE_NORMAL) != 0){ isNormal = true; } if ((fileAttributes & FILE_ATTRIBUTE_ARCHIVE) != 0){ isArchive = true; } if ((fileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0){ isHidden = true; } if ((fileAttributes & FILE_ATTRIBUTE_READONLY) != 0){ isReadOnly = true; } if ((fileAttributes & FILE_ATTRIBUTE_SYSTEM) != 0){ isSystem = true; } if ((fileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0){ isDirectory = true; } returnObj->Set(NanNew<String>("isNormal"), NanNew<Boolean>(isNormal)); returnObj->Set(NanNew<String>("isArchive"), NanNew<Boolean>(isArchive)); returnObj->Set(NanNew<String>("isHidden"), NanNew<Boolean>(isHidden)); returnObj->Set(NanNew<String>("isSystem"), NanNew<Boolean>(isSystem)); returnObj->Set(NanNew<String>("isReadOnly"), NanNew<Boolean>(isReadOnly)); returnObj->Set(NanNew<String>("isDirectory"), NanNew<Boolean>(isDirectory)); } NanReturnValue(returnObj); } void init(Handle<Object> exports) { exports->Set(NanNew<String>("getFileStats"), NanNew<FunctionTemplate>(GetFileStats)->GetFunction()); } NODE_MODULE(file, init) <|endoftext|>
<commit_before>/* Copyright (c) 2003, Arvid Norberg 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 author 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. */ #include "libtorrent/pch.hpp" #include "libtorrent/assert.hpp" #ifdef _WIN32 // windows part #include "libtorrent/utf8.hpp" #include <io.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #ifndef _MODE_T_ typedef int mode_t; #endif #ifdef UNICODE #include "libtorrent/storage.hpp" #endif #else // unix part #define _FILE_OFFSET_BITS 64 #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <errno.h> #include <boost/static_assert.hpp> // make sure the _FILE_OFFSET_BITS define worked // on this platform BOOST_STATIC_ASSERT(sizeof(lseek(0, 0, 0)) >= 8); #endif #include <boost/filesystem/operations.hpp> #include "libtorrent/file.hpp" #include <sstream> #ifndef O_BINARY #define O_BINARY 0 #endif #ifndef O_RANDOM #define O_RANDOM 0 #endif #ifdef UNICODE #include "libtorrent/storage.hpp" #endif namespace { enum { mode_in = 1, mode_out = 2 }; mode_t map_open_mode(int m) { if (m == (mode_in | mode_out)) return O_RDWR | O_CREAT | O_BINARY | O_RANDOM; if (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM; if (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM; TORRENT_ASSERT(false); return 0; } #ifdef WIN32 std::string utf8_native(std::string const& s) { try { std::wstring ws; libtorrent::utf8_wchar(s, ws); std::size_t size = wcstombs(0, ws.c_str(), 0); if (size == std::size_t(-1)) return s; std::string ret; ret.resize(size); size = wcstombs(&ret[0], ws.c_str(), size + 1); if (size == wchar_t(-1)) return s; ret.resize(size); return ret; } catch(std::exception) { return s; } } #else std::string utf8_native(std::string const& s) { return s; } #endif } namespace libtorrent { namespace fs = boost::filesystem; const file::open_mode file::in(mode_in); const file::open_mode file::out(mode_out); const file::seek_mode file::begin(1); const file::seek_mode file::end(2); struct file::impl { impl() : m_fd(-1) , m_open_mode(0) {} impl(fs::path const& path, int mode) : m_fd(-1) , m_open_mode(0) { open(path, mode); } ~impl() { close(); } void open(fs::path const& path, int mode) { TORRENT_ASSERT(path.is_complete()); close(); #if defined(_WIN32) && defined(UNICODE) std::wstring wpath(safe_convert(path.native_file_string())); m_fd = ::_wopen( wpath.c_str() , map_open_mode(mode) , S_IREAD | S_IWRITE); #else #ifdef _WIN32 m_fd = ::_open( #else m_fd = ::open( #endif utf8_native(path.native_file_string()).c_str() , map_open_mode(mode) #ifdef _WIN32 , S_IREAD | S_IWRITE); #else , S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); #endif #endif if (m_fd == -1) { std::stringstream msg; msg << "open failed: '" << path.native_file_string() << "'. " << strerror(errno); throw file_error(msg.str()); } m_open_mode = mode; } void close() { if (m_fd == -1) return; #ifdef _WIN32 ::_close(m_fd); #else ::close(m_fd); #endif m_fd = -1; m_open_mode = 0; } size_type read(char* buf, size_type num_bytes) { TORRENT_ASSERT(m_open_mode & mode_in); TORRENT_ASSERT(m_fd != -1); #ifdef _WIN32 size_type ret = ::_read(m_fd, buf, num_bytes); #else size_type ret = ::read(m_fd, buf, num_bytes); #endif if (ret == -1) { std::stringstream msg; msg << "read failed: " << strerror(errno); throw file_error(msg.str()); } return ret; } size_type write(const char* buf, size_type num_bytes) { TORRENT_ASSERT(m_open_mode & mode_out); TORRENT_ASSERT(m_fd != -1); // TODO: Test this a bit more, what happens with random failures in // the files? // if ((rand() % 100) > 80) // throw file_error("debug"); #ifdef _WIN32 size_type ret = ::_write(m_fd, buf, num_bytes); #else size_type ret = ::write(m_fd, buf, num_bytes); #endif if (ret == -1) { std::stringstream msg; msg << "write failed: " << strerror(errno); throw file_error(msg.str()); } return ret; } void set_size(size_type s) { #ifdef _WIN32 #error file.cpp is for posix systems only. use file_win.cpp on windows #else if (ftruncate(m_fd, s) < 0) { std::stringstream msg; msg << "ftruncate failed: '" << strerror(errno); throw file_error(msg.str()); } #endif } size_type seek(size_type offset, int m = 1) { TORRENT_ASSERT(m_open_mode); TORRENT_ASSERT(m_fd != -1); int seekdir = (m == 1)?SEEK_SET:SEEK_END; #ifdef _WIN32 size_type ret = _lseeki64(m_fd, offset, seekdir); #else size_type ret = lseek(m_fd, offset, seekdir); #endif // For some strange reason this fails // on win32. Use windows specific file // wrapper instead. if (ret == -1) { std::stringstream msg; msg << "seek failed: '" << strerror(errno) << "' fd: " << m_fd << " offset: " << offset << " seekdir: " << seekdir; throw file_error(msg.str()); } return ret; } size_type tell() { TORRENT_ASSERT(m_open_mode); TORRENT_ASSERT(m_fd != -1); #ifdef _WIN32 return _telli64(m_fd); #else return lseek(m_fd, 0, SEEK_CUR); #endif } int m_fd; int m_open_mode; }; // pimpl forwardings file::file() : m_impl(new impl()) {} file::file(fs::path const& p, file::open_mode m) : m_impl(new impl(p, m.m_mask)) {} file::~file() {} void file::open(fs::path const& p, file::open_mode m) { m_impl->open(p, m.m_mask); } void file::close() { m_impl->close(); } size_type file::write(const char* buf, size_type num_bytes) { return m_impl->write(buf, num_bytes); } size_type file::read(char* buf, size_type num_bytes) { return m_impl->read(buf, num_bytes); } void file::set_size(size_type s) { m_impl->set_size(s); } size_type file::seek(size_type pos, file::seek_mode m) { return m_impl->seek(pos, m.m_val); } size_type file::tell() { return m_impl->tell(); } } <commit_msg>fixed static assert being hit on linux systems<commit_after>/* Copyright (c) 2003, Arvid Norberg 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 author 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. */ #include "libtorrent/pch.hpp" #ifdef _WIN32 // windows part #include "libtorrent/utf8.hpp" #include <io.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #ifndef _MODE_T_ typedef int mode_t; #endif #ifdef UNICODE #include "libtorrent/storage.hpp" #endif #else // unix part #define _FILE_OFFSET_BITS 64 #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <errno.h> #include <boost/static_assert.hpp> // make sure the _FILE_OFFSET_BITS define worked // on this platform BOOST_STATIC_ASSERT(sizeof(lseek(0, 0, 0)) >= 8); #endif #include <boost/filesystem/operations.hpp> #include "libtorrent/file.hpp" #include <sstream> #ifndef O_BINARY #define O_BINARY 0 #endif #ifndef O_RANDOM #define O_RANDOM 0 #endif #ifdef UNICODE #include "libtorrent/storage.hpp" #endif #include "libtorrent/assert.hpp" namespace { enum { mode_in = 1, mode_out = 2 }; mode_t map_open_mode(int m) { if (m == (mode_in | mode_out)) return O_RDWR | O_CREAT | O_BINARY | O_RANDOM; if (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM; if (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM; TORRENT_ASSERT(false); return 0; } #ifdef WIN32 std::string utf8_native(std::string const& s) { try { std::wstring ws; libtorrent::utf8_wchar(s, ws); std::size_t size = wcstombs(0, ws.c_str(), 0); if (size == std::size_t(-1)) return s; std::string ret; ret.resize(size); size = wcstombs(&ret[0], ws.c_str(), size + 1); if (size == wchar_t(-1)) return s; ret.resize(size); return ret; } catch(std::exception) { return s; } } #else std::string utf8_native(std::string const& s) { return s; } #endif } namespace libtorrent { namespace fs = boost::filesystem; const file::open_mode file::in(mode_in); const file::open_mode file::out(mode_out); const file::seek_mode file::begin(1); const file::seek_mode file::end(2); struct file::impl { impl() : m_fd(-1) , m_open_mode(0) {} impl(fs::path const& path, int mode) : m_fd(-1) , m_open_mode(0) { open(path, mode); } ~impl() { close(); } void open(fs::path const& path, int mode) { TORRENT_ASSERT(path.is_complete()); close(); #if defined(_WIN32) && defined(UNICODE) std::wstring wpath(safe_convert(path.native_file_string())); m_fd = ::_wopen( wpath.c_str() , map_open_mode(mode) , S_IREAD | S_IWRITE); #else #ifdef _WIN32 m_fd = ::_open( #else m_fd = ::open( #endif utf8_native(path.native_file_string()).c_str() , map_open_mode(mode) #ifdef _WIN32 , S_IREAD | S_IWRITE); #else , S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); #endif #endif if (m_fd == -1) { std::stringstream msg; msg << "open failed: '" << path.native_file_string() << "'. " << strerror(errno); throw file_error(msg.str()); } m_open_mode = mode; } void close() { if (m_fd == -1) return; #ifdef _WIN32 ::_close(m_fd); #else ::close(m_fd); #endif m_fd = -1; m_open_mode = 0; } size_type read(char* buf, size_type num_bytes) { TORRENT_ASSERT(m_open_mode & mode_in); TORRENT_ASSERT(m_fd != -1); #ifdef _WIN32 size_type ret = ::_read(m_fd, buf, num_bytes); #else size_type ret = ::read(m_fd, buf, num_bytes); #endif if (ret == -1) { std::stringstream msg; msg << "read failed: " << strerror(errno); throw file_error(msg.str()); } return ret; } size_type write(const char* buf, size_type num_bytes) { TORRENT_ASSERT(m_open_mode & mode_out); TORRENT_ASSERT(m_fd != -1); // TODO: Test this a bit more, what happens with random failures in // the files? // if ((rand() % 100) > 80) // throw file_error("debug"); #ifdef _WIN32 size_type ret = ::_write(m_fd, buf, num_bytes); #else size_type ret = ::write(m_fd, buf, num_bytes); #endif if (ret == -1) { std::stringstream msg; msg << "write failed: " << strerror(errno); throw file_error(msg.str()); } return ret; } void set_size(size_type s) { #ifdef _WIN32 #error file.cpp is for posix systems only. use file_win.cpp on windows #else if (ftruncate(m_fd, s) < 0) { std::stringstream msg; msg << "ftruncate failed: '" << strerror(errno); throw file_error(msg.str()); } #endif } size_type seek(size_type offset, int m = 1) { TORRENT_ASSERT(m_open_mode); TORRENT_ASSERT(m_fd != -1); int seekdir = (m == 1)?SEEK_SET:SEEK_END; #ifdef _WIN32 size_type ret = _lseeki64(m_fd, offset, seekdir); #else size_type ret = lseek(m_fd, offset, seekdir); #endif // For some strange reason this fails // on win32. Use windows specific file // wrapper instead. if (ret == -1) { std::stringstream msg; msg << "seek failed: '" << strerror(errno) << "' fd: " << m_fd << " offset: " << offset << " seekdir: " << seekdir; throw file_error(msg.str()); } return ret; } size_type tell() { TORRENT_ASSERT(m_open_mode); TORRENT_ASSERT(m_fd != -1); #ifdef _WIN32 return _telli64(m_fd); #else return lseek(m_fd, 0, SEEK_CUR); #endif } int m_fd; int m_open_mode; }; // pimpl forwardings file::file() : m_impl(new impl()) {} file::file(fs::path const& p, file::open_mode m) : m_impl(new impl(p, m.m_mask)) {} file::~file() {} void file::open(fs::path const& p, file::open_mode m) { m_impl->open(p, m.m_mask); } void file::close() { m_impl->close(); } size_type file::write(const char* buf, size_type num_bytes) { return m_impl->write(buf, num_bytes); } size_type file::read(char* buf, size_type num_bytes) { return m_impl->read(buf, num_bytes); } void file::set_size(size_type s) { m_impl->set_size(s); } size_type file::seek(size_type pos, file::seek_mode m) { return m_impl->seek(pos, m.m_val); } size_type file::tell() { return m_impl->tell(); } } <|endoftext|>
<commit_before>/****************************************************************** * * Round for C++ * * Copyright (C) Satoshi Konno 2015 * * This is licensed under BSD-style license, see file COPYING. * ******************************************************************/ #include <boost/test/unit_test.hpp> #include <roundc/round.h> BOOST_AUTO_TEST_CASE(MutexTest) { RoundMutex *mutex; mutex = round_mutex_new(); BOOST_CHECK(mutex); BOOST_CHECK(round_mutex_lock(mutex)); BOOST_CHECK(round_mutex_unlock(mutex)); BOOST_CHECK(round_mutex_delete(mutex)); } <commit_msg>* Added tests for mutex functions.<commit_after>/****************************************************************** * * Round for C++ * * Copyright (C) Satoshi Konno 2015 * * This is licensed under BSD-style license, see file COPYING. * ******************************************************************/ #include <boost/test/unit_test.hpp> #include <roundc/round.h> BOOST_AUTO_TEST_CASE(MutexTest) { RoundMutex *mutex; mutex = round_mutex_new(); BOOST_CHECK(mutex); BOOST_CHECK(round_mutex_lock(mutex)); BOOST_CHECK(round_mutex_unlock(mutex)); BOOST_CHECK(round_mutex_delete(mutex)); } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (C) 2006 by FThauer FHammer * * f.thauer@web.de * * * * 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "game.h" #include "gamedata.h" #include <enginefactory.h> #include <guiinterface.h> #include <iostream> #include <sstream> using namespace std; Game::Game(GuiInterface* gui, boost::shared_ptr<EngineFactory> factory, const PlayerDataList &playerDataList, const GameData &gameData, const StartData &startData, int gameId) : myFactory(factory), myGui(gui), actualHand(0), actualBoard(0), startQuantityPlayers(startData.numberOfPlayers), startCash(gameData.startMoney), startSmallBlind(gameData.smallBlind), startHandsBeforeRaiseSmallBlind(gameData.handsBeforeRaise), myGameID(gameId), actualSmallBlind(gameData.smallBlind), actualHandID(0), dealerPosition(0) { // cout << "Create Game Object" << "\n"; int i; actualHandID = 0; // for(i=0; i<MAX_NUMBER_OF_PLAYERS; i++) { // playerArray[i] = 0; // } // Dealer Position bestimmen PlayerDataList::const_iterator player_i = playerDataList.begin(); PlayerDataList::const_iterator player_end = playerDataList.end(); bool dealerFound = false; i = 0; while (player_i != player_end) { if ((*player_i)->GetUniqueId() == startData.startDealerPlayerId) { dealerPosition = i; dealerFound = true; break; } ++player_i; ++i; } assert(dealerFound); // Board erstellen actualBoard = myFactory->createBoard(); // Player erstellen activePlayerList = PlayerList(new std::list<boost::shared_ptr<PlayerInterface> >); runningPlayerList = PlayerList(new std::list<boost::shared_ptr<PlayerInterface> >); player_i = playerDataList.begin(); player_end = playerDataList.end(); for(i=0; i<MAX_NUMBER_OF_PLAYERS; i++) { string myName; string myAvatarFile; unsigned uniqueId = 0; PlayerType type = PLAYER_TYPE_COMPUTER; boost::shared_ptr<SessionData> myNetSession; if (player_i != player_end) { uniqueId = (*player_i)->GetUniqueId(); type = (*player_i)->GetType(); myName = (*player_i)->GetName(); myAvatarFile = (*player_i)->GetAvatarFile(); myNetSession = (*player_i)->GetNetSessionData(); // TODO: set player type ++player_i; } // create Player Objects boost::shared_ptr<PlayerInterface> tmpPlayer = myFactory->createPlayer(actualBoard, i, uniqueId, type, myName, myAvatarFile, startCash, startQuantityPlayers > i, 0); // fill player lists playerArray.push_back(tmpPlayer); if(startQuantityPlayers > i) { activePlayerList->push_back(tmpPlayer); } (*runningPlayerList) = (*activePlayerList); playerArray[i]->setNetSessionData(myNetSession); } actualBoard->setPlayerLists(playerArray, activePlayerList, runningPlayerList); } Game::~Game() { // cout << "Delete Game Object" << "\n"; delete actualBoard; actualBoard = 0; delete actualHand; actualHand = 0; } HandInterface *Game::getCurrentHand() { return actualHand; } const HandInterface *Game::getCurrentHand() const { return actualHand; } void Game::initHand() { int i; // eventuell vorhandene Hand löschen if(actualHand) { delete actualHand; actualHand = 0; } actualHandID++; // smallBlind alle x Runden erhöhen if((actualHandID-1)%startHandsBeforeRaiseSmallBlind == 0 && actualHandID > 1) { actualSmallBlind *= 2; } // Spieler mit leerem Cash auf inactive setzen PlayerListIterator it; for(it = activePlayerList->begin(); it != activePlayerList->end(); it++) { if((*it)->getMyCash() == 0) { (*it)->setMyActiveStatus(0); it = activePlayerList->erase(it); } } //Spieler Action auf 0 setzen for(i=0; i<MAX_NUMBER_OF_PLAYERS; i++) { playerArray[i]->setMyAction(0); } runningPlayerList->clear(); (*runningPlayerList) = (*activePlayerList); // Hand erstellen actualHand = myFactory->createHand(myFactory, myGui, actualBoard, playerArray, activePlayerList, runningPlayerList, actualHandID, startQuantityPlayers, dealerPosition, actualSmallBlind, startCash); // Dealer-Button weiterschieben --> Achtung inactive for(i=0; (i<MAX_NUMBER_OF_PLAYERS && !(playerArray[dealerPosition]->getMyActiveStatus())) || i==0; i++) { dealerPosition = (dealerPosition+1)%(MAX_NUMBER_OF_PLAYERS); } // Abfrage Cash==0 -> player inactive -> actualQuantityPlayer-- } void Game::startHand() { assert(actualHand); //GUI bereinigen myGui->nextRoundCleanGui(); myGui->logNewGameHandMsg(myGameID, actualHandID); actualHand->start(); } boost::shared_ptr<PlayerInterface> Game::getPlayerByUniqueId(unsigned id) { boost::shared_ptr<PlayerInterface> tmpPlayer; for (int i = 0; i < startQuantityPlayers; i++) { if (playerArray[i]->getMyUniqueID() == id) { tmpPlayer = playerArray[i]; break; } } return tmpPlayer; } boost::shared_ptr<PlayerInterface> Game::getCurrentPlayer() { int curPlayerNum = getCurrentHand()->getCurrentBeRo()->getPlayersTurn(); assert(curPlayerNum < getStartQuantityPlayers()); return getPlayerArray()[curPlayerNum]; } <commit_msg>adds activePlayerList and runningPlayerList (VII) - BUGGY !!! please checkout rev856 for game play<commit_after>/*************************************************************************** * Copyright (C) 2006 by FThauer FHammer * * f.thauer@web.de * * * * 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "game.h" #include "gamedata.h" #include <enginefactory.h> #include <guiinterface.h> #include <iostream> #include <sstream> using namespace std; Game::Game(GuiInterface* gui, boost::shared_ptr<EngineFactory> factory, const PlayerDataList &playerDataList, const GameData &gameData, const StartData &startData, int gameId) : myFactory(factory), myGui(gui), actualHand(0), actualBoard(0), startQuantityPlayers(startData.numberOfPlayers), startCash(gameData.startMoney), startSmallBlind(gameData.smallBlind), startHandsBeforeRaiseSmallBlind(gameData.handsBeforeRaise), myGameID(gameId), actualSmallBlind(gameData.smallBlind), actualHandID(0), dealerPosition(0) { // cout << "Create Game Object" << "\n"; int i; actualHandID = 0; // for(i=0; i<MAX_NUMBER_OF_PLAYERS; i++) { // playerArray[i] = 0; // } // Dealer Position bestimmen PlayerDataList::const_iterator player_i = playerDataList.begin(); PlayerDataList::const_iterator player_end = playerDataList.end(); bool dealerFound = false; i = 0; while (player_i != player_end) { if ((*player_i)->GetUniqueId() == startData.startDealerPlayerId) { dealerPosition = i; dealerFound = true; break; } ++player_i; ++i; } assert(dealerFound); // Board erstellen actualBoard = myFactory->createBoard(); // Player erstellen activePlayerList = PlayerList(new std::list<boost::shared_ptr<PlayerInterface> >); runningPlayerList = PlayerList(new std::list<boost::shared_ptr<PlayerInterface> >); player_i = playerDataList.begin(); player_end = playerDataList.end(); for(i=0; i<MAX_NUMBER_OF_PLAYERS; i++) { string myName; string myAvatarFile; unsigned uniqueId = 0; PlayerType type = PLAYER_TYPE_COMPUTER; boost::shared_ptr<SessionData> myNetSession; if (player_i != player_end) { uniqueId = (*player_i)->GetUniqueId(); type = (*player_i)->GetType(); myName = (*player_i)->GetName(); myAvatarFile = (*player_i)->GetAvatarFile(); myNetSession = (*player_i)->GetNetSessionData(); // TODO: set player type ++player_i; } // create Player Objects boost::shared_ptr<PlayerInterface> tmpPlayer = myFactory->createPlayer(actualBoard, i, uniqueId, type, myName, myAvatarFile, startCash, startQuantityPlayers > i, 0); // fill player lists playerArray.push_back(tmpPlayer); if(startQuantityPlayers > i) { activePlayerList->push_back(tmpPlayer); } (*runningPlayerList) = (*activePlayerList); playerArray[i]->setNetSessionData(myNetSession); } actualBoard->setPlayerLists(playerArray, activePlayerList, runningPlayerList); } Game::~Game() { // cout << "Delete Game Object" << "\n"; delete actualBoard; actualBoard = 0; delete actualHand; actualHand = 0; } HandInterface *Game::getCurrentHand() { return actualHand; } const HandInterface *Game::getCurrentHand() const { return actualHand; } void Game::initHand() { int i; // eventuell vorhandene Hand löschen if(actualHand) { delete actualHand; actualHand = 0; } actualHandID++; // smallBlind alle x Runden erhöhen if((actualHandID-1)%startHandsBeforeRaiseSmallBlind == 0 && actualHandID > 1) { actualSmallBlind *= 2; } // Spieler mit leerem Cash auf inactive setzen PlayerListIterator it; // cout << "id: " << actualHandID << endl; for(it=activePlayerList->begin(); it!=activePlayerList->end(); it++) { // cout << "player" << (*it)->getMyID() << ": " << (*it)->getMyCash() << endl; if((*it)->getMyCash() == 0) { (*it)->setMyActiveStatus(0); it = activePlayerList->erase(it); } } // cout << activePlayerList->size() << endl; //Spieler Action auf 0 setzen for(i=0; i<MAX_NUMBER_OF_PLAYERS; i++) { playerArray[i]->setMyAction(0); } runningPlayerList->clear(); (*runningPlayerList) = (*activePlayerList); // Hand erstellen actualHand = myFactory->createHand(myFactory, myGui, actualBoard, playerArray, activePlayerList, runningPlayerList, actualHandID, startQuantityPlayers, dealerPosition, actualSmallBlind, startCash); // Dealer-Button weiterschieben --> Achtung inactive for(i=0; (i<MAX_NUMBER_OF_PLAYERS && !(playerArray[dealerPosition]->getMyActiveStatus())) || i==0; i++) { dealerPosition = (dealerPosition+1)%(MAX_NUMBER_OF_PLAYERS); } // Abfrage Cash==0 -> player inactive -> actualQuantityPlayer-- } void Game::startHand() { assert(actualHand); //GUI bereinigen myGui->nextRoundCleanGui(); myGui->logNewGameHandMsg(myGameID, actualHandID); actualHand->start(); } boost::shared_ptr<PlayerInterface> Game::getPlayerByUniqueId(unsigned id) { boost::shared_ptr<PlayerInterface> tmpPlayer; for (int i = 0; i < startQuantityPlayers; i++) { if (playerArray[i]->getMyUniqueID() == id) { tmpPlayer = playerArray[i]; break; } } return tmpPlayer; } boost::shared_ptr<PlayerInterface> Game::getCurrentPlayer() { int curPlayerNum = getCurrentHand()->getCurrentBeRo()->getPlayersTurn(); assert(curPlayerNum < getStartQuantityPlayers()); return getPlayerArray()[curPlayerNum]; } <|endoftext|>
<commit_before> #include "game.hpp" Game::Game() : window(sf::VideoMode(720,480), "SFML App") { frameTime = sf::seconds(1.f / 60.f); } void Game::run() { sf::Clock clock; sf::Time lastUpdateTime = sf::Time::Zero; while (window.isOpen()) { lastUpdateTime += clock.restart(); while (lastUpdateTime > frameTime) { lastUpdateTime -= frameTime; processEvents(); update(frameTime); } draw(); } } void Game::processEvents() { sf::Event event; while (window.pollEvent(event)) { switch (event.type) { case sf::Event::Closed: window.close(); break; case sf::Event::KeyPressed: handlePlayerInput(event.key.code, true); break; case sf::Event::KeyReleased: handlePlayerInput(event.key.code, false); break; default: break; } } } void Game::update(sf::Time deltaTime) { } void Game::draw() { } void Game::handlePlayerInput(sf::Keyboard::Key key, bool isPressed) { } <commit_msg>Got rid of accidental tabs instead of spaces.<commit_after> #include "game.hpp" Game::Game() : window(sf::VideoMode(720,480), "SFML App") { frameTime = sf::seconds(1.f / 60.f); } void Game::run() { sf::Clock clock; sf::Time lastUpdateTime = sf::Time::Zero; while (window.isOpen()) { lastUpdateTime += clock.restart(); while (lastUpdateTime > frameTime) { lastUpdateTime -= frameTime; processEvents(); update(frameTime); } draw(); } } void Game::processEvents() { sf::Event event; while (window.pollEvent(event)) { switch (event.type) { case sf::Event::Closed: window.close(); break; case sf::Event::KeyPressed: handlePlayerInput(event.key.code, true); break; case sf::Event::KeyReleased: handlePlayerInput(event.key.code, false); break; default: break; } } } void Game::update(sf::Time deltaTime) { } void Game::draw() { } void Game::handlePlayerInput(sf::Keyboard::Key key, bool isPressed) { } <|endoftext|>
<commit_before>#ifndef GAME_HXX_ #define GAME_HXX_ #include "tunnel.hxx" #include "distortion.hxx" class Game { Tunnel tunnel; Distortion distortion; public: Game(); ~Game(); void update(float); void configureGL(); void draw(); void motion(float,float); void button(unsigned); bool running() const; }; #endif /* GAME_HXX_ */ <commit_msg>Add field member to Game.<commit_after>#ifndef GAME_HXX_ #define GAME_HXX_ #include "tunnel.hxx" #include "distortion.hxx" #include "game_field.hxx" class Game { Tunnel tunnel; Distortion distortion; GameField field; public: Game(); ~Game(); void update(float); void configureGL(); void draw(); void motion(float,float); void button(unsigned); bool running() const; }; #endif /* GAME_HXX_ */ <|endoftext|>
<commit_before>#ifndef __NODE_GDAL_GLOBAL_H__ #define __NODE_GDAL_GLOBAL_H__ // node #include <node.h> // nan #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #include <nan.h> #pragma GCC diagnostic pop // ogr #include <ogr_api.h> #include <ogrsf_frmts.h> // gdal #include "gdal_common.hpp" #include "gdal_driver.hpp" #include "gdal_dataset.hpp" using namespace v8; using namespace node; namespace node_gdal { static NAN_METHOD(open) { Nan::HandleScope scope; std::string path; std::string mode = "r"; NODE_ARG_STR(0, "path", path); NODE_ARG_OPT_STR(1, "mode", mode); #if GDAL_VERSION_MAJOR < 2 GDALAccess access = GA_ReadOnly; if (mode == "r+") { access = GA_Update; } else if (mode != "r") { Nan::ThrowError("Invalid open mode. Must be \"r\" or \"r+\""); return; } OGRDataSource *ogr_ds = OGRSFDriverRegistrar::Open(path.c_str(), static_cast<int>(access)); if(ogr_ds) { info.GetReturnValue().Set(NanNewDataset::New(ogr_ds)); return; } GDALDataset *gdal_ds = (GDALDataset*) GDALOpen(path.c_str(), access); if(gdal_ds) { info.GetReturnValue().Set(Dataset::New(gdal_ds)); return; } #else unsigned int flags = 0; if (mode == "r+") { flags |= GDAL_OF_UPDATE; } else if (mode == "r") { flags |= GDAL_OF_READONLY; } else { Nan::ThrowError("Invalid open mode. Must be \"r\" or \"r+\""); return; } GDALDataset *ds = (GDALDataset*) GDALOpenEx(path.c_str(), flags, NULL, NULL, NULL); if(ds) { info.GetReturnValue().Set(Dataset::New(ds)); return; } #endif Nan::ThrowError("Error opening dataset"); return; } static NAN_METHOD(setConfigOption) { Nan::HandleScope scope; std::string name; NODE_ARG_STR(0, "name", name); if (info.Length() < 2) { Nan::ThrowError("string or null value must be provided"); return; } if(info[1]->IsString()){ std::string val = *Nan::Utf8String(info[1]); CPLSetConfigOption(name.c_str(), val.c_str()); } else if(info[1]->IsNull() || info[1]->IsUndefined()) { CPLSetConfigOption(name.c_str(), NULL); } else { Nan::ThrowError("value must be a string or null"); return; } return; } static NAN_METHOD(getConfigOption) { Nan::HandleScope scope; std::string name; NODE_ARG_STR(0, "name", name); info.GetReturnValue().Set(SafeString::New(CPLGetConfigOption(name.c_str(), NULL))); } /** * Convert decimal degrees to degrees, minutes, and seconds string * * @for gdal * @static * @method decToDMS * @param {Number} angle * @param {String} axis `"lat"` or `"long"` * @param {Integer} [precision=2] * @return {String} A string nndnn'nn.nn'"L where n is a number and L is either N or E */ static NAN_METHOD(decToDMS){ Nan::HandleScope scope; double angle; std::string axis; int precision = 2; NODE_ARG_DOUBLE(0, "angle", angle); NODE_ARG_STR(1, "axis", axis); NODE_ARG_INT_OPT(2, "precision", precision); if (axis.length() > 0) { axis[0] = toupper(axis[0]); } if (axis != "Lat" && axis != "Long") { Nan::ThrowError("Axis must be 'lat' or 'long'"); return; } info.GetReturnValue().Set(SafeString::New(GDALDecToDMS(angle, axis.c_str(), precision))); } } #endif <commit_msg>Fixing compiler errors for GDAL versions < 2.0<commit_after>#ifndef __NODE_GDAL_GLOBAL_H__ #define __NODE_GDAL_GLOBAL_H__ // node #include <node.h> // nan #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #include <nan.h> #pragma GCC diagnostic pop // ogr #include <ogr_api.h> #include <ogrsf_frmts.h> // gdal #include "gdal_common.hpp" #include "gdal_driver.hpp" #include "gdal_dataset.hpp" using namespace v8; using namespace node; namespace node_gdal { static NAN_METHOD(open) { Nan::HandleScope scope; std::string path; std::string mode = "r"; NODE_ARG_STR(0, "path", path); NODE_ARG_OPT_STR(1, "mode", mode); #if GDAL_VERSION_MAJOR < 2 GDALAccess access = GA_ReadOnly; if (mode == "r+") { access = GA_Update; } else if (mode != "r") { Nan::ThrowError("Invalid open mode. Must be \"r\" or \"r+\""); return; } OGRDataSource *ogr_ds = OGRSFDriverRegistrar::Open(path.c_str(), static_cast<int>(access)); if(ogr_ds) { info.GetReturnValue().Set(Dataset::New(ogr_ds)); return; } GDALDataset *gdal_ds = (GDALDataset*) GDALOpen(path.c_str(), access); if(gdal_ds) { info.GetReturnValue().Set(Dataset::New(gdal_ds)); return; } #else unsigned int flags = 0; if (mode == "r+") { flags |= GDAL_OF_UPDATE; } else if (mode == "r") { flags |= GDAL_OF_READONLY; } else { Nan::ThrowError("Invalid open mode. Must be \"r\" or \"r+\""); return; } GDALDataset *ds = (GDALDataset*) GDALOpenEx(path.c_str(), flags, NULL, NULL, NULL); if(ds) { info.GetReturnValue().Set(Dataset::New(ds)); return; } #endif Nan::ThrowError("Error opening dataset"); return; } static NAN_METHOD(setConfigOption) { Nan::HandleScope scope; std::string name; NODE_ARG_STR(0, "name", name); if (info.Length() < 2) { Nan::ThrowError("string or null value must be provided"); return; } if(info[1]->IsString()){ std::string val = *Nan::Utf8String(info[1]); CPLSetConfigOption(name.c_str(), val.c_str()); } else if(info[1]->IsNull() || info[1]->IsUndefined()) { CPLSetConfigOption(name.c_str(), NULL); } else { Nan::ThrowError("value must be a string or null"); return; } return; } static NAN_METHOD(getConfigOption) { Nan::HandleScope scope; std::string name; NODE_ARG_STR(0, "name", name); info.GetReturnValue().Set(SafeString::New(CPLGetConfigOption(name.c_str(), NULL))); } /** * Convert decimal degrees to degrees, minutes, and seconds string * * @for gdal * @static * @method decToDMS * @param {Number} angle * @param {String} axis `"lat"` or `"long"` * @param {Integer} [precision=2] * @return {String} A string nndnn'nn.nn'"L where n is a number and L is either N or E */ static NAN_METHOD(decToDMS){ Nan::HandleScope scope; double angle; std::string axis; int precision = 2; NODE_ARG_DOUBLE(0, "angle", angle); NODE_ARG_STR(1, "axis", axis); NODE_ARG_INT_OPT(2, "precision", precision); if (axis.length() > 0) { axis[0] = toupper(axis[0]); } if (axis != "Lat" && axis != "Long") { Nan::ThrowError("Axis must be 'lat' or 'long'"); return; } info.GetReturnValue().Set(SafeString::New(GDALDecToDMS(angle, axis.c_str(), precision))); } } #endif <|endoftext|>
<commit_before>#include "mpi.h" #include <Python.h> #include <string> #include <iostream> #include <cstring> #include "parquet/api/reader.h" #include "parquet/arrow/reader.h" #include "arrow/table.h" using parquet::arrow::FileReader; using parquet::ParquetFileReader; int64_t pq_get_size(std::string* file_name, int64_t column_idx); int pq_read(std::string* file_name, int64_t column_idx, void* out); PyMODINIT_FUNC PyInit_parquet_cpp(void) { PyObject *m; static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "parquet_cpp", "No docs", -1, NULL, }; m = PyModule_Create(&moduledef); if (m == NULL) return NULL; PyObject_SetAttrString(m, "read", PyLong_FromVoidPtr((void*)(&pq_read))); PyObject_SetAttrString(m, "get_size", PyLong_FromVoidPtr((void*)(&pq_get_size))); return m; } int64_t pq_get_size(std::string* file_name, int64_t column_idx) { auto pqreader = ParquetFileReader::OpenFile(*file_name); int64_t nrows = pqreader->metadata()->num_rows(); // std::cout << nrows << std::endl; pqreader->Close(); return nrows; } int pq_read(std::string* file_name, int64_t column_idx, void* out_data) { auto pool = ::arrow::default_memory_pool(); std::unique_ptr<FileReader> arrow_reader; arrow_reader.reset(new FileReader(pool, ParquetFileReader::OpenFile(*file_name, false))); // std::shared_ptr<::arrow::Table> table; arrow_reader->ReadTable(&table); // std::vector<int> column_indices; // column_indices.push_back(column_idx); // arrow_reader->ReadRowGroup(0, column_indices, &table); std::shared_ptr< ::arrow::Column > column = table->column(column_idx); int64_t num_values = column->length(); std::shared_ptr< ::arrow::ChunkedArray > data = column->data(); for(int i=0; i<data->num_chunks(); i++) { std::shared_ptr< ::arrow::Array > arr = data->chunk(i); auto buffers = arr->data()->buffers; std::cout<<"num buffs: "<< buffers.size()<<std::endl; int buff_size = buffers[1]->size(); memcpy(out_data, buffers[1]->data(), buff_size); } return 0; } <commit_msg>parquet read cleanup<commit_after>#include "mpi.h" #include <Python.h> #include <string> #include <iostream> #include <cstring> #include "parquet/api/reader.h" #include "parquet/arrow/reader.h" #include "arrow/table.h" using parquet::arrow::FileReader; using parquet::ParquetFileReader; int64_t pq_get_size(std::string* file_name, int64_t column_idx); int pq_read(std::string* file_name, int64_t column_idx, void* out); PyMODINIT_FUNC PyInit_parquet_cpp(void) { PyObject *m; static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "parquet_cpp", "No docs", -1, NULL, }; m = PyModule_Create(&moduledef); if (m == NULL) return NULL; PyObject_SetAttrString(m, "read", PyLong_FromVoidPtr((void*)(&pq_read))); PyObject_SetAttrString(m, "get_size", PyLong_FromVoidPtr((void*)(&pq_get_size))); return m; } int64_t pq_get_size(std::string* file_name, int64_t column_idx) { auto pqreader = ParquetFileReader::OpenFile(*file_name); int64_t nrows = pqreader->metadata()->num_rows(); // std::cout << nrows << std::endl; pqreader->Close(); return nrows; } int pq_read(std::string* file_name, int64_t column_idx, void* out_data) { auto pool = ::arrow::default_memory_pool(); std::unique_ptr<FileReader> arrow_reader; arrow_reader.reset(new FileReader(pool, ParquetFileReader::OpenFile(*file_name, false))); // std::shared_ptr< ::arrow::Array > arr; arrow_reader->ReadColumn(column_idx, &arr); // std::cout << arr->ToString() << std::endl; auto buffers = arr->data()->buffers; // std::cout<<"num buffs: "<< buffers.size()<<std::endl; if (buffers.size()!=2) { std::cerr << "invalid parquet number of array buffers" << std::endl; } int64_t buff_size = buffers[1]->size(); memcpy(out_data, buffers[1]->data(), buff_size); return 0; } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkMultiProcessController.cxx 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. =========================================================================*/ // This will be the default. #include "vtkMultiProcessController.h" #include "vtkDummyController.h" #include "vtkProcessGroup.h" #include "vtkSubCommunicator.h" #include "vtkToolkits.h" #ifdef VTK_USE_MPI #include "vtkMPIController.h" #endif #include "vtkCollection.h" #include "vtkObjectFactory.h" #include "vtkOutputWindow.h" //---------------------------------------------------------------------------- // Needed when we don't use the vtkStandardNewMacro. vtkInstantiatorNewMacro(vtkMultiProcessController); //---------------------------------------------------------------------------- // Helper class to contain the RMI information. // A subclass of vtkObject so that I can keep them in a collection. class VTK_PARALLEL_EXPORT vtkMultiProcessControllerRMI : public vtkObject { public: static vtkMultiProcessControllerRMI *New(); vtkTypeRevisionMacro(vtkMultiProcessControllerRMI, vtkObject); int Tag; vtkRMIFunctionType Function; void *LocalArgument; unsigned long Id; protected: vtkMultiProcessControllerRMI() {}; vtkMultiProcessControllerRMI(const vtkMultiProcessControllerRMI&); void operator=(const vtkMultiProcessControllerRMI&); }; vtkCxxRevisionMacro(vtkMultiProcessControllerRMI, "1.32"); vtkStandardNewMacro(vtkMultiProcessControllerRMI); vtkCxxRevisionMacro(vtkMultiProcessController, "1.32"); //---------------------------------------------------------------------------- // An RMI function that will break the "ProcessRMIs" loop. void vtkMultiProcessControllerBreakRMI(void *localArg, void *remoteArg, int remoteArgLength, int vtkNotUsed(remoteId)) { vtkMultiProcessController *controller; remoteArg = remoteArg; remoteArgLength = remoteArgLength; controller = (vtkMultiProcessController*)(localArg); controller->SetBreakFlag(1); } //---------------------------------------------------------------------------- vtkMultiProcessController::vtkMultiProcessController() { int i; this->RMICount = 1; this->RMIs = vtkCollection::New(); this->SingleMethod = 0; this->SingleData = 0; this->Communicator = 0; this->RMICommunicator = 0; for ( i = 0; i < VTK_MAX_THREADS; i++ ) { this->MultipleMethod[i] = NULL; this->MultipleData[i] = NULL; } this->BreakFlag = 0; this->ForceDeepCopy = 1; this->OutputWindow = 0; // Define an rmi internally to exit from the processing loop. this->AddRMI(vtkMultiProcessControllerBreakRMI, this, BREAK_RMI_TAG); } //---------------------------------------------------------------------------- // This is an old comment that I do not know is true: // (We need to have a "GetNetReferenceCount" to avoid memory leaks.) vtkMultiProcessController::~vtkMultiProcessController() { if ( this->OutputWindow && (this->OutputWindow == vtkOutputWindow::GetInstance()) ) { vtkOutputWindow::SetInstance(0); } if (this->OutputWindow) { this->OutputWindow->Delete(); } this->RMIs->Delete(); this->RMIs = NULL; } //---------------------------------------------------------------------------- void vtkMultiProcessController::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); vtkMultiProcessControllerRMI *rmi; vtkIndent nextIndent = indent.GetNextIndent(); os << indent << "Break flag: " << (this->BreakFlag ? "(yes)" : "(no)") << endl; os << indent << "Force deep copy: " << (this->ForceDeepCopy ? "(yes)" : "(no)") << endl; os << indent << "Output window: "; if (this->OutputWindow) { os << endl; this->OutputWindow->PrintSelf(os, nextIndent); } else { os << "(none)" << endl; } os << indent << "Communicator: "; if (this->Communicator) { os << endl; this->Communicator->PrintSelf(os, nextIndent); } else { os << "(none)" << endl; } os << indent << "RMI communicator: "; if (this->RMICommunicator) { os << endl; this->RMICommunicator->PrintSelf(os, nextIndent); } else { os << "(none)" << endl; } os << indent << "RMIs: \n"; this->RMIs->InitTraversal(); while ( (rmi = (vtkMultiProcessControllerRMI*)(this->RMIs->GetNextItemAsObject())) ) { os << nextIndent << rmi->Tag << endl; } } //---------------------------------------------------------------------------- void vtkMultiProcessController::SetNumberOfProcesses(int num) { if(this->Communicator) { this->Communicator->SetNumberOfProcesses(num); } else { vtkErrorMacro("Communicator not set."); } } //---------------------------------------------------------------------------- int vtkMultiProcessController::GetNumberOfProcesses() { if(this->Communicator) { return this->Communicator->GetNumberOfProcesses(); } else { vtkErrorMacro("Communicator not set."); return 0; } } //---------------------------------------------------------------------------- int vtkMultiProcessController::GetLocalProcessId() { if(this->Communicator) { return this->Communicator->GetLocalProcessId(); } else { vtkErrorMacro("Communicator not set."); return -1; } } //---------------------------------------------------------------------------- void vtkMultiProcessController::SetSingleMethod( vtkProcessFunctionType f, void *data ) { this->SingleMethod = f; this->SingleData = data; } //---------------------------------------------------------------------------- // Set one of the user defined methods that will be run on NumberOfProcesses // processes when MultipleMethodExecute is called. This method should be // called with index = 0, 1, .., NumberOfProcesses-1 to set up all the // required user defined methods void vtkMultiProcessController::SetMultipleMethod( int index, vtkProcessFunctionType f, void *data ) { // You can only set the method for 0 through NumberOfProcesses-1 if ( index >= this->GetNumberOfProcesses() ) { vtkErrorMacro( << "Can't set method " << index << " with a processes count of " << this->GetNumberOfProcesses() ); } else { this->MultipleMethod[index] = f; this->MultipleData[index] = data; } } //----------------------------------------------------------------------------- vtkMultiProcessController *vtkMultiProcessController::CreateSubController( vtkProcessGroup *group) { if (group->GetCommunicator() != this->Communicator) { vtkErrorMacro(<< "Invalid group for creating a sub controller."); return NULL; } if (group->FindProcessId(this->GetLocalProcessId()) < 0) { // The group does not contain this process. Just return NULL. return NULL; } vtkSubCommunicator *subcomm = vtkSubCommunicator::New(); subcomm->SetGroup(group); // We only need a basic implementation of vtkMultiProcessController for the // subgroup, so we just use vtkDummyController here. It's a bit of a misnomer // and may lead to confusion, but I think it's better than creating yet // another class we have to maintain. vtkDummyController *subcontroller = vtkDummyController::New(); subcontroller->SetCommunicator(subcomm); subcontroller->SetRMICommunicator(subcomm); subcomm->Delete(); return subcontroller; } //---------------------------------------------------------------------------- int vtkMultiProcessController::RemoveFirstRMI(int tag) { vtkMultiProcessControllerRMI *rmi = NULL; this->RMIs->InitTraversal(); while ( (rmi = (vtkMultiProcessControllerRMI*)(this->RMIs->GetNextItemAsObject())) ) { if (rmi->Tag == tag) { this->RMIs->RemoveItem(rmi); return 1; } } return 0; } //---------------------------------------------------------------------------- int vtkMultiProcessController::RemoveRMI(unsigned long id) { vtkMultiProcessControllerRMI *rmi = NULL; this->RMIs->InitTraversal(); while ( (rmi = (vtkMultiProcessControllerRMI*)(this->RMIs->GetNextItemAsObject())) ) { if (rmi->Id == id) { this->RMIs->RemoveItem(rmi); return 1; } } return 0; } //---------------------------------------------------------------------------- unsigned long vtkMultiProcessController::AddRMI(vtkRMIFunctionType f, void *localArg, int tag) { vtkMultiProcessControllerRMI *rmi = vtkMultiProcessControllerRMI::New(); // Remove any previously registered RMI handler for the tag. this->RemoveFirstRMI(tag); rmi->Tag = tag; rmi->Function = f; rmi->LocalArgument = localArg; rmi->Id = this->RMICount; this->RMICount++; this->RMIs->AddItem(rmi); rmi->Delete(); return rmi->Id; } //---------------------------------------------------------------------------- void vtkMultiProcessController::TriggerRMIOnAllChildren( void *arg, int argLength, int rmiTag) { int myid = this->GetLocalProcessId(); int childid = 2 * myid + 1; int numProcs = this->GetNumberOfProcesses(); if (numProcs > childid) { this->TriggerRMIInternal(childid, arg, argLength, rmiTag, true); } childid++; if (numProcs > childid) { this->TriggerRMIInternal(childid, arg, argLength, rmiTag, true); } } //---------------------------------------------------------------------------- void vtkMultiProcessController::TriggerRMI(int remoteProcessId, void *arg, int argLength, int rmiTag) { // Deal with sending RMI to ourself here for now. if (remoteProcessId == this->GetLocalProcessId()) { this->ProcessRMI(remoteProcessId, arg, argLength, rmiTag); return; } this->TriggerRMIInternal(remoteProcessId, arg, argLength, rmiTag, false); } //---------------------------------------------------------------------------- void vtkMultiProcessController::TriggerRMIInternal(int remoteProcessId, void* arg, int argLength, int rmiTag, bool propagate) { int triggerMessage[128]; triggerMessage[0] = rmiTag; triggerMessage[1] = argLength; // It is important for the remote process to know what process invoked it. // Multiple processes might try to invoke the method at the same time. // The remote method will know where to get additional args. triggerMessage[2] = this->GetLocalProcessId(); // Pass the propagate flag. triggerMessage[3] = propagate? 1 : 0; // If the message is small, we will try to get the message sent over using a // single Send(), rather than two. This helps speed up communication // significantly, since sending multiple small messages is generally slower // than sending a single large message. if (argLength >= 0 && static_cast<unsigned int>(argLength) < sizeof(int)*(128-4)) { if (argLength > 0) { memcpy(&triggerMessage[4], arg, argLength); } int num_ints = 4 + ceil(argLength/static_cast<double>(sizeof(int))); this->RMICommunicator->Send(triggerMessage, num_ints, remoteProcessId, RMI_TAG); } else { this->RMICommunicator->Send(triggerMessage, 4, remoteProcessId, RMI_TAG); if (argLength > 0) { this->RMICommunicator->Send((char*)arg, argLength, remoteProcessId, RMI_ARG_TAG); } } } //---------------------------------------------------------------------------- void vtkMultiProcessController::TriggerBreakRMIs() { int idx, num; if (this->GetLocalProcessId() != 0) { vtkErrorMacro("Break should be triggered from process 0."); return; } num = this->GetNumberOfProcesses(); for (idx = 1; idx < num; ++idx) { this->TriggerRMI(idx, NULL, 0, BREAK_RMI_TAG); } } //---------------------------------------------------------------------------- int vtkMultiProcessController::ProcessRMIs() { return this->ProcessRMIs(1, 0); } //---------------------------------------------------------------------------- int vtkMultiProcessController::ProcessRMIs(int reportErrors, int dont_loop) { int triggerMessage[128]; unsigned char *arg = NULL; int error = RMI_NO_ERROR; do { if (!this->RMICommunicator->Receive(triggerMessage, 128, ANY_SOURCE, RMI_TAG) || this->RMICommunicator->GetCount() < 4) { if (reportErrors) { vtkErrorMacro("Could not receive RMI trigger message."); } error = RMI_TAG_ERROR; break; } if (triggerMessage[1] > 0) { arg = new unsigned char[triggerMessage[1]]; // If the message length is small enough, the TriggerRMIInternal() call // packs the message data inline. So depending on the message length we // use the inline data or make a second receive to fetch the data. if (static_cast<unsigned int>(triggerMessage[1]) < sizeof(int)*(128-4)) { int num_ints = 4 + ceil(triggerMessage[1]/static_cast<double>(sizeof(int))); if (this->RMICommunicator->GetCount() != num_ints) { if (reportErrors) { vtkErrorMacro("Could not receive the RMI argument in its entirety."); } error= RMI_ARG_ERROR; break; } memcpy(arg, &triggerMessage[4], triggerMessage[1]); } else { if (!this->RMICommunicator->Receive((char*)(arg), triggerMessage[1], triggerMessage[2], RMI_ARG_TAG) || this->RMICommunicator->GetCount() != triggerMessage[1]) { if (reportErrors) { vtkErrorMacro("Could not receive RMI argument."); } error = RMI_ARG_ERROR; break; } } } if (triggerMessage[3] == 1)//propagate==true { this->TriggerRMIOnAllChildren(arg, triggerMessage[1], triggerMessage[0]); } this->ProcessRMI(triggerMessage[2], arg, triggerMessage[1], triggerMessage[0]); if (arg) { delete [] arg; arg = NULL; } // check for break if (this->BreakFlag) { this->BreakFlag = 0; return error; } } while (!dont_loop); return error; } //---------------------------------------------------------------------------- void vtkMultiProcessController::ProcessRMI(int remoteProcessId, void *arg, int argLength, int rmiTag) { vtkMultiProcessControllerRMI *rmi = NULL; int found = 0; // find the rmi this->RMIs->InitTraversal(); while ( !found && (rmi = (vtkMultiProcessControllerRMI*)(this->RMIs->GetNextItemAsObject())) ) { if (rmi->Tag == rmiTag) { found = 1; } } if ( ! found) { vtkErrorMacro("Process " << this->GetLocalProcessId() << " Could not find RMI with tag " << rmiTag); } else { if ( rmi->Function ) { (*rmi->Function)(rmi->LocalArgument, arg, argLength, remoteProcessId); } } } //============================================================================ // The intent is to give access to a processes controller from a static method. vtkMultiProcessController *VTK_GLOBAL_MULTI_PROCESS_CONTROLLER = NULL; //---------------------------------------------------------------------------- vtkMultiProcessController *vtkMultiProcessController::GetGlobalController() { if (VTK_GLOBAL_MULTI_PROCESS_CONTROLLER == NULL) { return NULL; } return VTK_GLOBAL_MULTI_PROCESS_CONTROLLER->GetLocalController(); } //---------------------------------------------------------------------------- // This can be overridden in the subclass to translate controllers. vtkMultiProcessController *vtkMultiProcessController::GetLocalController() { return VTK_GLOBAL_MULTI_PROCESS_CONTROLLER; } //---------------------------------------------------------------------------- // This can be overridden in the subclass to translate controllers. void vtkMultiProcessController::SetGlobalController( vtkMultiProcessController *controller) { VTK_GLOBAL_MULTI_PROCESS_CONTROLLER = controller; } <commit_msg>BUG: Fixed TriggerRMIOnAllChildren to work with SocketCommunicator. COMP: Fixed warnings.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkMultiProcessController.cxx 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. =========================================================================*/ // This will be the default. #include "vtkMultiProcessController.h" #include "vtkDummyController.h" #include "vtkProcessGroup.h" #include "vtkSubCommunicator.h" #include "vtkToolkits.h" #ifdef VTK_USE_MPI #include "vtkMPIController.h" #endif #include "vtkCollection.h" #include "vtkObjectFactory.h" #include "vtkOutputWindow.h" //---------------------------------------------------------------------------- // Needed when we don't use the vtkStandardNewMacro. vtkInstantiatorNewMacro(vtkMultiProcessController); //---------------------------------------------------------------------------- // Helper class to contain the RMI information. // A subclass of vtkObject so that I can keep them in a collection. class VTK_PARALLEL_EXPORT vtkMultiProcessControllerRMI : public vtkObject { public: static vtkMultiProcessControllerRMI *New(); vtkTypeRevisionMacro(vtkMultiProcessControllerRMI, vtkObject); int Tag; vtkRMIFunctionType Function; void *LocalArgument; unsigned long Id; protected: vtkMultiProcessControllerRMI() {}; vtkMultiProcessControllerRMI(const vtkMultiProcessControllerRMI&); void operator=(const vtkMultiProcessControllerRMI&); }; vtkCxxRevisionMacro(vtkMultiProcessControllerRMI, "1.33"); vtkStandardNewMacro(vtkMultiProcessControllerRMI); vtkCxxRevisionMacro(vtkMultiProcessController, "1.33"); //---------------------------------------------------------------------------- // An RMI function that will break the "ProcessRMIs" loop. void vtkMultiProcessControllerBreakRMI(void *localArg, void *remoteArg, int remoteArgLength, int vtkNotUsed(remoteId)) { vtkMultiProcessController *controller; remoteArg = remoteArg; remoteArgLength = remoteArgLength; controller = (vtkMultiProcessController*)(localArg); controller->SetBreakFlag(1); } //---------------------------------------------------------------------------- vtkMultiProcessController::vtkMultiProcessController() { int i; this->RMICount = 1; this->RMIs = vtkCollection::New(); this->SingleMethod = 0; this->SingleData = 0; this->Communicator = 0; this->RMICommunicator = 0; for ( i = 0; i < VTK_MAX_THREADS; i++ ) { this->MultipleMethod[i] = NULL; this->MultipleData[i] = NULL; } this->BreakFlag = 0; this->ForceDeepCopy = 1; this->OutputWindow = 0; // Define an rmi internally to exit from the processing loop. this->AddRMI(vtkMultiProcessControllerBreakRMI, this, BREAK_RMI_TAG); } //---------------------------------------------------------------------------- // This is an old comment that I do not know is true: // (We need to have a "GetNetReferenceCount" to avoid memory leaks.) vtkMultiProcessController::~vtkMultiProcessController() { if ( this->OutputWindow && (this->OutputWindow == vtkOutputWindow::GetInstance()) ) { vtkOutputWindow::SetInstance(0); } if (this->OutputWindow) { this->OutputWindow->Delete(); } this->RMIs->Delete(); this->RMIs = NULL; } //---------------------------------------------------------------------------- void vtkMultiProcessController::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); vtkMultiProcessControllerRMI *rmi; vtkIndent nextIndent = indent.GetNextIndent(); os << indent << "Break flag: " << (this->BreakFlag ? "(yes)" : "(no)") << endl; os << indent << "Force deep copy: " << (this->ForceDeepCopy ? "(yes)" : "(no)") << endl; os << indent << "Output window: "; if (this->OutputWindow) { os << endl; this->OutputWindow->PrintSelf(os, nextIndent); } else { os << "(none)" << endl; } os << indent << "Communicator: "; if (this->Communicator) { os << endl; this->Communicator->PrintSelf(os, nextIndent); } else { os << "(none)" << endl; } os << indent << "RMI communicator: "; if (this->RMICommunicator) { os << endl; this->RMICommunicator->PrintSelf(os, nextIndent); } else { os << "(none)" << endl; } os << indent << "RMIs: \n"; this->RMIs->InitTraversal(); while ( (rmi = (vtkMultiProcessControllerRMI*)(this->RMIs->GetNextItemAsObject())) ) { os << nextIndent << rmi->Tag << endl; } } //---------------------------------------------------------------------------- void vtkMultiProcessController::SetNumberOfProcesses(int num) { if(this->Communicator) { this->Communicator->SetNumberOfProcesses(num); } else { vtkErrorMacro("Communicator not set."); } } //---------------------------------------------------------------------------- int vtkMultiProcessController::GetNumberOfProcesses() { if(this->Communicator) { return this->Communicator->GetNumberOfProcesses(); } else { vtkErrorMacro("Communicator not set."); return 0; } } //---------------------------------------------------------------------------- int vtkMultiProcessController::GetLocalProcessId() { if(this->Communicator) { return this->Communicator->GetLocalProcessId(); } else { vtkErrorMacro("Communicator not set."); return -1; } } //---------------------------------------------------------------------------- void vtkMultiProcessController::SetSingleMethod( vtkProcessFunctionType f, void *data ) { this->SingleMethod = f; this->SingleData = data; } //---------------------------------------------------------------------------- // Set one of the user defined methods that will be run on NumberOfProcesses // processes when MultipleMethodExecute is called. This method should be // called with index = 0, 1, .., NumberOfProcesses-1 to set up all the // required user defined methods void vtkMultiProcessController::SetMultipleMethod( int index, vtkProcessFunctionType f, void *data ) { // You can only set the method for 0 through NumberOfProcesses-1 if ( index >= this->GetNumberOfProcesses() ) { vtkErrorMacro( << "Can't set method " << index << " with a processes count of " << this->GetNumberOfProcesses() ); } else { this->MultipleMethod[index] = f; this->MultipleData[index] = data; } } //----------------------------------------------------------------------------- vtkMultiProcessController *vtkMultiProcessController::CreateSubController( vtkProcessGroup *group) { if (group->GetCommunicator() != this->Communicator) { vtkErrorMacro(<< "Invalid group for creating a sub controller."); return NULL; } if (group->FindProcessId(this->GetLocalProcessId()) < 0) { // The group does not contain this process. Just return NULL. return NULL; } vtkSubCommunicator *subcomm = vtkSubCommunicator::New(); subcomm->SetGroup(group); // We only need a basic implementation of vtkMultiProcessController for the // subgroup, so we just use vtkDummyController here. It's a bit of a misnomer // and may lead to confusion, but I think it's better than creating yet // another class we have to maintain. vtkDummyController *subcontroller = vtkDummyController::New(); subcontroller->SetCommunicator(subcomm); subcontroller->SetRMICommunicator(subcomm); subcomm->Delete(); return subcontroller; } //---------------------------------------------------------------------------- int vtkMultiProcessController::RemoveFirstRMI(int tag) { vtkMultiProcessControllerRMI *rmi = NULL; this->RMIs->InitTraversal(); while ( (rmi = (vtkMultiProcessControllerRMI*)(this->RMIs->GetNextItemAsObject())) ) { if (rmi->Tag == tag) { this->RMIs->RemoveItem(rmi); return 1; } } return 0; } //---------------------------------------------------------------------------- int vtkMultiProcessController::RemoveRMI(unsigned long id) { vtkMultiProcessControllerRMI *rmi = NULL; this->RMIs->InitTraversal(); while ( (rmi = (vtkMultiProcessControllerRMI*)(this->RMIs->GetNextItemAsObject())) ) { if (rmi->Id == id) { this->RMIs->RemoveItem(rmi); return 1; } } return 0; } //---------------------------------------------------------------------------- unsigned long vtkMultiProcessController::AddRMI(vtkRMIFunctionType f, void *localArg, int tag) { vtkMultiProcessControllerRMI *rmi = vtkMultiProcessControllerRMI::New(); // Remove any previously registered RMI handler for the tag. this->RemoveFirstRMI(tag); rmi->Tag = tag; rmi->Function = f; rmi->LocalArgument = localArg; rmi->Id = this->RMICount; this->RMICount++; this->RMIs->AddItem(rmi); rmi->Delete(); return rmi->Id; } //---------------------------------------------------------------------------- void vtkMultiProcessController::TriggerRMIOnAllChildren( void *arg, int argLength, int rmiTag) { int myid = this->GetLocalProcessId(); int childid = 2 * myid + 1; int numProcs = this->GetNumberOfProcesses(); if (numProcs > childid) { this->TriggerRMIInternal(childid, arg, argLength, rmiTag, true); } childid++; if (numProcs > childid) { this->TriggerRMIInternal(childid, arg, argLength, rmiTag, true); } } //---------------------------------------------------------------------------- void vtkMultiProcessController::TriggerRMI(int remoteProcessId, void *arg, int argLength, int rmiTag) { // Deal with sending RMI to ourself here for now. if (remoteProcessId == this->GetLocalProcessId()) { this->ProcessRMI(remoteProcessId, arg, argLength, rmiTag); return; } this->TriggerRMIInternal(remoteProcessId, arg, argLength, rmiTag, false); } //---------------------------------------------------------------------------- void vtkMultiProcessController::TriggerRMIInternal(int remoteProcessId, void* arg, int argLength, int rmiTag, bool propagate) { int triggerMessage[128]; triggerMessage[0] = rmiTag; triggerMessage[1] = argLength; // It is important for the remote process to know what process invoked it. // Multiple processes might try to invoke the method at the same time. // The remote method will know where to get additional args. triggerMessage[2] = this->GetLocalProcessId(); // Pass the propagate flag. triggerMessage[3] = propagate? 1 : 0; // If the message is small, we will try to get the message sent over using a // single Send(), rather than two. This helps speed up communication // significantly, since sending multiple small messages is generally slower // than sending a single large message. if (argLength >= 0 && static_cast<unsigned int>(argLength) < sizeof(int)*(128-4)) { if (argLength > 0) { memcpy(&triggerMessage[4], arg, argLength); } int num_ints = 4 + static_cast<int>(ceil(argLength/static_cast<double>(sizeof(int)))); this->RMICommunicator->Send(triggerMessage, num_ints, remoteProcessId, RMI_TAG); } else { this->RMICommunicator->Send(triggerMessage, 4, remoteProcessId, RMI_TAG); if (argLength > 0) { this->RMICommunicator->Send((char*)arg, argLength, remoteProcessId, RMI_ARG_TAG); } } } //---------------------------------------------------------------------------- void vtkMultiProcessController::TriggerBreakRMIs() { int idx, num; if (this->GetLocalProcessId() != 0) { vtkErrorMacro("Break should be triggered from process 0."); return; } num = this->GetNumberOfProcesses(); for (idx = 1; idx < num; ++idx) { this->TriggerRMI(idx, NULL, 0, BREAK_RMI_TAG); } } //---------------------------------------------------------------------------- int vtkMultiProcessController::ProcessRMIs() { return this->ProcessRMIs(1, 0); } //---------------------------------------------------------------------------- int vtkMultiProcessController::ProcessRMIs(int reportErrors, int dont_loop) { int triggerMessage[128]; unsigned char *arg = NULL; int error = RMI_NO_ERROR; do { if (!this->RMICommunicator->Receive(triggerMessage, 128, ANY_SOURCE, RMI_TAG) || this->RMICommunicator->GetCount() < 4) { if (reportErrors) { vtkErrorMacro("Could not receive RMI trigger message."); } error = RMI_TAG_ERROR; break; } if (triggerMessage[1] > 0) { arg = new unsigned char[triggerMessage[1]]; // If the message length is small enough, the TriggerRMIInternal() call // packs the message data inline. So depending on the message length we // use the inline data or make a second receive to fetch the data. if (static_cast<unsigned int>(triggerMessage[1]) < sizeof(int)*(128-4)) { int num_ints = 4 + ceil(triggerMessage[1]/static_cast<double>(sizeof(int))); if (this->RMICommunicator->GetCount() != num_ints) { if (reportErrors) { vtkErrorMacro("Could not receive the RMI argument in its entirety."); } error= RMI_ARG_ERROR; break; } memcpy(arg, &triggerMessage[4], triggerMessage[1]); } else { if (!this->RMICommunicator->Receive((char*)(arg), triggerMessage[1], triggerMessage[2], RMI_ARG_TAG) || this->RMICommunicator->GetCount() != triggerMessage[1]) { if (reportErrors) { vtkErrorMacro("Could not receive RMI argument."); } error = RMI_ARG_ERROR; break; } } } if (triggerMessage[3] == 1 && this->GetNumberOfProcesses() > 3)//propagate==true { this->TriggerRMIOnAllChildren(arg, triggerMessage[1], triggerMessage[0]); } this->ProcessRMI(triggerMessage[2], arg, triggerMessage[1], triggerMessage[0]); if (arg) { delete [] arg; arg = NULL; } // check for break if (this->BreakFlag) { this->BreakFlag = 0; return error; } } while (!dont_loop); return error; } //---------------------------------------------------------------------------- void vtkMultiProcessController::ProcessRMI(int remoteProcessId, void *arg, int argLength, int rmiTag) { vtkMultiProcessControllerRMI *rmi = NULL; int found = 0; // find the rmi this->RMIs->InitTraversal(); while ( !found && (rmi = (vtkMultiProcessControllerRMI*)(this->RMIs->GetNextItemAsObject())) ) { if (rmi->Tag == rmiTag) { found = 1; } } if ( ! found) { vtkErrorMacro("Process " << this->GetLocalProcessId() << " Could not find RMI with tag " << rmiTag); } else { if ( rmi->Function ) { (*rmi->Function)(rmi->LocalArgument, arg, argLength, remoteProcessId); } } } //============================================================================ // The intent is to give access to a processes controller from a static method. vtkMultiProcessController *VTK_GLOBAL_MULTI_PROCESS_CONTROLLER = NULL; //---------------------------------------------------------------------------- vtkMultiProcessController *vtkMultiProcessController::GetGlobalController() { if (VTK_GLOBAL_MULTI_PROCESS_CONTROLLER == NULL) { return NULL; } return VTK_GLOBAL_MULTI_PROCESS_CONTROLLER->GetLocalController(); } //---------------------------------------------------------------------------- // This can be overridden in the subclass to translate controllers. vtkMultiProcessController *vtkMultiProcessController::GetLocalController() { return VTK_GLOBAL_MULTI_PROCESS_CONTROLLER; } //---------------------------------------------------------------------------- // This can be overridden in the subclass to translate controllers. void vtkMultiProcessController::SetGlobalController( vtkMultiProcessController *controller) { VTK_GLOBAL_MULTI_PROCESS_CONTROLLER = controller; } <|endoftext|>
<commit_before>/* * Copyright 2010-2012 PathScale, 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: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS * IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * guard.cc: Functions for thread-safe static initialisation. * * Static values in C++ can be initialised lazily their first use. This file * contains functions that are used to ensure that two threads attempting to * initialize the same static do not call the constructor twice. This is * important because constructors can have side effects, so calling the * constructor twice may be very bad. * * Statics that require initialisation are protected by a 64-bit value. Any * platform that can do 32-bit atomic test and set operations can use this * value as a low-overhead lock. Because statics (in most sane code) are * accessed far more times than they are initialised, this lock implementation * is heavily optimised towards the case where the static has already been * initialised. */ #include <stdint.h> #include <pthread.h> #include <assert.h> #include "atomic.h" #ifdef __arm__ // ARM ABI - 32-bit guards. /** * Acquires a lock on a guard, returning 0 if the object has already been * initialised, and 1 if it has not. If the object is already constructed then * this function just needs to read a byte from memory and return. */ extern "C" int __cxa_guard_acquire(volatile int32_t *guard_object) { if ((1<<31) == *guard_object) { return 0; } // If we can atomically move the value from 0 -> 1, then this is // uninitialised. if (__sync_bool_compare_and_swap(guard_object, 0, 1)) { return 1; } // If the value is not 0, some other thread was initialising this. Spin // until it's finished. while (__sync_bool_compare_and_swap(guard_object, (1<<31), (1<<31))) { // If the other thread aborted, then we grab the lock if (__sync_bool_compare_and_swap(guard_object, 0, 1)) { return 1; } sched_yield(); } return 0; } /** * Releases the lock without marking the object as initialised. This function * is called if initialising a static causes an exception to be thrown. */ extern "C" void __cxa_guard_abort(int32_t *guard_object) { assert(__sync_bool_compare_and_swap(guard_object, 1, 0)); } /** * Releases the guard and marks the object as initialised. This function is * called after successful initialisation of a static. */ extern "C" void __cxa_guard_release(int32_t *guard_object) { assert(__sync_bool_compare_and_swap(guard_object, 1, (1<<31))); } #else // Itanium ABI: 64-bit guards /** * Returns a pointer to the low 32 bits in a 64-bit value, respecting the * platform's byte order. */ static int32_t *low_32_bits(volatile int64_t *ptr) { int32_t *low= (int32_t*)ptr; // Test if the machine is big endian - constant propagation at compile // time should eliminate this completely. int one = 1; if (*(char*)&one != 1) { low++; } return low; } /** * Acquires a lock on a guard, returning 0 if the object has already been * initialised, and 1 if it has not. If the object is already constructed then * this function just needs to read a byte from memory and return. */ extern "C" int __cxa_guard_acquire(volatile int64_t *guard_object) { char first_byte = (*guard_object) >> 56; if (1 == first_byte) { return 0; } int32_t *lock = low_32_bits(guard_object); // Simple spin lock using the low 32 bits. We assume that concurrent // attempts to initialize statics are very rare, so we don't need to // optimise for the case where we have lots of threads trying to acquire // the lock at the same time. while (!__sync_bool_compare_and_swap_4(lock, 0, 1)) { if (1 == ((*guard_object) >> 56)) { break; } sched_yield(); } // We have to test the guard again, in case another thread has performed // the initialisation while we were trying to acquire the lock. first_byte = (*guard_object) >> 56; return (1 != first_byte); } /** * Releases the lock without marking the object as initialised. This function * is called if initialising a static causes an exception to be thrown. */ extern "C" void __cxa_guard_abort(int64_t *guard_object) { int32_t *lock = low_32_bits(guard_object); ATOMIC_STORE(lock, 0); } /** * Releases the guard and marks the object as initialised. This function is * called after successful initialisation of a static. */ extern "C" void __cxa_guard_release(int64_t *guard_object) { // Set the first byte to 1 // Note: We don't do an atomic load here because getting a stale value // is not a problem in the current implementation. ATOMIC_STORE(guard_object, (*guard_object | ((int64_t)1) << 56)); __cxa_guard_abort(guard_object); } #endif <commit_msg>am 992fe3a8: Fixes for ARM guard initialisation.<commit_after>/* * Copyright 2010-2012 PathScale, 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: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS * IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * guard.cc: Functions for thread-safe static initialisation. * * Static values in C++ can be initialised lazily their first use. This file * contains functions that are used to ensure that two threads attempting to * initialize the same static do not call the constructor twice. This is * important because constructors can have side effects, so calling the * constructor twice may be very bad. * * Statics that require initialisation are protected by a 64-bit value. Any * platform that can do 32-bit atomic test and set operations can use this * value as a low-overhead lock. Because statics (in most sane code) are * accessed far more times than they are initialised, this lock implementation * is heavily optimised towards the case where the static has already been * initialised. */ #include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <pthread.h> #include <assert.h> #include "atomic.h" #ifdef __arm__ // ARM ABI - 32-bit guards. /* * The least significant bit of the guard variable indicates that the object * has been initialised, the most significant bit is used for a spinlock. */ static const uint32_t LOCKED = ((uint32_t)1) << 31; static const uint32_t INITIALISED = 1; /** * Acquires a lock on a guard, returning 0 if the object has already been * initialised, and 1 if it has not. If the object is already constructed then * this function just needs to read a byte from memory and return. */ extern "C" int __cxa_guard_acquire(volatile uint32_t *guard_object) { // Not an atomic read, doesn't establish a happens-before relationship, but // if one is already established and we end up seeing an initialised state // then it's a fast path, otherwise we'll do something more expensive than // this test anyway... if ((INITIALISED == *guard_object)) { return 0; } // Spin trying to do the initialisation while (1) { // Loop trying to move the value of the guard from 0 (not // locked, not initialised) to the locked-uninitialised // position. switch (__sync_val_compare_and_swap(guard_object, 0, LOCKED)) { // If the old value was 0, we succeeded, so continue // initialising case 0: return 1; // If this was already initialised, return and let the caller skip // initialising it again. case INITIALISED: return 0; // If it is locked by another thread, relinquish the CPU and try // again later. case LOCKED: sched_yield(); break; // If it is some other value, then something has gone badly wrong. // Give up. default: fprintf(stderr, "Invalid state detected attempting to lock static initialiser.\n"); abort(); } } __builtin_unreachable(); } /** * Releases the lock without marking the object as initialised. This function * is called if initialising a static causes an exception to be thrown. */ extern "C" void __cxa_guard_abort(uint32_t *guard_object) { __attribute__((unused)) bool reset = __sync_bool_compare_and_swap(guard_object, LOCKED, 0); assert(reset); } /** * Releases the guard and marks the object as initialised. This function is * called after successful initialisation of a static. */ extern "C" void __cxa_guard_release(uint32_t *guard_object) { __attribute__((unused)) bool reset = __sync_bool_compare_and_swap(guard_object, LOCKED, INITIALISED); assert(reset); } #else // Itanium ABI: 64-bit guards /** * Returns a pointer to the low 32 bits in a 64-bit value, respecting the * platform's byte order. */ static int32_t *low_32_bits(volatile int64_t *ptr) { int32_t *low= (int32_t*)ptr; // Test if the machine is big endian - constant propagation at compile // time should eliminate this completely. int one = 1; if (*(char*)&one != 1) { low++; } return low; } /** * Acquires a lock on a guard, returning 0 if the object has already been * initialised, and 1 if it has not. If the object is already constructed then * this function just needs to read a byte from memory and return. */ extern "C" int __cxa_guard_acquire(volatile int64_t *guard_object) { char first_byte = (*guard_object) >> 56; if (1 == first_byte) { return 0; } int32_t *lock = low_32_bits(guard_object); // Simple spin lock using the low 32 bits. We assume that concurrent // attempts to initialize statics are very rare, so we don't need to // optimise for the case where we have lots of threads trying to acquire // the lock at the same time. while (!__sync_bool_compare_and_swap_4(lock, 0, 1)) { if (1 == ((*guard_object) >> 56)) { break; } sched_yield(); } // We have to test the guard again, in case another thread has performed // the initialisation while we were trying to acquire the lock. first_byte = (*guard_object) >> 56; return (1 != first_byte); } /** * Releases the lock without marking the object as initialised. This function * is called if initialising a static causes an exception to be thrown. */ extern "C" void __cxa_guard_abort(int64_t *guard_object) { int32_t *lock = low_32_bits(guard_object); ATOMIC_STORE(lock, 0); } /** * Releases the guard and marks the object as initialised. This function is * called after successful initialisation of a static. */ extern "C" void __cxa_guard_release(int64_t *guard_object) { // Set the first byte to 1 // Note: We don't do an atomic load here because getting a stale value // is not a problem in the current implementation. ATOMIC_STORE(guard_object, (*guard_object | ((int64_t)1) << 56)); __cxa_guard_abort(guard_object); } #endif <|endoftext|>
<commit_before>// Copyright (c) 2013 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 <stdio.h> #include <stdlib.h> #include <map> #include "base/command_line.h" #include "base/environment.h" #include "base/files/file_util.h" #include "base/process/launch.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "tools/gn/commands.h" #include "tools/gn/filesystem_utils.h" #include "tools/gn/input_file.h" #include "tools/gn/parse_tree.h" #include "tools/gn/setup.h" #include "tools/gn/standard_out.h" #include "tools/gn/tokenizer.h" #include "tools/gn/trace.h" #if defined(OS_WIN) #include <windows.h> #include <shellapi.h> #endif namespace commands { namespace { const char kSwitchList[] = "list"; const char kSwitchShort[] = "short"; bool DoesLineBeginWithComment(const base::StringPiece& line) { // Skip whitespace. size_t i = 0; while (i < line.size() && IsAsciiWhitespace(line[i])) i++; return i < line.size() && line[i] == '#'; } // Returns the offset of the beginning of the line identified by |offset|. size_t BackUpToLineBegin(const std::string& data, size_t offset) { // Degenerate case of an empty line. Below we'll try to return the // character after the newline, but that will be incorrect in this case. if (offset == 0 || Tokenizer::IsNewline(data, offset)) return offset; size_t cur = offset; do { cur --; if (Tokenizer::IsNewline(data, cur)) return cur + 1; // Want the first character *after* the newline. } while (cur > 0); return 0; } // Assumes DoesLineBeginWithComment(), this strips the # character from the // beginning and normalizes preceeding whitespace. std::string StripHashFromLine(const base::StringPiece& line) { // Replace the # sign and everything before it with 3 spaces, so that a // normal comment that has a space after the # will be indented 4 spaces // (which makes our formatting come out nicely). If the comment is indented // from there, we want to preserve that indenting. return " " + line.substr(line.find('#') + 1).as_string(); } // Tries to find the comment before the setting of the given value. void GetContextForValue(const Value& value, std::string* location_str, std::string* comment) { Location location = value.origin()->GetRange().begin(); const InputFile* file = location.file(); if (!file) return; *location_str = file->name().value() + ":" + base::IntToString(location.line_number()); const std::string& data = file->contents(); size_t line_off = Tokenizer::ByteOffsetOfNthLine(data, location.line_number()); while (line_off > 1) { line_off -= 2; // Back up to end of previous line. size_t previous_line_offset = BackUpToLineBegin(data, line_off); base::StringPiece line(&data[previous_line_offset], line_off - previous_line_offset + 1); if (!DoesLineBeginWithComment(line)) break; comment->insert(0, StripHashFromLine(line) + "\n"); line_off = previous_line_offset; } } void PrintArgHelp(const base::StringPiece& name, const Value& value) { OutputString(name.as_string(), DECORATION_YELLOW); OutputString(" Default = " + value.ToString(true) + "\n"); if (value.origin()) { std::string location, comment; GetContextForValue(value, &location, &comment); OutputString(" " + location + "\n" + comment); } else { OutputString(" (Internally set)\n"); } } int ListArgs(const std::string& build_dir) { Setup* setup = new Setup; setup->set_check_for_bad_items(false); if (!setup->DoSetup(build_dir, false) || !setup->Run()) return 1; Scope::KeyValueMap build_args; setup->build_settings().build_args().MergeDeclaredArguments(&build_args); // Find all of the arguments we care about. Use a regular map so they're // sorted nicely when we write them out. std::map<base::StringPiece, Value> sorted_args; std::string list_value = base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(kSwitchList); if (list_value.empty()) { // List all values. for (const auto& arg : build_args) sorted_args.insert(arg); } else { // List just the one specified as the parameter to --list. Scope::KeyValueMap::const_iterator found_arg = build_args.find(list_value); if (found_arg == build_args.end()) { Err(Location(), "Unknown build argument.", "You asked for \"" + list_value + "\" which I didn't find in any " "build file\nassociated with this build.").PrintToStdout(); return 1; } sorted_args.insert(*found_arg); } if (base::CommandLine::ForCurrentProcess()->HasSwitch(kSwitchShort)) { // Short key=value output. for (const auto& arg : sorted_args) { OutputString(arg.first.as_string()); OutputString(" = "); OutputString(arg.second.ToString(true)); OutputString("\n"); } return 0; } // Long output. for (const auto& arg : sorted_args) { PrintArgHelp(arg.first, arg.second); OutputString("\n"); } return 0; } #if defined(OS_WIN) bool RunEditor(const base::FilePath& file_to_edit) { SHELLEXECUTEINFO info; memset(&info, 0, sizeof(info)); info.cbSize = sizeof(info); info.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_CLASSNAME; info.lpFile = file_to_edit.value().c_str(); info.nShow = SW_SHOW; info.lpClass = L".txt"; if (!::ShellExecuteEx(&info)) { Err(Location(), "Couldn't run editor.", "Just edit \"" + FilePathToUTF8(file_to_edit) + "\" manually instead.").PrintToStdout(); return false; } if (!info.hProcess) { // Windows re-used an existing process. OutputString("\"" + FilePathToUTF8(file_to_edit) + "\" opened in editor, save it and press <Enter> when done.\n"); getchar(); } else { OutputString("Waiting for editor on \"" + FilePathToUTF8(file_to_edit) + "\"...\n"); ::WaitForSingleObject(info.hProcess, INFINITE); ::CloseHandle(info.hProcess); } return true; } #else // POSIX bool RunEditor(const base::FilePath& file_to_edit) { // Prefer $VISUAL, then $EDITOR, then vi. const char* editor_ptr = getenv("VISUAL"); if (!editor_ptr) editor_ptr = getenv("EDITOR"); if (!editor_ptr) editor_ptr = "vi"; std::string cmd(editor_ptr); cmd.append(" \""); // Its impossible to do this properly since we don't know the user's shell, // but quoting and escaping internal quotes should handle 99.999% of all // cases. std::string escaped_name = file_to_edit.value(); ReplaceSubstringsAfterOffset(&escaped_name, 0, "\"", "\\\""); cmd.append(escaped_name); cmd.push_back('"'); OutputString("Waiting for editor on \"" + file_to_edit.value() + "\"...\n"); return system(cmd.c_str()) == 0; } #endif int EditArgsFile(const std::string& build_dir) { { // Scope the setup. We only use it for some basic state. We'll do the // "real" build below in the gen command. Setup setup; setup.set_check_for_bad_items(false); // Don't fill build arguments. We're about to edit the file which supplies // these in the first place. setup.set_fill_arguments(false); if (!setup.DoSetup(build_dir, true)) return 1; // Ensure the file exists. Need to normalize path separators since on // Windows they can come out as forward slashes here, and that confuses some // of the commands. base::FilePath arg_file = setup.build_settings().GetFullPath(setup.GetBuildArgFile()) .NormalizePathSeparators(); if (!base::PathExists(arg_file)) { std::string argfile_default_contents = "# Build arguments go here. Examples:\n" "# enable_doom_melon = true\n" "# crazy_something = \"absolutely\"\n"; #if defined(OS_WIN) // Use Windows lineendings for this file since it will often open in // Notepad which can't handle Unix ones. ReplaceSubstringsAfterOffset(&argfile_default_contents, 0, "\n", "\r\n"); #endif base::CreateDirectory(arg_file.DirName()); base::WriteFile(arg_file, argfile_default_contents.c_str(), static_cast<int>(argfile_default_contents.size())); } ScopedTrace editor_trace(TraceItem::TRACE_SETUP, "Waiting for editor"); if (!RunEditor(arg_file)) return 1; } // Now do a normal "gen" command. OutputString("Generating files...\n"); std::vector<std::string> gen_commands; gen_commands.push_back(build_dir); return RunGen(gen_commands); } } // namespace extern const char kArgs[] = "args"; extern const char kArgs_HelpShort[] = "args: Display or configure arguments declared by the build."; extern const char kArgs_Help[] = "gn args [arg name]\n" "\n" " See also \"gn help buildargs\" for a more high-level overview of how\n" " build arguments work.\n" "\n" "Usage\n" " gn args <dir_name>\n" " Open the arguments for the given build directory in an editor\n" " (as specified by the EDITOR environment variable). If the given\n" " build directory doesn't exist, it will be created and an empty\n" " args file will be opened in the editor. You would type something\n" " like this into that file:\n" " enable_doom_melon=false\n" " os=\"android\"\n" "\n" " Note: you can edit the build args manually by editing the file\n" " \"args.gn\" in the build directory and then running\n" " \"gn gen <build_dir>\".\n" "\n" " gn args <dir_name> --list[=<exact_arg>] [--short]\n" " Lists all build arguments available in the current configuration,\n" " or, if an exact_arg is specified for the list flag, just that one\n" " build argument.\n" "\n" " The output will list the declaration location, default value, and\n" " comment preceeding the declaration. If --short is specified,\n" " only the names and values will be printed.\n" "\n" " If the dir_name is specified, the build configuration will be\n" " taken from that build directory. The reason this is needed is that\n" " the definition of some arguments is dependent on the build\n" " configuration, so setting some values might add, remove, or change\n" " the default values for other arguments. Specifying your exact\n" " configuration allows the proper arguments to be displayed.\n" "\n" " Instead of specifying the dir_name, you can also use the\n" " command-line flag to specify the build configuration:\n" " --args=<exact list of args to use>\n" "\n" "Examples\n" " gn args out/Debug\n" " Opens an editor with the args for out/Debug.\n" "\n" " gn args out/Debug --list --short\n" " Prints all arguments with their default values for the out/Debug\n" " build.\n" "\n" " gn args out/Debug --list=cpu_arch\n" " Prints information about the \"cpu_arch\" argument for the out/Debug\n" " build.\n" "\n" " gn args --list --args=\"os=\\\"android\\\" enable_doom_melon=true\"\n" " Prints all arguments with the default values for a build with the\n" " given arguments set (which may affect the values of other\n" " arguments).\n"; int RunArgs(const std::vector<std::string>& args) { if (args.size() != 1) { Err(Location(), "Exactly one build dir needed.", "Usage: \"gn args <build_dir>\"\n" "Or see \"gn help args\" for more variants.").PrintToStdout(); return 1; } if (base::CommandLine::ForCurrentProcess()->HasSwitch(kSwitchList)) return ListArgs(args[0]); return EditArgsFile(args[0]); } } // namespace commands <commit_msg>gn: Check GN_EDITOR before EDITOR in environment variables.<commit_after>// Copyright (c) 2013 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 <stdio.h> #include <stdlib.h> #include <map> #include "base/command_line.h" #include "base/environment.h" #include "base/files/file_util.h" #include "base/process/launch.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "tools/gn/commands.h" #include "tools/gn/filesystem_utils.h" #include "tools/gn/input_file.h" #include "tools/gn/parse_tree.h" #include "tools/gn/setup.h" #include "tools/gn/standard_out.h" #include "tools/gn/tokenizer.h" #include "tools/gn/trace.h" #if defined(OS_WIN) #include <windows.h> #include <shellapi.h> #endif namespace commands { namespace { const char kSwitchList[] = "list"; const char kSwitchShort[] = "short"; bool DoesLineBeginWithComment(const base::StringPiece& line) { // Skip whitespace. size_t i = 0; while (i < line.size() && IsAsciiWhitespace(line[i])) i++; return i < line.size() && line[i] == '#'; } // Returns the offset of the beginning of the line identified by |offset|. size_t BackUpToLineBegin(const std::string& data, size_t offset) { // Degenerate case of an empty line. Below we'll try to return the // character after the newline, but that will be incorrect in this case. if (offset == 0 || Tokenizer::IsNewline(data, offset)) return offset; size_t cur = offset; do { cur --; if (Tokenizer::IsNewline(data, cur)) return cur + 1; // Want the first character *after* the newline. } while (cur > 0); return 0; } // Assumes DoesLineBeginWithComment(), this strips the # character from the // beginning and normalizes preceeding whitespace. std::string StripHashFromLine(const base::StringPiece& line) { // Replace the # sign and everything before it with 3 spaces, so that a // normal comment that has a space after the # will be indented 4 spaces // (which makes our formatting come out nicely). If the comment is indented // from there, we want to preserve that indenting. return " " + line.substr(line.find('#') + 1).as_string(); } // Tries to find the comment before the setting of the given value. void GetContextForValue(const Value& value, std::string* location_str, std::string* comment) { Location location = value.origin()->GetRange().begin(); const InputFile* file = location.file(); if (!file) return; *location_str = file->name().value() + ":" + base::IntToString(location.line_number()); const std::string& data = file->contents(); size_t line_off = Tokenizer::ByteOffsetOfNthLine(data, location.line_number()); while (line_off > 1) { line_off -= 2; // Back up to end of previous line. size_t previous_line_offset = BackUpToLineBegin(data, line_off); base::StringPiece line(&data[previous_line_offset], line_off - previous_line_offset + 1); if (!DoesLineBeginWithComment(line)) break; comment->insert(0, StripHashFromLine(line) + "\n"); line_off = previous_line_offset; } } void PrintArgHelp(const base::StringPiece& name, const Value& value) { OutputString(name.as_string(), DECORATION_YELLOW); OutputString(" Default = " + value.ToString(true) + "\n"); if (value.origin()) { std::string location, comment; GetContextForValue(value, &location, &comment); OutputString(" " + location + "\n" + comment); } else { OutputString(" (Internally set)\n"); } } int ListArgs(const std::string& build_dir) { Setup* setup = new Setup; setup->set_check_for_bad_items(false); if (!setup->DoSetup(build_dir, false) || !setup->Run()) return 1; Scope::KeyValueMap build_args; setup->build_settings().build_args().MergeDeclaredArguments(&build_args); // Find all of the arguments we care about. Use a regular map so they're // sorted nicely when we write them out. std::map<base::StringPiece, Value> sorted_args; std::string list_value = base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(kSwitchList); if (list_value.empty()) { // List all values. for (const auto& arg : build_args) sorted_args.insert(arg); } else { // List just the one specified as the parameter to --list. Scope::KeyValueMap::const_iterator found_arg = build_args.find(list_value); if (found_arg == build_args.end()) { Err(Location(), "Unknown build argument.", "You asked for \"" + list_value + "\" which I didn't find in any " "build file\nassociated with this build.").PrintToStdout(); return 1; } sorted_args.insert(*found_arg); } if (base::CommandLine::ForCurrentProcess()->HasSwitch(kSwitchShort)) { // Short key=value output. for (const auto& arg : sorted_args) { OutputString(arg.first.as_string()); OutputString(" = "); OutputString(arg.second.ToString(true)); OutputString("\n"); } return 0; } // Long output. for (const auto& arg : sorted_args) { PrintArgHelp(arg.first, arg.second); OutputString("\n"); } return 0; } #if defined(OS_WIN) bool RunEditor(const base::FilePath& file_to_edit) { SHELLEXECUTEINFO info; memset(&info, 0, sizeof(info)); info.cbSize = sizeof(info); info.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_CLASSNAME; info.lpFile = file_to_edit.value().c_str(); info.nShow = SW_SHOW; info.lpClass = L".txt"; if (!::ShellExecuteEx(&info)) { Err(Location(), "Couldn't run editor.", "Just edit \"" + FilePathToUTF8(file_to_edit) + "\" manually instead.").PrintToStdout(); return false; } if (!info.hProcess) { // Windows re-used an existing process. OutputString("\"" + FilePathToUTF8(file_to_edit) + "\" opened in editor, save it and press <Enter> when done.\n"); getchar(); } else { OutputString("Waiting for editor on \"" + FilePathToUTF8(file_to_edit) + "\"...\n"); ::WaitForSingleObject(info.hProcess, INFINITE); ::CloseHandle(info.hProcess); } return true; } #else // POSIX bool RunEditor(const base::FilePath& file_to_edit) { const char* editor_ptr = getenv("VISUAL"); if (!editor_ptr) editor_ptr = getenv("GN_EDITOR"); if (!editor_ptr) editor_ptr = getenv("EDITOR"); if (!editor_ptr) editor_ptr = "vi"; std::string cmd(editor_ptr); cmd.append(" \""); // Its impossible to do this properly since we don't know the user's shell, // but quoting and escaping internal quotes should handle 99.999% of all // cases. std::string escaped_name = file_to_edit.value(); ReplaceSubstringsAfterOffset(&escaped_name, 0, "\"", "\\\""); cmd.append(escaped_name); cmd.push_back('"'); OutputString("Waiting for editor on \"" + file_to_edit.value() + "\"...\n"); return system(cmd.c_str()) == 0; } #endif int EditArgsFile(const std::string& build_dir) { { // Scope the setup. We only use it for some basic state. We'll do the // "real" build below in the gen command. Setup setup; setup.set_check_for_bad_items(false); // Don't fill build arguments. We're about to edit the file which supplies // these in the first place. setup.set_fill_arguments(false); if (!setup.DoSetup(build_dir, true)) return 1; // Ensure the file exists. Need to normalize path separators since on // Windows they can come out as forward slashes here, and that confuses some // of the commands. base::FilePath arg_file = setup.build_settings().GetFullPath(setup.GetBuildArgFile()) .NormalizePathSeparators(); if (!base::PathExists(arg_file)) { std::string argfile_default_contents = "# Build arguments go here. Examples:\n" "# enable_doom_melon = true\n" "# crazy_something = \"absolutely\"\n"; #if defined(OS_WIN) // Use Windows lineendings for this file since it will often open in // Notepad which can't handle Unix ones. ReplaceSubstringsAfterOffset(&argfile_default_contents, 0, "\n", "\r\n"); #endif base::CreateDirectory(arg_file.DirName()); base::WriteFile(arg_file, argfile_default_contents.c_str(), static_cast<int>(argfile_default_contents.size())); } ScopedTrace editor_trace(TraceItem::TRACE_SETUP, "Waiting for editor"); if (!RunEditor(arg_file)) return 1; } // Now do a normal "gen" command. OutputString("Generating files...\n"); std::vector<std::string> gen_commands; gen_commands.push_back(build_dir); return RunGen(gen_commands); } } // namespace extern const char kArgs[] = "args"; extern const char kArgs_HelpShort[] = "args: Display or configure arguments declared by the build."; extern const char kArgs_Help[] = "gn args [arg name]\n" "\n" " See also \"gn help buildargs\" for a more high-level overview of how\n" " build arguments work.\n" "\n" "Usage\n" " gn args <dir_name>\n" " Open the arguments for the given build directory in an editor\n" " (as specified by the EDITOR environment variable). If the given\n" " build directory doesn't exist, it will be created and an empty\n" " args file will be opened in the editor. You would type something\n" " like this into that file:\n" " enable_doom_melon=false\n" " os=\"android\"\n" "\n" " Note: you can edit the build args manually by editing the file\n" " \"args.gn\" in the build directory and then running\n" " \"gn gen <build_dir>\".\n" "\n" " gn args <dir_name> --list[=<exact_arg>] [--short]\n" " Lists all build arguments available in the current configuration,\n" " or, if an exact_arg is specified for the list flag, just that one\n" " build argument.\n" "\n" " The output will list the declaration location, default value, and\n" " comment preceeding the declaration. If --short is specified,\n" " only the names and values will be printed.\n" "\n" " If the dir_name is specified, the build configuration will be\n" " taken from that build directory. The reason this is needed is that\n" " the definition of some arguments is dependent on the build\n" " configuration, so setting some values might add, remove, or change\n" " the default values for other arguments. Specifying your exact\n" " configuration allows the proper arguments to be displayed.\n" "\n" " Instead of specifying the dir_name, you can also use the\n" " command-line flag to specify the build configuration:\n" " --args=<exact list of args to use>\n" "\n" "Examples\n" " gn args out/Debug\n" " Opens an editor with the args for out/Debug.\n" "\n" " gn args out/Debug --list --short\n" " Prints all arguments with their default values for the out/Debug\n" " build.\n" "\n" " gn args out/Debug --list=cpu_arch\n" " Prints information about the \"cpu_arch\" argument for the out/Debug\n" " build.\n" "\n" " gn args --list --args=\"os=\\\"android\\\" enable_doom_melon=true\"\n" " Prints all arguments with the default values for a build with the\n" " given arguments set (which may affect the values of other\n" " arguments).\n"; int RunArgs(const std::vector<std::string>& args) { if (args.size() != 1) { Err(Location(), "Exactly one build dir needed.", "Usage: \"gn args <build_dir>\"\n" "Or see \"gn help args\" for more variants.").PrintToStdout(); return 1; } if (base::CommandLine::ForCurrentProcess()->HasSwitch(kSwitchList)) return ListArgs(args[0]); return EditArgsFile(args[0]); } } // namespace commands <|endoftext|>
<commit_before>#include "otc/otcli.h" #include "otc/util.h" using namespace otc; typedef otc::RootedTreeNode<RTSplits> Node_t; typedef RTreeOttIDMapping<RTSplits> RootedTreeForNodeType; typedef otc::RootedTree<RTSplits, RootedTreeForNodeType> Tree_t; bool processNextTree(OTCLI & otCLI, std::unique_ptr<Tree_t> tree); extern const char * badNTreesMessage; const char * badNTreesMessage = "Expecting only 1 tree to prune\n"; struct SubtreePrunerState { std::unique_ptr<Tree_t> toPrune; std::set<long> designators; bool emitParent; int numErrors; SubtreePrunerState() :toPrune(nullptr), emitParent(false), numErrors(0) { } void summarize(OTCLI &otCLI) { if (toPrune == nullptr) { otCLI.err << badNTreesMessage; numErrors = 1; return; } if (designators.empty()) { otCLI.err << "Expecting a -n or -p arg to specify the IDs whose MRCA defines the subtree"; numErrors = 1; return; } const Node_t * mrca = findMRCAFromIDSet(*toPrune, designators, -1); if (mrca == nullptr) { otCLI.err << "MRCA could not be found\n"; numErrors = 1; return; } const Node_t * toEmit = (emitParent ? mrca->getParent() : mrca); if (toEmit == nullptr) { otCLI.err << "MRCA had no parent\n"; numErrors = 1; return; } writeNewick<Node_t>(otCLI.out, toEmit); otCLI.out << ";\n"; } }; inline bool processNextTree(OTCLI & otCLI, std::unique_ptr<Tree_t> tree) { SubtreePrunerState * ctsp = static_cast<SubtreePrunerState *>(otCLI.blob); assert(ctsp != nullptr); assert(tree != nullptr); if (ctsp->toPrune == nullptr) { ctsp->toPrune = std::move(tree); } else { otCLI.err << badNTreesMessage; return false; } return true; } bool handleNodeFlag(OTCLI & otCLI, const std::string &nextArg); bool handleParentFlag(OTCLI & otCLI, const std::string &nextArg); bool handleNodeFlag(OTCLI & otCLI, const std::string &nextArg) { SubtreePrunerState * fusp = static_cast<SubtreePrunerState *>(otCLI.blob); assert(fusp != nullptr); assert(!nextArg.empty()); fusp->designators = parseDelimSeparatedIDs(nextArg, ','); return true; } bool handleParentFlag(OTCLI & otCLI, const std::string &nextArg) { if (!handleNodeFlag(otCLI, nextArg)) { return false; } SubtreePrunerState * fusp = static_cast<SubtreePrunerState *>(otCLI.blob); assert(fusp != nullptr); fusp->emitParent = true; return true; } int main(int argc, char *argv[]) { OTCLI otCLI("otc-prune-to-subtree", "takes a -p or -n argument followed by one filepath to a newick. Writes the specified subtree to standard output stream.", "-n5315,3512 some.tre"); SubtreePrunerState cts; otCLI.blob = static_cast<void *>(&cts); otCLI.addFlag('p', "ARG=a comma separated list of OTT numbers. The parent of the MRCA of the IDs will be printed.", handleParentFlag, true); otCLI.addFlag('n', "ARG=a comma separated list of OTT numbers. The MRCA of the IDs will be printed.", handleNodeFlag, true); auto rc = treeProcessingMain<Tree_t>(otCLI, argc, argv, processNextTree, nullptr, 1); if (rc == 0) { cts.summarize(otCLI); return cts.numErrors; } return rc; } <commit_msg>added -c and -s flags to emit children newicks and sibling newicks<commit_after>#include "otc/otcli.h" #include "otc/util.h" using namespace otc; typedef otc::RootedTreeNode<RTSplits> Node_t; typedef RTreeOttIDMapping<RTSplits> RootedTreeForNodeType; typedef otc::RootedTree<RTSplits, RootedTreeForNodeType> Tree_t; bool processNextTree(OTCLI & otCLI, std::unique_ptr<Tree_t> tree); extern const char * badNTreesMessage; const char * badNTreesMessage = "Expecting only 1 tree to prune\n"; struct SubtreePrunerState { std::unique_ptr<Tree_t> toPrune; std::set<long> designators; bool emitParent; bool emitChildren; bool emitSiblings; int numErrors; SubtreePrunerState() :toPrune(nullptr), emitParent(false), emitChildren(false), emitSiblings(false), numErrors(0) { } void summarize(OTCLI &otCLI) { if (toPrune == nullptr) { otCLI.err << badNTreesMessage; numErrors = 1; return; } if (designators.empty()) { otCLI.err << "Expecting a -n or -p arg to specify the IDs whose MRCA defines the subtree"; numErrors = 1; return; } const Node_t * mrca = findMRCAFromIDSet(*toPrune, designators, -1); if (mrca == nullptr) { otCLI.err << "MRCA could not be found\n"; numErrors = 1; return; } const Node_t * toEmit = ((emitParent || emitSiblings) ? mrca->getParent() : mrca); if (toEmit == nullptr) { otCLI.err << "MRCA had no parent\n"; numErrors = 1; return; } if ((!emitSiblings) && (!emitChildren)) { writeNewick<Node_t>(otCLI.out, toEmit); otCLI.out << ";\n"; } else { for (auto c : iter_child_const(*toEmit)) { if (emitSiblings && c == mrca) { continue; } writeNewick<Node_t>(otCLI.out, c); otCLI.out << ";\n"; } } } }; inline bool processNextTree(OTCLI & otCLI, std::unique_ptr<Tree_t> tree) { SubtreePrunerState * ctsp = static_cast<SubtreePrunerState *>(otCLI.blob); assert(ctsp != nullptr); assert(tree != nullptr); if (ctsp->toPrune == nullptr) { ctsp->toPrune = std::move(tree); } else { otCLI.err << badNTreesMessage; return false; } return true; } bool handleNodeFlag(OTCLI & otCLI, const std::string &nextArg); bool handleParentFlag(OTCLI & otCLI, const std::string &nextArg); bool handleChildrenFlag(OTCLI & otCLI, const std::string &nextArg); bool handleSiblingsFlag(OTCLI & otCLI, const std::string &nextArg); bool handleNodeFlag(OTCLI & otCLI, const std::string &nextArg) { SubtreePrunerState * fusp = static_cast<SubtreePrunerState *>(otCLI.blob); assert(fusp != nullptr); assert(!nextArg.empty()); if (!fusp->designators.empty()) { otCLI.err << "Expecting only 1 flag listing designators.\n"; return false; } fusp->designators = parseDelimSeparatedIDs(nextArg, ','); return true; } bool handleParentFlag(OTCLI & otCLI, const std::string &nextArg) { if (!handleNodeFlag(otCLI, nextArg)) { return false; } SubtreePrunerState * fusp = static_cast<SubtreePrunerState *>(otCLI.blob); assert(fusp != nullptr); fusp->emitParent = true; return true; } bool handleChildrenFlag(OTCLI & otCLI, const std::string &nextArg) { if (!handleNodeFlag(otCLI, nextArg)) { return false; } SubtreePrunerState * fusp = static_cast<SubtreePrunerState *>(otCLI.blob); assert(fusp != nullptr); fusp->emitChildren = true; return true; } bool handleSiblingsFlag(OTCLI & otCLI, const std::string &nextArg) { if (!handleNodeFlag(otCLI, nextArg)) { return false; } SubtreePrunerState * fusp = static_cast<SubtreePrunerState *>(otCLI.blob); assert(fusp != nullptr); fusp->emitSiblings = true; return true; } int main(int argc, char *argv[]) { OTCLI otCLI("otc-prune-to-subtree", "takes a -p or -n argument followed by one filepath to a newick. Writes the specified subtree to standard output stream.", "-n5315,3512 some.tre"); SubtreePrunerState cts; otCLI.blob = static_cast<void *>(&cts); otCLI.addFlag('p', "ARG=a comma separated list of OTT numbers. The parent of the MRCA of the IDs will be printed.", handleParentFlag, true); otCLI.addFlag('n', "ARG=a comma separated list of OTT numbers. The MRCA of the IDs will be printed.", handleNodeFlag, true); otCLI.addFlag('s', "ARG=a comma separated list of OTT numbers. The siblings of the MRCA of the IDs will be printed.", handleSiblingsFlag, true); otCLI.addFlag('c', "ARG=a comma separated list of OTT numbers. The children of the MRCA of the IDs will be printed.", handleChildrenFlag, true); auto rc = treeProcessingMain<Tree_t>(otCLI, argc, argv, processNextTree, nullptr, 1); if (rc == 0) { cts.summarize(otCLI); return cts.numErrors; } return rc; } <|endoftext|>
<commit_before>/* * * MIT License * * Copyright (c) 2016-2017 The Cats Project * * 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. * */ #ifndef CATS_CORECAT_STREAM_HPP #define CATS_CORECAT_STREAM_HPP #include <cstdint> #include <cstdlib> #include <algorithm> #include <iostream> #include <memory> #include <system_error> #include <type_traits> namespace Cats { namespace Corecat { namespace Stream { template <typename T = char> struct Stream { using CharType = T; enum class SeekOrigin { Begin, Current, End }; virtual bool isReadable() const { return false; }; virtual T read() { T data; return read(&data, 1) ? data : 0; } virtual std::size_t read(T* /*data*/, std::size_t /*count*/) { throw std::runtime_error("not implemented"); } virtual T peek() { T data; return peek(&data, 1) ? data : 0; } virtual std::size_t peek(T* /*data*/, std::size_t /*count*/) { throw std::runtime_error("not implemented"); } virtual bool isWriteable() const { return false; }; virtual void write(T data) { write(&data, 1); } virtual void write(const T* /*data*/, std::size_t /*count*/) { throw std::runtime_error("not implemented"); } virtual void flush() { throw std::runtime_error("not implemented"); } virtual bool isSeekable() const { return false; }; virtual std::intmax_t seek(std::intmax_t /*offset*/, SeekOrigin /*method*/) { throw std::runtime_error("not implemented"); } virtual std::intmax_t getPosition() { throw std::runtime_error("not implemented"); } }; template <typename T> class StreamBuffer { private: T* data; T* start; T* end; std::size_t size; public: StreamBuffer(std::size_t size_ = 4096) : data(new T[size_]), start(data), end(data), size(size_) {} void read(Stream<T>& stream) { std::size_t count = stream.read(end, data + size - end); end += count; } std::size_t read(T* data_, std::size_t count) noexcept { count = std::min(count, end - start); std::copy(start, start + count, data_); start += count; if(start == end) start = end = data; return count; } void reset() noexcept { start = data; end = data; } std::size_t getAvail() const noexcept { return end - start; } }; template <typename T> class BufferedStream : public Stream<T> { private: Stream<T>* stream; StreamBuffer<T> readBuffer; StreamBuffer<T> writeBuffer; public: BufferedStream(Stream<T>& stream_) : stream(&stream), readBuffer(), writeBuffer() {} bool isReadable() const override { return stream->isReadable(); }; bool isWriteable() const override { return stream->isWriteable(); }; bool isSeekable() const override { return stream->isSeekable(); }; Stream<T>& getStream() { return *stream; } void setStream(Stream<T>& stream_) { stream = &stream_; } }; template <typename T, typename = void> class WrapperStream; template <> class WrapperStream<std::FILE*> : public Stream<> { private: std::FILE* file; public: WrapperStream(std::FILE* file_) : file(file_) {} bool isReadable() const override { return true; }; std::size_t read(char* data, std::size_t count) override { std::size_t ret = std::fread(data, 1, count, file); return ret; } bool isWriteable() const override { return true; }; void write(const char* data, std::size_t count) override { std::fwrite(data, 1, count, file); } void flush() override { std::fflush(file); }; bool isSeekable() const override { return true; }; std::intmax_t seek(std::intmax_t offset, SeekOrigin origin) override { int ori; switch(origin) { case SeekOrigin::Begin: ori = SEEK_SET; break; case SeekOrigin::Current: ori = SEEK_CUR; break; case SeekOrigin::End: ori = SEEK_END; break; default: throw std::runtime_error("invalid origin"); } std::fseek(file, offset, ori); return getPosition(); } std::intmax_t getPosition() override { return std::ftell(file); } }; template <typename T> class WrapperStream<T, typename std::enable_if<std::is_base_of<std::istream, T>::value && !std::is_base_of<std::ostream, T>::value>::type> : public Stream<> { private: std::istream* is; public: WrapperStream(std::istream& is_) : is(&is_) {} bool isReadable() const override { return true; }; std::size_t read(char* data, std::size_t count) override { is->read(data, count); return is->gcount(); } bool isSeekable() const override { return true; }; std::intmax_t seek(std::intmax_t offset, SeekOrigin origin) override { std::ios_base::seekdir dir; switch(origin) { case SeekOrigin::Begin: dir = std::ios_base::beg; break; case SeekOrigin::Current: dir = std::ios_base::cur; break; case SeekOrigin::End: dir = std::ios_base::end; break; default: throw std::runtime_error("invalid origin"); } is->seekg(offset, dir); return getPosition(); } std::intmax_t getPosition() override { return is->tellg(); } }; template <typename T> class WrapperStream<T, typename std::enable_if<std::is_base_of<std::ostream, T>::value && !std::is_base_of<std::istream, T>::value>::type> : public Stream<> { private: std::ostream* os; public: WrapperStream(std::ostream& os_) : os(&os_) {} bool isWriteable() const override { return true; }; void write(const char* data, std::size_t count) override { os->write(data, count); } void flush() override { os->flush(); }; bool isSeekable() const override { return true; }; std::intmax_t seek(std::intmax_t offset, SeekOrigin origin) override { std::ios_base::seekdir dir; switch(origin) { case SeekOrigin::Begin: dir = std::ios_base::beg; break; case SeekOrigin::Current: dir = std::ios_base::cur; break; case SeekOrigin::End: dir = std::ios_base::end; break; default: throw std::runtime_error("invalid origin"); } os->seekp(offset, dir); return getPosition(); } std::intmax_t getPosition() override { return os->tellp(); } }; template <typename T> class WrapperStream<T, typename std::enable_if<std::is_base_of<std::iostream, T>::value>::type> : public Stream<> { private: std::iostream* ios; public: WrapperStream(std::iostream& ios_) : ios(&ios_) {} bool isReadable() const override { return true; }; std::size_t read(char* data, std::size_t count) override { ios->read(data, count); return ios->gcount(); } bool isWriteable() const override { return true; }; void write(const char* data, std::size_t count) override { ios->write(data, count); } void flush() override { ios->flush(); }; bool isSeekable() const override { return true; }; std::intmax_t seek(std::intmax_t offset, SeekOrigin origin) override { std::ios_base::seekdir dir; switch(origin) { case SeekOrigin::Begin: dir = std::ios_base::beg; break; case SeekOrigin::Current: dir = std::ios_base::cur; break; case SeekOrigin::End: dir = std::ios_base::end; break; default: throw std::runtime_error("invalid origin"); } return ios->rdbuf()->pubseekoff(static_cast<std::iostream::pos_type>(offset), dir); } std::intmax_t getPosition() override { return ios->tellg(); } }; template <typename T> inline WrapperStream<T> createWrapperStream(T& t) { return WrapperStream<T>(t); } } } } #endif <commit_msg>remove StreamBuffer<commit_after>/* * * MIT License * * Copyright (c) 2016-2017 The Cats Project * * 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. * */ #ifndef CATS_CORECAT_STREAM_HPP #define CATS_CORECAT_STREAM_HPP #include <cstdint> #include <cstdlib> #include <algorithm> #include <iostream> #include <memory> #include <system_error> #include <type_traits> namespace Cats { namespace Corecat { namespace Stream { template <typename T = char> struct Stream { using CharType = T; enum class SeekOrigin { Begin, Current, End }; virtual bool isReadable() const { return false; }; virtual T read() { T data; return read(&data, 1) ? data : 0; } virtual std::size_t read(T* /*data*/, std::size_t /*count*/) { throw std::runtime_error("not implemented"); } virtual T peek() { T data; return peek(&data, 1) ? data : 0; } virtual std::size_t peek(T* /*data*/, std::size_t /*count*/) { throw std::runtime_error("not implemented"); } virtual bool isWriteable() const { return false; }; virtual void write(T data) { write(&data, 1); } virtual void write(const T* /*data*/, std::size_t /*count*/) { throw std::runtime_error("not implemented"); } virtual void flush() { throw std::runtime_error("not implemented"); } virtual bool isSeekable() const { return false; }; virtual std::intmax_t seek(std::intmax_t /*offset*/, SeekOrigin /*method*/) { throw std::runtime_error("not implemented"); } virtual std::intmax_t getPosition() { throw std::runtime_error("not implemented"); } }; template <typename T> class BufferedStream : public Stream<T> { private: Stream<T>* stream; std::size_t bufferSize; T* readBufferData; T* readBufferStart; T* readBufferEnd; T* writeBufferData; T* writeBufferEnd; private: std::size_t readToBuffer() { std::size_t res = stream->read(readBufferEnd, readBufferData + bufferSize - readBufferEnd); return res; } std::size_t readFromBuffer(T* data, std::size_t count) noexcept { std::copy(readBufferStart, readBufferStart + count, data); readBufferStart += count; if(readBufferStart == readBufferEnd) readBufferStart = readBufferEnd = readBufferData; return count; } public: BufferedStream(Stream<T>& stream_, std::size_t bufferSize_ = 4096) : stream(&stream_), bufferSize(bufferSize_), readBufferData(), readBufferStart(), readBufferEnd(), writeBufferData(), writeBufferEnd() {} ~BufferedStream() { if(readBufferData) { delete[] readBufferData; readBufferData = nullptr; } if(writeBufferData) { delete[] writeBufferData; writeBufferData = nullptr; } } bool isReadable() const override { return stream->isReadable(); }; std::size_t read(char* data, std::size_t count) override { if(!readBufferData) { readBufferData = new T[bufferSize]; readBufferStart = readBufferEnd = readBufferData; } } bool isWriteable() const override { return stream->isWriteable(); }; bool isSeekable() const override { return stream->isSeekable(); }; Stream<T>& getStream() { return *stream; } void setStream(Stream<T>& stream_) { stream = &stream_; } }; template <typename T, typename = void> class WrapperStream; template <> class WrapperStream<std::FILE*> : public Stream<> { private: std::FILE* file; public: WrapperStream(std::FILE* file_) : file(file_) {} bool isReadable() const override { return true; }; std::size_t read(char* data, std::size_t count) override { std::size_t ret = std::fread(data, 1, count, file); return ret; } bool isWriteable() const override { return true; }; void write(const char* data, std::size_t count) override { std::fwrite(data, 1, count, file); } void flush() override { std::fflush(file); }; bool isSeekable() const override { return true; }; std::intmax_t seek(std::intmax_t offset, SeekOrigin origin) override { int ori; switch(origin) { case SeekOrigin::Begin: ori = SEEK_SET; break; case SeekOrigin::Current: ori = SEEK_CUR; break; case SeekOrigin::End: ori = SEEK_END; break; default: throw std::runtime_error("invalid origin"); } std::fseek(file, offset, ori); return getPosition(); } std::intmax_t getPosition() override { return std::ftell(file); } }; template <typename T> class WrapperStream<T, typename std::enable_if<std::is_base_of<std::istream, T>::value && !std::is_base_of<std::ostream, T>::value>::type> : public Stream<> { private: std::istream* is; public: WrapperStream(std::istream& is_) : is(&is_) {} bool isReadable() const override { return true; }; std::size_t read(char* data, std::size_t count) override { is->read(data, count); return is->gcount(); } bool isSeekable() const override { return true; }; std::intmax_t seek(std::intmax_t offset, SeekOrigin origin) override { std::ios_base::seekdir dir; switch(origin) { case SeekOrigin::Begin: dir = std::ios_base::beg; break; case SeekOrigin::Current: dir = std::ios_base::cur; break; case SeekOrigin::End: dir = std::ios_base::end; break; default: throw std::runtime_error("invalid origin"); } is->seekg(offset, dir); return getPosition(); } std::intmax_t getPosition() override { return is->tellg(); } }; template <typename T> class WrapperStream<T, typename std::enable_if<std::is_base_of<std::ostream, T>::value && !std::is_base_of<std::istream, T>::value>::type> : public Stream<> { private: std::ostream* os; public: WrapperStream(std::ostream& os_) : os(&os_) {} bool isWriteable() const override { return true; }; void write(const char* data, std::size_t count) override { os->write(data, count); } void flush() override { os->flush(); }; bool isSeekable() const override { return true; }; std::intmax_t seek(std::intmax_t offset, SeekOrigin origin) override { std::ios_base::seekdir dir; switch(origin) { case SeekOrigin::Begin: dir = std::ios_base::beg; break; case SeekOrigin::Current: dir = std::ios_base::cur; break; case SeekOrigin::End: dir = std::ios_base::end; break; default: throw std::runtime_error("invalid origin"); } os->seekp(offset, dir); return getPosition(); } std::intmax_t getPosition() override { return os->tellp(); } }; template <typename T> class WrapperStream<T, typename std::enable_if<std::is_base_of<std::iostream, T>::value>::type> : public Stream<> { private: std::iostream* ios; public: WrapperStream(std::iostream& ios_) : ios(&ios_) {} bool isReadable() const override { return true; }; std::size_t read(char* data, std::size_t count) override { ios->read(data, count); return ios->gcount(); } bool isWriteable() const override { return true; }; void write(const char* data, std::size_t count) override { ios->write(data, count); } void flush() override { ios->flush(); }; bool isSeekable() const override { return true; }; std::intmax_t seek(std::intmax_t offset, SeekOrigin origin) override { std::ios_base::seekdir dir; switch(origin) { case SeekOrigin::Begin: dir = std::ios_base::beg; break; case SeekOrigin::Current: dir = std::ios_base::cur; break; case SeekOrigin::End: dir = std::ios_base::end; break; default: throw std::runtime_error("invalid origin"); } return ios->rdbuf()->pubseekoff(static_cast<std::iostream::pos_type>(offset), dir); } std::intmax_t getPosition() override { return ios->tellg(); } }; template <typename T> inline WrapperStream<T> createWrapperStream(T& t) { return WrapperStream<T>(t); } } } } #endif <|endoftext|>
<commit_before>/* * * MIT License * * Copyright (c) 2016-2017 The Cats Project * * 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. * */ #ifndef CATS_CORECAT_STRING_HPP #define CATS_CORECAT_STRING_HPP #include <cstdlib> #include <algorithm> #include <iostream> #include <iterator> #include <string> #include <type_traits> #include "Charset.hpp" namespace Cats { namespace Corecat { template <typename C> class StringViewBase; template <typename C> class StringBase { public: static constexpr std::size_t BUFFER_SIZE = 32; using CharType = typename C::CharType; using CharsetType = C; using Iterator = CharType*; using ConstIterator = const CharType*; using ReverseIterator = std::reverse_iterator<Iterator>; using ConstReverseIterator = std::reverse_iterator<ConstIterator>; using View = StringViewBase<C>; private: union { struct { CharType* data; std::size_t length; std::size_t capacity; }; struct { CharType data[BUFFER_SIZE - 1]; CharType length; } buffer; } storage; private: bool isSmall() const noexcept { return static_cast<std::size_t>(storage.buffer.length) < BUFFER_SIZE; } public: StringBase(const StringBase& src) : StringBase() { append(src); } StringBase(StringBase&& src) noexcept : StringBase() { swap(src); } ~StringBase() noexcept { if(!isSmall()) delete[] storage.data; } StringBase() noexcept { storage.buffer.data[0] = 0; storage.buffer.length = BUFFER_SIZE - 1; } StringBase(CharType ch, std::size_t count = 1) : StringBase() { append(ch, count); } StringBase(const CharType* data_) : StringBase() { append(data_); } StringBase(const CharType* data_, std::size_t length_) : StringBase() { append(data_, length_); } StringBase(const View& sv) : StringBase() { append(sv); } StringBase& operator =(const StringBase& src) { clear(); append(src); return *this; } StringBase& operator =(StringBase&& src) noexcept { swap(src); return *this; } StringBase& operator =(const CharType* data_) { clear(); append(data_); return *this; } StringBase& operator =(const View& sv) { clear(); append(sv); return *this; } StringBase& operator +=(CharType ch) { append(ch); return *this; } StringBase& operator +=(const CharType* data_) { append(data_); return *this; } StringBase& operator +=(const StringBase& str) { append(str); return *this; } StringBase& operator +=(const View& sv) { append(sv); return *this; } friend StringBase operator +(const StringBase& a, CharType b) { StringBase t(a); t += b; return t; } friend StringBase operator +(const StringBase& a, const CharType* b) { StringBase t(a); t += b; return t; } friend StringBase operator +(const StringBase& a, const StringBase& b) { StringBase t(a); t += b; return t; } friend StringBase operator +(const StringBase& a, const View& b) { StringBase t(a); t += b; return t; } friend StringBase operator +(CharType a, const StringBase& b) { StringBase t(a); t += b; return t; } friend StringBase operator +(const CharType* a, const StringBase& b) { StringBase t(a); t += b; return t; } friend StringBase operator +(const View& a, const StringBase& b) { StringBase t(a); t += b; return t; } CharType& operator [](std::size_t index) noexcept { return getData()[index]; }; const CharType& operator [](std::size_t index) const noexcept { return getData()[index]; }; operator View() const noexcept { return { getData(), getLength() }; } friend std::basic_ostream<CharType>& operator <<(std::basic_ostream<CharType>& stream, const StringBase<C>& str) { stream.write(str.getData(), str.getLength()); return stream; } CharType* getData() noexcept { return isSmall() ? storage.buffer.data : storage.data; } const CharType* getData() const noexcept { return const_cast<StringBase*>(this)->getData(); } std::size_t getLength() const noexcept { return isSmall() ? BUFFER_SIZE - storage.buffer.length - 1 : storage.length; } std::size_t getCapacity() const noexcept { return isSmall() ? BUFFER_SIZE - 1 : storage.capacity; } bool isEmpty() const noexcept { return getLength() == 0; } void clear() noexcept { if(isSmall()) { storage.buffer.data[0] = 0; storage.buffer.length = BUFFER_SIZE - 1; } else { storage.data[0] = 0; storage.length = 0; } } void reserve(std::size_t cap) { if(cap > getCapacity()) { auto length = getLength(); auto oldData = getData(); auto newData = new CharType[cap + 1]; std::copy(oldData, oldData + length + 1, newData); storage.data = newData; storage.capacity = cap; if(isSmall()) storage.buffer.length = BUFFER_SIZE; else delete[] oldData; } } StringBase& append(CharType ch, std::size_t count = 1) { auto length = getLength(); reserve(length + count); auto data = getData(); std::fill(data + length, data + length + count, ch); length += count; data[length] = 0; if(isSmall()) storage.buffer.length = BUFFER_SIZE - length - 1; else storage.length = length; return *this; } StringBase& append(const CharType* data_, std::size_t length_) { auto length = getLength(); reserve(length + length_); auto data = getData(); *std::copy(data_, data_ + length_, data + length) = 0; length += length_; if(isSmall()) storage.buffer.length = BUFFER_SIZE - length - 1; else storage.length = length; return *this; } StringBase& append(const CharType* data_) { return append(data_, std::char_traits<CharType>::length(data_)); } StringBase& append(const StringBase& str) { return append(str.getData(), str.getLength()); } StringBase& append(const View& sv) { return append(sv.getData(), sv.getLength()); } void swap(StringBase& src) noexcept { std::swap(storage, src.storage); } Iterator begin() noexcept { return getData(); } ConstIterator begin() const noexcept { return getData(); } ConstIterator cbegin() const noexcept { return getData(); } Iterator end() noexcept { return getData() + getLength(); } ConstIterator end() const noexcept { return getData() + getLength(); } ConstIterator cend() const noexcept { return getData() + getLength(); } ReverseIterator rbegin() noexcept { return ReverseIterator(end()); } ConstReverseIterator rbegin() const noexcept { return ConstReverseIterator(end()); } ConstReverseIterator crbegin() const noexcept { return ConstReverseIterator(cend()); } ReverseIterator rend() noexcept { return ReverseIterator(begin()); } ConstReverseIterator rend() const noexcept { return ConstReverseIterator(begin()); } ConstReverseIterator crend() const noexcept { return ConstReverseIterator(cbegin()); } }; using String = StringBase<Charset::UTF8<>>; using String16 = StringBase<Charset::UTF16<>>; using String32 = StringBase<Charset::UTF32<>>; template <typename C> class StringViewBase { public: using CharType = typename C::CharType; using CharsetType = C; using Iterator = const CharType*; using ReverseIterator = std::reverse_iterator<Iterator>; private: const CharType* data; std::size_t length; public: StringViewBase(const StringViewBase& src) = default; ~StringViewBase() = default; StringViewBase() : data(""), length() {} StringViewBase(const CharType* data_) : data(data_), length(std::char_traits<CharType>::length(data_)) {} StringViewBase(const CharType* data_, std::size_t length_) : data(data_), length(length_) {} StringViewBase& operator =(const StringViewBase& src) = default; const CharType& operator [](std::size_t index) const noexcept { return data[index]; } bool operator ==(StringViewBase sv) const noexcept { if(length != sv.length) return false; const CharType* p = data; const CharType* q = sv.data; for(const CharType* end = data + length; p != end; ++p, ++q) if(*p != *q) return false; return true; } bool operator !=(StringViewBase sv) const noexcept { return !(*this == sv); } friend std::basic_ostream<CharType>& operator <<(std::basic_ostream<CharType>& stream, const StringViewBase& sv) { stream.write(sv.getData(), sv.getLength()); return stream; } const CharType* getData() const noexcept { return data; } void setData(const CharType* data_) noexcept { data = data_; } std::size_t getLength() const noexcept { return length; } void setLength(std::size_t length_) noexcept { length = length_; } Iterator begin() const noexcept { return getData(); } Iterator end() const noexcept { return getData() + getLength(); } ReverseIterator rbegin() const noexcept { return ReverseIterator(end()); } ReverseIterator rend() const noexcept { return ReverseIterator(begin()); } }; using StringView = StringViewBase<Charset::UTF8<>>; using StringView16 = StringViewBase<Charset::UTF16<>>; using StringView32 = StringViewBase<Charset::UTF32<>>; } } #endif <commit_msg>Update String<commit_after>/* * * MIT License * * Copyright (c) 2016-2017 The Cats Project * * 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. * */ #ifndef CATS_CORECAT_STRING_HPP #define CATS_CORECAT_STRING_HPP #include <cstdlib> #include <algorithm> #include <iostream> #include <iterator> #include <string> #include <type_traits> #include "Charset.hpp" namespace Cats { namespace Corecat { template <typename C> class StringViewBase; template <typename C> class StringBase { public: static constexpr std::size_t BUFFER_SIZE = 32; using CharType = typename C::CharType; using CharsetType = C; using Iterator = CharType*; using ConstIterator = const CharType*; using ReverseIterator = std::reverse_iterator<Iterator>; using ConstReverseIterator = std::reverse_iterator<ConstIterator>; using View = StringViewBase<C>; private: union { struct { CharType* data; std::size_t length; std::size_t capacity; }; struct { CharType data[BUFFER_SIZE - 1]; CharType length; } buffer; } storage; private: bool isSmall() const noexcept { return static_cast<std::size_t>(storage.buffer.length) < BUFFER_SIZE; } public: StringBase(const StringBase& src) : StringBase() { append(src); } StringBase(StringBase&& src) noexcept : StringBase() { swap(src); } ~StringBase() noexcept { if(!isSmall()) delete[] storage.data; } StringBase() noexcept { storage.buffer.data[0] = 0; storage.buffer.length = BUFFER_SIZE - 1; } StringBase(CharType ch, std::size_t count = 1) : StringBase() { append(ch, count); } StringBase(const CharType* data_) : StringBase() { append(data_); } StringBase(const CharType* data_, std::size_t length_) : StringBase() { append(data_, length_); } StringBase(const View& sv) : StringBase() { append(sv); } StringBase& operator =(const StringBase& src) { clear(); append(src); return *this; } StringBase& operator =(StringBase&& src) noexcept { swap(src); return *this; } StringBase& operator =(const CharType* data_) { clear(); append(data_); return *this; } StringBase& operator =(const View& sv) { clear(); append(sv); return *this; } StringBase& operator +=(CharType ch) { append(ch); return *this; } StringBase& operator +=(const CharType* data_) { append(data_); return *this; } StringBase& operator +=(const StringBase& str) { append(str); return *this; } StringBase& operator +=(const View& sv) { append(sv); return *this; } friend StringBase operator +(const StringBase& a, CharType b) { StringBase t(a); t += b; return t; } friend StringBase operator +(const StringBase& a, const CharType* b) { StringBase t(a); t += b; return t; } friend StringBase operator +(const StringBase& a, const StringBase& b) { StringBase t(a); t += b; return t; } friend StringBase operator +(const StringBase& a, const View& b) { StringBase t(a); t += b; return t; } friend StringBase operator +(CharType a, const StringBase& b) { StringBase t(a); t += b; return t; } friend StringBase operator +(const CharType* a, const StringBase& b) { StringBase t(a); t += b; return t; } friend StringBase operator +(const View& a, const StringBase& b) { StringBase t(a); t += b; return t; } CharType& operator [](std::size_t index) noexcept { return getData()[index]; }; const CharType& operator [](std::size_t index) const noexcept { return getData()[index]; }; operator View() const noexcept { return getView(); } friend std::basic_ostream<CharType>& operator <<(std::basic_ostream<CharType>& stream, const StringBase<C>& str) { stream.write(str.getData(), str.getLength()); return stream; } CharType* getData() noexcept { return isSmall() ? storage.buffer.data : storage.data; } const CharType* getData() const noexcept { return const_cast<StringBase*>(this)->getData(); } std::size_t getLength() const noexcept { return isSmall() ? BUFFER_SIZE - storage.buffer.length - 1 : storage.length; } std::size_t getCapacity() const noexcept { return isSmall() ? BUFFER_SIZE - 1 : storage.capacity; } View getView() const noexcept { return View(getData(), getLength()); } bool isEmpty() const noexcept { return getLength() == 0; } void clear() noexcept { if(isSmall()) { storage.buffer.data[0] = 0; storage.buffer.length = BUFFER_SIZE - 1; } else { storage.data[0] = 0; storage.length = 0; } } void reserve(std::size_t cap) { if(cap > getCapacity()) { auto length = getLength(); auto oldData = getData(); auto newData = new CharType[cap + 1]; std::copy(oldData, oldData + length + 1, newData); storage.data = newData; storage.length = length; storage.capacity = cap; if(isSmall()) storage.buffer.length = BUFFER_SIZE; else delete[] oldData; } } StringBase& append(CharType ch, std::size_t count = 1) { auto length = getLength(); reserve(length + count); auto data = getData(); std::fill(data + length, data + length + count, ch); length += count; data[length] = 0; if(isSmall()) storage.buffer.length = BUFFER_SIZE - length - 1; else storage.length = length; return *this; } StringBase& append(const CharType* data_, std::size_t length_) { auto length = getLength(); reserve(length + length_); auto data = getData(); *std::copy(data_, data_ + length_, data + length) = 0; length += length_; if(isSmall()) storage.buffer.length = BUFFER_SIZE - length - 1; else storage.length = length; return *this; } StringBase& append(const CharType* data_) { return append(data_, std::char_traits<CharType>::length(data_)); } StringBase& append(const StringBase& str) { return append(str.getData(), str.getLength()); } StringBase& append(const View& sv) { return append(sv.getData(), sv.getLength()); } void swap(StringBase& src) noexcept { std::swap(storage, src.storage); } StringBase repeat(std::size_t count) const { return getView().repeat(count); } View substr(std::size_t pos) const noexcept { return getView().substr(pos); } View substr(std::size_t pos, std::size_t count) const noexcept { return getView().substr(pos, count); } Iterator begin() noexcept { return getData(); } ConstIterator begin() const noexcept { return getData(); } ConstIterator cbegin() const noexcept { return getData(); } Iterator end() noexcept { return getData() + getLength(); } ConstIterator end() const noexcept { return getData() + getLength(); } ConstIterator cend() const noexcept { return getData() + getLength(); } ReverseIterator rbegin() noexcept { return ReverseIterator(end()); } ConstReverseIterator rbegin() const noexcept { return ConstReverseIterator(end()); } ConstReverseIterator crbegin() const noexcept { return ConstReverseIterator(cend()); } ReverseIterator rend() noexcept { return ReverseIterator(begin()); } ConstReverseIterator rend() const noexcept { return ConstReverseIterator(begin()); } ConstReverseIterator crend() const noexcept { return ConstReverseIterator(cbegin()); } }; using String = StringBase<Charset::UTF8<>>; using String16 = StringBase<Charset::UTF16<>>; using String32 = StringBase<Charset::UTF32<>>; template <typename C> class StringViewBase { public: using CharType = typename C::CharType; using CharsetType = C; using Iterator = const CharType*; using ReverseIterator = std::reverse_iterator<Iterator>; using String = StringBase<C>; private: const CharType* data; std::size_t length; public: StringViewBase(const StringViewBase& src) = default; ~StringViewBase() = default; StringViewBase() : data(""), length() {} StringViewBase(const CharType* data_) : data(data_), length(std::char_traits<CharType>::length(data_)) {} StringViewBase(const CharType* data_, std::size_t length_) : data(data_), length(length_) {} StringViewBase& operator =(const StringViewBase& src) = default; const CharType& operator [](std::size_t index) const noexcept { return data[index]; } bool operator ==(StringViewBase sv) const noexcept { if(length != sv.length) return false; const CharType* p = data; const CharType* q = sv.data; for(const CharType* end = data + length; p != end; ++p, ++q) if(*p != *q) return false; return true; } bool operator !=(StringViewBase sv) const noexcept { return !(*this == sv); } friend std::basic_ostream<CharType>& operator <<(std::basic_ostream<CharType>& stream, const StringViewBase& sv) { stream.write(sv.getData(), sv.getLength()); return stream; } const CharType* getData() const noexcept { return data; } void setData(const CharType* data_) noexcept { data = data_; } std::size_t getLength() const noexcept { return length; } void setLength(std::size_t length_) noexcept { length = length_; } String repeat(std::size_t count) const { String t; t.reserve(getLength() * count); for(std::size_t i = 0; i < count; ++i) { t += *this; } return t; } StringViewBase substr(std::size_t pos) const noexcept { if(pos <= length) return {data + pos, length - pos}; else return {}; } StringViewBase substr(std::size_t pos, std::size_t count) const noexcept { if(pos <= length) return {data + pos, std::min(count, length - pos)}; else return {}; } Iterator begin() const noexcept { return getData(); } Iterator end() const noexcept { return getData() + getLength(); } ReverseIterator rbegin() const noexcept { return ReverseIterator(end()); } ReverseIterator rend() const noexcept { return ReverseIterator(begin()); } }; using StringView = StringViewBase<Charset::UTF8<>>; using StringView16 = StringViewBase<Charset::UTF16<>>; using StringView32 = StringViewBase<Charset::UTF32<>>; } } #endif <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2010, 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 Image Engine Design 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. // ////////////////////////////////////////////////////////////////////////// #ifndef IECORE_COMPOUNDDATA_INL #define IECORE_COMPOUNDDATA_INL #include "boost/format.hpp" #include "IECore/Exception.h" namespace IECore { template<typename T> T *CompoundData::member( const InternedString &name, bool throwExceptions ) { return member<T>( name, throwExceptions, false ); } template<typename T> const T *CompoundData::member( const InternedString &name, bool throwExceptions ) const { CompoundDataMap::const_iterator it = readable().find( name ); if( it!=readable().end() ) { const T *result = runTimeCast<const T>( it->second.get() ); if( result ) { return result; } else { if( throwExceptions ) { throw Exception( boost::str( boost::format( "CompoundData child \"%s\" is not of type \"%s\"." ) % T::staticTypeName() ) ); } else { return 0; } } } else { if( throwExceptions ) { throw Exception( boost::str( boost::format( "CompoundData has no child named \"%s\"." ) % name.value() ) ); } else { return 0; } } return 0; // shouldn't get here anyway } template<typename T> T *CompoundData::member( const InternedString &name, bool throwExceptions, bool createIfMissing ) { CompoundDataMap::const_iterator it = readable().find( name ); if( it!=readable().end() ) { T *result = runTimeCast<T>( it->second.get() ); if( result ) { return result; } else { if( throwExceptions ) { throw Exception( boost::str( boost::format( "CompoundData child \"%s\" is not of type \"%s\"." ) % T::staticTypeName() ) ); } else { return 0; } } } else { if( createIfMissing ) { typename T::Ptr member = staticPointerCast<T>( Object::create( T::staticTypeId() ) ); writable()[name] = member; return member; } else if( throwExceptions ) { throw Exception( boost::str( boost::format( "CompoundData has no child named \"%s\"." ) % name.value() ) ); } else { return 0; } } return 0; // shouldn't get here anyway } }; // namespace IECore #endif // IECORE_COMPOUNDDATA_INL <commit_msg>Fixing bug which caused wrong exception to be thrown.<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2010, 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 Image Engine Design 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. // ////////////////////////////////////////////////////////////////////////// #ifndef IECORE_COMPOUNDDATA_INL #define IECORE_COMPOUNDDATA_INL #include "boost/format.hpp" #include "IECore/Exception.h" namespace IECore { template<typename T> T *CompoundData::member( const InternedString &name, bool throwExceptions ) { return member<T>( name, throwExceptions, false ); } template<typename T> const T *CompoundData::member( const InternedString &name, bool throwExceptions ) const { CompoundDataMap::const_iterator it = readable().find( name ); if( it!=readable().end() ) { const T *result = runTimeCast<const T>( it->second.get() ); if( result ) { return result; } else { if( throwExceptions ) { throw Exception( boost::str( boost::format( "CompoundData child \"%s\" is not of type \"%s\"." ) % name.value() % T::staticTypeName() ) ); } else { return 0; } } } else { if( throwExceptions ) { throw Exception( boost::str( boost::format( "CompoundData has no child named \"%s\"." ) % name.value() ) ); } else { return 0; } } return 0; // shouldn't get here anyway } template<typename T> T *CompoundData::member( const InternedString &name, bool throwExceptions, bool createIfMissing ) { CompoundDataMap::const_iterator it = readable().find( name ); if( it!=readable().end() ) { T *result = runTimeCast<T>( it->second.get() ); if( result ) { return result; } else { if( throwExceptions ) { throw Exception( boost::str( boost::format( "CompoundData child \"%s\" is not of type \"%s\"." ) % T::staticTypeName() ) ); } else { return 0; } } } else { if( createIfMissing ) { typename T::Ptr member = staticPointerCast<T>( Object::create( T::staticTypeId() ) ); writable()[name] = member; return member; } else if( throwExceptions ) { throw Exception( boost::str( boost::format( "CompoundData has no child named \"%s\"." ) % name.value() ) ); } else { return 0; } } return 0; // shouldn't get here anyway } }; // namespace IECore #endif // IECORE_COMPOUNDDATA_INL <|endoftext|>
<commit_before>extern "C" { #include "q.h" } #include <gtest/gtest.h> #include <deque> #include <functional> #include <algorithm> #include <random> #include <chrono> #include <limits> #include <iterator> class Model : public ::testing::Test { protected: virtual void SetUp() { seed = std::chrono::system_clock::now().time_since_epoch().count(); rng.seed(seed); } virtual void TearDown() { } std::mt19937 rng; size_t seed; }; template <typename RNG, typename D> bool run_isolated_test(int ninserts, int npops, int nreinserts, D dist, RNG entropy) { Q q; InitQ(&q); std::deque<int> model; auto result(true); for(auto n = 0; n < ninserts; ++n) { auto d = dist(entropy); model.push_back(d); AddQ(&q, &d); } for(auto n = 0; n < npops; ++n) { model.pop_front(); DelQ(&q); } for(auto n = 0; n < nreinserts; ++n) { auto d = dist(entropy); model.push_back(d); AddQ(&q, &d); } for(auto r : model) { auto u = *DelQ(&q); //std::cout << "Actual: " << r << " Expected: " << u <<'\n'; if(r != u) { result = false; } } FreeQ(&q); return result; } bool run_isolated_test(int ninserts, int npops, int nreinserts) { std::mt19937 rng(0); std::uniform_int_distribution<int> input_data(std::numeric_limits<int>::min(), std::numeric_limits<int>::max()); return run_isolated_test(ninserts, npops, nreinserts, input_data, rng); } TEST_F(Model, TheIDontHaveAllFuckingDaySoMakeTheComputerDoMyHomeworkTest) { std::uniform_int_distribution<int> ntests(0, 1000); std::uniform_int_distribution<int> input_data(std::numeric_limits<int>::min(), std::numeric_limits<int>::max()); //Generate a random number of inserts auto ninserts = ntests(rng); //Generate a random number of reads/pops auto npops = ntests(rng); //Generate a random number of more inserts to verify circular //dynamic functionality. Verify we can write, read, write and read //again in any amount. auto nreinserts = ntests(rng); std::cout << "Test:\n" << "\tSeed: " << seed << '\n' << "\tInserts: " << ninserts << '\n' << "\tDeletes: " << npops << '\n' << "\tReinserts: " << nreinserts << '\n'; //Verify from the model if(!run_isolated_test(ninserts, npops, nreinserts, input_data, rng)) { std::cout << "Test Failed, minimizing.\n"; while(ninserts > 0 && run_isolated_test(ninserts, npops, nreinserts, input_data, rng) == false) { --ninserts; } ++ninserts; //Make it fail again. while(npops > 0 && run_isolated_test(ninserts, npops, nreinserts, input_data, rng) == false) { --npops; } ++npops; //Make it fail again. while(nreinserts > 0 && run_isolated_test(ninserts, npops, nreinserts, input_data, rng) == false) { --nreinserts; } ++nreinserts; //Make it fail again. ADD_FAILURE(); std::cout << "Test:\n" << "\tInserts: " << ninserts << '\n' << "\tDeletes: " << npops << '\n' << "\tReinserts: " << nreinserts << '\n'; } } class Directed : public ::testing::Test { protected: virtual void SetUp() { InitQ(&q); } virtual void TearDown() { FreeQ(&q); } Q q; }; TEST_F(Directed, RandomMinimizedTest) { ASSERT_TRUE(run_isolated_test(1, 0, 9)); //Random test generator found this test case } TEST_F(Directed, Weirdness) { ASSERT_TRUE(run_isolated_test(10240, 0, 0)); //10 straight inserts don't fail, but 1 and 9 do. } TEST_F(Directed, RandomMinimizedTest2) { ASSERT_TRUE(run_isolated_test(1, 1, 8)); } TEST_F(Directed, RandomMinimizedTest3) { ASSERT_TRUE(run_isolated_test(1, 1, 9)); } TEST_F(Directed, Add) { for(int i = 1; i < 100; ++i) { AddQ(&q, &i); ASSERT_EQ(i, size_(&q)); } ASSERT_EQ(99, size_(&q)); for(int i = 1; i < 100; ++i) { ASSERT_EQ(i, *DelQ(&q)); } ASSERT_EQ(0, size_(&q)); } TEST_F(Directed, PutGet) { int i = 8; AddQ(&q, &i); ASSERT_EQ(8, *DelQ(&q)); } TEST_F(Directed, DeleteEmpty) { Q q; InitQ(&q); DelQ(&q); } <commit_msg>Working on another minimized test case.<commit_after>extern "C" { #include "q.h" } #include <gtest/gtest.h> #include <deque> #include <functional> #include <algorithm> #include <random> #include <chrono> #include <limits> #include <iterator> class Model : public ::testing::Test { protected: virtual void SetUp() { seed = std::chrono::system_clock::now().time_since_epoch().count(); rng.seed(seed); } virtual void TearDown() { } std::mt19937 rng; size_t seed; }; template <typename RNG, typename D> bool run_isolated_test(int ninserts, int npops, int nreinserts, D dist, RNG entropy) { Q q; InitQ(&q); std::deque<int> model; auto result(true); for(auto n = 0; n < ninserts; ++n) { auto d = dist(entropy); model.push_back(d); AddQ(&q, &d); } for(auto n = 0; n < npops; ++n) { model.pop_front(); DelQ(&q); } for(auto n = 0; n < nreinserts; ++n) { auto d = dist(entropy); model.push_back(d); AddQ(&q, &d); } for(auto r : model) { auto u = DelQ(&q); if(u == 0) { result = false; #if 0 std::cout << "Queue Ended Early.\n"; #endif } else { if(r != *u) { result = false; #if 0 std::cout << "Actual: " << r << " Expected: " << *u <<'\n'; std::cout << "Test:\n" << "\tInserts: " << ninserts << '\n' << "\tDeletes: " << npops << '\n' << "\tReinserts: " << nreinserts << '\n'; #endif } } } FreeQ(&q); return result; } bool run_isolated_test(int ninserts, int npops, int nreinserts) { std::mt19937 rng(0); std::uniform_int_distribution<int> input_data(std::numeric_limits<int>::min(), std::numeric_limits<int>::max()); return run_isolated_test(ninserts, npops, nreinserts, input_data, rng); } TEST_F(Model, TheIDontHaveAllFuckingDaySoMakeTheComputerDoMyHomeworkTest) { std::uniform_int_distribution<int> ntests(0, 1000); std::uniform_int_distribution<int> input_data(std::numeric_limits<int>::min(), std::numeric_limits<int>::max()); //Generate a random number of inserts auto ninserts = ntests(rng); //Generate a random number of reads/pops auto npops = ntests(rng); //Generate a random number of more inserts to verify circular //dynamic functionality. Verify we can write, read, write and read //again in any amount. auto nreinserts = ntests(rng); std::cout << "Test:\n" << "\tSeed: " << seed << '\n' << "\tInserts: " << ninserts << '\n' << "\tDeletes: " << npops << '\n' << "\tReinserts: " << nreinserts << '\n'; //Verify from the model if(!run_isolated_test(ninserts, npops, nreinserts, input_data, rng)) { std::cout << "Test Failed, minimizing.\n"; while(ninserts > 0 && run_isolated_test(ninserts, npops, nreinserts, input_data, rng) == false) { --ninserts; } ++ninserts; //Make it fail again. while(npops > 0 && run_isolated_test(ninserts, npops, nreinserts, input_data, rng) == false) { --npops; } ++npops; //Make it fail again. while(nreinserts > 0 && run_isolated_test(ninserts, npops, nreinserts, input_data, rng) == false) { --nreinserts; } ++nreinserts; //Make it fail again. ADD_FAILURE(); std::cout << "Test:\n" << "\tInserts: " << ninserts << '\n' << "\tDeletes: " << npops << '\n' << "\tReinserts: " << nreinserts << '\n'; } } class Directed : public ::testing::Test { protected: virtual void SetUp() { InitQ(&q); } virtual void TearDown() { FreeQ(&q); } Q q; }; TEST_F(Directed, RandomMinimizedTest) { ASSERT_TRUE(run_isolated_test(1, 0, 9)); //Random test generator found this test case } TEST_F(Directed, Weirdness) { ASSERT_TRUE(run_isolated_test(10240, 0, 0)); } TEST_F(Directed, RandomMinimizedTest2) { ASSERT_TRUE(run_isolated_test(1, 1, 8)); } TEST_F(Directed, RandomMinimizedTest3) { ASSERT_TRUE(run_isolated_test(1, 1, 9)); } TEST_F(Directed, RandomMinimizedTest4) { ASSERT_TRUE(run_isolated_test(1, 2, 2)); } TEST_F(Directed, Add) { for(int i = 1; i < 100; ++i) { AddQ(&q, &i); ASSERT_EQ(i, size_(&q)); } ASSERT_EQ(99, size_(&q)); for(int i = 1; i < 100; ++i) { ASSERT_EQ(i, *DelQ(&q)); } ASSERT_EQ(0, size_(&q)); } TEST_F(Directed, PutGet) { int i = 8; AddQ(&q, &i); ASSERT_EQ(8, *DelQ(&q)); } TEST_F(Directed, DeleteEmpty) { Q q; InitQ(&q); DelQ(&q); } <|endoftext|>
<commit_before>/* Copyright (c) 2008-2012, Arvid Norberg 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 author 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. */ #ifndef TORRENT_BITFIELD_HPP_INCLUDED #define TORRENT_BITFIELD_HPP_INCLUDED #include "libtorrent/assert.hpp" #include "libtorrent/config.hpp" #include <cstring> // for memset and memcpy #include <cstdlib> // for malloc, free and realloc #include <boost/cstdint.hpp> // uint32_t namespace libtorrent { // The bitfiled type stores any number of bits as a bitfield in an array. struct TORRENT_EXPORT bitfield { bitfield(): m_bytes(0), m_size(0), m_own(false) {} bitfield(int bits): m_bytes(0), m_size(0), m_own(false) { resize(bits); } bitfield(int bits, bool val): m_bytes(0), m_size(0), m_own(false) { resize(bits, val); } bitfield(char const* b, int bits): m_bytes(0), m_size(0), m_own(false) { assign(b, bits); } bitfield(bitfield const& rhs): m_bytes(0), m_size(0), m_own(false) { assign(rhs.bytes(), rhs.size()); } void borrow_bytes(char* b, int bits) { dealloc(); m_bytes = (unsigned char*)b; m_size = bits; m_own = false; } ~bitfield() { dealloc(); } void assign(char const* b, int bits) { resize(bits); std::memcpy(m_bytes, b, (bits + 7) / 8); clear_trailing_bits(); } bool operator[](int index) const { return get_bit(index); } bool get_bit(int index) const { TORRENT_ASSERT(index >= 0); TORRENT_ASSERT(index < m_size); return (m_bytes[index / 8] & (0x80 >> (index & 7))) != 0; } void clear_bit(int index) { TORRENT_ASSERT(index >= 0); TORRENT_ASSERT(index < m_size); m_bytes[index / 8] &= ~(0x80 >> (index & 7)); } // returns true if all bits in the bitfield are set bool all_set() const { const int num_words = m_size / 32; const int num_bytes = m_size / 8; boost::uint32_t* bits = (boost::uint32_t*)m_bytes; for (int i = 0; i < num_words; ++i) { if (bits[i] != 0xffffffff) return false; } for (int i = num_words * 4; i < num_bytes; ++i) { if (m_bytes[i] != 0xff) return false; } int rest = m_size - num_bytes * 8; boost::uint8_t mask = 0xff << (8-rest); if (rest > 0 && (m_bytes[num_bytes] & mask) != mask) return false; return true; } void set_bit(int index) { TORRENT_ASSERT(index >= 0); TORRENT_ASSERT(index < m_size); m_bytes[index / 8] |= (0x80 >> (index & 7)); } std::size_t size() const { return m_size; } bool empty() const { return m_size == 0; } char const* bytes() const { return (char*)m_bytes; } bitfield& operator=(bitfield const& rhs) { assign(rhs.bytes(), rhs.size()); return *this; } int count() const { // 0000, 0001, 0010, 0011, 0100, 0101, 0110, 0111, // 1000, 1001, 1010, 1011, 1100, 1101, 1110, 1111 const static char num_bits[] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 }; int ret = 0; const int num_bytes = m_size / 8; for (int i = 0; i < num_bytes; ++i) { ret += num_bits[m_bytes[i] & 0xf] + num_bits[m_bytes[i] >> 4]; } int rest = m_size - num_bytes * 8; for (int i = 0; i < rest; ++i) { ret += (m_bytes[num_bytes] >> (7-i)) & 1; } TORRENT_ASSERT(ret <= m_size); TORRENT_ASSERT(ret >= 0); return ret; } struct const_iterator { friend struct bitfield; typedef bool value_type; typedef ptrdiff_t difference_type; typedef bool const* pointer; typedef bool& reference; typedef std::forward_iterator_tag iterator_category; bool operator*() { return (*byte & bit) != 0; } const_iterator& operator++() { inc(); return *this; } const_iterator operator++(int) { const_iterator ret(*this); inc(); return ret; } const_iterator& operator--() { dec(); return *this; } const_iterator operator--(int) { const_iterator ret(*this); dec(); return ret; } const_iterator(): byte(0), bit(0x80) {} bool operator==(const_iterator const& rhs) const { return byte == rhs.byte && bit == rhs.bit; } bool operator!=(const_iterator const& rhs) const { return byte != rhs.byte || bit != rhs.bit; } private: void inc() { TORRENT_ASSERT(byte); if (bit == 0x01) { bit = 0x80; ++byte; } else { bit >>= 1; } } void dec() { TORRENT_ASSERT(byte); if (bit == 0x80) { bit = 0x01; --byte; } else { bit <<= 1; } } const_iterator(unsigned char const* ptr, int offset) : byte(ptr), bit(0x80 >> offset) {} unsigned char const* byte; int bit; }; const_iterator begin() const { return const_iterator(m_bytes, 0); } const_iterator end() const { return const_iterator(m_bytes + m_size / 8, m_size & 7); } void resize(int bits, bool val) { int s = m_size; int b = m_size & 7; resize(bits); if (s >= m_size) return; int old_size_bytes = (s + 7) / 8; int new_size_bytes = (m_size + 7) / 8; if (val) { if (old_size_bytes && b) m_bytes[old_size_bytes - 1] |= (0xff >> b); if (old_size_bytes < new_size_bytes) std::memset(m_bytes + old_size_bytes, 0xff, new_size_bytes - old_size_bytes); clear_trailing_bits(); } else { if (old_size_bytes < new_size_bytes) std::memset(m_bytes + old_size_bytes, 0x00, new_size_bytes - old_size_bytes); } } void set_all() { std::memset(m_bytes, 0xff, (m_size + 7) / 8); clear_trailing_bits(); } void clear_all() { std::memset(m_bytes, 0x00, (m_size + 7) / 8); } void resize(int bits) { TORRENT_ASSERT(bits >= 0); const int b = (bits + 7) / 8; if (m_bytes) { if (m_own) { m_bytes = (unsigned char*)std::realloc(m_bytes, b); m_own = true; } else if (bits > m_size) { unsigned char* tmp = (unsigned char*)std::malloc(b); std::memcpy(tmp, m_bytes, (std::min)(int(m_size + 7)/ 8, b)); m_bytes = tmp; m_own = true; } } else if (bits > 0) { m_bytes = (unsigned char*)std::malloc(b); m_own = true; } m_size = bits; clear_trailing_bits(); } void free() { dealloc(); m_size = 0; } private: void clear_trailing_bits() { // clear the tail bits in the last byte if (m_size & 7) m_bytes[(m_size + 7) / 8 - 1] &= 0xff << (8 - (m_size & 7)); } void dealloc() { if (m_own) std::free(m_bytes); m_bytes = 0; } unsigned char* m_bytes; int m_size:31; // in bits bool m_own:1; }; } #endif // TORRENT_BITFIELD_HPP_INCLUDED <commit_msg>documented bitfield<commit_after>/* Copyright (c) 2008-2012, Arvid Norberg 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 author 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. */ #ifndef TORRENT_BITFIELD_HPP_INCLUDED #define TORRENT_BITFIELD_HPP_INCLUDED #include "libtorrent/assert.hpp" #include "libtorrent/config.hpp" #include <cstring> // for memset and memcpy #include <cstdlib> // for malloc, free and realloc #include <boost/cstdint.hpp> // uint32_t namespace libtorrent { // The bitfiled type stores any number of bits as a bitfield // in a heap allocated or borrowed array. struct TORRENT_EXPORT bitfield { // constructs a new bitfield. The default constructor creates an empty // bitfield. ``bits`` is the size of the bitfield (specified in bits). // `` val`` is the value to initialize the bits to. If not specified // all bits are initialized to 0. // // The constructor taking a pointer ``b`` and ``bits`` copies a bitfield // from the specified buffer, and ``bits`` number of bits (rounded up to // the nearest byte boundry). bitfield(): m_bytes(0), m_size(0), m_own(false) {} bitfield(int bits): m_bytes(0), m_size(0), m_own(false) { resize(bits); } bitfield(int bits, bool val): m_bytes(0), m_size(0), m_own(false) { resize(bits, val); } bitfield(char const* b, int bits): m_bytes(0), m_size(0), m_own(false) { assign(b, bits); } bitfield(bitfield const& rhs): m_bytes(0), m_size(0), m_own(false) { assign(rhs.bytes(), rhs.size()); } // assigns a bitfield pointed to ``b`` of ``bits`` number of bits, without // taking ownership of the buffer. This is a way to avoid copying data and // yet provide a raw buffer to functions that may operate on the bitfield // type. It is the user's responsibility to make sure the passed-in buffer's // life time exceeds all uses of the bitfield. void borrow_bytes(char* b, int bits) { dealloc(); m_bytes = (unsigned char*)b; m_size = bits; m_own = false; } // hidden ~bitfield() { dealloc(); } // copy bitfield from buffer ``b`` of ``bits`` number of bits, rounded up to // the nearest byte boundary. void assign(char const* b, int bits) { resize(bits); std::memcpy(m_bytes, b, (bits + 7) / 8); clear_trailing_bits(); } // query bit at ``index``. Returns true if bit is 1, otherwise false. bool operator[](int index) const { return get_bit(index); } bool get_bit(int index) const { TORRENT_ASSERT(index >= 0); TORRENT_ASSERT(index < m_size); return (m_bytes[index / 8] & (0x80 >> (index & 7))) != 0; } // set bit at ``index`` to 0 (clear_bit) or 1 (set_bit). void clear_bit(int index) { TORRENT_ASSERT(index >= 0); TORRENT_ASSERT(index < m_size); m_bytes[index / 8] &= ~(0x80 >> (index & 7)); } void set_bit(int index) { TORRENT_ASSERT(index >= 0); TORRENT_ASSERT(index < m_size); m_bytes[index / 8] |= (0x80 >> (index & 7)); } // returns true if all bits in the bitfield are set bool all_set() const { const int num_words = m_size / 32; const int num_bytes = m_size / 8; boost::uint32_t* bits = (boost::uint32_t*)m_bytes; for (int i = 0; i < num_words; ++i) { if (bits[i] != 0xffffffff) return false; } for (int i = num_words * 4; i < num_bytes; ++i) { if (m_bytes[i] != 0xff) return false; } int rest = m_size - num_bytes * 8; boost::uint8_t mask = 0xff << (8-rest); if (rest > 0 && (m_bytes[num_bytes] & mask) != mask) return false; return true; } // returns the size of the bitfield in bits. std::size_t size() const { return m_size; } // returns true if the bitfield has zero size. bool empty() const { return m_size == 0; } // returns a pointer to the internal buffer of the bitfield. char const* bytes() const { return (char*)m_bytes; } // copy operator bitfield& operator=(bitfield const& rhs) { assign(rhs.bytes(), rhs.size()); return *this; } // count the number of bits in the bitfield that are set to 1. int count() const { // 0000, 0001, 0010, 0011, 0100, 0101, 0110, 0111, // 1000, 1001, 1010, 1011, 1100, 1101, 1110, 1111 const static char num_bits[] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 }; int ret = 0; const int num_bytes = m_size / 8; for (int i = 0; i < num_bytes; ++i) { ret += num_bits[m_bytes[i] & 0xf] + num_bits[m_bytes[i] >> 4]; } int rest = m_size - num_bytes * 8; for (int i = 0; i < rest; ++i) { ret += (m_bytes[num_bytes] >> (7-i)) & 1; } TORRENT_ASSERT(ret <= m_size); TORRENT_ASSERT(ret >= 0); return ret; } struct const_iterator { friend struct bitfield; typedef bool value_type; typedef ptrdiff_t difference_type; typedef bool const* pointer; typedef bool& reference; typedef std::forward_iterator_tag iterator_category; bool operator*() { return (*byte & bit) != 0; } const_iterator& operator++() { inc(); return *this; } const_iterator operator++(int) { const_iterator ret(*this); inc(); return ret; } const_iterator& operator--() { dec(); return *this; } const_iterator operator--(int) { const_iterator ret(*this); dec(); return ret; } const_iterator(): byte(0), bit(0x80) {} bool operator==(const_iterator const& rhs) const { return byte == rhs.byte && bit == rhs.bit; } bool operator!=(const_iterator const& rhs) const { return byte != rhs.byte || bit != rhs.bit; } private: void inc() { TORRENT_ASSERT(byte); if (bit == 0x01) { bit = 0x80; ++byte; } else { bit >>= 1; } } void dec() { TORRENT_ASSERT(byte); if (bit == 0x80) { bit = 0x01; --byte; } else { bit <<= 1; } } const_iterator(unsigned char const* ptr, int offset) : byte(ptr), bit(0x80 >> offset) {} unsigned char const* byte; int bit; }; const_iterator begin() const { return const_iterator(m_bytes, 0); } const_iterator end() const { return const_iterator(m_bytes + m_size / 8, m_size & 7); } // set the size of the bitfield to ``bits`` length. If the bitfield is extended, // the new bits are initialized to ``val``. void resize(int bits, bool val) { int s = m_size; int b = m_size & 7; resize(bits); if (s >= m_size) return; int old_size_bytes = (s + 7) / 8; int new_size_bytes = (m_size + 7) / 8; if (val) { if (old_size_bytes && b) m_bytes[old_size_bytes - 1] |= (0xff >> b); if (old_size_bytes < new_size_bytes) std::memset(m_bytes + old_size_bytes, 0xff, new_size_bytes - old_size_bytes); clear_trailing_bits(); } else { if (old_size_bytes < new_size_bytes) std::memset(m_bytes + old_size_bytes, 0x00, new_size_bytes - old_size_bytes); } } void resize(int bits) { TORRENT_ASSERT(bits >= 0); const int b = (bits + 7) / 8; if (m_bytes) { if (m_own) { m_bytes = (unsigned char*)std::realloc(m_bytes, b); m_own = true; } else if (bits > m_size) { unsigned char* tmp = (unsigned char*)std::malloc(b); std::memcpy(tmp, m_bytes, (std::min)(int(m_size + 7)/ 8, b)); m_bytes = tmp; m_own = true; } } else if (bits > 0) { m_bytes = (unsigned char*)std::malloc(b); m_own = true; } m_size = bits; clear_trailing_bits(); } // set all bits in the bitfield to 1 (set_all) or 0 (clear_all). void set_all() { std::memset(m_bytes, 0xff, (m_size + 7) / 8); clear_trailing_bits(); } void clear_all() { std::memset(m_bytes, 0x00, (m_size + 7) / 8); } // make the bitfield empty, of zero size. void clear() { dealloc(); m_size = 0; } private: void clear_trailing_bits() { // clear the tail bits in the last byte if (m_size & 7) m_bytes[(m_size + 7) / 8 - 1] &= 0xff << (8 - (m_size & 7)); } void dealloc() { if (m_own) std::free(m_bytes); m_bytes = 0; } unsigned char* m_bytes; int m_size:31; // in bits bool m_own:1; }; } #endif // TORRENT_BITFIELD_HPP_INCLUDED <|endoftext|>
<commit_before>// // MessagePack for C++ static resolution routine // // Copyright (C) 2015 KONDO Takatoshi // // 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. // #ifndef MSGPACK_TYPE_EXT_HPP #define MSGPACK_TYPE_EXT_HPP #include "msgpack/versioning.hpp" #include "msgpack/adaptor/adaptor_base.hpp" #include <cstring> #include <string> #include <cassert> namespace msgpack { /// @cond MSGPACK_API_VERSION_NAMESPACE(v1) { /// @endcond namespace type { class ext_ref; class ext { public: ext() : m_data(1, 0) {} ext(int8_t t, const char* p, uint32_t s) { detail::check_container_size_for_ext<sizeof(std::size_t)>(s); m_data.reserve(static_cast<std::size_t>(s) + 1); m_data.push_back(static_cast<char>(t)); m_data.insert(m_data.end(), p, p + s); } ext(int8_t t, uint32_t s) { detail::check_container_size_for_ext<sizeof(std::size_t)>(s); m_data.resize(static_cast<std::size_t>(s) + 1); m_data[0] = static_cast<char>(t); } ext(ext_ref const&); int8_t type() const { return static_cast<int8_t>(m_data[0]); } const char* data() const { return &m_data[1]; } char* data() { return &m_data[1]; } uint32_t size() const { return m_data.size() - 1; } bool operator== (const ext& x) const { return m_data == x.m_data; } bool operator!= (const ext& x) const { return !(*this == x); } bool operator< (const ext& x) const { return m_data < x.m_data; } bool operator> (const ext& x) const { return m_data > x.m_data; } private: std::vector<char> m_data; friend class ext_ref; }; } // namespace type namespace adaptor { template <> struct convert<msgpack::type::ext> { msgpack::object const& operator()(msgpack::object const& o, msgpack::type::ext& v) const { if(o.type != msgpack::type::EXT) { throw msgpack::type_error(); } v = msgpack::type::ext(o.via.ext.type(), o.via.ext.data(), o.via.ext.size); return o; } }; template <> struct pack<msgpack::type::ext> { template <typename Stream> msgpack::packer<Stream>& operator()(msgpack::packer<Stream>& o, const msgpack::type::ext& v) const { // size limit has aleady been checked at ext's constructor uint32_t size = v.size(); o.pack_ext(size, v.type()); o.pack_ext_body(v.data(), size); return o; } }; template <> struct object_with_zone<msgpack::type::ext> { void operator()(msgpack::object::with_zone& o, const msgpack::type::ext& v) const { // size limit has aleady been checked at ext's constructor uint32_t size = v.size(); o.type = msgpack::type::EXT; char* ptr = static_cast<char*>(o.zone.allocate_align(size + 1)); o.via.ext.ptr = ptr; o.via.ext.size = size; ptr[0] = static_cast<char>(v.type()); std::memcpy(ptr + 1, v.data(), size); } }; } // namespace adaptor namespace type { class ext_ref { public: // ext_ref should be default constructible to support 'convert'. // A default constructed ext_ref object::m_ptr doesn't have the buffer to point to. // In order to avoid nullptr checking branches, m_ptr points to m_size. // So type() returns unspecified but valid value. It might be a zero because m_size // is initialized as zero, but shoudn't assume that. ext_ref() : m_ptr(static_cast<char*>(static_cast<void*>(&m_size))), m_size(0) {} ext_ref(const char* p, uint32_t s) : m_ptr(s == 0 ? static_cast<char*>(static_cast<void*>(&m_size)) : p), m_size(s == 0 ? 0 : s - 1) { detail::check_container_size_for_ext<sizeof(std::size_t)>(s); } // size limit has aleady been checked at ext's constructor ext_ref(ext const& x) : m_ptr(&x.m_data[0]), m_size(x.size()) {} const char* data() const { return m_ptr + 1; } uint32_t size() const { return m_size; } int8_t type() const { return static_cast<int8_t>(m_ptr[0]); } std::string str() const { return std::string(m_ptr + 1, m_size); } bool operator== (const ext_ref& x) const { return m_size == x.m_size && std::memcmp(m_ptr, x.m_ptr, m_size) == 0; } bool operator!= (const ext_ref& x) const { return !(*this == x); } bool operator< (const ext_ref& x) const { if (m_size < x.m_size) return true; if (m_size > x.m_size) return false; return std::memcmp(m_ptr, x.m_ptr, m_size) < 0; } bool operator> (const ext_ref& x) const { if (m_size > x.m_size) return true; if (m_size < x.m_size) return false; return std::memcmp(m_ptr, x.m_ptr, m_size) > 0; } private: const char* m_ptr; uint32_t m_size; friend struct msgpack::adaptor::object<msgpack::type::ext_ref>; }; ext::ext(ext_ref const& x) { // size limit has aleady been checked at ext_ref's constructor m_data.reserve(x.size() + 1); m_data.push_back(x.type()); m_data.insert(m_data.end(), x.data(), x.data() + x.size()); } } // namespace type namespace adaptor { template <> struct convert<msgpack::type::ext_ref> { msgpack::object const& operator()(msgpack::object const& o, msgpack::type::ext_ref& v) const { if(o.type != msgpack::type::EXT) { throw msgpack::type_error(); } v = msgpack::type::ext_ref(o.via.ext.ptr, o.via.ext.size + 1); return o; } }; template <> struct pack<msgpack::type::ext_ref> { template <typename Stream> msgpack::packer<Stream>& operator()(msgpack::packer<Stream>& o, const msgpack::type::ext_ref& v) const { // size limit has aleady been checked at ext_ref's constructor uint32_t size = v.size(); o.pack_ext(size, v.type()); o.pack_ext_body(v.data(), size); return o; } }; template <> struct object<msgpack::type::ext_ref> { void operator()(msgpack::object& o, const msgpack::type::ext_ref& v) const { // size limit has aleady been checked at ext_ref's constructor uint32_t size = v.size(); o.type = msgpack::type::EXT; o.via.ext.ptr = v.m_ptr; o.via.ext.size = size; } }; template <> struct object_with_zone<msgpack::type::ext_ref> { void operator()(msgpack::object::with_zone& o, const msgpack::type::ext_ref& v) const { static_cast<msgpack::object&>(o) << v; } }; } // namespace adaptor /// @cond } // MSGPACK_API_VERSION_NAMESPACE(v1) /// @endcond } // namespace msgpack #endif // MSGPACK_TYPE_EXT_HPP <commit_msg>Fixed #307. Added 'inline' keyword to ext's constructor that defined at outside of the class definition.<commit_after>// // MessagePack for C++ static resolution routine // // Copyright (C) 2015 KONDO Takatoshi // // 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. // #ifndef MSGPACK_TYPE_EXT_HPP #define MSGPACK_TYPE_EXT_HPP #include "msgpack/versioning.hpp" #include "msgpack/adaptor/adaptor_base.hpp" #include <cstring> #include <string> #include <cassert> namespace msgpack { /// @cond MSGPACK_API_VERSION_NAMESPACE(v1) { /// @endcond namespace type { class ext_ref; class ext { public: ext() : m_data(1, 0) {} ext(int8_t t, const char* p, uint32_t s) { detail::check_container_size_for_ext<sizeof(std::size_t)>(s); m_data.reserve(static_cast<std::size_t>(s) + 1); m_data.push_back(static_cast<char>(t)); m_data.insert(m_data.end(), p, p + s); } ext(int8_t t, uint32_t s) { detail::check_container_size_for_ext<sizeof(std::size_t)>(s); m_data.resize(static_cast<std::size_t>(s) + 1); m_data[0] = static_cast<char>(t); } ext(ext_ref const&); int8_t type() const { return static_cast<int8_t>(m_data[0]); } const char* data() const { return &m_data[1]; } char* data() { return &m_data[1]; } uint32_t size() const { return m_data.size() - 1; } bool operator== (const ext& x) const { return m_data == x.m_data; } bool operator!= (const ext& x) const { return !(*this == x); } bool operator< (const ext& x) const { return m_data < x.m_data; } bool operator> (const ext& x) const { return m_data > x.m_data; } private: std::vector<char> m_data; friend class ext_ref; }; } // namespace type namespace adaptor { template <> struct convert<msgpack::type::ext> { msgpack::object const& operator()(msgpack::object const& o, msgpack::type::ext& v) const { if(o.type != msgpack::type::EXT) { throw msgpack::type_error(); } v = msgpack::type::ext(o.via.ext.type(), o.via.ext.data(), o.via.ext.size); return o; } }; template <> struct pack<msgpack::type::ext> { template <typename Stream> msgpack::packer<Stream>& operator()(msgpack::packer<Stream>& o, const msgpack::type::ext& v) const { // size limit has aleady been checked at ext's constructor uint32_t size = v.size(); o.pack_ext(size, v.type()); o.pack_ext_body(v.data(), size); return o; } }; template <> struct object_with_zone<msgpack::type::ext> { void operator()(msgpack::object::with_zone& o, const msgpack::type::ext& v) const { // size limit has aleady been checked at ext's constructor uint32_t size = v.size(); o.type = msgpack::type::EXT; char* ptr = static_cast<char*>(o.zone.allocate_align(size + 1)); o.via.ext.ptr = ptr; o.via.ext.size = size; ptr[0] = static_cast<char>(v.type()); std::memcpy(ptr + 1, v.data(), size); } }; } // namespace adaptor namespace type { class ext_ref { public: // ext_ref should be default constructible to support 'convert'. // A default constructed ext_ref object::m_ptr doesn't have the buffer to point to. // In order to avoid nullptr checking branches, m_ptr points to m_size. // So type() returns unspecified but valid value. It might be a zero because m_size // is initialized as zero, but shoudn't assume that. ext_ref() : m_ptr(static_cast<char*>(static_cast<void*>(&m_size))), m_size(0) {} ext_ref(const char* p, uint32_t s) : m_ptr(s == 0 ? static_cast<char*>(static_cast<void*>(&m_size)) : p), m_size(s == 0 ? 0 : s - 1) { detail::check_container_size_for_ext<sizeof(std::size_t)>(s); } // size limit has aleady been checked at ext's constructor ext_ref(ext const& x) : m_ptr(&x.m_data[0]), m_size(x.size()) {} const char* data() const { return m_ptr + 1; } uint32_t size() const { return m_size; } int8_t type() const { return static_cast<int8_t>(m_ptr[0]); } std::string str() const { return std::string(m_ptr + 1, m_size); } bool operator== (const ext_ref& x) const { return m_size == x.m_size && std::memcmp(m_ptr, x.m_ptr, m_size) == 0; } bool operator!= (const ext_ref& x) const { return !(*this == x); } bool operator< (const ext_ref& x) const { if (m_size < x.m_size) return true; if (m_size > x.m_size) return false; return std::memcmp(m_ptr, x.m_ptr, m_size) < 0; } bool operator> (const ext_ref& x) const { if (m_size > x.m_size) return true; if (m_size < x.m_size) return false; return std::memcmp(m_ptr, x.m_ptr, m_size) > 0; } private: const char* m_ptr; uint32_t m_size; friend struct msgpack::adaptor::object<msgpack::type::ext_ref>; }; inline ext::ext(ext_ref const& x) { // size limit has aleady been checked at ext_ref's constructor m_data.reserve(x.size() + 1); m_data.push_back(x.type()); m_data.insert(m_data.end(), x.data(), x.data() + x.size()); } } // namespace type namespace adaptor { template <> struct convert<msgpack::type::ext_ref> { msgpack::object const& operator()(msgpack::object const& o, msgpack::type::ext_ref& v) const { if(o.type != msgpack::type::EXT) { throw msgpack::type_error(); } v = msgpack::type::ext_ref(o.via.ext.ptr, o.via.ext.size + 1); return o; } }; template <> struct pack<msgpack::type::ext_ref> { template <typename Stream> msgpack::packer<Stream>& operator()(msgpack::packer<Stream>& o, const msgpack::type::ext_ref& v) const { // size limit has aleady been checked at ext_ref's constructor uint32_t size = v.size(); o.pack_ext(size, v.type()); o.pack_ext_body(v.data(), size); return o; } }; template <> struct object<msgpack::type::ext_ref> { void operator()(msgpack::object& o, const msgpack::type::ext_ref& v) const { // size limit has aleady been checked at ext_ref's constructor uint32_t size = v.size(); o.type = msgpack::type::EXT; o.via.ext.ptr = v.m_ptr; o.via.ext.size = size; } }; template <> struct object_with_zone<msgpack::type::ext_ref> { void operator()(msgpack::object::with_zone& o, const msgpack::type::ext_ref& v) const { static_cast<msgpack::object&>(o) << v; } }; } // namespace adaptor /// @cond } // MSGPACK_API_VERSION_NAMESPACE(v1) /// @endcond } // namespace msgpack #endif // MSGPACK_TYPE_EXT_HPP <|endoftext|>
<commit_before>//---------------------------------------------------------------------------- /// \file rate_throttler.hpp /// \author Serge Aleynikov //---------------------------------------------------------------------------- /// \brief Efficiently calculates the throttling rate over a number of seconds. /// /// The algorithm implements a variation of token bucket algorithm that /// doesn't require to add tokens to the bucket on a timer but rather it /// maintains a circular buffer of tokens with resolution of 1/BucketsPerSec. /// The basic_rate_throttler::add() function is used to adds items to a bucket /// associated with the timestamp passed as the first argument to the /// function. The throttler::running_sum() returns the total number of /// items over the given interval of seconds. /// \note See also this article on a throttling algorithm /// http://www.devquotes.com/2010/11/24/an-efficient-network-throttling-algorithm. /// \note Another article on rate limiting /// http://www.pennedobjects.com/2010/10/better-rate-limiting-with-dot-net. //---------------------------------------------------------------------------- // Created: 2011-01-20 //---------------------------------------------------------------------------- /* ***** BEGIN LICENSE BLOCK ***** This file is part of the utxx open-source project. Copyright (C) 2011 Serge Aleynikov <saleyn@gmail.com> 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 ***** END LICENSE BLOCK ***** */ #ifndef _UTXX_THROTTLER_HPP_ #define _UTXX_THROTTLER_HPP_ #include <utxx/error.hpp> #include <utxx/meta.hpp> #include <utxx/time_val.hpp> #include <utxx/compiler_hints.hpp> #include <time.h> namespace utxx { /// @brief Throttle given rate over a number of seconds. /// Implementation uses time spacing reservation algorithm where each /// allocation of samples reserves a fraction of space in the throttling /// window. The reservation gets freed as the time goes by. No more than /// the "rate()" number of samples are allowed to fit in the "window_msec()" /// window. template <typename T = uint32_t> class basic_time_spacing_throttle { public: basic_time_spacing_throttle(uint32_t a_rate, uint32_t a_window_msec = 1000, time_val a_now = now_utc()) : m_rate (a_rate) , m_window_us (a_window_msec * 1000) , m_step_us (m_window_us / m_rate) , m_next_time (a_now) {} /// Add \a a_samples to the throtlle's counter. /// @return number of samples that fit in the throttling window. 0 means /// that the throttler is fully congested, and more time needs to elapse /// before the throttles gets reset to accept more samples. T add(T a_samples = 1, time_val a_now = now_utc()) { auto next_time = m_next_time; next_time.add_usec(a_samples * m_step_us); auto diff = next_time.microseconds() - (a_now.microseconds() + m_window_us); if (diff < 0) { // All samples fit the throttling threshold m_next_time = next_time; return a_samples; } // Figure out how many samples fit the throttling threshold auto n = std::max<T>(0, a_samples - (T(diff) / m_step_us)); m_next_time.add_usec(n * m_step_us); return n; } T rate() const { return m_rate; } long step() const { return m_step_us; } long window_msec() const { return m_window_us / 1000; } long window_usec() const { return m_window_us; } time_val next_time() const { return m_next_time; } /// Return the number of available samples given \a a_now current time. T available(time_val a_now = now_utc()) const{ auto diff = (a_now - m_next_time).microseconds(); return diff >= 0 ? m_rate : T(m_window_us + diff) / m_step_us; } private: T m_rate; long m_window_us; T m_step_us; time_val m_next_time; }; using time_spacing_throttle = basic_time_spacing_throttle<>; /** * \brief Efficiently calculates the throttling rate over a number of seconds. * The algorithm implements a variation of token bucket algorithm that * doesn't require to add tokens to the bucket on a timer but rather it * maintains a cirtular buffer of tokens with resolution of 1/BucketsPerSec. * The basic_rate_throttler::add() function is used to adds items to a bucket * associated with the timestamp passed as the first argument to the * function. The throttler::running_sum() returns the total number of * items over the given interval of seconds. The items automatically expire * when the time moves on the successive invocations of the add() method. * @tparam MaxSeconds defines the max number of seconds of data to hold * in the circuling buffer. * @tparam BucketsPerSec defines the number of bucket slots per second. * The larger the number the more accurate the running sum will be. */ template<size_t MaxSeconds = 16, size_t BucketsPerSec = 2> class basic_rate_throttler { public: static const size_t s_max_seconds = upper_power<MaxSeconds,2>::value; static const size_t s_buckets_per_sec = upper_power<BucketsPerSec,2>::value; static const size_t s_log_buckets_sec = log<s_buckets_per_sec,2>::value; static const size_t s_bucket_count = s_max_seconds * s_buckets_per_sec; static const size_t s_bucket_mask = s_bucket_count - 1; explicit basic_rate_throttler(int a_interval = 1) : m_interval(-1) { init(a_interval); } basic_rate_throttler (const basic_rate_throttler&) = default; basic_rate_throttler (basic_rate_throttler&&) = default; basic_rate_throttler& operator=(const basic_rate_throttler&) = default; /// Initialize the internal buffer setting the throttling interval /// measured in seconds. void init(int a_throttle_interval) throw(badarg_error) { if (a_throttle_interval == m_interval) return; m_interval = a_throttle_interval << s_log_buckets_sec; if (a_throttle_interval < 0 || (size_t)a_throttle_interval > s_bucket_count / s_buckets_per_sec) throw badarg_error("Invalid throttle interval:", a_throttle_interval); reset(); } /// Reset the inturnal circular buffer. void reset() { memset(m_buckets, 0, sizeof(m_buckets)); m_last_time = 0; m_sum = 0; } /// Return running interval. long interval() const { return m_interval >> s_log_buckets_sec; } /// Return current running sum over the interval. long running_sum() const { return m_sum; } /// Return current running sum over the interval. double running_avg() const { return (double)m_sum / (m_interval >> s_log_buckets_sec); } /// Add \a a_count number of items to the bucket associated with \a a_time. /// @param a_time is monotonically increasing time value. /// @param a_count is the count to add to the bucket associated with \a a_time. /// @return current running sum. long add(time_val a_time, int a_count = 1); /// Update current timestamp. long refresh(time_val a_time) { return add(a_time, 0); } /// Dump the internal state to stream void dump(std::ostream& out, time_val a_time); private: size_t m_buckets[s_bucket_count]; time_t m_last_time; long m_sum; long m_interval; // must be power of two BOOST_STATIC_ASSERT((s_bucket_count & (s_bucket_count - 1)) == 0); }; //------------------------------------------------------------------------------ // Implementation //------------------------------------------------------------------------------ template<size_t MaxSeconds, size_t BucketsPerSec> long basic_rate_throttler<MaxSeconds, BucketsPerSec>:: add(time_val a_time, int a_count) { time_t l_now = (time_t)(a_time.seconds() * s_buckets_per_sec); if (unlikely(!m_last_time)) m_last_time = l_now; int l_bucket = l_now & s_bucket_mask; long l_time_diff = l_now - m_last_time; if (unlikely(l_now < m_last_time)) { // Clock was adjusted m_buckets[l_bucket] = a_count; m_sum = a_count; } else if (!l_time_diff) { m_sum += a_count; m_buckets[l_bucket] += a_count; } else if (l_time_diff >= m_interval) { int l_start = (l_now - m_interval + 1) & s_bucket_mask; int l_end = l_now & s_bucket_mask; for (int i = l_start; i != l_end; i = (i+1) & s_bucket_mask) m_buckets[i] = 0; m_buckets[l_bucket] = a_count; m_sum = a_count; } else { // Calculate sum of buckets from int l_valid_buckets = m_interval - l_time_diff; int l_start, l_end; if (l_valid_buckets <= (m_interval>>1)) { l_start = (l_now - m_interval + 1) & s_bucket_mask; l_end = (m_last_time+1) & s_bucket_mask; m_sum = a_count; #ifdef THROTTLE_DEBUG printf("Summing %d through %d\n", l_start, l_end); #endif for (int i = l_start; i != l_end; i = (i+1) & s_bucket_mask) { m_sum += m_buckets[i]; } l_start = l_end; l_end = l_now & s_bucket_mask; } else { l_start = (m_last_time - m_interval + 1) & s_bucket_mask; l_end = (l_now - m_interval + 1) & s_bucket_mask; #ifdef THROTTLE_DEBUG printf("Subtracting/resetting %d through %d\n", l_start, l_end); #endif for (int i = l_start; i != l_end; i = (i+1) & s_bucket_mask) { m_sum -= m_buckets[i]; // BOOST_ASSERT(m_sum >= 0); if (m_sum < 0) { m_sum = 0; std::cerr << "ERROR " << __FILE__ << ':' << __LINE__ << std::endl; dump(std::cerr, a_time); } m_buckets[i] = 0; } l_start = (m_last_time + 1) & s_bucket_mask; l_end = l_now & s_bucket_mask; m_sum += a_count; } #ifdef THROTTLE_DEBUG printf("Resetting %d through %d\n", l_start, l_end); #endif // Reset values in intermediate buckets since there was no activity there for (int i = l_start; i != l_end; i = (i+1) & s_bucket_mask) m_buckets[i] = 0; m_buckets[l_bucket] = a_count; } m_last_time = l_now; #ifdef THROTTLE_DEBUG dump(std::cout); #endif return m_sum; } template<size_t MaxSeconds, size_t BucketsPerSec> void basic_rate_throttler<MaxSeconds, BucketsPerSec>:: dump(std::ostream& out, time_val a_time) { time_t l_now = (time_t)(a_time.seconds() * s_buckets_per_sec); size_t l_bucket = l_now & s_bucket_mask; char buf[256]; std::stringstream s; sprintf(buf, "last_time=%ld, last_bucket=%3zu, sum=%ld (interval=%ld)\n", m_last_time, l_bucket, m_sum, m_interval); s << buf; int k = 0; size_t n = (l_bucket-m_interval) & s_bucket_mask; for (size_t j=0; j < s_bucket_count; j++) { k += snprintf(buf+k, sizeof(buf)-k, "%3zu%c", j, (j == l_bucket || j == n) ? '|' : ' '); k += snprintf(buf+k, sizeof(buf)-k, "%s", (j < s_bucket_count-1) ? "" : "\n"); } s << buf; k = 0; for (size_t j=0; j < s_bucket_count; j++) { k += snprintf(buf+k, sizeof(buf)-k, "%3zu%c", m_buckets[j], (j == l_bucket || j == n) ? '|' : ' '); k += snprintf(buf+k, sizeof(buf)-k, "%s", (j < s_bucket_count-1) ? "" : "\n"); } s << buf; out << s.str(); } } // namespace utxx #endif // _UTXX_THROTTLER_HPP_ <commit_msg>Update rate_throttler.hpp<commit_after>//---------------------------------------------------------------------------- /// \file rate_throttler.hpp /// \author Serge Aleynikov //---------------------------------------------------------------------------- /// \brief Efficiently calculates the throttling rate over a number of seconds. /// /// The algorithm implements a variation of token bucket algorithm that /// doesn't require to add tokens to the bucket on a timer but rather it /// maintains a circular buffer of tokens with resolution of 1/BucketsPerSec. /// The basic_rate_throttler::add() function is used to adds items to a bucket /// associated with the timestamp passed as the first argument to the /// function. The throttler::running_sum() returns the total number of /// items over the given interval of seconds. /// \note See also this article on a throttling algorithm /// http://www.devquotes.com/2010/11/24/an-efficient-network-throttling-algorithm. /// \note Another article on rate limiting /// http://www.pennedobjects.com/2010/10/better-rate-limiting-with-dot-net. //---------------------------------------------------------------------------- // Created: 2011-01-20 //---------------------------------------------------------------------------- /* ***** BEGIN LICENSE BLOCK ***** This file is part of the utxx open-source project. Copyright (C) 2011 Serge Aleynikov <saleyn@gmail.com> 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 ***** END LICENSE BLOCK ***** */ #ifndef _UTXX_THROTTLER_HPP_ #define _UTXX_THROTTLER_HPP_ #include <utxx/error.hpp> #include <utxx/meta.hpp> #include <utxx/time_val.hpp> #include <utxx/compiler_hints.hpp> #include <time.h> namespace utxx { /// @brief Throttle given rate over a number of seconds. /// Implementation uses time spacing reservation algorithm where each /// allocation of samples reserves a fraction of space in the throttling /// window. The reservation gets freed as the time goes by. No more than /// the "rate()" number of samples are allowed to fit in the "window_msec()" /// window. template <typename T = uint32_t> class basic_time_spacing_throttle { public: basic_time_spacing_throttle(uint32_t a_rate, uint32_t a_window_msec = 1000, time_val a_now = now_utc()) : m_rate (a_rate) , m_window_us (a_window_msec * 1000) , m_step_us (m_window_us / m_rate) , m_next_time (a_now) {} /// Add \a a_samples to the throtlle's counter. /// @return number of samples that fit in the throttling window. 0 means /// that the throttler is fully congested, and more time needs to elapse /// before the throttles gets reset to accept more samples. T add(T a_samples = 1, time_val a_now = now_utc()) { auto next_time = m_next_time; next_time.add_usec(a_samples * m_step_us); auto diff = next_time.microseconds() - (a_now.microseconds() + m_window_us); if (diff < 0) { // All samples fit the throttling threshold m_next_time = next_time; return a_samples; } // Figure out how many samples fit the throttling threshold auto n = std::max<T>(0, a_samples - (T(diff) / m_step_us)); m_next_time.add_usec(n * m_step_us); return n; } T rate() const { return m_rate; } long step() const { return m_step_us; } long window_msec() const { return m_window_us / 1000; } long window_usec() const { return m_window_us; } time_val next_time() const { return m_next_time; } /// Return the number of available samples given \a a_now current time. T available(time_val a_now = now_utc()) const { auto diff = (a_now - m_next_time).microseconds(); return diff >= 0 ? m_rate : T(m_window_us + diff) / m_step_us; } private: T m_rate; long m_window_us; T m_step_us; time_val m_next_time; }; using time_spacing_throttle = basic_time_spacing_throttle<>; /** * \brief Efficiently calculates the throttling rate over a number of seconds. * The algorithm implements a variation of token bucket algorithm that * doesn't require to add tokens to the bucket on a timer but rather it * maintains a cirtular buffer of tokens with resolution of 1/BucketsPerSec. * The basic_rate_throttler::add() function is used to adds items to a bucket * associated with the timestamp passed as the first argument to the * function. The throttler::running_sum() returns the total number of * items over the given interval of seconds. The items automatically expire * when the time moves on the successive invocations of the add() method. * @tparam MaxSeconds defines the max number of seconds of data to hold * in the circuling buffer. * @tparam BucketsPerSec defines the number of bucket slots per second. * The larger the number the more accurate the running sum will be. */ template<size_t MaxSeconds = 16, size_t BucketsPerSec = 2> class basic_rate_throttler { public: static const size_t s_max_seconds = upper_power<MaxSeconds,2>::value; static const size_t s_buckets_per_sec = upper_power<BucketsPerSec,2>::value; static const size_t s_log_buckets_sec = log<s_buckets_per_sec,2>::value; static const size_t s_bucket_count = s_max_seconds * s_buckets_per_sec; static const size_t s_bucket_mask = s_bucket_count - 1; explicit basic_rate_throttler(int a_interval = 1) : m_interval(-1) { init(a_interval); } basic_rate_throttler (const basic_rate_throttler&) = default; basic_rate_throttler (basic_rate_throttler&&) = default; basic_rate_throttler& operator=(const basic_rate_throttler&) = default; /// Initialize the internal buffer setting the throttling interval /// measured in seconds. void init(int a_throttle_interval) throw(badarg_error) { if (a_throttle_interval == m_interval) return; m_interval = a_throttle_interval << s_log_buckets_sec; if (a_throttle_interval < 0 || (size_t)a_throttle_interval > s_bucket_count / s_buckets_per_sec) throw badarg_error("Invalid throttle interval:", a_throttle_interval); reset(); } /// Reset the inturnal circular buffer. void reset() { memset(m_buckets, 0, sizeof(m_buckets)); m_last_time = 0; m_sum = 0; } /// Return running interval. long interval() const { return m_interval >> s_log_buckets_sec; } /// Return current running sum over the interval. long running_sum() const { return m_sum; } /// Return current running sum over the interval. double running_avg() const { return (double)m_sum / (m_interval >> s_log_buckets_sec); } /// Add \a a_count number of items to the bucket associated with \a a_time. /// @param a_time is monotonically increasing time value. /// @param a_count is the count to add to the bucket associated with \a a_time. /// @return current running sum. long add(time_val a_time, int a_count = 1); /// Update current timestamp. long refresh(time_val a_time) { return add(a_time, 0); } /// Dump the internal state to stream void dump(std::ostream& out, time_val a_time); private: size_t m_buckets[s_bucket_count]; time_t m_last_time; long m_sum; long m_interval; // must be power of two BOOST_STATIC_ASSERT((s_bucket_count & (s_bucket_count - 1)) == 0); }; //------------------------------------------------------------------------------ // Implementation //------------------------------------------------------------------------------ template<size_t MaxSeconds, size_t BucketsPerSec> long basic_rate_throttler<MaxSeconds, BucketsPerSec>:: add(time_val a_time, int a_count) { time_t l_now = (time_t)(a_time.seconds() * s_buckets_per_sec); if (unlikely(!m_last_time)) m_last_time = l_now; int l_bucket = l_now & s_bucket_mask; long l_time_diff = l_now - m_last_time; if (unlikely(l_now < m_last_time)) { // Clock was adjusted m_buckets[l_bucket] = a_count; m_sum = a_count; } else if (!l_time_diff) { m_sum += a_count; m_buckets[l_bucket] += a_count; } else if (l_time_diff >= m_interval) { int l_start = (l_now - m_interval + 1) & s_bucket_mask; int l_end = l_now & s_bucket_mask; for (int i = l_start; i != l_end; i = (i+1) & s_bucket_mask) m_buckets[i] = 0; m_buckets[l_bucket] = a_count; m_sum = a_count; } else { // Calculate sum of buckets from int l_valid_buckets = m_interval - l_time_diff; int l_start, l_end; if (l_valid_buckets <= (m_interval>>1)) { l_start = (l_now - m_interval + 1) & s_bucket_mask; l_end = (m_last_time+1) & s_bucket_mask; m_sum = a_count; #ifdef THROTTLE_DEBUG printf("Summing %d through %d\n", l_start, l_end); #endif for (int i = l_start; i != l_end; i = (i+1) & s_bucket_mask) { m_sum += m_buckets[i]; } l_start = l_end; l_end = l_now & s_bucket_mask; } else { l_start = (m_last_time - m_interval + 1) & s_bucket_mask; l_end = (l_now - m_interval + 1) & s_bucket_mask; #ifdef THROTTLE_DEBUG printf("Subtracting/resetting %d through %d\n", l_start, l_end); #endif for (int i = l_start; i != l_end; i = (i+1) & s_bucket_mask) { m_sum -= m_buckets[i]; // BOOST_ASSERT(m_sum >= 0); if (m_sum < 0) { m_sum = 0; std::cerr << "ERROR " << __FILE__ << ':' << __LINE__ << std::endl; dump(std::cerr, a_time); } m_buckets[i] = 0; } l_start = (m_last_time + 1) & s_bucket_mask; l_end = l_now & s_bucket_mask; m_sum += a_count; } #ifdef THROTTLE_DEBUG printf("Resetting %d through %d\n", l_start, l_end); #endif // Reset values in intermediate buckets since there was no activity there for (int i = l_start; i != l_end; i = (i+1) & s_bucket_mask) m_buckets[i] = 0; m_buckets[l_bucket] = a_count; } m_last_time = l_now; #ifdef THROTTLE_DEBUG dump(std::cout); #endif return m_sum; } template<size_t MaxSeconds, size_t BucketsPerSec> void basic_rate_throttler<MaxSeconds, BucketsPerSec>:: dump(std::ostream& out, time_val a_time) { time_t l_now = (time_t)(a_time.seconds() * s_buckets_per_sec); size_t l_bucket = l_now & s_bucket_mask; char buf[256]; std::stringstream s; sprintf(buf, "last_time=%ld, last_bucket=%3zu, sum=%ld (interval=%ld)\n", m_last_time, l_bucket, m_sum, m_interval); s << buf; int k = 0; size_t n = (l_bucket-m_interval) & s_bucket_mask; for (size_t j=0; j < s_bucket_count; j++) { k += snprintf(buf+k, sizeof(buf)-k, "%3zu%c", j, (j == l_bucket || j == n) ? '|' : ' '); k += snprintf(buf+k, sizeof(buf)-k, "%s", (j < s_bucket_count-1) ? "" : "\n"); } s << buf; k = 0; for (size_t j=0; j < s_bucket_count; j++) { k += snprintf(buf+k, sizeof(buf)-k, "%3zu%c", m_buckets[j], (j == l_bucket || j == n) ? '|' : ' '); k += snprintf(buf+k, sizeof(buf)-k, "%s", (j < s_bucket_count-1) ? "" : "\n"); } s << buf; out << s.str(); } } // namespace utxx #endif // _UTXX_THROTTLER_HPP_ <|endoftext|>
<commit_before>/* <HttpRangeDef.cc> * * This file is part of the x0 web server project and is released under LGPL-3. * http://www.xzero.io/ * * (c) 2009-2012 Christian Parpart <trapni@gentoo.org> */ #ifndef x0_HttpRangeDef_ipp #define x0_HttpRangeDef_ipp #include <x0/Tokenizer.h> // XXX http://tools.ietf.org/html/draft-fielding-http-p5-range-00 #include <cstdlib> namespace x0 { inline HttpRangeDef::HttpRangeDef() : ranges_() { } inline HttpRangeDef::HttpRangeDef(const BufferRef& spec) : ranges_() { parse(spec); } /** * parses an HTTP/1.1 conform Range header \p value. * \param value the HTTP header field value retrieved from the Range header field. * * The following ranges can be specified: * <ul> * <li>explicit range, from \em first to \em last (first-last)</li> * <li>explicit begin to the end of the entity (first-)</li> * <li>the last N units of the entity (-last)</li> * </ul> */ inline bool HttpRangeDef::parse(const BufferRef& value) { // ranges-specifier = byte-ranges-specifier // byte-ranges-specifier = bytes-unit "=" byte-range-set // byte-range-set = 1#( byte-range-spec | suffix-byte-range-spec ) // byte-range-spec = first-byte-pos "-" [last-byte-pos] // first-byte-pos = 1*DIGIT // last-byte-pos = 1*DIGIT // suffix-byte-range-spec = "-" suffix-length // suffix-length = 1*DIGIT for (Tokenizer<BufferRef> spec(value, "="); !spec.end(); spec.nextToken()) { unitName = spec.token(); if (unitName() == "bytes") { for (auto& range: Tokenizer<BufferRef>::tokenize(spec.nextToken(), ",")) { if (!parseRangeSpec(range)) return false; } } } return true; } inline bool HttpRangeDef::parseRangeSpec(const BufferRef& spec) { std::size_t a, b; const char* i = const_cast<char *>(spec.cbegin()); const char* e = spec.cend(); if (i == e) return false; // parse first element char* eptr; a = std::isdigit(*i) ? strtoul(i, &eptr, 10) : npos; i = eptr; if (*i != '-') { // printf("parse error: %s (%s)\n", i, spec.c_str()); return false; } ++i; // parse second element b = std::isdigit(*i) ? strtoul(i, &eptr, 10) : npos; i = eptr; if (i != e) // garbage at the end return false; ranges_.push_back(std::make_pair(a, b)); return true; } inline void HttpRangeDef::push_back(std::size_t offset1, std::size_t offset2) { ranges_.push_back(std::make_pair(offset1, offset2)); } inline void HttpRangeDef::push_back(const std::pair<std::size_t, std::size_t>& range) { ranges_.push_back(range); } inline std::size_t HttpRangeDef::size() const { return ranges_.size(); } inline bool HttpRangeDef::empty() const { return !ranges_.size(); } inline const HttpRangeDef::element_type& HttpRangeDef::operator[](std::size_t index) const { return ranges_[index]; } inline HttpRangeDef::iterator HttpRangeDef::begin() { return ranges_.begin(); } inline HttpRangeDef::iterator HttpRangeDef::end() { return ranges_.end(); } inline HttpRangeDef::const_iterator HttpRangeDef::begin() const { return ranges_.begin(); } inline HttpRangeDef::const_iterator HttpRangeDef::end() const { return ranges_.end(); } inline std::string HttpRangeDef::str() const { std::stringstream sstr; int count = 0; sstr << unitName(); for (const_iterator i = begin(), e = end(); i != e; ++i) { if (count++) { sstr << ", "; } if (i->first != npos) { sstr << i->first; } sstr << '-'; if (i->second != npos) { sstr << i->second; } } return sstr.str(); } } // namespace x0 // vim:syntax=cpp #endif <commit_msg>[http] HttpRangeDef: refs #51<commit_after>/* <HttpRangeDef.cc> * * This file is part of the x0 web server project and is released under LGPL-3. * http://www.xzero.io/ * * (c) 2009-2012 Christian Parpart <trapni@gentoo.org> */ #ifndef x0_HttpRangeDef_ipp #define x0_HttpRangeDef_ipp #include <x0/Tokenizer.h> // XXX http://tools.ietf.org/html/draft-fielding-http-p5-range-00 #include <cstdlib> namespace x0 { inline HttpRangeDef::HttpRangeDef() : ranges_() { } inline HttpRangeDef::HttpRangeDef(const BufferRef& spec) : ranges_() { parse(spec); } /** * parses an HTTP/1.1 conform Range header \p value. * \param value the HTTP header field value retrieved from the Range header field. * * The following ranges can be specified: * <ul> * <li>explicit range, from \em first to \em last (first-last)</li> * <li>explicit begin to the end of the entity (first-)</li> * <li>the last N units of the entity (-last)</li> * </ul> */ inline bool HttpRangeDef::parse(const BufferRef& value) { // ranges-specifier = byte-ranges-specifier // byte-ranges-specifier = bytes-unit "=" byte-range-set // byte-range-set = 1#( byte-range-spec | suffix-byte-range-spec ) // byte-range-spec = first-byte-pos "-" [last-byte-pos] // first-byte-pos = 1*DIGIT // last-byte-pos = 1*DIGIT // suffix-byte-range-spec = "-" suffix-length // suffix-length = 1*DIGIT for (Tokenizer<BufferRef> spec(value, "="); !spec.end(); spec.nextToken()) { unitName = spec.token(); if (unitName() == "bytes") { for (auto& range: Tokenizer<BufferRef>::tokenize(spec.nextToken(), ",")) { if (!parseRangeSpec(range)) return false; } } } return true; } inline bool HttpRangeDef::parseRangeSpec(const BufferRef& spec) { std::size_t a, b; const char* i = const_cast<char *>(spec.cbegin()); const char* e = spec.cend(); if (i == e) return false; // parse first element char* eptr = const_cast<char*>(i); a = std::isdigit(*i) ? strtoul(i, &eptr, 10) : npos; i = eptr; if (*i != '-') { // printf("parse error: %s (%s)\n", i, spec.c_str()); return false; } ++i; // parse second element b = std::isdigit(*i) ? strtoul(i, &eptr, 10) : npos; i = eptr; if (i != e) // garbage at the end return false; ranges_.push_back(std::make_pair(a, b)); return true; } inline void HttpRangeDef::push_back(std::size_t offset1, std::size_t offset2) { ranges_.push_back(std::make_pair(offset1, offset2)); } inline void HttpRangeDef::push_back(const std::pair<std::size_t, std::size_t>& range) { ranges_.push_back(range); } inline std::size_t HttpRangeDef::size() const { return ranges_.size(); } inline bool HttpRangeDef::empty() const { return !ranges_.size(); } inline const HttpRangeDef::element_type& HttpRangeDef::operator[](std::size_t index) const { return ranges_[index]; } inline HttpRangeDef::iterator HttpRangeDef::begin() { return ranges_.begin(); } inline HttpRangeDef::iterator HttpRangeDef::end() { return ranges_.end(); } inline HttpRangeDef::const_iterator HttpRangeDef::begin() const { return ranges_.begin(); } inline HttpRangeDef::const_iterator HttpRangeDef::end() const { return ranges_.end(); } inline std::string HttpRangeDef::str() const { std::stringstream sstr; int count = 0; sstr << unitName(); for (const_iterator i = begin(), e = end(); i != e; ++i) { if (count++) { sstr << ", "; } if (i->first != npos) { sstr << i->first; } sstr << '-'; if (i->second != npos) { sstr << i->second; } } return sstr.str(); } } // namespace x0 // vim:syntax=cpp #endif <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/legacy_window_manager/initial_browser_window_observer.h" #include "base/bind.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/logging.h" #include "chrome/common/chrome_notification_types.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_service.h" namespace { // Taken from the --initial_chrome_window_mapped_file flag in the chromeos-wm // command line: http://goo.gl/uLwIL const char kInitialWindowFile[] = "/var/run/state/windowmanager/initial-chrome-window-mapped"; void WriteInitialWindowFile() { if (file_util::WriteFile(FilePath(kInitialWindowFile), "", 0) == -1) LOG(ERROR) << "Failed to touch " << kInitialWindowFile; } } // namespace namespace chromeos { InitialBrowserWindowObserver::InitialBrowserWindowObserver() { registrar_.Add(this, chrome::NOTIFICATION_BROWSER_WINDOW_READY, content::NotificationService::AllSources()); } void InitialBrowserWindowObserver::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { registrar_.RemoveAll(); content::BrowserThread::PostTask( content::BrowserThread::IO, FROM_HERE, base::Bind(&WriteInitialWindowFile)); } } // namespace chromeos <commit_msg>Aura: Write initial-chrome-window-mapped file from FILE thread<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 "chrome/browser/chromeos/legacy_window_manager/initial_browser_window_observer.h" #include "base/bind.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/logging.h" #include "chrome/common/chrome_notification_types.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_service.h" namespace { // Taken from the --initial_chrome_window_mapped_file flag in the chromeos-wm // command line: http://goo.gl/uLwIL const char kInitialWindowFile[] = "/var/run/state/windowmanager/initial-chrome-window-mapped"; void WriteInitialWindowFile() { if (file_util::WriteFile(FilePath(kInitialWindowFile), "", 0) == -1) LOG(ERROR) << "Failed to touch " << kInitialWindowFile; } } // namespace namespace chromeos { InitialBrowserWindowObserver::InitialBrowserWindowObserver() { registrar_.Add(this, chrome::NOTIFICATION_BROWSER_WINDOW_READY, content::NotificationService::AllSources()); } void InitialBrowserWindowObserver::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { registrar_.RemoveAll(); content::BrowserThread::PostTask( content::BrowserThread::FILE, FROM_HERE, base::Bind(&WriteInitialWindowFile)); } } // namespace chromeos <|endoftext|>
<commit_before>#include "grid.h" #include <math.h> int SCREEN_HEIGHT = 768, SCREEN_WIDTH = 1024; float PADDING_TOP_BOTTOM = SCREEN_HEIGHT/10; float PADDING_LEFT_RIGHT = SCREEN_WIDTH/10; Grid::Grid() { this->height = SCREEN_HEIGHT-PADDING_TOP_BOTTOM*2; this->width = SCREEN_WIDTH-PADDING_LEFT_RIGHT*2; this->cellWidth = this->width/7; this->cellHeight = this->height/6; this->cursorPosition = 0; this->filledSpaces = 0; for(int i = 0; i < 6; i++) { for(int j = 0; j < 7; j++) { cells[i][j] = 0; } } } /* * * Public interface * */ void Grid::moveCursor(direction dir) { if(dir == LEFT && this->cursorPosition > 0) { this->cursorPosition--; } else if(dir == RIGHT && this->cursorPosition < 6) { this->cursorPosition++; } } bool Grid::dropToken(player currentPlayer) { for(int i = 5; i >= 0; i--) { if(cells[i][this->cursorPosition] == 0) { cells[i][this->cursorPosition] = currentPlayer; this->filledSpaces++; return true; } } return false; } bool Grid::checkEndGame() { if(this->filledSpaces == 6*7) { return true; } return somebodyWon(); } /* * * Draw functions * */ void Grid::draw() { ALLEGRO_COLOR white = al_map_rgb(0,0,0); ALLEGRO_COLOR red = al_map_rgb(208,0,0); ALLEGRO_COLOR blue = al_map_rgb(30,144,255); float coords[7]; for(int i = 0; i < 6; i++) { for(int j = 0; j < 7; j++) { this->cell(i, j, coords); int cellValue = this->cells[i][j]; al_draw_rectangle( coords[0], coords[1], coords[2], coords[3], white, 5.0 ); if(cellValue != 0) { if(cellValue == PLAYER1) { al_draw_filled_circle(coords[4], coords[5], coords[6], blue); } else { al_draw_filled_circle(coords[4], coords[5], coords[6], red); } } } } this->drawCursor(); } void Grid::drawCursor() { ALLEGRO_COLOR white = al_map_rgb(0,0,0); float cursorHeight = sqrt(pow(cellWidth/2, 2.0)-pow(cellWidth/4, 2.0)); float x1 = PADDING_LEFT_RIGHT+(cellWidth/4)+(cellWidth*this->cursorPosition); float y1 = PADDING_TOP_BOTTOM/2-(cursorHeight/2); float x2 = PADDING_LEFT_RIGHT+(cellWidth/4)*3+(cellWidth*this->cursorPosition); float y2 = PADDING_TOP_BOTTOM/2-(cursorHeight/2); float x3 = PADDING_LEFT_RIGHT+(cellWidth/4)*2+(cellWidth*this->cursorPosition); float y3 = (PADDING_TOP_BOTTOM/2)+(cursorHeight/2); al_draw_triangle(x1, y1, x2, y2, x3, y3, white, 5); } /* * * Utility functions * */ void Grid::cell(int i, int j, float* coords) { // x1,y1 coords[0] = ((this->width/7)*j)+PADDING_LEFT_RIGHT; coords[1] = ((this->height/6)*i)+PADDING_TOP_BOTTOM; // x2,y2 coords[2] = ((this->width/7)*j)+cellWidth+PADDING_LEFT_RIGHT; coords[3] = ((this->height/6)*i)+cellHeight+PADDING_TOP_BOTTOM; // x center, y center coords[4] = (coords[0] + coords[2])/2; coords[5] = (coords[1] + coords[3])/2; // radius coords[6] = (cellWidth/100)*25; } bool Grid::somebodyWon() { for(int i = 5; i >= 0; i--) { for(int j = 0; j < 6; j++) { unsigned sameFound = 0; if(cells[i][j] == 0) { continue; } // controllo a destra for(int delta = 0; delta < 4; delta++) { if(j+delta < 7 && cells[i][j] == cells[i][j+delta]) { sameFound++; } } if(sameFound == 4) { printf("controllo a destra: %d\n", sameFound); return true; } sameFound = 0; // controllo in alto for(int delta = 0; delta < 4; delta++) { if(i-delta >= 0 && cells[i][j] == cells[i-delta][j]) { sameFound++; } } if(sameFound == 4) { return true; } sameFound = 0; // controllo in alto a sinistra for(int delta = 0; delta < 4; delta++) { if(i-delta >= 0 && j-delta >= 0 && cells[i][j] == cells[i-delta][j-delta]) { sameFound++; } } if(sameFound == 4) { return true; } sameFound = 0; // controllo in alto a destra for(int delta = 0; delta < 4; delta++) { if(i-delta >= 0 && j+delta < 7 && cells[i][j] == cells[i-delta][j+delta]) { sameFound++; } } if(sameFound == 4) { return true; } } } return false; } <commit_msg>Remove printf of "Controllo a destra"<commit_after>#include "grid.h" #include <math.h> int SCREEN_HEIGHT = 768, SCREEN_WIDTH = 1024; float PADDING_TOP_BOTTOM = SCREEN_HEIGHT/10; float PADDING_LEFT_RIGHT = SCREEN_WIDTH/10; Grid::Grid() { this->height = SCREEN_HEIGHT-PADDING_TOP_BOTTOM*2; this->width = SCREEN_WIDTH-PADDING_LEFT_RIGHT*2; this->cellWidth = this->width/7; this->cellHeight = this->height/6; this->cursorPosition = 0; this->filledSpaces = 0; for(int i = 0; i < 6; i++) { for(int j = 0; j < 7; j++) { cells[i][j] = 0; } } } /* * * Public interface * */ void Grid::moveCursor(direction dir) { if(dir == LEFT && this->cursorPosition > 0) { this->cursorPosition--; } else if(dir == RIGHT && this->cursorPosition < 6) { this->cursorPosition++; } } bool Grid::dropToken(player currentPlayer) { for(int i = 5; i >= 0; i--) { if(cells[i][this->cursorPosition] == 0) { cells[i][this->cursorPosition] = currentPlayer; this->filledSpaces++; return true; } } return false; } bool Grid::checkEndGame() { if(this->filledSpaces == 6*7) { return true; } return somebodyWon(); } /* * * Draw functions * */ void Grid::draw() { ALLEGRO_COLOR white = al_map_rgb(0,0,0); ALLEGRO_COLOR red = al_map_rgb(208,0,0); ALLEGRO_COLOR blue = al_map_rgb(30,144,255); float coords[7]; for(int i = 0; i < 6; i++) { for(int j = 0; j < 7; j++) { this->cell(i, j, coords); int cellValue = this->cells[i][j]; al_draw_rectangle( coords[0], coords[1], coords[2], coords[3], white, 5.0 ); if(cellValue != 0) { if(cellValue == PLAYER1) { al_draw_filled_circle(coords[4], coords[5], coords[6], blue); } else { al_draw_filled_circle(coords[4], coords[5], coords[6], red); } } } } this->drawCursor(); } void Grid::drawCursor() { ALLEGRO_COLOR white = al_map_rgb(0,0,0); float cursorHeight = sqrt(pow(cellWidth/2, 2.0)-pow(cellWidth/4, 2.0)); float x1 = PADDING_LEFT_RIGHT+(cellWidth/4)+(cellWidth*this->cursorPosition); float y1 = PADDING_TOP_BOTTOM/2-(cursorHeight/2); float x2 = PADDING_LEFT_RIGHT+(cellWidth/4)*3+(cellWidth*this->cursorPosition); float y2 = PADDING_TOP_BOTTOM/2-(cursorHeight/2); float x3 = PADDING_LEFT_RIGHT+(cellWidth/4)*2+(cellWidth*this->cursorPosition); float y3 = (PADDING_TOP_BOTTOM/2)+(cursorHeight/2); al_draw_triangle(x1, y1, x2, y2, x3, y3, white, 5); } /* * * Utility functions * */ void Grid::cell(int i, int j, float* coords) { // x1,y1 coords[0] = ((this->width/7)*j)+PADDING_LEFT_RIGHT; coords[1] = ((this->height/6)*i)+PADDING_TOP_BOTTOM; // x2,y2 coords[2] = ((this->width/7)*j)+cellWidth+PADDING_LEFT_RIGHT; coords[3] = ((this->height/6)*i)+cellHeight+PADDING_TOP_BOTTOM; // x center, y center coords[4] = (coords[0] + coords[2])/2; coords[5] = (coords[1] + coords[3])/2; // radius coords[6] = (cellWidth/100)*25; } bool Grid::somebodyWon() { for(int i = 5; i >= 0; i--) { for(int j = 0; j < 6; j++) { unsigned sameFound = 0; if(cells[i][j] == 0) { continue; } // controllo a destra for(int delta = 0; delta < 4; delta++) { if(j+delta < 7 && cells[i][j] == cells[i][j+delta]) { sameFound++; } } if(sameFound == 4) { return true; } sameFound = 0; // controllo in alto for(int delta = 0; delta < 4; delta++) { if(i-delta >= 0 && cells[i][j] == cells[i-delta][j]) { sameFound++; } } if(sameFound == 4) { return true; } sameFound = 0; // controllo in alto a sinistra for(int delta = 0; delta < 4; delta++) { if(i-delta >= 0 && j-delta >= 0 && cells[i][j] == cells[i-delta][j-delta]) { sameFound++; } } if(sameFound == 4) { return true; } sameFound = 0; // controllo in alto a destra for(int delta = 0; delta < 4; delta++) { if(i-delta >= 0 && j+delta < 7 && cells[i][j] == cells[i-delta][j+delta]) { sameFound++; } } if(sameFound == 4) { return true; } } } return false; } <|endoftext|>
<commit_before>#include <stdio.h> #include <sys/types.h> #include <dirent.h> #include <sys/stat.h> #include <string.h> #include <stdlib.h> #include <unistd.h> int do_install = 0; int end_alert = 0; int do_libinstall = 0; int lib_exit = 0; char type[256]; char bin[256]; char hdr[256]; char opc[256]; char doh[256]; char lib[256]; char envy[256]; # include "installer.cxx" #if defined(linux) # define LIBEXT "so" #elif defined(__MACH__) # define LIBEXT "dynlib" #elif #define LIBEXT "dll" #endif void set_system(Fl_Check_Button*, void*) { bindir->value(bin); hdrdir->value(hdr); opcdir->value(opc); doc->value(doh); libdir->value(lib); } Fl_Double_Window* err; void do_alert(char *msg) { err_text->value(msg); end_alert = 0; err->show(); while (end_alert==0) Fl::wait(); err->hide(); } /* Unsure that dir exists with all directories on the way. */ void check_exists(const char *dir) { char test[80]; char *p; int ans; struct stat buf; strcpy(test,dir); // printf("Checking %s\n", dir); p = test; while ((p = strchr(p+1, '/')) != NULL) { *p = '\0'; if (test[0]=='\0') break; // Should not happen // printf("..Checking %s\n", test); ans = stat(test, &buf); if (ans!=0 || !S_ISDIR(buf.st_mode)) { if (ans!=0) { // printf("Directory %s does not exist; creating...\n", test); mkdir(test, 0755); } else { do_alert("Trouble with file; stopping"); exit(1); } } else { // printf("Directory %s OK\n", test); } *p = '/'; } return; } void wrap(char *dest, char *src, const char *file, const char *opcd) { /* Need to setup OPCODEDIR or OPCODEDIR64 */ /* This differs according to which shell is being used, so for bash/sh add to .profile "OPCODEDIRxx=yyy; export OPCODEDIRxx" csh/tcsh add to .cshrc "setenv OPCODEDIRxx yyyy" */ char buff[120]; char binlink[256]; char oplink[256]; FILE *rc; //printf("wrap: dest=%s src=%s file=%s opcd=%s\n", dest, src, file, opcd); // Make full address if (bindir->value()[0]!='/') { char bb[200]; getcwd(bb, 200); sprintf(binlink, "%s/%s", bb, src); } else strcpy(binlink, src); //printf(" : binlink=%s\n", binlink); if (opcdir->value()[0]!='/') { char bb[200]; getcwd(bb, 200); sprintf(oplink, "%s/%s", bb, opcd); } else strcpy(oplink, opcd); //printf(" : oplink=%s\n", oplink); sprintf(buff, "%s/%s", dest, file); rc = fopen(buff, "w"); fprintf(rc, "#!/bin/sh\nexport %s=\"%s\"\nexec \"%s%s\" \"$@\"\n", envy, oplink, binlink, file); fclose(rc); chmod(buff,S_IEXEC|S_IREAD|S_IWRITE|S_IXGRP|S_IRGRP|S_IXOTH|S_IROTH); } int main(void) { FILE *defs = fopen("def.ins", "r"); Fl_Double_Window* www; char *p; if (defs==0) { err = make_alert(); do_alert("Definitions file is missing"); exit(1); } fgets(type,256,defs); p = strchr(type,'\n'); if (p!=type) *p = '\0'; fgets(bin,256,defs); p = strchr(bin,'\n'); if (p!=bin) *p = '\0'; fgets(hdr,256,defs); p = strchr(hdr,'\n'); if (p!=hdr) *p = '\0'; fgets(opc,256,defs); p = strchr(opc,'\n'); if (p!=opc) *p = '\0'; fgets(doh,256,defs); p = strchr(doh,'\n'); if (p!=doh) *p = '\0'; fgets(lib,256,defs); p = strchr(lib,'\n'); if (p!=lib) *p = '\0'; fgets(envy,256,defs); p = strchr(envy,'\n'); if (p!=envy) *p = '\0'; www = make_window(type); doBin->value(1); doOpc->value(1); www->show(); err = make_alert(); again: while (do_install==0) Fl::wait(1.0); // Check that install is correct if (doBin->value() && strlen(bindir->value())==0) { do_alert("No binary directory"); goto again; } if (doOpc->value() && strlen(opcdir->value())==0) { do_alert("No opcode directory"); goto again; } //Copy binaries if (doBin->value()) { struct dirent **namelist; char b[256]; char c[256]; int n = scandir("./bin", &namelist, NULL, alphasort); int i; float pr = 0; progress->label("binaries"); strcpy(b, bindir->value()); if (b[strlen(b)-1]!='/') strcat(b, "/"); strcpy(c, b); strcat(c, "bin/"); check_exists(c); progress->minimum(0.0f); progress->maximum((float)(n+n)); progress->value(0.0f); Fl::wait(0.1); for (i=0; i<n; i++) if ((namelist[i]->d_name)[0]!='.') { char buff[256]; sprintf(buff,"cp -pv ./bin/%s %s >/dev/null", namelist[i]->d_name,c); //printf("**** %s\n", buff); system(buff); progress->value(pr+= 1.0f); Fl::wait(0.1); if (strlen(opcdir->value())!=0) wrap(b, c, namelist[i]->d_name, opcdir->value()); progress->value(pr+1.0f); Fl::wait(0.1); } else progress->value(pr+= 2.0f); } //Copy headers if (doHdr->value()) { struct dirent **namelist; char b[256]; int n = scandir("./hdr", &namelist, NULL, alphasort); int i; progress->label("headers"); strcpy(b, hdrdir->value()); if (b[strlen(b)-1]!='/') strcat(b, "/"); check_exists(b); progress->minimum(0.0f); progress->maximum((float)n); progress->value(0.0f); Fl::wait(0.1); for (i=0; i<n; i++) if ((namelist[i]->d_name)[0]!='.') { char buff[256]; sprintf(buff,"cp -pv ./hdr/%s %s>/dev/null", namelist[i]->d_name,b); system(buff); progress->value((float)(i+1)); Fl::wait(0.1); } else progress->value((float)(i+1)); } //Copy opcodes if (doOpc->value()) { struct dirent **namelist; char b[256]; int n = scandir("./opc", &namelist, NULL, alphasort); int i; progress->label("opcodes"); strcpy(b, opcdir->value()); if (b[strlen(b)-1]!='/') strcat(b, "/"); check_exists(b); { char c[256]; sprintf(c, "%s/frontends", b); check_exists(c); } progress->minimum(0.0f); progress->maximum((float)n); progress->value(0.0f); Fl::wait(0.1); for (i=0; i<n; i++) if (strcmp(namelist[i]->d_name, "frontends")==0) { char buff[256]; sprintf(buff,"cp -prv ./opc/frontends %s>/dev/null", b); system(buff); progress->value((float)(i+1)); Fl::wait(0.1); } else if ((namelist[i]->d_name)[0]!='.') { char buff[256]; sprintf(buff,"cp -pv ./opc/%s %s>/dev/null", namelist[i]->d_name,b); system(buff); progress->value((float)(i+1)); Fl::wait(0.1); } else progress->value((float)(i+1)); } if (doDoc->value() && strlen(doc->value())!=0) { struct dirent **namelist; char b[256]; int n = scandir("./html", &namelist, NULL, alphasort); int i; progress->label("documentation"); strcpy(b, doc->value()); check_exists(b); if (b[strlen(b)-1]!='/') strcat(b, "/"); check_exists(b); check_exists(doc->value()); progress->minimum(0.0f); progress->maximum((float)n); progress->value(0.0f); Fl::wait(0.1); for (i=0; i<n; i++) if ((namelist[i]->d_name)[0]!='.') { char buff[256]; sprintf(buff,"cp -pv ./html/%s %s>/dev/null", namelist[i]->d_name,b); system(buff); progress->value((float)(i+1)); Fl::wait(0.1); } else progress->value((float)(i+1)); } if (doLib->value() && strlen(libdir->value())!=0) { char b[256]; Fl_Double_Window *ll = make_libraries(); strcpy(b, libdir->value()); // really ought to pre-mark acording to availability lib_exit = 0; ll->show(); while (lib_exit==0) Fl::wait(); progress->label("libraries"); progress->minimum(0.0f); progress->maximum(7.0); progress->value(0.0f); if (do_libinstall) { char buff[256]; char name[256]; char *p; float n = 0.0f; fgets(name,256,defs); p = strchr(name,'\n'); if (p!=name) *p = '\0'; check_exists(b); sprintf(buff,"cp -pv ./lib/%s %s>/dev/null", name, b); system(buff); progress->value(n+= 1.0f); if (do_asound->value()) { sprintf(buff,"cp -pv ./lib/libasound." LIBEXT ".2 %s>/dev/null", b); system(buff); sprintf(buff,"ln -s %s/libasound." LIBEXT ".2 %s/libasound." LIBEXT,b,b); system(buff); progress->value(n+= 1.0f); } if (do_fluidsynth->value()) { sprintf(buff,"cp -pv ./lib/libfluidsynth." LIBEXT ".1 %s>/dev/null", b); system(buff); sprintf(buff,"ln -s %s/libfluidsynth." LIBEXT ".1 %s/libfluidsynth." LIBEXT,b,b); system(buff); progress->value(n+= 1.0f); } if (do_jack->value()) { sprintf(buff,"cp -pv ./lib/libjack." LIBEXT ".0 %s>/dev/null", b); system(buff); sprintf(buff,"ln -s %s/libjacl.0 %s/libjack." LIBEXT "",b,b); system(buff); progress->value(n+= 1.0f); } if (do_lo->value()) { sprintf(buff,"cp -pv ./lib/liblo." LIBEXT ".0 %s>/dev/null", b); system(buff); sprintf(buff,"ln -s %s/liblo." LIBEXT ".0 %s/liblo." LIBEXT "",b,b); system(buff); progress->value(n+= 1.0f); } if (do_portaudio->value()) { sprintf(buff,"cp -pv ./lib/libportaudio." LIBEXT " %s>/dev/null", b); system(buff); progress->value(n+= 1.0f); } if (do_sndfile->value()) { sprintf(buff,"cp -pv ./lib/libsndfile." LIBEXT ".1 %s>/dev/null", b); system(buff); sprintf(buff,"ln -s %s/libsndfile." LIBEXT ".1 %s/libsndfile." LIBEXT,b,b); system(buff); progress->value(n+= 1.0f); } } } err->color(FL_GRAY); do_alert("Installation finished"); } <commit_msg>Fixed OS X shared library file name extension; code formatting<commit_after>/* new_install.cxx: Copyright (C) 2005 John ffitch This file is part of Csound. The Csound 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. Csound 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 Csound; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <stdio.h> #include <sys/types.h> #include <dirent.h> #include <sys/stat.h> #include <string.h> #include <stdlib.h> #include <unistd.h> int do_install = 0; int end_alert = 0; int do_libinstall = 0; int lib_exit = 0; char type[256]; char bin[256]; char hdr[256]; char opc[256]; char doh[256]; char lib[256]; char envy[256]; #include "installer.cxx" #if defined(linux) # define LIBEXT "so" #elif defined(__MACH__) # define LIBEXT "dylib" #else # define LIBEXT "dll" #endif void set_system(Fl_Check_Button *, void *) { bindir->value(bin); hdrdir->value(hdr); opcdir->value(opc); doc->value(doh); libdir->value(lib); } Fl_Double_Window *err; void do_alert(char *msg) { err_text->value(msg); end_alert = 0; err->show(); while (end_alert == 0) Fl::wait(); err->hide(); } /* Unsure that dir exists with all directories on the way. */ void check_exists(const char *dir) { char test[80]; char *p; int ans; struct stat buf; strcpy(test, dir); // printf("Checking %s\n", dir); p = test; while ((p = strchr(p + 1, '/')) != NULL) { *p = '\0'; if (test[0] == '\0') break; // Should not happen // printf("..Checking %s\n", test); ans = stat(test, &buf); if (ans != 0 || !S_ISDIR(buf.st_mode)) { if (ans != 0) { // printf("Directory %s does not exist; creating...\n", test); mkdir(test, 0755); } else { do_alert("Trouble with file; stopping"); exit(1); } } else { // printf("Directory %s OK\n", test); } *p = '/'; } return; } void wrap(char *dest, char *src, const char *file, const char *opcd) { /* Need to setup OPCODEDIR or OPCODEDIR64 */ /* This differs according to which shell is being used, so for bash/sh add to .profile "OPCODEDIRxx=yyy; export OPCODEDIRxx" csh/tcsh add to .cshrc "setenv OPCODEDIRxx yyyy" */ char buff[120]; char binlink[256]; char oplink[256]; FILE *rc; // printf("wrap: dest=%s src=%s file=%s opcd=%s\n", dest, src, file, opcd); // Make full address if (bindir->value()[0] != '/') { char bb[200]; getcwd(bb, 200); sprintf(binlink, "%s/%s", bb, src); } else strcpy(binlink, src); // printf(" : binlink=%s\n", binlink); if (opcdir->value()[0] != '/') { char bb[200]; getcwd(bb, 200); sprintf(oplink, "%s/%s", bb, opcd); } else strcpy(oplink, opcd); // printf(" : oplink=%s\n", oplink); sprintf(buff, "%s/%s", dest, file); rc = fopen(buff, "w"); fprintf(rc, "#!/bin/sh\nexport %s=\"%s\"\nexec \"%s%s\" \"$@\"\n", envy, oplink, binlink, file); fclose(rc); chmod(buff, S_IEXEC | S_IREAD | S_IWRITE | S_IXGRP | S_IRGRP | S_IXOTH | S_IROTH); } int main(void) { FILE *defs = fopen("def.ins", "r"); Fl_Double_Window *www; char *p; if (defs == 0) { err = make_alert(); do_alert("Definitions file is missing"); exit(1); } fgets(type, 256, defs); p = strchr(type, '\n'); if (p != type) *p = '\0'; fgets(bin, 256, defs); p = strchr(bin, '\n'); if (p != bin) *p = '\0'; fgets(hdr, 256, defs); p = strchr(hdr, '\n'); if (p != hdr) *p = '\0'; fgets(opc, 256, defs); p = strchr(opc, '\n'); if (p != opc) *p = '\0'; fgets(doh, 256, defs); p = strchr(doh, '\n'); if (p != doh) *p = '\0'; fgets(lib, 256, defs); p = strchr(lib, '\n'); if (p != lib) *p = '\0'; fgets(envy, 256, defs); p = strchr(envy, '\n'); if (p != envy) *p = '\0'; www = make_window(type); doBin->value(1); doOpc->value(1); www->show(); err = make_alert(); again: while (do_install == 0) Fl::wait(1.0); // Check that install is correct if (doBin->value() && strlen(bindir->value()) == 0) { do_alert("No binary directory"); goto again; } if (doOpc->value() && strlen(opcdir->value()) == 0) { do_alert("No opcode directory"); goto again; } // Copy binaries if (doBin->value()) { struct dirent **namelist; char b[256]; char c[256]; int n = scandir("./bin", &namelist, NULL, alphasort); int i; float pr = 0; progress->label("binaries"); strcpy(b, bindir->value()); if (b[strlen(b) - 1] != '/') strcat(b, "/"); strcpy(c, b); strcat(c, "bin/"); check_exists(c); progress->minimum(0.0f); progress->maximum((float) (n + n)); progress->value(0.0f); Fl::wait(0.1); for (i = 0; i < n; i++) if ((namelist[i]->d_name)[0] != '.') { char buff[256]; sprintf(buff, "cp -pv ./bin/%s %s >/dev/null", namelist[i]->d_name, c); // printf("**** %s\n", buff); system(buff); progress->value(pr += 1.0f); Fl::wait(0.1); if (strlen(opcdir->value()) != 0) wrap(b, c, namelist[i]->d_name, opcdir->value()); progress->value(pr + 1.0f); Fl::wait(0.1); } else progress->value(pr += 2.0f); } // Copy headers if (doHdr->value()) { struct dirent **namelist; char b[256]; int n = scandir("./hdr", &namelist, NULL, alphasort); int i; progress->label("headers"); strcpy(b, hdrdir->value()); if (b[strlen(b) - 1] != '/') strcat(b, "/"); check_exists(b); progress->minimum(0.0f); progress->maximum((float) n); progress->value(0.0f); Fl::wait(0.1); for (i = 0; i < n; i++) if ((namelist[i]->d_name)[0] != '.') { char buff[256]; sprintf(buff, "cp -pv ./hdr/%s %s>/dev/null", namelist[i]->d_name, b); system(buff); progress->value((float) (i + 1)); Fl::wait(0.1); } else progress->value((float) (i + 1)); } // Copy opcodes if (doOpc->value()) { struct dirent **namelist; char b[256]; int n = scandir("./opc", &namelist, NULL, alphasort); int i; progress->label("opcodes"); strcpy(b, opcdir->value()); if (b[strlen(b) - 1] != '/') strcat(b, "/"); check_exists(b); { char c[256]; sprintf(c, "%s/frontends", b); check_exists(c); } progress->minimum(0.0f); progress->maximum((float) n); progress->value(0.0f); Fl::wait(0.1); for (i = 0; i < n; i++) if (strcmp(namelist[i]->d_name, "frontends") == 0) { char buff[256]; sprintf(buff, "cp -prv ./opc/frontends %s>/dev/null", b); system(buff); progress->value((float) (i + 1)); Fl::wait(0.1); } else if ((namelist[i]->d_name)[0] != '.') { char buff[256]; sprintf(buff, "cp -pv ./opc/%s %s>/dev/null", namelist[i]->d_name, b); system(buff); progress->value((float) (i + 1)); Fl::wait(0.1); } else progress->value((float) (i + 1)); } if (doDoc->value() && strlen(doc->value()) != 0) { struct dirent **namelist; char b[256]; int n = scandir("./html", &namelist, NULL, alphasort); int i; progress->label("documentation"); strcpy(b, doc->value()); check_exists(b); if (b[strlen(b) - 1] != '/') strcat(b, "/"); check_exists(b); check_exists(doc->value()); progress->minimum(0.0f); progress->maximum((float) n); progress->value(0.0f); Fl::wait(0.1); for (i = 0; i < n; i++) if ((namelist[i]->d_name)[0] != '.') { char buff[256]; sprintf(buff, "cp -pv ./html/%s %s>/dev/null", namelist[i]->d_name, b); system(buff); progress->value((float) (i + 1)); Fl::wait(0.1); } else progress->value((float) (i + 1)); } if (doLib->value() && strlen(libdir->value()) != 0) { char b[256]; Fl_Double_Window *ll = make_libraries(); strcpy(b, libdir->value()); // really ought to pre-mark acording to availability lib_exit = 0; ll->show(); while (lib_exit == 0) Fl::wait(); progress->label("libraries"); progress->minimum(0.0f); progress->maximum(7.0); progress->value(0.0f); if (do_libinstall) { char buff[256]; char name[256]; char *p; float n = 0.0f; fgets(name, 256, defs); p = strchr(name, '\n'); if (p != name) *p = '\0'; check_exists(b); sprintf(buff, "cp -pv ./lib/%s %s>/dev/null", name, b); system(buff); progress->value(n += 1.0f); if (do_asound->value()) { sprintf(buff, "cp -pv ./lib/libasound." LIBEXT ".2 %s>/dev/null", b); system(buff); sprintf(buff, "ln -s %s/libasound." LIBEXT ".2 %s/libasound." LIBEXT, b, b); system(buff); progress->value(n += 1.0f); } if (do_fluidsynth->value()) { sprintf(buff, "cp -pv ./lib/libfluidsynth." LIBEXT ".1 %s>/dev/null", b); system(buff); sprintf(buff, "ln -s %s/libfluidsynth." LIBEXT ".1 %s/libfluidsynth." LIBEXT, b, b); system(buff); progress->value(n += 1.0f); } if (do_jack->value()) { sprintf(buff, "cp -pv ./lib/libjack." LIBEXT ".0 %s>/dev/null", b); system(buff); sprintf(buff, "ln -s %s/libjacl.0 %s/libjack." LIBEXT "", b, b); system(buff); progress->value(n += 1.0f); } if (do_lo->value()) { sprintf(buff, "cp -pv ./lib/liblo." LIBEXT ".0 %s>/dev/null", b); system(buff); sprintf(buff, "ln -s %s/liblo." LIBEXT ".0 %s/liblo." LIBEXT "", b, b); system(buff); progress->value(n += 1.0f); } if (do_portaudio->value()) { sprintf(buff, "cp -pv ./lib/libportaudio." LIBEXT " %s>/dev/null", b); system(buff); progress->value(n += 1.0f); } if (do_sndfile->value()) { sprintf(buff, "cp -pv ./lib/libsndfile." LIBEXT ".1 %s>/dev/null", b); system(buff); sprintf(buff, "ln -s %s/libsndfile." LIBEXT ".1 %s/libsndfile." LIBEXT, b, b); system(buff); progress->value(n += 1.0f); } } } err->color(FL_GRAY); do_alert("Installation finished"); } <|endoftext|>
<commit_before>#include <iostream> #include <functional> #include <memory> #include <future> #include "integration_test_helper.h" #include "dronecore.h" using namespace dronecore; using namespace std::placeholders; // for `_1` static std::shared_ptr<MissionItem> add_mission_item(double latitude_deg, double longitude_deg, float relative_altitude_m, float speed_m_s, bool is_fly_through, float gimbal_pitch_deg, float gimbal_yaw_deg, MissionItem::CameraAction camera_action); static void receive_mission_progress(int current, int total, Device *device); static bool _break_done = false; TEST_F(SitlTest, MissionAddWaypointsAndFly) { DroneCore dc; DroneCore::ConnectionResult ret = dc.add_udp_connection(); ASSERT_EQ(ret, DroneCore::ConnectionResult::SUCCESS); // Wait for device to connect via heartbeat. std::this_thread::sleep_for(std::chrono::seconds(2)); Device &device = dc.device(); while (!device.telemetry().health_all_ok()) { LogInfo() << "waiting for device to be ready"; std::this_thread::sleep_for(std::chrono::seconds(1)); } LogInfo() << "Device ready, let's start"; std::vector<std::shared_ptr<MissionItem>> mission_items; mission_items.push_back( add_mission_item(47.398170327054473, 8.5456490218639658, 10.0f, 5.0f, false, 20.0f, 60.0f, MissionItem::CameraAction::NONE)); mission_items.push_back( add_mission_item(47.398241338125118, 8.5455360114574432, 10.0f, 2.0f, true, 0.0f, -60.0f, MissionItem::CameraAction::TAKE_PHOTO)); mission_items.push_back( add_mission_item(47.398139363821485, 8.5453846156597137, 10.0f, 5.0f, true, -46.0f, 0.0f, MissionItem::CameraAction::START_VIDEO)); mission_items.push_back( add_mission_item(47.398058617228855, 8.5454618036746979, 10.0f, 2.0f, false, -90.0f, 30.0f, MissionItem::CameraAction::STOP_VIDEO)); mission_items.push_back( add_mission_item(47.398100366082858, 8.5456969141960144, 10.0f, 5.0f, false, -45.0f, -30.0f, MissionItem::CameraAction::START_PHOTO_INTERVAL)); mission_items.push_back( add_mission_item(47.398001890458097, 8.5455576181411743, 10.0f, 5.0f, false, 0.0f, 0.0f, MissionItem::CameraAction::STOP_PHOTO_INTERVAL)); { // We only have the send_mission function asynchronous for now, so we wrap it using // std::future. auto prom = std::make_shared<std::promise<void>>(); auto future_result = prom->get_future(); device.mission().send_mission_async( mission_items, [prom](Mission::Result result) { EXPECT_EQ(result, Mission::Result::SUCCESS); prom->set_value(); }); future_result.wait(); future_result.get(); } const Action::Result arm_result = device.action().arm(); EXPECT_EQ(arm_result, Action::Result::SUCCESS); // Before starting the mission, we want to be sure to subscribe to the mission progress. // We pass on device to receive_mission_progress because we need it in the callback. device.mission().subscribe_progress(std::bind(&receive_mission_progress, _1, _2, &device)); { auto prom = std::make_shared<std::promise<void>>(); auto future_result = prom->get_future(); device.mission().start_mission_async( [prom](Mission::Result result) { EXPECT_EQ(result, Mission::Result::SUCCESS); prom->set_value(); }); future_result.wait(); future_result.get(); } // Make sure we have taken off before checking for landed. std::this_thread::sleep_for(std::chrono::seconds(5)); // FIXME: this check does currently not work in SITL. while (device.telemetry().in_air()) { // Wait until we're done. std::this_thread::sleep_for(std::chrono::seconds(1)); LogInfo() << "in air"; } LogInfo() << "Landed, exiting."; } std::shared_ptr<MissionItem> add_mission_item(double latitude_deg, double longitude_deg, float relative_altitude_m, float speed_m_s, bool is_fly_through, float gimbal_pitch_deg, float gimbal_yaw_deg, MissionItem::CameraAction camera_action) { std::shared_ptr<MissionItem> new_item(new MissionItem()); new_item->set_position(latitude_deg, longitude_deg); new_item->set_relative_altitude(relative_altitude_m); new_item->set_speed(speed_m_s); new_item->set_fly_through(is_fly_through); new_item->set_gimbal_pitch_and_yaw(gimbal_pitch_deg, gimbal_yaw_deg); new_item->set_camera_action(camera_action); return new_item; } void receive_mission_progress(int current, int total, Device *device) { LogInfo() << "Mission status update: " << current << " / " << total; if (current == 2) { // Some time after the mission item 2, we take a quick break. std::this_thread::sleep_for(std::chrono::seconds(2)); { auto prom = std::make_shared<std::promise<void>>(); auto future_result = prom->get_future(); device->mission().pause_mission_async( [prom](Mission::Result result) { EXPECT_EQ(result, Mission::Result::SUCCESS); prom->set_value(); }); future_result.wait(); future_result.get(); } // We don't want to pause muptiple times in case we get the progress notification // several times. _break_done = true; // Pause for 5 seconds. std::this_thread::sleep_for(std::chrono::seconds(5)); // Then continue. { auto prom = std::make_shared<std::promise<void>>(); auto future_result = prom->get_future(); device->mission().start_mission_async( [prom](Mission::Result result) { EXPECT_EQ(result, Mission::Result::SUCCESS); prom->set_value(); }); future_result.wait(); future_result.get(); } } if (current == total) { // We are done, and can do RTL to go home. const Action::Result result = device->action().return_to_launch(); EXPECT_EQ(result, Action::Result::SUCCESS); } } <commit_msg>integration_tests: actually check if break is done<commit_after>#include <iostream> #include <functional> #include <memory> #include <future> #include "integration_test_helper.h" #include "dronecore.h" using namespace dronecore; using namespace std::placeholders; // for `_1` static std::shared_ptr<MissionItem> add_mission_item(double latitude_deg, double longitude_deg, float relative_altitude_m, float speed_m_s, bool is_fly_through, float gimbal_pitch_deg, float gimbal_yaw_deg, MissionItem::CameraAction camera_action); static void receive_mission_progress(int current, int total, Device *device); static bool _break_done = false; TEST_F(SitlTest, MissionAddWaypointsAndFly) { DroneCore dc; DroneCore::ConnectionResult ret = dc.add_udp_connection(); ASSERT_EQ(ret, DroneCore::ConnectionResult::SUCCESS); // Wait for device to connect via heartbeat. std::this_thread::sleep_for(std::chrono::seconds(2)); Device &device = dc.device(); while (!device.telemetry().health_all_ok()) { LogInfo() << "waiting for device to be ready"; std::this_thread::sleep_for(std::chrono::seconds(1)); } LogInfo() << "Device ready, let's start"; std::vector<std::shared_ptr<MissionItem>> mission_items; mission_items.push_back( add_mission_item(47.398170327054473, 8.5456490218639658, 10.0f, 5.0f, false, 20.0f, 60.0f, MissionItem::CameraAction::NONE)); mission_items.push_back( add_mission_item(47.398241338125118, 8.5455360114574432, 10.0f, 2.0f, true, 0.0f, -60.0f, MissionItem::CameraAction::TAKE_PHOTO)); mission_items.push_back( add_mission_item(47.398139363821485, 8.5453846156597137, 10.0f, 5.0f, true, -46.0f, 0.0f, MissionItem::CameraAction::START_VIDEO)); mission_items.push_back( add_mission_item(47.398058617228855, 8.5454618036746979, 10.0f, 2.0f, false, -90.0f, 30.0f, MissionItem::CameraAction::STOP_VIDEO)); mission_items.push_back( add_mission_item(47.398100366082858, 8.5456969141960144, 10.0f, 5.0f, false, -45.0f, -30.0f, MissionItem::CameraAction::START_PHOTO_INTERVAL)); mission_items.push_back( add_mission_item(47.398001890458097, 8.5455576181411743, 10.0f, 5.0f, false, 0.0f, 0.0f, MissionItem::CameraAction::STOP_PHOTO_INTERVAL)); { // We only have the send_mission function asynchronous for now, so we wrap it using // std::future. auto prom = std::make_shared<std::promise<void>>(); auto future_result = prom->get_future(); device.mission().send_mission_async( mission_items, [prom](Mission::Result result) { EXPECT_EQ(result, Mission::Result::SUCCESS); prom->set_value(); }); future_result.wait(); future_result.get(); } const Action::Result arm_result = device.action().arm(); EXPECT_EQ(arm_result, Action::Result::SUCCESS); // Before starting the mission, we want to be sure to subscribe to the mission progress. // We pass on device to receive_mission_progress because we need it in the callback. device.mission().subscribe_progress(std::bind(&receive_mission_progress, _1, _2, &device)); { auto prom = std::make_shared<std::promise<void>>(); auto future_result = prom->get_future(); device.mission().start_mission_async( [prom](Mission::Result result) { EXPECT_EQ(result, Mission::Result::SUCCESS); prom->set_value(); }); future_result.wait(); future_result.get(); } // Make sure we have taken off before checking for landed. std::this_thread::sleep_for(std::chrono::seconds(5)); // FIXME: this check does currently not work in SITL. while (device.telemetry().in_air()) { // Wait until we're done. std::this_thread::sleep_for(std::chrono::seconds(1)); LogInfo() << "in air"; } LogInfo() << "Landed, exiting."; } std::shared_ptr<MissionItem> add_mission_item(double latitude_deg, double longitude_deg, float relative_altitude_m, float speed_m_s, bool is_fly_through, float gimbal_pitch_deg, float gimbal_yaw_deg, MissionItem::CameraAction camera_action) { std::shared_ptr<MissionItem> new_item(new MissionItem()); new_item->set_position(latitude_deg, longitude_deg); new_item->set_relative_altitude(relative_altitude_m); new_item->set_speed(speed_m_s); new_item->set_fly_through(is_fly_through); new_item->set_gimbal_pitch_and_yaw(gimbal_pitch_deg, gimbal_yaw_deg); new_item->set_camera_action(camera_action); return new_item; } void receive_mission_progress(int current, int total, Device *device) { LogInfo() << "Mission status update: " << current << " / " << total; if (current == 2 && !_break_done) { // Some time after the mission item 2, we take a quick break. std::this_thread::sleep_for(std::chrono::seconds(2)); { auto prom = std::make_shared<std::promise<void>>(); auto future_result = prom->get_future(); device->mission().pause_mission_async( [prom](Mission::Result result) { EXPECT_EQ(result, Mission::Result::SUCCESS); prom->set_value(); }); future_result.wait(); future_result.get(); } // We don't want to pause muptiple times in case we get the progress notification // several times. _break_done = true; // Pause for 5 seconds. std::this_thread::sleep_for(std::chrono::seconds(5)); // Then continue. { auto prom = std::make_shared<std::promise<void>>(); auto future_result = prom->get_future(); device->mission().start_mission_async( [prom](Mission::Result result) { EXPECT_EQ(result, Mission::Result::SUCCESS); prom->set_value(); }); future_result.wait(); future_result.get(); } } if (current == total) { // We are done, and can do RTL to go home. const Action::Result result = device->action().return_to_launch(); EXPECT_EQ(result, Action::Result::SUCCESS); } } <|endoftext|>
<commit_before>/****************************************************************************** * renderwindow_bind.cpp - bindings for Ogre::RenderWindow ****************************************************************************** * This file is part of * __ __ _ * / // /_____ ____ (_) * / // // ___// __ \ / / * / // // /__ / /_/ // / * /_//_/ \___/ \____//_/ * * Low Level C Ogre Interface (llcoi) * * See http://code.google.com/p/llcoi/ for more information. * * Copyright (c) 2011, Llcoi Team * * License: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ #include "ogre_interface.h" #include <OgreRoot.h> #include <OgreRenderWindow.h> #include "ogre_manager.h" void render_window_set_visible(RenderWindowHandle window_handle, int visible) { Ogre::RenderWindow* window = reinterpret_cast<Ogre::RenderWindow*>(window_handle); window->setActive(true); window->setVisible(visible); } size_t render_window_get_hwnd(RenderWindowHandle window_handle) { size_t windowHnd = 0; Ogre::RenderWindow* window = reinterpret_cast<Ogre::RenderWindow*>(window_handle); window->getCustomAttribute("WINDOW", &windowHnd); return windowHnd; } void render_window_update(RenderWindowHandle window_handle, int swap_buffers) { Ogre::RenderWindow* window = reinterpret_cast<Ogre::RenderWindow*>(window_handle); window->update(swap_buffers); } void current_window_update(int swap_buffers) { OgreManager::getSingletonPtr()->getActiveRenderWindow()->update(swap_buffers); } RenderWindowHandle create_render_window(const char* name, const int width, const int height, const int full_screen) { Ogre::RenderWindow* window = Ogre::Root::getSingletonPtr()->createRenderWindow(name, width, height, full_screen); OgreManager::getSingletonPtr()->setActiveRenderWindow(window); return reinterpret_cast<RenderWindowHandle>(window); } DLL RenderWindowHandle create_render_window_hwnd(const char* name, const int width, const int height, const int full_screen, unsigned long hwnd) { Ogre::NameValuePairList misc; misc["parentWindowHandle"] = Ogre::StringConverter::toString(hwnd); Ogre::RenderWindow* window = Ogre::Root::getSingletonPtr()->createRenderWindow(name, width, height, full_screen, &misc); OgreManager::getSingletonPtr()->setActiveRenderWindow(window); window->setActive(true); return reinterpret_cast<RenderWindowHandle>(window); } RenderWindowHandle create_render_window_gl_context(const char* name, const int width, const int height, const int full_screen) { Ogre::NameValuePairList misc; // Tell Ogre to use the current GL context. This works on Linux/GLX but // you *will* need something different on Windows or Mac. misc["currentGLContext"] = Ogre::String("True"); Ogre::RenderWindow* window = Ogre::Root::getSingletonPtr()->createRenderWindow(name, width, height, full_screen, &misc); OgreManager::getSingletonPtr()->setActiveRenderWindow(window); return reinterpret_cast<RenderWindowHandle>(window); } void render_window_resize(unsigned int width, unsigned int height) { OgreManager::getSingletonPtr()->getActiveRenderWindow()->resize(width, height); } void render_window_moved_or_resized() { OgreManager::getSingletonPtr()->getActiveRenderWindow()->windowMovedOrResized(); } int render_window_closed() { if(OgreManager::getSingletonPtr()->getActiveRenderWindow()->isClosed()) return 1; return 0; } // Rendertarget->addViewport ViewportHandle render_window_add_viewport(RenderWindowHandle window_handle, CameraHandle camera_handle, int zorder, float left, float top, float width, float height) { Ogre::RenderWindow* window = reinterpret_cast<Ogre::RenderWindow*>(window_handle); Ogre::Camera* camera = reinterpret_cast<Ogre::Camera*>(camera_handle); return reinterpret_cast<ViewportHandle>(window->addViewport(camera, zorder, left, top, width, height)); } // RenderWindow::isClosed int render_window_is_closed(RenderWindowHandle handle) { Ogre::RenderWindow* window = reinterpret_cast<Ogre::RenderWindow*>(handle); if (window->isClosed()) return 1; return 0; } /* Ogre::RenderWindow::operator=(Ogre::RenderWindow const&) Ogre::RenderWindow::RenderWindow(Ogre::RenderWindow const&) Ogre::RenderWindow::RenderWindow() Ogre::RenderWindow::create(std::string const&, unsigned int, unsigned int, bool, std::map<std::string, std::string, std::less<std::string>, Ogre::STLAllocator<std::pair<std::string const, std::string>, Ogre::CategorisedAllocPolicy<(Ogre::MemoryCategory)0> > > const*) Ogre::RenderWindow::setFullscreen(bool, unsigned int, unsigned int) Ogre::RenderWindow::destroy() Ogre::RenderWindow::resize(unsigned int, unsigned int) Ogre::RenderWindow::windowMovedOrResized() Ogre::RenderWindow::reposition(int, int) Ogre::RenderWindow::isVisible() const Ogre::RenderWindow::setVisible(bool) Ogre::RenderWindow::isHidden() const Ogre::RenderWindow::setHidden(bool) Ogre::RenderWindow::setVSyncEnabled(bool) Ogre::RenderWindow::isVSyncEnabled() const Ogre::RenderWindow::setVSyncInterval(unsigned int) Ogre::RenderWindow::getVSyncInterval() const Ogre::RenderWindow::isActive() const Ogre::RenderWindow::isClosed() const Ogre::RenderWindow::isPrimary() const Ogre::RenderWindow::isFullScreen() const Ogre::RenderWindow::getMetrics(unsigned int&, unsigned int&, unsigned int&, int&, int&) Ogre::RenderWindow::suggestPixelFormat() const Ogre::RenderWindow::isDeactivatedOnFocusChange() const Ogre::RenderWindow::setDeactivateOnFocusChange(bool) Ogre::RenderWindow::~RenderWindow() */ <commit_msg>added method setActive<commit_after>/****************************************************************************** * renderwindow_bind.cpp - bindings for Ogre::RenderWindow ****************************************************************************** * This file is part of * __ __ _ * / // /_____ ____ (_) * / // // ___// __ \ / / * / // // /__ / /_/ // / * /_//_/ \___/ \____//_/ * * Low Level C Ogre Interface (llcoi) * * See http://code.google.com/p/llcoi/ for more information. * * Copyright (c) 2011, Llcoi Team * * License: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ #include "ogre_interface.h" #include <OgreRoot.h> #include <OgreRenderWindow.h> #include "ogre_manager.h" void render_window_set_visible(RenderWindowHandle window_handle, int visible) { Ogre::RenderWindow* window = reinterpret_cast<Ogre::RenderWindow*>(window_handle); window->setActive(true); window->setVisible(visible); } size_t render_window_get_hwnd(RenderWindowHandle window_handle) { size_t windowHnd = 0; Ogre::RenderWindow* window = reinterpret_cast<Ogre::RenderWindow*>(window_handle); window->getCustomAttribute("WINDOW", &windowHnd); return windowHnd; } void render_window_update(RenderWindowHandle window_handle, int swap_buffers) { Ogre::RenderWindow* window = reinterpret_cast<Ogre::RenderWindow*>(window_handle); window->update(swap_buffers); } void current_window_update(int swap_buffers) { OgreManager::getSingletonPtr()->getActiveRenderWindow()->update(swap_buffers); } RenderWindowHandle create_render_window(const char* name, const int width, const int height, const int full_screen) { Ogre::RenderWindow* window = Ogre::Root::getSingletonPtr()->createRenderWindow(name, width, height, full_screen); OgreManager::getSingletonPtr()->setActiveRenderWindow(window); return reinterpret_cast<RenderWindowHandle>(window); } DLL RenderWindowHandle create_render_window_hwnd(const char* name, const int width, const int height, const int full_screen, unsigned long hwnd) { Ogre::NameValuePairList misc; misc["parentWindowHandle"] = Ogre::StringConverter::toString(hwnd); Ogre::RenderWindow* window = Ogre::Root::getSingletonPtr()->createRenderWindow(name, width, height, full_screen, &misc); OgreManager::getSingletonPtr()->setActiveRenderWindow(window); window->setActive(true); return reinterpret_cast<RenderWindowHandle>(window); } RenderWindowHandle create_render_window_gl_context(const char* name, const int width, const int height, const int full_screen) { Ogre::NameValuePairList misc; // Tell Ogre to use the current GL context. This works on Linux/GLX but // you *will* need something different on Windows or Mac. misc["currentGLContext"] = Ogre::String("True"); Ogre::RenderWindow* window = Ogre::Root::getSingletonPtr()->createRenderWindow(name, width, height, full_screen, &misc); OgreManager::getSingletonPtr()->setActiveRenderWindow(window); return reinterpret_cast<RenderWindowHandle>(window); } void render_window_resize(unsigned int width, unsigned int height) { OgreManager::getSingletonPtr()->getActiveRenderWindow()->resize(width, height); } void render_window_moved_or_resized() { OgreManager::getSingletonPtr()->getActiveRenderWindow()->windowMovedOrResized(); } int render_window_closed() { if(OgreManager::getSingletonPtr()->getActiveRenderWindow()->isClosed()) return 1; return 0; } // Rendertarget->addViewport ViewportHandle render_window_add_viewport(RenderWindowHandle window_handle, CameraHandle camera_handle, int zorder, float left, float top, float width, float height) { Ogre::RenderWindow* window = reinterpret_cast<Ogre::RenderWindow*>(window_handle); Ogre::Camera* camera = reinterpret_cast<Ogre::Camera*>(camera_handle); return reinterpret_cast<ViewportHandle>(window->addViewport(camera, zorder, left, top, width, height)); } // RenderWindow::isClosed int render_window_is_closed(RenderWindowHandle handle) { Ogre::RenderWindow* window = reinterpret_cast<Ogre::RenderWindow*>(handle); if (window->isClosed()) return 1; return 0; } void render_window_set_active(RenderWindowHandle handle, int state) { Ogre::RenderWindow* window = reinterpret_cast<Ogre::RenderWindow*>(handle); window->setActive(state); } /* Ogre::RenderWindow::operator=(Ogre::RenderWindow const&) Ogre::RenderWindow::RenderWindow(Ogre::RenderWindow const&) Ogre::RenderWindow::RenderWindow() Ogre::RenderWindow::create(std::string const&, unsigned int, unsigned int, bool, std::map<std::string, std::string, std::less<std::string>, Ogre::STLAllocator<std::pair<std::string const, std::string>, Ogre::CategorisedAllocPolicy<(Ogre::MemoryCategory)0> > > const*) Ogre::RenderWindow::setFullscreen(bool, unsigned int, unsigned int) Ogre::RenderWindow::destroy() Ogre::RenderWindow::resize(unsigned int, unsigned int) Ogre::RenderWindow::windowMovedOrResized() Ogre::RenderWindow::reposition(int, int) Ogre::RenderWindow::isVisible() const Ogre::RenderWindow::setVisible(bool) Ogre::RenderWindow::isHidden() const Ogre::RenderWindow::setHidden(bool) Ogre::RenderWindow::setVSyncEnabled(bool) Ogre::RenderWindow::isVSyncEnabled() const Ogre::RenderWindow::setVSyncInterval(unsigned int) Ogre::RenderWindow::getVSyncInterval() const Ogre::RenderWindow::isActive() const Ogre::RenderWindow::isClosed() const Ogre::RenderWindow::isPrimary() const Ogre::RenderWindow::isFullScreen() const Ogre::RenderWindow::getMetrics(unsigned int&, unsigned int&, unsigned int&, int&, int&) Ogre::RenderWindow::suggestPixelFormat() const Ogre::RenderWindow::isDeactivatedOnFocusChange() const Ogre::RenderWindow::setDeactivateOnFocusChange(bool) Ogre::RenderWindow::~RenderWindow() */ <|endoftext|>
<commit_before>/*************************************************************************/ /* lightmap_raycaster.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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. */ /*************************************************************************/ #ifdef TOOLS_ENABLED #include "lightmap_raycaster.h" #include <pmmintrin.h> LightmapRaycaster *LightmapRaycasterEmbree::create_embree_raycaster() { return memnew(LightmapRaycasterEmbree); } void LightmapRaycasterEmbree::make_default_raycaster() { create_function = create_embree_raycaster; } void LightmapRaycasterEmbree::filter_function(const struct RTCFilterFunctionNArguments *p_args) { RTCHit *hit = (RTCHit *)p_args->hit; unsigned int geomID = hit->geomID; float u = hit->u; float v = hit->v; LightmapRaycasterEmbree *scene = (LightmapRaycasterEmbree *)p_args->geometryUserPtr; RTCGeometry geom = rtcGetGeometry(scene->embree_scene, geomID); rtcInterpolate0(geom, hit->primID, hit->u, hit->v, RTC_BUFFER_TYPE_VERTEX_ATTRIBUTE, 0, &hit->u, 2); if (scene->alpha_textures.has(geomID)) { const AlphaTextureData &alpha_texture = scene->alpha_textures[geomID]; if (alpha_texture.sample(hit->u, hit->v) < 128) { p_args->valid[0] = 0; return; } } rtcInterpolate0(geom, hit->primID, u, v, RTC_BUFFER_TYPE_VERTEX_ATTRIBUTE, 1, &hit->Ng_x, 3); } bool LightmapRaycasterEmbree::intersect(Ray &r_ray) { RTCIntersectContext context; rtcInitIntersectContext(&context); rtcIntersect1(embree_scene, &context, (RTCRayHit *)&r_ray); return r_ray.geomID != RTC_INVALID_GEOMETRY_ID; } void LightmapRaycasterEmbree::intersect(Vector<Ray> &r_rays) { Ray *rays = r_rays.ptrw(); for (int i = 0; i < r_rays.size(); ++i) { intersect(rays[i]); } } void LightmapRaycasterEmbree::set_mesh_alpha_texture(Ref<Image> p_alpha_texture, unsigned int p_id) { if (p_alpha_texture.is_valid() && p_alpha_texture->get_size() != Vector2i()) { AlphaTextureData tex; tex.size = p_alpha_texture->get_size(); tex.data = p_alpha_texture->get_data(); alpha_textures.insert(p_id, tex); } } float blerp(float c00, float c10, float c01, float c11, float tx, float ty) { return Math::lerp(Math::lerp(c00, c10, tx), Math::lerp(c01, c11, tx), ty); } uint8_t LightmapRaycasterEmbree::AlphaTextureData::sample(float u, float v) const { float x = u * size.x; float y = v * size.y; int xi = (int)x; int yi = (int)y; uint8_t texels[4]; for (int i = 0; i < 4; ++i) { int sample_x = CLAMP(xi + i % 2, 0, size.x - 1); int sample_y = CLAMP(yi + i / 2, 0, size.y - 1); texels[i] = data[sample_y * size.x + sample_x]; } return Math::round(blerp(texels[0], texels[1], texels[2], texels[3], x - xi, y - yi)); } void LightmapRaycasterEmbree::add_mesh(const Vector<Vector3> &p_vertices, const Vector<Vector3> &p_normals, const Vector<Vector2> &p_uv2s, unsigned int p_id) { RTCGeometry embree_mesh = rtcNewGeometry(embree_device, RTC_GEOMETRY_TYPE_TRIANGLE); rtcSetGeometryVertexAttributeCount(embree_mesh, 2); int vertex_count = p_vertices.size(); ERR_FAIL_COND(vertex_count % 3 != 0); ERR_FAIL_COND(vertex_count != p_uv2s.size()); ERR_FAIL_COND(!p_normals.is_empty() && vertex_count != p_normals.size()); Vector3 *embree_vertices = (Vector3 *)rtcSetNewGeometryBuffer(embree_mesh, RTC_BUFFER_TYPE_VERTEX, 0, RTC_FORMAT_FLOAT3, sizeof(Vector3), vertex_count); memcpy(embree_vertices, p_vertices.ptr(), sizeof(Vector3) * vertex_count); Vector2 *embree_light_uvs = (Vector2 *)rtcSetNewGeometryBuffer(embree_mesh, RTC_BUFFER_TYPE_VERTEX_ATTRIBUTE, 0, RTC_FORMAT_FLOAT2, sizeof(Vector2), vertex_count); memcpy(embree_light_uvs, p_uv2s.ptr(), sizeof(Vector2) * vertex_count); uint32_t *embree_triangles = (uint32_t *)rtcSetNewGeometryBuffer(embree_mesh, RTC_BUFFER_TYPE_INDEX, 0, RTC_FORMAT_UINT3, sizeof(uint32_t) * 3, vertex_count / 3); for (int i = 0; i < vertex_count; i++) { embree_triangles[i] = i; } if (!p_normals.is_empty()) { Vector3 *embree_normals = (Vector3 *)rtcSetNewGeometryBuffer(embree_mesh, RTC_BUFFER_TYPE_VERTEX_ATTRIBUTE, 1, RTC_FORMAT_FLOAT3, sizeof(Vector3), vertex_count); memcpy(embree_normals, p_normals.ptr(), sizeof(Vector3) * vertex_count); } rtcCommitGeometry(embree_mesh); rtcSetGeometryIntersectFilterFunction(embree_mesh, filter_function); rtcSetGeometryUserData(embree_mesh, this); rtcAttachGeometryByID(embree_scene, embree_mesh, p_id); rtcReleaseGeometry(embree_mesh); } void LightmapRaycasterEmbree::commit() { rtcCommitScene(embree_scene); } void LightmapRaycasterEmbree::set_mesh_filter(const Set<int> &p_mesh_ids) { for (Set<int>::Element *E = p_mesh_ids.front(); E; E = E->next()) { rtcDisableGeometry(rtcGetGeometry(embree_scene, E->get())); } rtcCommitScene(embree_scene); filter_meshes = p_mesh_ids; } void LightmapRaycasterEmbree::clear_mesh_filter() { for (Set<int>::Element *E = filter_meshes.front(); E; E = E->next()) { rtcEnableGeometry(rtcGetGeometry(embree_scene, E->get())); } rtcCommitScene(embree_scene); filter_meshes.clear(); } void embree_error_handler(void *p_user_data, RTCError p_code, const char *p_str) { print_error("Embree error: " + String(p_str)); } LightmapRaycasterEmbree::LightmapRaycasterEmbree() { _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON); embree_device = rtcNewDevice(nullptr); rtcSetDeviceErrorFunction(embree_device, &embree_error_handler, nullptr); embree_scene = rtcNewScene(embree_device); } LightmapRaycasterEmbree::~LightmapRaycasterEmbree() { _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_OFF); _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_OFF); if (embree_scene != nullptr) { rtcReleaseScene(embree_scene); } if (embree_device != nullptr) { rtcReleaseDevice(embree_device); } } #endif <commit_msg>Add checks for __SSE2__ in the lightmap raycaster<commit_after>/*************************************************************************/ /* lightmap_raycaster.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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. */ /*************************************************************************/ #ifdef TOOLS_ENABLED #include "lightmap_raycaster.h" #ifdef __SSE2__ #include <pmmintrin.h> #endif LightmapRaycaster *LightmapRaycasterEmbree::create_embree_raycaster() { return memnew(LightmapRaycasterEmbree); } void LightmapRaycasterEmbree::make_default_raycaster() { create_function = create_embree_raycaster; } void LightmapRaycasterEmbree::filter_function(const struct RTCFilterFunctionNArguments *p_args) { RTCHit *hit = (RTCHit *)p_args->hit; unsigned int geomID = hit->geomID; float u = hit->u; float v = hit->v; LightmapRaycasterEmbree *scene = (LightmapRaycasterEmbree *)p_args->geometryUserPtr; RTCGeometry geom = rtcGetGeometry(scene->embree_scene, geomID); rtcInterpolate0(geom, hit->primID, hit->u, hit->v, RTC_BUFFER_TYPE_VERTEX_ATTRIBUTE, 0, &hit->u, 2); if (scene->alpha_textures.has(geomID)) { const AlphaTextureData &alpha_texture = scene->alpha_textures[geomID]; if (alpha_texture.sample(hit->u, hit->v) < 128) { p_args->valid[0] = 0; return; } } rtcInterpolate0(geom, hit->primID, u, v, RTC_BUFFER_TYPE_VERTEX_ATTRIBUTE, 1, &hit->Ng_x, 3); } bool LightmapRaycasterEmbree::intersect(Ray &r_ray) { RTCIntersectContext context; rtcInitIntersectContext(&context); rtcIntersect1(embree_scene, &context, (RTCRayHit *)&r_ray); return r_ray.geomID != RTC_INVALID_GEOMETRY_ID; } void LightmapRaycasterEmbree::intersect(Vector<Ray> &r_rays) { Ray *rays = r_rays.ptrw(); for (int i = 0; i < r_rays.size(); ++i) { intersect(rays[i]); } } void LightmapRaycasterEmbree::set_mesh_alpha_texture(Ref<Image> p_alpha_texture, unsigned int p_id) { if (p_alpha_texture.is_valid() && p_alpha_texture->get_size() != Vector2i()) { AlphaTextureData tex; tex.size = p_alpha_texture->get_size(); tex.data = p_alpha_texture->get_data(); alpha_textures.insert(p_id, tex); } } float blerp(float c00, float c10, float c01, float c11, float tx, float ty) { return Math::lerp(Math::lerp(c00, c10, tx), Math::lerp(c01, c11, tx), ty); } uint8_t LightmapRaycasterEmbree::AlphaTextureData::sample(float u, float v) const { float x = u * size.x; float y = v * size.y; int xi = (int)x; int yi = (int)y; uint8_t texels[4]; for (int i = 0; i < 4; ++i) { int sample_x = CLAMP(xi + i % 2, 0, size.x - 1); int sample_y = CLAMP(yi + i / 2, 0, size.y - 1); texels[i] = data[sample_y * size.x + sample_x]; } return Math::round(blerp(texels[0], texels[1], texels[2], texels[3], x - xi, y - yi)); } void LightmapRaycasterEmbree::add_mesh(const Vector<Vector3> &p_vertices, const Vector<Vector3> &p_normals, const Vector<Vector2> &p_uv2s, unsigned int p_id) { RTCGeometry embree_mesh = rtcNewGeometry(embree_device, RTC_GEOMETRY_TYPE_TRIANGLE); rtcSetGeometryVertexAttributeCount(embree_mesh, 2); int vertex_count = p_vertices.size(); ERR_FAIL_COND(vertex_count % 3 != 0); ERR_FAIL_COND(vertex_count != p_uv2s.size()); ERR_FAIL_COND(!p_normals.is_empty() && vertex_count != p_normals.size()); Vector3 *embree_vertices = (Vector3 *)rtcSetNewGeometryBuffer(embree_mesh, RTC_BUFFER_TYPE_VERTEX, 0, RTC_FORMAT_FLOAT3, sizeof(Vector3), vertex_count); memcpy(embree_vertices, p_vertices.ptr(), sizeof(Vector3) * vertex_count); Vector2 *embree_light_uvs = (Vector2 *)rtcSetNewGeometryBuffer(embree_mesh, RTC_BUFFER_TYPE_VERTEX_ATTRIBUTE, 0, RTC_FORMAT_FLOAT2, sizeof(Vector2), vertex_count); memcpy(embree_light_uvs, p_uv2s.ptr(), sizeof(Vector2) * vertex_count); uint32_t *embree_triangles = (uint32_t *)rtcSetNewGeometryBuffer(embree_mesh, RTC_BUFFER_TYPE_INDEX, 0, RTC_FORMAT_UINT3, sizeof(uint32_t) * 3, vertex_count / 3); for (int i = 0; i < vertex_count; i++) { embree_triangles[i] = i; } if (!p_normals.is_empty()) { Vector3 *embree_normals = (Vector3 *)rtcSetNewGeometryBuffer(embree_mesh, RTC_BUFFER_TYPE_VERTEX_ATTRIBUTE, 1, RTC_FORMAT_FLOAT3, sizeof(Vector3), vertex_count); memcpy(embree_normals, p_normals.ptr(), sizeof(Vector3) * vertex_count); } rtcCommitGeometry(embree_mesh); rtcSetGeometryIntersectFilterFunction(embree_mesh, filter_function); rtcSetGeometryUserData(embree_mesh, this); rtcAttachGeometryByID(embree_scene, embree_mesh, p_id); rtcReleaseGeometry(embree_mesh); } void LightmapRaycasterEmbree::commit() { rtcCommitScene(embree_scene); } void LightmapRaycasterEmbree::set_mesh_filter(const Set<int> &p_mesh_ids) { for (Set<int>::Element *E = p_mesh_ids.front(); E; E = E->next()) { rtcDisableGeometry(rtcGetGeometry(embree_scene, E->get())); } rtcCommitScene(embree_scene); filter_meshes = p_mesh_ids; } void LightmapRaycasterEmbree::clear_mesh_filter() { for (Set<int>::Element *E = filter_meshes.front(); E; E = E->next()) { rtcEnableGeometry(rtcGetGeometry(embree_scene, E->get())); } rtcCommitScene(embree_scene); filter_meshes.clear(); } void embree_error_handler(void *p_user_data, RTCError p_code, const char *p_str) { print_error("Embree error: " + String(p_str)); } LightmapRaycasterEmbree::LightmapRaycasterEmbree() { #ifdef __SSE2__ _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON); #endif embree_device = rtcNewDevice(nullptr); rtcSetDeviceErrorFunction(embree_device, &embree_error_handler, nullptr); embree_scene = rtcNewScene(embree_device); } LightmapRaycasterEmbree::~LightmapRaycasterEmbree() { #ifdef __SSE2__ _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_OFF); _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_OFF); #endif if (embree_scene != nullptr) { rtcReleaseScene(embree_scene); } if (embree_device != nullptr) { rtcReleaseDevice(embree_device); } } #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: randomwipe.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-07 20:57: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 * ************************************************************************/ #if ! defined INCLUDED_SLIDESHOW_RANDOMWIPE_HXX #define INCLUDED_SLIDESHOW_RANDOMWIPE_HXX #include "parametricpolypolygon.hxx" #include "transitiontools.hxx" #include "basegfx/polygon/b2dpolygon.hxx" #include "basegfx/point/b2dpoint.hxx" #include "boost/scoped_array.hpp" namespace presentation { namespace internal { class RandomWipe : public ParametricPolyPolygon { public: RandomWipe( sal_Int32 nElements, bool randomBars /* true: generates a horizontal random bar wipe, false: generates a dissolve wipe */ ); virtual ::basegfx::B2DPolyPolygon operator () ( double t ); private: ::boost::scoped_array< ::basegfx::B2DPoint > m_positions; sal_Int32 m_nElements; ::basegfx::B2DPolygon m_rect; }; } } #endif /* INCLUDED_SLIDESHOW_RANDOMWIPE_HXX */ <commit_msg>INTEGRATION: CWS presfixes09 (1.3.18); FILE MERGED 2006/04/24 13:25:33 thb 1.3.18.2: #i53194# Unified include statements (local headers always have double quotes; external headers angle brackets); reverted EventMultiplexer pause events to shared_ptr; removed EventMultiplexer::removeViewHandler(), since the handler is held weakly, anyway. 2006/03/24 18:23:25 thb 1.3.18.1: #i37778# Moved whole slideshow engine from namespace presentation (which conflicts with one of the UNO subnamespaces) to slideshow<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: randomwipe.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: kz $ $Date: 2006-12-13 15:44:49 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #if ! defined INCLUDED_SLIDESHOW_RANDOMWIPE_HXX #define INCLUDED_SLIDESHOW_RANDOMWIPE_HXX #include <basegfx/polygon/b2dpolygon.hxx> #include <basegfx/point/b2dpoint.hxx> #include <boost/scoped_array.hpp> #include "parametricpolypolygon.hxx" #include "transitiontools.hxx" namespace slideshow { namespace internal { class RandomWipe : public ParametricPolyPolygon { public: RandomWipe( sal_Int32 nElements, bool randomBars /* true: generates a horizontal random bar wipe, false: generates a dissolve wipe */ ); virtual ::basegfx::B2DPolyPolygon operator () ( double t ); private: ::boost::scoped_array< ::basegfx::B2DPoint > m_positions; sal_Int32 m_nElements; ::basegfx::B2DPolygon m_rect; }; } } #endif /* INCLUDED_SLIDESHOW_RANDOMWIPE_HXX */ <|endoftext|>
<commit_before><commit_msg>Update GeneralServerFeature.cpp<commit_after><|endoftext|>
<commit_before> /** * 所有 #include <外部文件> 的头文件 都必须保证 本文件被首先#include * 以下项目可以由本文件保证包含: * <cstdint> * <cstddef> * 并保证 全局名称空间包含所有stdint。 * CS_DEBUG = 1 时保证 #include <iostream> */ #pragma once /** * 平台兼容原则:以不大的代价换取一定的兼容性;以首要目标平台0-overhead为前提。 */ #ifndef NDEBUG # ifndef CS_DEBUG # define CS_DEBUG 2 # endif # ifndef CS_LOG_ON # define CS_LOG_ON 1 # endif #else # undef CS_DEBUG # define CS_DEBUG 0 # undef CS_LOG_ON # define CS_LOG_ON 0 #endif #if ! CS_DEBUG #ifndef NDEBUG # define NDEBUG #endif # define BOOST_DISABLE_ASSERTS #endif #if defined(__cplusplus) && __cplusplus >= 201103L # define CS_CPP11 1 #else # define CS_CPP11 0 // Use wchar_t/wstring wcout/wcerr/wcin wfstream or not. // It's just a standard, not make used in this file. #ifndef CS_USE_WCS # define CS_USE_WCS 0 #endif // Use wcout/wcerr/wcin or not. This will make use in this file. #ifndef CS_USE_WIO # define CS_USE_WIO 0 #endif #if defined(CS_USE_WCS) && CS_USE_WCS # define CS_STR_LITER(str_liter) L##str_liter #else # define CS_STR_LITER(str_liter) #str_liter #endif #ifndef __GNUC__ # define __attribute__(...) #endif #ifdef __cplusplus // avoid from boost if possible. # if defined(__GNUC__) \ && (!defined(__GXX_EXPERIMENTAL_CXX0X__) || !__GXX_EXPERIMENTAL_CXX0X__) # include <boost/cstdint.hpp> # else # include <cstdint> # endif # include <cstddef> #else # include <stdint.h> # include <stddef.h> #endif #define CS_EXIT_STATUS_FAILED EXIT_FAILURE #ifdef __cplusplus # define CS_PREF_STD(symbol) ::std::symbol #else # define CS_PREF_STD(symbol) symbol #endif #if CS_USE_WIO # define CS_STDIN ::std::wcin # define CS_STDOUT ::std::wcout # define CS_STDERR ::std::wcerr #else # define CS_STDIN ::std::cin # define CS_STDOUT ::std::cout # define CS_STDERR ::std::cerr #endif #ifdef __linux__ # define CS_OC_BLACK(...) "\033[32;30;5m" << __VA_ARGS__ << "\033[0m" # define CS_OC_BLUE(...) "\033[32;34;5m" << __VA_ARGS__ << "\033[0m" # define CS_OC_RED(...) "\033[32;31;5m" << __VA_ARGS__ << "\033[0m" # define CS_OC_GREEN(...) "\033[32;49;5m" << __VA_ARGS__ << "\033[0m" #else # define CS_OC_BLACK(...) __VA_ARGS__ # define CS_OC_BLUE(...) __VA_ARGS__ # define CS_OC_RED(...) __VA_ARGS__ # define CS_OC_GREEN(...) __VA_ARGS__ #endif // line-seperator, should only use for IO.. #ifdef __linux__ # define CS_LINESEP '\n' # define CS_LINESEP_STR "\n" #else # ifdef(__WIN32__) # define CS_LINESEP "\r\n" # define CS_LINESEP_STR CS_LINESEP # else # define CS_LINESEP ::std::endl # define CS_LINESEP_STR ::std::endl() # endif #endif #if CS_DEBUG # define CS_DEBUG_OMIT(...) # include <iostream> # if CS_DEBUG > 1 # if CS_USE_WCS # define CS_OUT(ostream, ...) \ do { \ ostream << __FILE__ << ":" << __LINE__ \ << ":" << __FUNCTION__ << "()" << ":\t" \ << __VA_ARGS__ \ << ::std::endl; \ } while(false); # else # define CS_OUT(ostream, ...) \ do { \ ostream << CS_OC_BLACK(__FILE__ << ":" << __LINE__) \ << ":" << CS_OC_BLUE(__FUNCTION__ << "()") << ":\t" \ << CS_OC_GREEN(__VA_ARGS__) \ << ::std::endl; \ } while(false); # endif # else # define CS_OUT(ostream, ...) do {ostream << __VA_ARGS__ << ::std::endl;} while(false); # endif #else # define CS_DEBUG_OMIT(...) __VA_ARGS__ # define CS_OUT(ostream, ...) #endif #define CS_SAY(...) CS_OUT(CS_STDOUT, __VA_ARGS__) // NOTE: 要自行 #include <iostream> #define CS_ECHO(...) CS_STDOUT << __VA_ARGS__ << ::std::endl; #define CS_ERR(...) CS_STDERR << __VA_ARGS__ << ::std::endl; // #define CS_DUMP(...) CS_OUT(CS_STDOUT, GOL_OC_BLUE(#__VA_ARGS__) << ": " << GOL_OC_GREEN(__VA_ARGS__)) #define CS_DUMP(...) \ CS_OUT(CS_STDOUT, CS_OC_RED(#__VA_ARGS__) << ":[" << CS_OC_GREEN(__VA_ARGS__) << "]") #define CS_DUMP_N(...) \ CS_OUT(CS_STDOUT, CS_OC_RED(#__VA_ARGS__) << ":" << ::std::endl << CS_OC_GREEN(__VA_ARGS__)) // #define CS_ERR(msg) // CS_STDERR << msg << ::std::endl // --- 要自行 #include <cstdlib> #define CS_DIE(msg) \ CS_ERR(msg); \ ::std::exit(CS_EXIT_STATUS_FAILED) #ifndef CS_USED # ifdef __GNUC__ # define CS_USED __attribute__((__used__)) # else # define CS_USED # endif #endif #ifndef CS_ATTR_CONST # ifdef __GNUC__ # define CS_ATTR_CONST __attribute__((const)) # else # define CS_ATTR_CONST # endif #endif #ifndef CS_MUST_CHECK # ifdef __GNUC__ # define CS_MUST_CHECK __attribute__((warn_unused_result)) # else # define CS_MUST_CHECK # endif #endif #ifndef CS_DEPRECATED # ifdef __GNUC__ # define CS_DEPRECATED __attribute__((deprecated)) # else # define CS_DEPRECATED # endif #endif #ifndef CS_FORCE_INLINE # ifdef __GNUC__ # define CS_FORCE_INLINE __attribute__((always_inline)) # else # define CS_FORCE_INLINE inline # endif #endif #if !defined(CS_LIKELY) && !defined(CS_UNLIKELY) # ifdef __GNUC__ # define CS_LIKELY(...) __builtin_expect(!!(__VA_ARGS__), 1) # define CS_UNLIKELY(...) __builtin_expect(!!(__VA_ARGS__), 0) # define CS_BLIKELY(...) __builtin_expect((__VA_ARGS__), true) # define CS_BUNLIKELY(...) __builtin_expect((__VA_ARGS__), false) # else # define CS_LIKELY(expr) (expr) # define CS_UNLIKELY(expr) (expr) # define CS_BLIKELY(expr) (expr) # define CS_BUNLIKELY(expr) (expr) # endif #endif #ifndef CS_PREFETCH # ifdef __GNUC__ # define CS_PREFETCH(addr,rw,clean) __builtin_prefetch(addr,rw,clean) # else # define CS_PREFETCH(addr,rw,clean) # endif #endif #define CS_RETURN_IF_NORMAL(cond, ...) \ if (cond) \ { \ return __VA_ARGS__; \ } #define CS_RETURN_IF(cond, ...) CS_RETURN_IF_NORMAL(CS_BUNLIKELY(cond), __VA_ARGS__) #define CS_ABORT_IF_NORMAL(cond) \ if (cond) \ { \ ::std::exit(CS_EXIT_STATUS_FAILED); \ } #define CS_ABORT_IF(cond) CS_ABORT_IF_NORMAL(CS_BUNLIKELY(cond)) #define _CS_DIE_IF_NORMAL(cond, info, why) \ if (cond) \ { \ CS_DIE(__FILE__ << ":" << __LINE__ << "::" << __FUNCTION__ << "() die on " << info << ", results from {" << #why << "}."); \ } #define CS_DIE_IF_NORMAL(cond, info) CS_DIE_IF_NORMAL(cond, info, cond) #define CS_DIE_IF(cond, info) _CS_DIE_IF_NORMAL(CS_BUNLIKELY(cond), info, cond) <commit_msg>c++11 flag<commit_after> /** * 所有 #include <外部文件> 的头文件 都必须保证 本文件被首先#include * 以下项目可以由本文件保证包含: * <cstdint> * <cstddef> * 并保证 全局名称空间包含所有stdint。 * CS_DEBUG = 1 时保证 #include <iostream> */ #pragma once /** * 平台兼容原则:以不大的代价换取一定的兼容性;以首要目标平台0-overhead为前提。 */ #ifndef NDEBUG # ifndef CS_DEBUG # define CS_DEBUG 2 # endif # ifndef CS_LOG_ON # define CS_LOG_ON 1 # endif #else # undef CS_DEBUG # define CS_DEBUG 0 # undef CS_LOG_ON # define CS_LOG_ON 0 #endif #if ! CS_DEBUG #ifndef NDEBUG # define NDEBUG #endif # define BOOST_DISABLE_ASSERTS #endif #if defined(__cplusplus) && __cplusplus >= 201103L # define CS_CPP11 1 #else # define CS_CPP11 0 #endif // Use wchar_t/wstring wcout/wcerr/wcin wfstream or not. // It's just a standard, not make used in this file. #ifndef CS_USE_WCS # define CS_USE_WCS 0 #endif // Use wcout/wcerr/wcin or not. This will make use in this file. #ifndef CS_USE_WIO # define CS_USE_WIO 0 #endif #if defined(CS_USE_WCS) && CS_USE_WCS # define CS_STR_LITER(str_liter) L##str_liter #else # define CS_STR_LITER(str_liter) #str_liter #endif #ifndef __GNUC__ # define __attribute__(...) #endif #ifdef __cplusplus // avoid from boost if possible. # if defined(__GNUC__) \ && (!defined(__GXX_EXPERIMENTAL_CXX0X__) || !__GXX_EXPERIMENTAL_CXX0X__) # include <boost/cstdint.hpp> # else # include <cstdint> # endif # include <cstddef> #else # include <stdint.h> # include <stddef.h> #endif #define CS_EXIT_STATUS_FAILED EXIT_FAILURE #ifdef __cplusplus # define CS_PREF_STD(symbol) ::std::symbol #else # define CS_PREF_STD(symbol) symbol #endif #if CS_USE_WIO # define CS_STDIN ::std::wcin # define CS_STDOUT ::std::wcout # define CS_STDERR ::std::wcerr #else # define CS_STDIN ::std::cin # define CS_STDOUT ::std::cout # define CS_STDERR ::std::cerr #endif #ifdef __linux__ # define CS_OC_BLACK(...) "\033[32;30;5m" << __VA_ARGS__ << "\033[0m" # define CS_OC_BLUE(...) "\033[32;34;5m" << __VA_ARGS__ << "\033[0m" # define CS_OC_RED(...) "\033[32;31;5m" << __VA_ARGS__ << "\033[0m" # define CS_OC_GREEN(...) "\033[32;49;5m" << __VA_ARGS__ << "\033[0m" #else # define CS_OC_BLACK(...) __VA_ARGS__ # define CS_OC_BLUE(...) __VA_ARGS__ # define CS_OC_RED(...) __VA_ARGS__ # define CS_OC_GREEN(...) __VA_ARGS__ #endif // line-seperator, should only use for IO.. #ifdef __linux__ # define CS_LINESEP '\n' # define CS_LINESEP_STR "\n" #else # ifdef(__WIN32__) # define CS_LINESEP "\r\n" # define CS_LINESEP_STR CS_LINESEP # else # define CS_LINESEP ::std::endl # define CS_LINESEP_STR ::std::endl() # endif #endif #if CS_DEBUG # define CS_DEBUG_OMIT(...) # include <iostream> # if CS_DEBUG > 1 # if CS_USE_WCS # define CS_OUT(ostream, ...) \ do { \ ostream << __FILE__ << ":" << __LINE__ \ << ":" << __FUNCTION__ << "()" << ":\t" \ << __VA_ARGS__ \ << ::std::endl; \ } while(false); # else # define CS_OUT(ostream, ...) \ do { \ ostream << CS_OC_BLACK(__FILE__ << ":" << __LINE__) \ << ":" << CS_OC_BLUE(__FUNCTION__ << "()") << ":\t" \ << CS_OC_GREEN(__VA_ARGS__) \ << ::std::endl; \ } while(false); # endif # else # define CS_OUT(ostream, ...) do {ostream << __VA_ARGS__ << ::std::endl;} while(false); # endif #else # define CS_DEBUG_OMIT(...) __VA_ARGS__ # define CS_OUT(ostream, ...) #endif #define CS_SAY(...) CS_OUT(CS_STDOUT, __VA_ARGS__) // NOTE: 要自行 #include <iostream> #define CS_ECHO(...) CS_STDOUT << __VA_ARGS__ << ::std::endl; #define CS_ERR(...) CS_STDERR << __VA_ARGS__ << ::std::endl; // #define CS_DUMP(...) CS_OUT(CS_STDOUT, GOL_OC_BLUE(#__VA_ARGS__) << ": " << GOL_OC_GREEN(__VA_ARGS__)) #define CS_DUMP(...) \ CS_OUT(CS_STDOUT, CS_OC_RED(#__VA_ARGS__) << ":[" << CS_OC_GREEN(__VA_ARGS__) << "]") #define CS_DUMP_N(...) \ CS_OUT(CS_STDOUT, CS_OC_RED(#__VA_ARGS__) << ":" << ::std::endl << CS_OC_GREEN(__VA_ARGS__)) // #define CS_ERR(msg) // CS_STDERR << msg << ::std::endl // --- 要自行 #include <cstdlib> #define CS_DIE(msg) \ CS_ERR(msg); \ ::std::exit(CS_EXIT_STATUS_FAILED) #ifndef CS_USED # ifdef __GNUC__ # define CS_USED __attribute__((__used__)) # else # define CS_USED # endif #endif #ifndef CS_ATTR_CONST # ifdef __GNUC__ # define CS_ATTR_CONST __attribute__((const)) # else # define CS_ATTR_CONST # endif #endif #ifndef CS_MUST_CHECK # ifdef __GNUC__ # define CS_MUST_CHECK __attribute__((warn_unused_result)) # else # define CS_MUST_CHECK # endif #endif #ifndef CS_DEPRECATED # ifdef __GNUC__ # define CS_DEPRECATED __attribute__((deprecated)) # else # define CS_DEPRECATED # endif #endif #ifndef CS_FORCE_INLINE # ifdef __GNUC__ # define CS_FORCE_INLINE __attribute__((always_inline)) # else # define CS_FORCE_INLINE inline # endif #endif #if !defined(CS_LIKELY) && !defined(CS_UNLIKELY) # ifdef __GNUC__ # define CS_LIKELY(...) __builtin_expect(!!(__VA_ARGS__), 1) # define CS_UNLIKELY(...) __builtin_expect(!!(__VA_ARGS__), 0) # define CS_BLIKELY(...) __builtin_expect((__VA_ARGS__), true) # define CS_BUNLIKELY(...) __builtin_expect((__VA_ARGS__), false) # else # define CS_LIKELY(expr) (expr) # define CS_UNLIKELY(expr) (expr) # define CS_BLIKELY(expr) (expr) # define CS_BUNLIKELY(expr) (expr) # endif #endif #ifndef CS_PREFETCH # ifdef __GNUC__ # define CS_PREFETCH(addr,rw,clean) __builtin_prefetch(addr,rw,clean) # else # define CS_PREFETCH(addr,rw,clean) # endif #endif #define CS_RETURN_IF_NORMAL(cond, ...) \ if (cond) \ { \ return __VA_ARGS__; \ } #define CS_RETURN_IF(cond, ...) CS_RETURN_IF_NORMAL(CS_BUNLIKELY(cond), __VA_ARGS__) #define CS_ABORT_IF_NORMAL(cond) \ if (cond) \ { \ ::std::exit(CS_EXIT_STATUS_FAILED); \ } #define CS_ABORT_IF(cond) CS_ABORT_IF_NORMAL(CS_BUNLIKELY(cond)) #define _CS_DIE_IF_NORMAL(cond, info, why) \ if (cond) \ { \ CS_DIE(__FILE__ << ":" << __LINE__ << "::" << __FUNCTION__ << "() die on " << info << ", results from {" << #why << "}."); \ } #define CS_DIE_IF_NORMAL(cond, info) CS_DIE_IF_NORMAL(cond, info, cond) #define CS_DIE_IF(cond, info) _CS_DIE_IF_NORMAL(CS_BUNLIKELY(cond), info, cond) <|endoftext|>
<commit_before>/*********************************************************************** dbdriver.cpp - Implements the DBDriver class. Copyright (c) 2005-2009 by Educational Technology Resources, Inc. Others may also hold copyrights on code in this file. See the CREDITS.txt file in the top directory of the distribution for details. This file is part of MySQL++. MySQL++ 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. MySQL++ 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 MySQL++; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #define MYSQLPP_NOT_HEADER #include "dbdriver.h" #include "exceptions.h" #include <cstring> #include <memory> #include <sstream> // An argument was added to mysql_shutdown() in MySQL 4.1.3 and 5.0.1. #if ((MYSQL_VERSION_ID >= 40103) && (MYSQL_VERSION_ID <= 49999)) || (MYSQL_VERSION_ID >= 50001) # define SHUTDOWN_ARG ,SHUTDOWN_DEFAULT #else # define SHUTDOWN_ARG #endif using namespace std; namespace mysqlpp { DBDriver::DBDriver() : is_connected_(false) { // We won't allow calls to mysql_*() functions that take a MYSQL // object until we get a connection up. Such calls are nonsense. // MySQL++ coped with them before, but this masks bugs. memset(&mysql_, 0, sizeof(mysql_)); } DBDriver::DBDriver(const DBDriver& other) : is_connected_(false) { copy(other); } DBDriver::~DBDriver() { if (connected()) { disconnect(); } OptionList::const_iterator it; for (it = applied_options_.begin(); it != applied_options_.end(); ++it) { delete *it; } } bool DBDriver::connect(const char* host, const char* socket_name, unsigned int port, const char* db, const char* user, const char* password) { return is_connected_ = connect_prepare() && mysql_real_connect(&mysql_, host, user, password, db, port, socket_name, mysql_.client_flag); } bool DBDriver::connect(const MYSQL& other) { return is_connected_ = connect_prepare() && mysql_real_connect(&mysql_, other.host, other.user, other.passwd, other.db, other.port, other.unix_socket, other.client_flag); } bool DBDriver::connect_prepare() { // Drop previous connection, if any, then prepare underlying C API // library to establish a new connection. if (connected()) { disconnect(); } // Set up to call MySQL C API mysql_init(&mysql_); // Apply any pending options error_message_.clear(); OptionListIt it = pending_options_.begin(); while (it != pending_options_.end() && set_option_impl(*it)) { ++it; } if (it == pending_options_.end()) { pending_options_.clear(); return true; } else { return false; } } void DBDriver::copy(const DBDriver& other) { if (other.connected()) { connect(other.mysql_); } else { is_connected_ = false; } } void DBDriver::disconnect() { if (is_connected_) { mysql_close(&mysql_); memset(&mysql_, 0, sizeof(mysql_)); is_connected_ = false; error_message_.clear(); } } bool DBDriver::enable_ssl(const char* key, const char* cert, const char* ca, const char* capath, const char* cipher) { error_message_.clear(); #if defined(HAVE_MYSQL_SSL_SET) return mysql_ssl_set(&mysql_, key, cert, ca, capath, cipher) == 0; #else (void)key; (void)cert; (void)ca; (void)capath; (void)cipher; return false; #endif } size_t DBDriver::escape_string(std::string* ps, const char* original, size_t length) { error_message_.clear(); if (ps == 0) { // Can't do any real work! return 0; } else if (original == 0) { // ps must point to the original data as well as to the // receiving string, so get the pointer and the length from it. original = ps->data(); length = ps->length(); } else if (length == 0) { // We got a pointer to a C++ string just for holding the result // and also a C string pointing to the original, so find the // length of the original. length = strlen(original); } char* escaped = new char[length * 2 + 1]; length = escape_string(escaped, original, length); ps->assign(escaped, length); delete[] escaped; return length; } size_t DBDriver::escape_string_no_conn(std::string* ps, const char* original, size_t length) { if (ps == 0) { // Can't do any real work! return 0; } else if (original == 0) { // ps must point to the original data as well as to the // receiving string, so get the pointer and the length from it. original = ps->data(); length = ps->length(); } else if (length == 0) { // We got a pointer to a C++ string just for holding the result // and also a C string pointing to the original, so find the // length of the original. length = strlen(original); } char* escaped = new char[length * 2 + 1]; length = DBDriver::escape_string_no_conn(escaped, original, length); ps->assign(escaped, length); delete[] escaped; return length; } DBDriver& DBDriver::operator=(const DBDriver& rhs) { copy(rhs); return *this; } string DBDriver::query_info() { error_message_.clear(); const char* i = mysql_info(&mysql_); return i ? string(i) : string(); } bool DBDriver::set_option(unsigned int o, bool arg) { // If we get through this loop and n is 1, only one bit is set in // the option value, which is as it should be. int n = o; while (n && ((n & 1) == 0)) { n >>= 1; } if ((n == 1) && (o >= CLIENT_LONG_PASSWORD) && #if MYSQL_VERSION_ID > 40000 // highest flag value varies by version (o <= CLIENT_MULTI_RESULTS) #else (o <= CLIENT_TRANSACTIONS) #endif ) { // Option value seems sane, so go ahead and set/clear the flag if (arg) { mysql_.client_flag |= o; } else { mysql_.client_flag &= ~o; } return true; } else { // Option value is outside the range we understand, or caller // erroneously passed a value with multiple bits set. return false; } } bool DBDriver::set_option(Option* o) { if (connected()) { return set_option_impl(o); } else { error_message_.clear(); pending_options_.push_back(o); return true; // we won't know if it fails until ::connect() } } bool DBDriver::set_option_impl(Option* o) { std::ostringstream os; std::auto_ptr<Option> cleanup(o); switch (o->set(this)) { case Option::err_NONE: applied_options_.push_back(o); cleanup.release(); break; case Option::err_api_limit: os << "Option not supported by database driver v" << client_version(); throw BadOption(os.str(), typeid(*o)); // mandatory throw! case Option::err_api_reject: os << "Database driver failed to set option"; break; case Option::err_connected: os << "Option can only be set before connection is established"; break; case Option::err_disconnected: os << "Option can only be set while the connection is established"; break; } error_message_ = os.str(); return error_message_.empty(); } bool DBDriver::shutdown() { error_message_.clear(); return mysql_shutdown(&mysql_ SHUTDOWN_ARG); } bool DBDriver::thread_aware() { #if defined(MYSQLPP_PLATFORM_WINDOWS) || defined(HAVE_PTHREAD) || defined(HAVE_SYNCH_H) // Okay, good, MySQL++ itself is thread-aware, but only return true // if the underlying C API library is also thread-aware. return mysql_thread_safe(); #else // MySQL++ itself isn't thread-aware, so we don't need to do any // further tests. All pieces must be thread-aware to return true. return false; #endif } } // end namespace mysqlpp <commit_msg>The DBDriver::operator= would leak a live connection if you assigned a disconnected DBDriver to it. Patch by Quentin Armitage <quentin@armitage.org.uk><commit_after>/*********************************************************************** dbdriver.cpp - Implements the DBDriver class. Copyright (c) 2005-2009 by Educational Technology Resources, Inc. Others may also hold copyrights on code in this file. See the CREDITS.txt file in the top directory of the distribution for details. This file is part of MySQL++. MySQL++ 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. MySQL++ 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 MySQL++; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #define MYSQLPP_NOT_HEADER #include "dbdriver.h" #include "exceptions.h" #include <cstring> #include <memory> #include <sstream> // An argument was added to mysql_shutdown() in MySQL 4.1.3 and 5.0.1. #if ((MYSQL_VERSION_ID >= 40103) && (MYSQL_VERSION_ID <= 49999)) || (MYSQL_VERSION_ID >= 50001) # define SHUTDOWN_ARG ,SHUTDOWN_DEFAULT #else # define SHUTDOWN_ARG #endif using namespace std; namespace mysqlpp { DBDriver::DBDriver() : is_connected_(false) { // We won't allow calls to mysql_*() functions that take a MYSQL // object until we get a connection up. Such calls are nonsense. // MySQL++ coped with them before, but this masks bugs. memset(&mysql_, 0, sizeof(mysql_)); } DBDriver::DBDriver(const DBDriver& other) : is_connected_(false) { copy(other); } DBDriver::~DBDriver() { if (connected()) { disconnect(); } OptionList::const_iterator it; for (it = applied_options_.begin(); it != applied_options_.end(); ++it) { delete *it; } } bool DBDriver::connect(const char* host, const char* socket_name, unsigned int port, const char* db, const char* user, const char* password) { return is_connected_ = connect_prepare() && mysql_real_connect(&mysql_, host, user, password, db, port, socket_name, mysql_.client_flag); } bool DBDriver::connect(const MYSQL& other) { return is_connected_ = connect_prepare() && mysql_real_connect(&mysql_, other.host, other.user, other.passwd, other.db, other.port, other.unix_socket, other.client_flag); } bool DBDriver::connect_prepare() { // Drop previous connection, if any, then prepare underlying C API // library to establish a new connection. if (connected()) { disconnect(); } // Set up to call MySQL C API mysql_init(&mysql_); // Apply any pending options error_message_.clear(); OptionListIt it = pending_options_.begin(); while (it != pending_options_.end() && set_option_impl(*it)) { ++it; } if (it == pending_options_.end()) { pending_options_.clear(); return true; } else { return false; } } void DBDriver::copy(const DBDriver& other) { if (connected()) { disconnect(); } if (other.connected()) { connect(other.mysql_); } } void DBDriver::disconnect() { if (is_connected_) { mysql_close(&mysql_); memset(&mysql_, 0, sizeof(mysql_)); is_connected_ = false; error_message_.clear(); } } bool DBDriver::enable_ssl(const char* key, const char* cert, const char* ca, const char* capath, const char* cipher) { error_message_.clear(); #if defined(HAVE_MYSQL_SSL_SET) return mysql_ssl_set(&mysql_, key, cert, ca, capath, cipher) == 0; #else (void)key; (void)cert; (void)ca; (void)capath; (void)cipher; return false; #endif } size_t DBDriver::escape_string(std::string* ps, const char* original, size_t length) { error_message_.clear(); if (ps == 0) { // Can't do any real work! return 0; } else if (original == 0) { // ps must point to the original data as well as to the // receiving string, so get the pointer and the length from it. original = ps->data(); length = ps->length(); } else if (length == 0) { // We got a pointer to a C++ string just for holding the result // and also a C string pointing to the original, so find the // length of the original. length = strlen(original); } char* escaped = new char[length * 2 + 1]; length = escape_string(escaped, original, length); ps->assign(escaped, length); delete[] escaped; return length; } size_t DBDriver::escape_string_no_conn(std::string* ps, const char* original, size_t length) { if (ps == 0) { // Can't do any real work! return 0; } else if (original == 0) { // ps must point to the original data as well as to the // receiving string, so get the pointer and the length from it. original = ps->data(); length = ps->length(); } else if (length == 0) { // We got a pointer to a C++ string just for holding the result // and also a C string pointing to the original, so find the // length of the original. length = strlen(original); } char* escaped = new char[length * 2 + 1]; length = DBDriver::escape_string_no_conn(escaped, original, length); ps->assign(escaped, length); delete[] escaped; return length; } DBDriver& DBDriver::operator=(const DBDriver& rhs) { copy(rhs); return *this; } string DBDriver::query_info() { error_message_.clear(); const char* i = mysql_info(&mysql_); return i ? string(i) : string(); } bool DBDriver::set_option(unsigned int o, bool arg) { // If we get through this loop and n is 1, only one bit is set in // the option value, which is as it should be. int n = o; while (n && ((n & 1) == 0)) { n >>= 1; } if ((n == 1) && (o >= CLIENT_LONG_PASSWORD) && #if MYSQL_VERSION_ID > 40000 // highest flag value varies by version (o <= CLIENT_MULTI_RESULTS) #else (o <= CLIENT_TRANSACTIONS) #endif ) { // Option value seems sane, so go ahead and set/clear the flag if (arg) { mysql_.client_flag |= o; } else { mysql_.client_flag &= ~o; } return true; } else { // Option value is outside the range we understand, or caller // erroneously passed a value with multiple bits set. return false; } } bool DBDriver::set_option(Option* o) { if (connected()) { return set_option_impl(o); } else { error_message_.clear(); pending_options_.push_back(o); return true; // we won't know if it fails until ::connect() } } bool DBDriver::set_option_impl(Option* o) { std::ostringstream os; std::auto_ptr<Option> cleanup(o); switch (o->set(this)) { case Option::err_NONE: applied_options_.push_back(o); cleanup.release(); break; case Option::err_api_limit: os << "Option not supported by database driver v" << client_version(); throw BadOption(os.str(), typeid(*o)); // mandatory throw! case Option::err_api_reject: os << "Database driver failed to set option"; break; case Option::err_connected: os << "Option can only be set before connection is established"; break; case Option::err_disconnected: os << "Option can only be set while the connection is established"; break; } error_message_ = os.str(); return error_message_.empty(); } bool DBDriver::shutdown() { error_message_.clear(); return mysql_shutdown(&mysql_ SHUTDOWN_ARG); } bool DBDriver::thread_aware() { #if defined(MYSQLPP_PLATFORM_WINDOWS) || defined(HAVE_PTHREAD) || defined(HAVE_SYNCH_H) // Okay, good, MySQL++ itself is thread-aware, but only return true // if the underlying C API library is also thread-aware. return mysql_thread_safe(); #else // MySQL++ itself isn't thread-aware, so we don't need to do any // further tests. All pieces must be thread-aware to return true. return false; #endif } } // end namespace mysqlpp <|endoftext|>
<commit_before>#include <iostream> #include "bmp.hh" namespace DG { namespace Image { void BMP::open(const std::string& fname) { std::ifstream ifs(fname, std::ios::binary); ifs >> data; } void BMP::write(const std::string& fname) { std::ofstream ofs(fname, std::ios::binary); ofs << data; } void BMP::byte_set_mask(int index, unsigned mask) { unsigned byte = data.byte_array[index]; byte |= mask; data.byte_array[index] = byte; return; } void BMP::byte_unset_mask(int index, unsigned mask) { unsigned byte = data.byte_array[index]; byte &= ~mask; data.byte_array[index] = byte; return; } //// friend non-member operators std::ostream& operator<<(std::ostream& os, const DG::Image::BMP& bmp) { return os; } std::istream& operator>>(std::istream& is, DG::Image::BMP& bmp) { return is; } } } <commit_msg>Fixed byte mask implementations so that tests now pass<commit_after>#include <iostream> #include "bmp.hh" namespace DG { namespace Image { void BMP::open(const std::string& fname) { std::ifstream ifs(fname, std::ios::binary); ifs >> data; } void BMP::write(const std::string& fname) { std::ofstream ofs(fname, std::ios::binary); ofs << data; } void BMP::byte_set_mask(int index, unsigned mask) { unsigned byte = data.byte_array[index + data.image_offset()]; byte |= mask; data.byte_array[index + data.image_offset()] = byte; return; } void BMP::byte_unset_mask(int index, unsigned mask) { unsigned byte = data.byte_array[index + data.image_offset()]; byte &= ~mask; data.byte_array[index + data.image_offset()] = byte; return; } //// friend non-member operators std::ostream& operator<<(std::ostream& os, const DG::Image::BMP& bmp) { return os; } std::istream& operator>>(std::istream& is, DG::Image::BMP& bmp) { return is; } } } <|endoftext|>
<commit_before>//============================================================================= //File Name: ButtonTracker.hpp //Description: Helps user determine if joystick button was just pressed or just // released //Author: FRC Team 3512, Spartatroniks //============================================================================= #ifndef BUTTON_TRACKER_HPP #define BUTTON_TRACKER_HPP /* This class allows you to check if a button was pressed or released without * having to wait in one spot of code until that happens. * * It is useful for situations in which you need to toggle a variable and just * checking for it with Joystick::GetRawButton(UINT32) would cause it to toggle * every loop. * * USAGE * 1) Call updateButtons() at beginning of OperatorControl loop to get new button * statuses from the Driver Station * 2) Call pressedButton(UINT32) or releasedButton(UINT32) to poll for whether the * button was pressed or released since last loop * * None of these functions block. */ class DriverStation; class ButtonTracker { public: ButtonTracker( UINT32 port ); void updateButtons(); // gets new button statuses for joystick from Driver Station bool pressedButton( UINT32 button ); // returns true if button wasn't pressed but is now bool releasedButton( UINT32 button ); // returns true if button was pressed but isn't now protected: UINT32 m_port; private: static bool getButtonState( short& buttonStates , UINT32& button ); static bool m_driverStationInit; static DriverStation* m_driverStation; short m_oldStates; short m_newStates; }; #endif // BUTTON_TRACKER_H <commit_msg>Edited ButtonTracker class description<commit_after>//============================================================================= //File Name: ButtonTracker.hpp //Description: Helps user determine if joystick button was just pressed or just // released //Author: FRC Team 3512, Spartatroniks //============================================================================= #ifndef BUTTON_TRACKER_HPP #define BUTTON_TRACKER_HPP /* This class allows you to check if a button was pressed or released without * having to wait in one spot of code until that happens. * * It is useful for situations in which you need to toggle a variable and just * checking for it with Joystick::GetRawButton(UINT32) would cause it to toggle * in every iteration of a loop. * * USAGE * 1) Call updateButtons() at beginning of loop to get new button statuses from * the Driver Station * 2) Call pressedButton(UINT32) or releasedButton(UINT32) to poll for whether * the button was pressed or released since last loop iteration * * None of these functions block. */ class DriverStation; class ButtonTracker { public: ButtonTracker( UINT32 port ); void updateButtons(); // gets new button statuses for joystick from Driver Station bool pressedButton( UINT32 button ); // returns true if button wasn't pressed but is now bool releasedButton( UINT32 button ); // returns true if button was pressed but isn't now protected: UINT32 m_port; private: static bool getButtonState( short& buttonStates , UINT32& button ); static bool m_driverStationInit; static DriverStation* m_driverStation; short m_oldStates; short m_newStates; }; #endif // BUTTON_TRACKER_H <|endoftext|>
<commit_before>#include "cnn/training.h" #include "cnn/gpu-ops.h" namespace cnn { using namespace std; Trainer::~Trainer() {} /** @scale : proportional to the number of samples trained in parallel */ float Trainer::clip_gradients(float samples) { float gscale = 1; if (clipping_enabled) { float gg = model->gradient_l2_norm(); if (gg > clip_threshold * samples) { ++clips; gscale = (clip_threshold * samples) / gg; } } return gscale; } void SimpleSGDTrainer::update(float nutt, real scale) { update(model->lookup_parameters_list(), model->parameters_list(), nutt, scale); } void SimpleSGDTrainer::update(const std::vector<LookupParameters*> &lookup_params, const std::vector<Parameters*> &params, float samples, real scale) { const float gscale = clip_gradients(samples); float nutt_scale = 1.0 / samples; for (auto p : params) { #if HAVE_CUDA gpu::sgd_update(p->values.d.size(), p->g.v, p->values.v, eta * scale * gscale * nutt_scale, lambda); #else auto reg = (*p->values) * lambda; *p->values -= nutt_scale * ((eta * scale * gscale) * *p->g + reg); #endif p->clear(); } for (auto p : lookup_params) { for (auto i : p->non_zero_grads) { #if HAVE_CUDA gpu::sgd_update(p->values[i].d.size(), p->grads[i].v, p->values[i].v, eta * scale * gscale * nutt_scale, lambda); #else auto reg = (*p->values[i]) * lambda; *p->values[i] -= (*p->grads[i] * (eta * scale * gscale * nutt_scale) + reg); #endif } p->clear(); } ++updates; } void MomentumSGDTrainer::update(real nutt, real scale) { // executed on the first iteration to create vectors to // store the velocity if (!velocity_allocated) { vp = AllocateShadowParameters(*model); vlp = AllocateShadowLookupParameters(*model); velocity_allocated = true; } const float gscale = clip_gradients(nutt); float nutt_scale = 1.0 / nutt; unsigned pi = 0; for (auto p : model->parameters_list()) { Tensor& v = vp[pi++].h; auto reg = *p->values * lambda; (*v) = momentum * (*v) - (eta * scale * gscale*nutt_scale) * (*p->g); *p->values += *v - reg; p->clear(); } pi = 0; for (auto p : model->lookup_parameters_list()) { vector<Tensor>& vx = vlp[pi++].h; for (auto i : p->non_zero_grads) { Tensor& v = vx[i]; auto reg = (*p->values[i]) * lambda; (*v) = momentum * (*v) - (eta * scale * gscale*nutt_scale) * (*p->grads[i]); *p->values[i] += *v - reg; } p->clear(); } ++updates; } void AdagradTrainer::update(real nsamples, real scale) { unsigned pi; if (!shadow_params_allocated) { vp = AllocateShadowParameters(*model); vlp = AllocateShadowLookupParameters(*model); shadow_params_allocated = true; } pi = 0; const float gscale = clip_gradients(nsamples); for (auto p : model->parameters_list()) { Tensor& v = vp[pi++].h; auto reg = (*p->values) * lambda; auto g2 = (*p->g).cwiseProduct(*p->g); (*v) += g2; auto delta = -(eta * scale * gscale) * (*p->g).cwiseQuotient(((*v).array() + epsilon).matrix().cwiseSqrt()); *p->values += delta - reg; p->clear(); } pi = 0; for (auto p : model->lookup_parameters_list()) { vector<Tensor>& vx = vlp[pi++].h; for (auto i : p->non_zero_grads) { Tensor& v = vx[i]; auto reg = (*p->values[i]) * lambda; auto g2 = (*p->grads[i]).cwiseProduct(*p->grads[i]); (*v) += g2; auto delta = -(eta * scale * gscale) * (*p->grads[i]).cwiseQuotient(((*v).array() + epsilon).matrix().cwiseSqrt()); *p->values[i] += delta - reg; } p->clear(); } ++updates; } void AdadeltaTrainer::update(real nutt, real scale) { unsigned pi; if (!shadow_params_allocated) { hg = AllocateShadowParameters(*model); hlg = AllocateShadowLookupParameters(*model); hd = AllocateShadowParameters(*model); hld = AllocateShadowLookupParameters(*model); /*pi = 0; for (auto p : model->parameters_list()) { TensorTools::Constant(hg[pi].h, epsilon); TensorTools::Constant(hd[pi].h, epsilon); ++pi; } pi = 0; for (auto p : model->lookup_parameters_list()) { vector<Tensor>& hgx = hlg[pi].h; vector<Tensor>& hdx = hld[pi].h; for (unsigned i = 0; i < hgx.size(); ++i) { TensorTools::Constant(hgx[i], epsilon); TensorTools::Constant(hdx[i], epsilon); } ++pi; }*/ shadow_params_allocated = true; } const float gscale = clip_gradients(nutt); float nutt_scale = 1.0 / nutt; pi = 0; for (auto p : model->parameters_list()) { auto& g = (scale * gscale * nutt_scale) * *p->g; Tensor& hgv = hg[pi].h; Tensor& hdv = hd[pi].h; auto reg = (*p->values) * lambda; auto g2 = g.cwiseProduct(g); *hgv = rho * *hgv + (1.0 - rho) * g2; auto num = -g.cwiseProduct(((*hdv).array() + epsilon).matrix().cwiseSqrt()); auto den = ((*hgv).array() + epsilon).matrix().cwiseSqrt(); auto delta = num.cwiseQuotient(den); auto d2 = delta.cwiseProduct(delta); *hdv = rho * *hdv + (1.0 - rho) * d2; *p->values += delta - reg; p->clear(); pi++; } pi = 0; for (auto p : model->lookup_parameters_list()) { vector<Tensor>& hgvx = hlg[pi].h; vector<Tensor>& hdvx = hld[pi].h; for (auto i : p->non_zero_grads) { Tensor& hgv = hgvx[i]; Tensor& hdv = hdvx[i]; auto& g = scale * gscale * nutt_scale * *p->grads[i]; auto reg = (*p->values[i]) * lambda; auto g2 = g.cwiseProduct(g); *hgv = rho * *hgv + (1.0 - rho) * g2; auto num = -g.cwiseProduct(((*hdv).array() + epsilon).matrix().cwiseSqrt()); auto den = ((*hgv).array() + epsilon).matrix().cwiseSqrt(); auto delta = num.cwiseQuotient(den); auto d2 = delta.cwiseProduct(delta); *hdv = rho * *hdv + (1.0 - rho) * d2; *p->values[i] += delta - reg; } p->clear(); pi++; } ++updates; } void RmsPropTrainer::update(real nutt, real scale) { unsigned pi = 0; if (!shadow_params_allocated) { hg.resize(model->parameters_list().size()); pi = 0; hlg.resize(model->lookup_parameters_list().size()); for (auto p : model->lookup_parameters_list()) { hlg[pi++].resize(p->size()); } shadow_params_allocated = true; } const float gscale = clip_gradients(nutt); float nutt_scale = 1.0 / nutt; pi = 0; for (auto p : model->parameters_list()) { real& d2 = hg[pi++]; auto reg = (*p->values) * lambda; real g2 = (*p->g).squaredNorm(); d2 = rho * d2 + (1.0 - rho) * g2; *p->values -= ((eta * scale * gscale * nutt_scale / sqrt(d2 + epsilon)) * *p->g + reg); p->clear(); } pi = 0; for (auto p : model->lookup_parameters_list()) { vector<real>& hlgx = hlg[pi++]; for (auto i : p->non_zero_grads) { real& d2 = hlgx[i]; auto reg = (*p->values[i]) * lambda; real g2 = (*p->grads[i]).squaredNorm(); d2 = rho * d2 + (1.0 - rho) * g2; *p->values[i] -= ((eta * scale * gscale * nutt_scale / sqrt(d2 + epsilon)) * *p->grads[i] + reg); } p->clear(); } ++updates; } void AdamTrainer::update(real nutt, real scale) { unsigned pi; if (!shadow_params_allocated) { m = AllocateShadowParameters(*model); lm = AllocateShadowLookupParameters(*model); v = AllocateShadowParameters(*model); lv = AllocateShadowLookupParameters(*model); shadow_params_allocated = true; } const float gscale = clip_gradients(); float nutt_scale = 1.0 / nutt; pi = 0; static unsigned t = 0; for (auto p : model->parameters_list()) { ++t; auto g_t = (scale * gscale * nutt_scale) * *p->g; auto m_t = *m[pi].h; auto v_t = *v[pi].h; auto reg = (*p->values) * lambda; m_t = beta_1 * m_t + (1 - beta_1) * g_t; auto g2 = g_t.cwiseProduct(g_t); v_t = beta_2 * v_t + (1 - beta_2) * g2; float s1 = 1 - pow(beta_1, t); float s2 = 1 - pow(beta_2, t); auto mhat = m_t / s1; auto vhat = v_t / s2; auto delta = (-eta * mhat).cwiseQuotient((vhat.array().sqrt() + eps).matrix()); *p->values += delta - reg; p->clear(); pi++; } pi = 0; for (auto p : model->lookup_parameters_list()) { vector<Tensor>& vm = lm[pi].h; vector<Tensor>& vv = lv[pi].h; for (auto i : p->non_zero_grads) { auto m_t = *vm[i]; auto v_t = *vv[i]; auto g_t = scale * gscale * nutt_scale * *p->grads[i]; auto g2 = g_t.cwiseProduct(g_t); auto reg = (*p->values[i]) * lambda; m_t = beta_1 * m_t + (1 - beta_1) * g_t; v_t = beta_2 * v_t + (1 - beta_2) * g2; float s1 = 1 - pow(beta_1, t); float s2 = 1 - pow(beta_2, t); auto mhat = m_t / s1; auto vhat = v_t / s2; auto delta = (-eta * mhat).cwiseQuotient((vhat.array().sqrt() + eps).matrix()); *p->values[i] += delta - reg; } p->clear(); pi++; } ++updates; } } // namespace cnn <commit_msg>print model parameter update info<commit_after>#include "cnn/training.h" #include "cnn/gpu-ops.h" extern int verbose; namespace cnn { using namespace std; Trainer::~Trainer() {} /** @scale : proportional to the number of samples trained in parallel */ float Trainer::clip_gradients(float samples) { float gscale = 1; if (clipping_enabled) { float gg = model->gradient_l2_norm(); if (gg > clip_threshold * samples) { ++clips; gscale = (clip_threshold * samples) / gg; } } return gscale; } void SimpleSGDTrainer::update(float nutt, real scale) { update(model->lookup_parameters_list(), model->parameters_list(), nutt, scale); } void SimpleSGDTrainer::update(const std::vector<LookupParameters*> &lookup_params, const std::vector<Parameters*> &params, float samples, real scale) { const float gscale = clip_gradients(samples); float nutt_scale = 1.0 / samples; for (auto p : params) { #if HAVE_CUDA gpu::sgd_update(p->values.d.size(), p->g.v, p->values.v, eta * scale * gscale * nutt_scale, lambda); #else auto reg = (*p->values) * lambda; *p->values -= nutt_scale * ((eta * scale * gscale) * *p->g + reg); #endif p->clear(); } for (auto p : lookup_params) { for (auto i : p->non_zero_grads) { #if HAVE_CUDA gpu::sgd_update(p->values[i].d.size(), p->grads[i].v, p->values[i].v, eta * scale * gscale * nutt_scale, lambda); #else auto reg = (*p->values[i]) * lambda; *p->values[i] -= (*p->grads[i] * (eta * scale * gscale * nutt_scale) + reg); #endif } p->clear(); } ++updates; } void MomentumSGDTrainer::update(real nutt, real scale) { // executed on the first iteration to create vectors to // store the velocity if (!velocity_allocated) { vp = AllocateShadowParameters(*model); vlp = AllocateShadowLookupParameters(*model); velocity_allocated = true; } const float gscale = clip_gradients(nutt); float nutt_scale = 1.0 / nutt; unsigned pi = 0; for (auto p : model->parameters_list()) { Tensor& v = vp[pi++].h; auto reg = *p->values * lambda; (*v) = momentum * (*v) - (eta * scale * gscale*nutt_scale) * (*p->g); if (verbose) { cout << "name= " << p->name << " v= " << p->values.v[0] << " g= " << p->g.v[0] << " dv=" << v.v[0] << endl; } *p->values += *v - reg; p->clear(); } pi = 0; for (auto p : model->lookup_parameters_list()) { vector<Tensor>& vx = vlp[pi++].h; for (auto i : p->non_zero_grads) { Tensor& v = vx[i]; auto reg = (*p->values[i]) * lambda; (*v) = momentum * (*v) - (eta * scale * gscale*nutt_scale) * (*p->grads[i]); *p->values[i] += *v - reg; } p->clear(); } ++updates; } void AdagradTrainer::update(real nsamples, real scale) { unsigned pi; if (!shadow_params_allocated) { vp = AllocateShadowParameters(*model); vlp = AllocateShadowLookupParameters(*model); shadow_params_allocated = true; } pi = 0; const float gscale = clip_gradients(nsamples); for (auto p : model->parameters_list()) { Tensor& v = vp[pi++].h; auto reg = (*p->values) * lambda; auto g2 = (*p->g).cwiseProduct(*p->g); (*v) += g2; auto delta = -(eta * scale * gscale) * (*p->g).cwiseQuotient(((*v).array() + epsilon).matrix().cwiseSqrt()); *p->values += delta - reg; p->clear(); } pi = 0; for (auto p : model->lookup_parameters_list()) { vector<Tensor>& vx = vlp[pi++].h; for (auto i : p->non_zero_grads) { Tensor& v = vx[i]; auto reg = (*p->values[i]) * lambda; auto g2 = (*p->grads[i]).cwiseProduct(*p->grads[i]); (*v) += g2; auto delta = -(eta * scale * gscale) * (*p->grads[i]).cwiseQuotient(((*v).array() + epsilon).matrix().cwiseSqrt()); *p->values[i] += delta - reg; } p->clear(); } ++updates; } void AdadeltaTrainer::update(real nutt, real scale) { unsigned pi; if (!shadow_params_allocated) { hg = AllocateShadowParameters(*model); hlg = AllocateShadowLookupParameters(*model); hd = AllocateShadowParameters(*model); hld = AllocateShadowLookupParameters(*model); /*pi = 0; for (auto p : model->parameters_list()) { TensorTools::Constant(hg[pi].h, epsilon); TensorTools::Constant(hd[pi].h, epsilon); ++pi; } pi = 0; for (auto p : model->lookup_parameters_list()) { vector<Tensor>& hgx = hlg[pi].h; vector<Tensor>& hdx = hld[pi].h; for (unsigned i = 0; i < hgx.size(); ++i) { TensorTools::Constant(hgx[i], epsilon); TensorTools::Constant(hdx[i], epsilon); } ++pi; }*/ shadow_params_allocated = true; } const float gscale = clip_gradients(nutt); float nutt_scale = 1.0 / nutt; pi = 0; for (auto p : model->parameters_list()) { auto& g = (scale * gscale * nutt_scale) * *p->g; Tensor& hgv = hg[pi].h; Tensor& hdv = hd[pi].h; auto reg = (*p->values) * lambda; auto g2 = g.cwiseProduct(g); *hgv = rho * *hgv + (1.0 - rho) * g2; auto num = -g.cwiseProduct(((*hdv).array() + epsilon).matrix().cwiseSqrt()); auto den = ((*hgv).array() + epsilon).matrix().cwiseSqrt(); auto delta = num.cwiseQuotient(den); auto d2 = delta.cwiseProduct(delta); *hdv = rho * *hdv + (1.0 - rho) * d2; *p->values += delta - reg; p->clear(); pi++; } pi = 0; for (auto p : model->lookup_parameters_list()) { vector<Tensor>& hgvx = hlg[pi].h; vector<Tensor>& hdvx = hld[pi].h; for (auto i : p->non_zero_grads) { Tensor& hgv = hgvx[i]; Tensor& hdv = hdvx[i]; auto& g = scale * gscale * nutt_scale * *p->grads[i]; auto reg = (*p->values[i]) * lambda; auto g2 = g.cwiseProduct(g); *hgv = rho * *hgv + (1.0 - rho) * g2; auto num = -g.cwiseProduct(((*hdv).array() + epsilon).matrix().cwiseSqrt()); auto den = ((*hgv).array() + epsilon).matrix().cwiseSqrt(); auto delta = num.cwiseQuotient(den); auto d2 = delta.cwiseProduct(delta); *hdv = rho * *hdv + (1.0 - rho) * d2; *p->values[i] += delta - reg; } p->clear(); pi++; } ++updates; } void RmsPropTrainer::update(real nutt, real scale) { unsigned pi = 0; if (!shadow_params_allocated) { hg.resize(model->parameters_list().size()); pi = 0; hlg.resize(model->lookup_parameters_list().size()); for (auto p : model->lookup_parameters_list()) { hlg[pi++].resize(p->size()); } shadow_params_allocated = true; } const float gscale = clip_gradients(nutt); float nutt_scale = 1.0 / nutt; pi = 0; for (auto p : model->parameters_list()) { real& d2 = hg[pi++]; auto reg = (*p->values) * lambda; real g2 = (*p->g).squaredNorm(); d2 = rho * d2 + (1.0 - rho) * g2; *p->values -= ((eta * scale * gscale * nutt_scale / sqrt(d2 + epsilon)) * *p->g + reg); p->clear(); } pi = 0; for (auto p : model->lookup_parameters_list()) { vector<real>& hlgx = hlg[pi++]; for (auto i : p->non_zero_grads) { real& d2 = hlgx[i]; auto reg = (*p->values[i]) * lambda; real g2 = (*p->grads[i]).squaredNorm(); d2 = rho * d2 + (1.0 - rho) * g2; *p->values[i] -= ((eta * scale * gscale * nutt_scale / sqrt(d2 + epsilon)) * *p->grads[i] + reg); } p->clear(); } ++updates; } void AdamTrainer::update(real nutt, real scale) { unsigned pi; if (!shadow_params_allocated) { m = AllocateShadowParameters(*model); lm = AllocateShadowLookupParameters(*model); v = AllocateShadowParameters(*model); lv = AllocateShadowLookupParameters(*model); shadow_params_allocated = true; } const float gscale = clip_gradients(); float nutt_scale = 1.0 / nutt; pi = 0; static unsigned t = 0; for (auto p : model->parameters_list()) { ++t; auto g_t = (scale * gscale * nutt_scale) * *p->g; auto m_t = *m[pi].h; auto v_t = *v[pi].h; auto reg = (*p->values) * lambda; m_t = beta_1 * m_t + (1 - beta_1) * g_t; auto g2 = g_t.cwiseProduct(g_t); v_t = beta_2 * v_t + (1 - beta_2) * g2; float s1 = 1 - pow(beta_1, t); float s2 = 1 - pow(beta_2, t); auto mhat = m_t / s1; auto vhat = v_t / s2; auto delta = (-eta * mhat).cwiseQuotient((vhat.array().sqrt() + eps).matrix()); *p->values += delta - reg; p->clear(); pi++; } pi = 0; for (auto p : model->lookup_parameters_list()) { vector<Tensor>& vm = lm[pi].h; vector<Tensor>& vv = lv[pi].h; for (auto i : p->non_zero_grads) { auto m_t = *vm[i]; auto v_t = *vv[i]; auto g_t = scale * gscale * nutt_scale * *p->grads[i]; auto g2 = g_t.cwiseProduct(g_t); auto reg = (*p->values[i]) * lambda; m_t = beta_1 * m_t + (1 - beta_1) * g_t; v_t = beta_2 * v_t + (1 - beta_2) * g2; float s1 = 1 - pow(beta_1, t); float s2 = 1 - pow(beta_2, t); auto mhat = m_t / s1; auto vhat = v_t / s2; auto delta = (-eta * mhat).cwiseQuotient((vhat.array().sqrt() + eps).matrix()); *p->values[i] += delta - reg; } p->clear(); pi++; } ++updates; } } // namespace cnn <|endoftext|>
<commit_before>#include <algorithm> #include <assert.h> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> #include <exception> #include <iostream> #include "Map.h" #include "MapManager.h" #include "utils.h" #include "Create.h" #include "Create_Enums.h" #include "File.h" MapManager::MapManager(): map(nullptr) {} void MapManager::closeMap() { delete map; map = nullptr; } void MapManager::openMap(int mapNum) { using namespace Maps; Map* loadMap = Create::newMap(mapNum); setMap( loadMap ); } void MapManager::setMap(Maps::Map* map) { if (this->map != nullptr) { delete map; } this->map = map; } void MapManager::play() { assert( map != nullptr ); while ( true ) // TODO: Make variable for this { map->activate(); if (tempMap != nullptr) { std::swap(tempMap, map); delete tempMap; tempMap = nullptr; } } } void MapManager::save(const std::string &fileName) { assert(map != nullptr); map->save(); File::save(fileName); } void MapManager::load(const std::string &fileName) { using namespace File; using namespace boost::property_tree; fs::fstream file; fs::path filePath = savePath; filePath /= fs::path{fileName}; if (file.is_open()) { file.close(); } // make tree and load from file treeType loadTree; try { file.open( filePath, std::fstream::in ); xml_parser::read_xml(file, loadTree, xml_parser::trim_whitespace); } catch (std::exception &e) { std::cerr << e.what(); } auto it = loadTree.begin(); while (it != loadTree.end()) { const std::string &key = it->first; const std::string &data = it->second.data(); if (key == "Map") { delete tempMap; // just in case tempMap = Create::newMap(*it); } it++; } // tempMap and map are swapped automatically later. } <commit_msg>MapManager load<commit_after>#include <algorithm> #include <assert.h> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> #include <exception> #include <iostream> #include "Map.h" #include "MapManager.h" #include "utils.h" #include "Create.h" #include "Create_Enums.h" #include "File.h" MapManager::MapManager(): map(nullptr) {} void MapManager::closeMap() { delete map; map = nullptr; } void MapManager::openMap(int mapNum) { using namespace Maps; Map* loadMap = Create::newMap(mapNum); setMap( loadMap ); } void MapManager::setMap(Maps::Map* map) { if (this->map != nullptr) { delete map; } this->map = map; } void MapManager::play() { assert( map != nullptr ); while ( true ) // TODO: Make variable for this { map->activate(); if (tempMap != nullptr) { std::swap(tempMap, map); delete tempMap; tempMap = nullptr; } } } void MapManager::save(const std::string &fileName) { assert(map != nullptr); map->save(); File::save(fileName); } void MapManager::load(const std::string &fileName) { File::load(fileName); // tempMap and map are swapped automatically later. delete tempMap; tempMap = Create::loadNewMap(); } <|endoftext|>
<commit_before>#ifndef VEXCL_BACKEND_OPENCL_COMPILER_HPP #define VEXCL_BACKEND_OPENCL_COMPILER_HPP /* The MIT License Copyright (c) 2012-2016 Denis Demidov <dennis.demidov@gmail.com> 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. */ /** * \file vexcl/backend/opencl/compiler.hpp * \author Denis Demidov <dennis.demidov@gmail.com> * \brief OpenCL source code compilation wrapper. */ #include <cstdlib> #include <boost/thread.hpp> #include <vexcl/backend/common.hpp> #include <vexcl/detail/backtrace.hpp> #include <vexcl/backend/opencl/defines.hpp> #include <CL/cl.hpp> namespace vex { namespace backend { namespace opencl { /// Saves program binaries for future reuse. inline void save_program_binaries( const std::string &hash, const cl::Program &program ) { // Prevent writing to the same file by several threads at the same time. static boost::mutex mx; boost::lock_guard<boost::mutex> lock(mx); std::ofstream bfile(program_binaries_path(hash, true) + "kernel", std::ios::binary); if (!bfile) return; std::vector<size_t> sizes = program.getInfo<CL_PROGRAM_BINARY_SIZES>(); std::vector<char*> binaries = program.getInfo<CL_PROGRAM_BINARIES>(); assert(sizes.size() == 1); bfile.write((char*)&sizes[0], sizeof(size_t)); bfile.write(binaries[0], sizes[0]); delete[] binaries[0]; } /// Tries to read program binaries from file cache. inline boost::optional<cl::Program> load_program_binaries( const std::string &hash, const cl::Context &context, const std::vector<cl::Device> &device, const std::string &options = "" ) { std::ifstream bfile(program_binaries_path(hash) + "kernel", std::ios::binary); if (!bfile) return boost::optional<cl::Program>(); size_t n; std::vector<char> buf; bfile.read((char*)&n, sizeof(size_t)); buf.resize(n); bfile.read(buf.data(), n); cl::Program program(context, device, cl::Program::Binaries( - 1, std::make_pair(static_cast<const void*>(buf.data()), n))); try { program.build(device, options.c_str()); } catch(const cl::Error&) { std::cerr << "Loading binaries failed:" << std::endl << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(device[0]) << std::endl; return boost::optional<cl::Program>(); } return boost::optional<cl::Program>(program); } /// Create and build a program from source string. /** * If VEXCL_CACHE_KERNELS macro is defined, then program binaries are cached * in filesystem and reused in the following runs. */ inline cl::Program build_sources( const cl::CommandQueue &queue, const std::string &source, const std::string &options = "" ) { #ifdef VEXCL_SHOW_KERNELS std::cout << source << std::endl; #else # ifdef _MSC_VER # pragma warning(push) # pragma warning(disable: 4996) # endif if (getenv("VEXCL_SHOW_KERNELS")) std::cout << source << std::endl; # ifdef _MSC_VER # pragma warning(pop) # endif #endif auto context = queue.getInfo<CL_QUEUE_CONTEXT>(); auto device = context.getInfo<CL_CONTEXT_DEVICES>(); std::string compile_options = options + " " + get_compile_options(queue); #ifdef VEXCL_CACHE_KERNELS // Get unique (hopefully) hash string for the kernel. std::ostringstream compiler_tag; compiler_tag #if defined(_MSC_VER) << "MSC " << _MSC_VER #elif defined(__clang__) << "Clang " << __clang_major__ << "." << __clang_minor__ #elif defined(__GNUC__) << "g++ " << __GNUC__ << "." << __GNUC_MINOR__ #else << "unknown" #endif ; sha1_hasher sha1; sha1.process(source) .process(cl::Platform(device[0].getInfo<CL_DEVICE_PLATFORM>()).getInfo<CL_PLATFORM_NAME>()) .process(device[0].getInfo<CL_DEVICE_NAME>()) .process(compile_options) .process(compiler_tag.str()) ; std::string hash = static_cast<std::string>(sha1); // Try to get cached program binaries: try { if (boost::optional<cl::Program> program = load_program_binaries(hash, context, device, compile_options)) return *program; } catch (...) { // Shit happens. std::cerr << "Shit happened" << std::endl; } #endif // If cache is not available, just compile the sources. cl::Program program(context, source); try { program.build(device, (options + " " + get_compile_options(queue)).c_str()); } catch(const cl::Error&) { std::cerr << source << std::endl << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(device[0]) << std::endl; vex::detail::print_backtrace(); throw; } #ifdef VEXCL_CACHE_KERNELS // Save program binaries for future reuse: save_program_binaries(hash, program); #endif return program; } } // namespace opencl } // namespace backend } // namespace vex #endif <commit_msg>Fix an error in backend/opencl/compiler.hpp<commit_after>#ifndef VEXCL_BACKEND_OPENCL_COMPILER_HPP #define VEXCL_BACKEND_OPENCL_COMPILER_HPP /* The MIT License Copyright (c) 2012-2016 Denis Demidov <dennis.demidov@gmail.com> 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. */ /** * \file vexcl/backend/opencl/compiler.hpp * \author Denis Demidov <dennis.demidov@gmail.com> * \brief OpenCL source code compilation wrapper. */ #include <cstdlib> #include <boost/thread.hpp> #include <vexcl/backend/common.hpp> #include <vexcl/detail/backtrace.hpp> #include <vexcl/backend/opencl/defines.hpp> #include <CL/cl.hpp> namespace vex { namespace backend { namespace opencl { /// Saves program binaries for future reuse. inline void save_program_binaries( const std::string &hash, const cl::Program &program ) { // Prevent writing to the same file by several threads at the same time. static boost::mutex mx; boost::lock_guard<boost::mutex> lock(mx); std::ofstream bfile(program_binaries_path(hash, true) + "kernel", std::ios::binary); if (!bfile) return; std::vector<size_t> sizes = program.getInfo<CL_PROGRAM_BINARY_SIZES>(); std::vector<char*> binaries = program.getInfo<CL_PROGRAM_BINARIES>(); assert(sizes.size() == 1); bfile.write((char*)&sizes[0], sizeof(size_t)); bfile.write(binaries[0], sizes[0]); delete[] binaries[0]; } /// Tries to read program binaries from file cache. inline boost::optional<cl::Program> load_program_binaries( const std::string &hash, const cl::Context &context, const std::vector<cl::Device> &device, const std::string &options = "" ) { std::ifstream bfile(program_binaries_path(hash) + "kernel", std::ios::binary); if (!bfile) return boost::optional<cl::Program>(); size_t n; std::vector<char> buf; bfile.read((char*)&n, sizeof(size_t)); buf.resize(n); bfile.read(buf.data(), n); cl::Program program(context, device, cl::Program::Binaries( 1, std::make_pair(static_cast<const void*>(buf.data()), n))); try { program.build(device, options.c_str()); } catch(const cl::Error&) { std::cerr << "Loading binaries failed:" << std::endl << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(device[0]) << std::endl; return boost::optional<cl::Program>(); } return boost::optional<cl::Program>(program); } /// Create and build a program from source string. /** * If VEXCL_CACHE_KERNELS macro is defined, then program binaries are cached * in filesystem and reused in the following runs. */ inline cl::Program build_sources( const cl::CommandQueue &queue, const std::string &source, const std::string &options = "" ) { #ifdef VEXCL_SHOW_KERNELS std::cout << source << std::endl; #else # ifdef _MSC_VER # pragma warning(push) # pragma warning(disable: 4996) # endif if (getenv("VEXCL_SHOW_KERNELS")) std::cout << source << std::endl; # ifdef _MSC_VER # pragma warning(pop) # endif #endif auto context = queue.getInfo<CL_QUEUE_CONTEXT>(); auto device = context.getInfo<CL_CONTEXT_DEVICES>(); std::string compile_options = options + " " + get_compile_options(queue); #ifdef VEXCL_CACHE_KERNELS // Get unique (hopefully) hash string for the kernel. std::ostringstream compiler_tag; compiler_tag #if defined(_MSC_VER) << "MSC " << _MSC_VER #elif defined(__clang__) << "Clang " << __clang_major__ << "." << __clang_minor__ #elif defined(__GNUC__) << "g++ " << __GNUC__ << "." << __GNUC_MINOR__ #else << "unknown" #endif ; sha1_hasher sha1; sha1.process(source) .process(cl::Platform(device[0].getInfo<CL_DEVICE_PLATFORM>()).getInfo<CL_PLATFORM_NAME>()) .process(device[0].getInfo<CL_DEVICE_NAME>()) .process(compile_options) .process(compiler_tag.str()) ; std::string hash = static_cast<std::string>(sha1); // Try to get cached program binaries: try { if (boost::optional<cl::Program> program = load_program_binaries(hash, context, device, compile_options)) return *program; } catch (...) { // Shit happens. std::cerr << "Failed to load precompiled binaries" << std::endl; } #endif // If cache is not available, just compile the sources. cl::Program program(context, source); try { program.build(device, (options + " " + get_compile_options(queue)).c_str()); } catch(const cl::Error&) { std::cerr << source << std::endl << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(device[0]) << std::endl; vex::detail::print_backtrace(); throw; } #ifdef VEXCL_CACHE_KERNELS // Save program binaries for future reuse: save_program_binaries(hash, program); #endif return program; } } // namespace opencl } // namespace backend } // namespace vex #endif <|endoftext|>
<commit_before>/* Copyright 2011 Dirk-Willem van Gulik, All Rights Reserved. * dirkx(at)webweaving(dot)org * * 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. * * $Id: QuadratureAnalyserAnalyzerSettings.cpp 1037 2011-09-12 09:49:58Z dirkx $ */ #include "QuadratureAnalyserAnalyzerSettings.h" #include <AnalyzerHelpers.h> QuadratureAnalyserAnalyzerSettings::QuadratureAnalyserAnalyzerSettings() : mInputChannelA( UNDEFINED_CHANNEL ), mInputChannelB( UNDEFINED_CHANNEL ), ticksPerRotation( 0 ) { mInputChannelAInterface.reset( new AnalyzerSettingInterfaceChannel() ); mInputChannelAInterface->SetTitleAndTooltip( "Quadrature A", "Standard Quadrature Decoder - input A (or left/cw/first)" ); mInputChannelAInterface->SetChannel( mInputChannelA ); mInputChannelBInterface.reset( new AnalyzerSettingInterfaceChannel() ); mInputChannelBInterface->SetTitleAndTooltip( "Quadrature B", "Standard Quadrature Decoder - input Bi (or right/ccw/last)" ); mInputChannelBInterface->SetChannel( mInputChannelB ); mTicksPerRotationInterface.reset( new AnalyzerSettingInterfaceInteger() ); mTicksPerRotationInterface->SetTitleAndTooltip( "Impules/rotation", "Specify the number of changes per full revolution (or some other measure). Set to '0' to ignore - and not do speed/change calculations."); mTicksPerRotationInterface->SetMax( 1e12 ); mTicksPerRotationInterface->SetMin( 0 ); mTicksPerRotationInterface->SetInteger( ticksPerRotation); AddInterface( mInputChannelAInterface.get() ); AddInterface( mInputChannelBInterface.get() ); AddInterface( mTicksPerRotationInterface.get() ); AddExportOption( 0, "Export as text/csv file" ); AddExportExtension( 0, "text", "txt" ); AddExportExtension( 0, "csv", "csv" ); ClearChannels(); AddChannel( mInputChannelA, "Quadrature A", false ); AddChannel( mInputChannelB, "Quadrature B", false ); } QuadratureAnalyserAnalyzerSettings::~QuadratureAnalyserAnalyzerSettings() { } bool QuadratureAnalyserAnalyzerSettings::SetSettingsFromInterfaces() { mInputChannelA = mInputChannelAInterface->GetChannel(); mInputChannelB = mInputChannelBInterface->GetChannel(); ticksPerRotation = mTicksPerRotationInterface->GetInteger(); ClearChannels(); AddChannel( mInputChannelA, "Quadrature A", true); AddChannel( mInputChannelB, "Quadrature B", true); return true; } void QuadratureAnalyserAnalyzerSettings::UpdateInterfacesFromSettings() { mInputChannelAInterface->SetChannel( mInputChannelA ); mInputChannelBInterface->SetChannel( mInputChannelB ); mTicksPerRotationInterface->SetInteger( ticksPerRotation ); } void QuadratureAnalyserAnalyzerSettings::LoadSettings( const char* settings ) { SimpleArchive text_archive; text_archive.SetString( settings ); text_archive >> mInputChannelA; text_archive >> mInputChannelB; text_archive >> ticksPerRotation; ClearChannels(); AddChannel( mInputChannelA, "Quadrature A", true); AddChannel( mInputChannelB, "Quadrature B", true); UpdateInterfacesFromSettings(); } const char* QuadratureAnalyserAnalyzerSettings::SaveSettings() { SimpleArchive text_archive; text_archive << mInputChannelA; text_archive << mInputChannelB; text_archive << ticksPerRotation; return SetReturnString( text_archive.GetString() ); } <commit_msg>fix - rage of ticks per rotation setting was set to a number outside of the 32 bit integer range.<commit_after>/* Copyright 2011 Dirk-Willem van Gulik, All Rights Reserved. * dirkx(at)webweaving(dot)org * * 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. * * $Id: QuadratureAnalyserAnalyzerSettings.cpp 1037 2011-09-12 09:49:58Z dirkx $ */ #include <climits> #include "QuadratureAnalyserAnalyzerSettings.h" #include <AnalyzerHelpers.h> QuadratureAnalyserAnalyzerSettings::QuadratureAnalyserAnalyzerSettings() : mInputChannelA( UNDEFINED_CHANNEL ), mInputChannelB( UNDEFINED_CHANNEL ), ticksPerRotation( 0 ) { mInputChannelAInterface.reset( new AnalyzerSettingInterfaceChannel() ); mInputChannelAInterface->SetTitleAndTooltip( "Quadrature A", "Standard Quadrature Decoder - input A (or left/cw/first)" ); mInputChannelAInterface->SetChannel( mInputChannelA ); mInputChannelBInterface.reset( new AnalyzerSettingInterfaceChannel() ); mInputChannelBInterface->SetTitleAndTooltip( "Quadrature B", "Standard Quadrature Decoder - input Bi (or right/ccw/last)" ); mInputChannelBInterface->SetChannel( mInputChannelB ); mTicksPerRotationInterface.reset( new AnalyzerSettingInterfaceInteger() ); mTicksPerRotationInterface->SetTitleAndTooltip( "Impules/rotation", "Specify the number of changes per full revolution (or some other measure). Set to '0' to ignore - and not do speed/change calculations."); mTicksPerRotationInterface->SetMax( INT_MAX ); mTicksPerRotationInterface->SetMin( 0 ); mTicksPerRotationInterface->SetInteger( ticksPerRotation); AddInterface( mInputChannelAInterface.get() ); AddInterface( mInputChannelBInterface.get() ); AddInterface( mTicksPerRotationInterface.get() ); AddExportOption( 0, "Export as text/csv file" ); AddExportExtension( 0, "text", "txt" ); AddExportExtension( 0, "csv", "csv" ); ClearChannels(); AddChannel( mInputChannelA, "Quadrature A", false ); AddChannel( mInputChannelB, "Quadrature B", false ); } QuadratureAnalyserAnalyzerSettings::~QuadratureAnalyserAnalyzerSettings() { } bool QuadratureAnalyserAnalyzerSettings::SetSettingsFromInterfaces() { mInputChannelA = mInputChannelAInterface->GetChannel(); mInputChannelB = mInputChannelBInterface->GetChannel(); ticksPerRotation = mTicksPerRotationInterface->GetInteger(); ClearChannels(); AddChannel( mInputChannelA, "Quadrature A", true); AddChannel( mInputChannelB, "Quadrature B", true); return true; } void QuadratureAnalyserAnalyzerSettings::UpdateInterfacesFromSettings() { mInputChannelAInterface->SetChannel( mInputChannelA ); mInputChannelBInterface->SetChannel( mInputChannelB ); mTicksPerRotationInterface->SetInteger( ticksPerRotation ); } void QuadratureAnalyserAnalyzerSettings::LoadSettings( const char* settings ) { SimpleArchive text_archive; text_archive.SetString( settings ); text_archive >> mInputChannelA; text_archive >> mInputChannelB; text_archive >> ticksPerRotation; ClearChannels(); AddChannel( mInputChannelA, "Quadrature A", true); AddChannel( mInputChannelB, "Quadrature B", true); UpdateInterfacesFromSettings(); } const char* QuadratureAnalyserAnalyzerSettings::SaveSettings() { SimpleArchive text_archive; text_archive << mInputChannelA; text_archive << mInputChannelB; text_archive << ticksPerRotation; return SetReturnString( text_archive.GetString() ); } <|endoftext|>
<commit_before>#include "PoissonDiskSampling.h" #include <random> PoissonDiskSampling::PoissonDiskSampling(int pointWidth, int pointHeight, double pointMinDist, double pointCount) : m_width(pointWidth), m_height(pointHeight), m_minDist(pointMinDist), m_pointCount(pointCount), m_cellSize(m_minDist / 1.414214), m_gridWidth(ceil(m_width / m_cellSize)), m_gridHeight(ceil(m_height / m_cellSize)), m_grid(std::vector<std::vector<std::shared_ptr<Point>>>(m_gridWidth, std::vector<std::shared_ptr<Point>>(m_gridHeight, nullptr))) { } std::vector<std::pair<double, double>> PoissonDiskSampling::Generate() { std::random_device rd; std::mt19937 gen(rd()); Point firstPoint(gen() / m_width, gen() / m_height); m_process.push_back(firstPoint); m_sample.push_back(std::make_pair(firstPoint.x, firstPoint.y)); int firstPointX = firstPoint.x / m_cellSize; int firstPointY = firstPoint.y / m_cellSize; m_grid[firstPointX][firstPointY] = std::make_shared<Point>(firstPoint); while (!m_process.empty()) { int newPointIndex = gen() / m_process.size(); Point newPoint = m_process[newPointIndex]; m_process.erase(m_process.begin() + newPointIndex); for (int i = 0; i < m_pointCount; ++i) { Point newPointAround = GeneratePointAround(newPoint); if (IsInRectangle(newPointAround) && !IsInNeighbourhood(newPointAround)) { m_process.push_back(newPointAround); m_sample.push_back(std::make_pair(newPointAround.x, newPointAround.y)); int newPointX = newPointAround.x / m_cellSize; int newPointY = newPointAround.y / m_cellSize; m_grid[newPointX][newPointY] = std::make_shared<Point>(newPointAround); } } } return m_sample; } PoissonDiskSampling::Point PoissonDiskSampling::GeneratePointAround(Point p) { std::random_device rd; std::mt19937 gen(rd()); double r1 = static_cast<double>(gen()) / gen.max(); double r2 = static_cast<double>(gen()) / gen.max(); double radius = m_minDist * (r1 + 1); double angle = 2 * 3.14159265 * r2; double newX = p.x + radius * cos(angle); double newY = p.y + radius * sin(angle); return Point(newX, newY); } bool PoissonDiskSampling::IsInRectangle(Point p) { return (p.x >= 0 && p.y >= 0 && p.x < m_width && p.y < m_height); } bool PoissonDiskSampling::IsInNeighbourhood(Point p) { std::vector<std::shared_ptr<Point>> cells = GetCellsAround(p); int size = cells.size(); for (int i = 0; i < size; ++i) { } } <commit_msg>Implement IsInNeighbourhood()<commit_after>#include "PoissonDiskSampling.h" #include <random> PoissonDiskSampling::PoissonDiskSampling(int pointWidth, int pointHeight, double pointMinDist, double pointCount) : m_width(pointWidth), m_height(pointHeight), m_minDist(pointMinDist), m_pointCount(pointCount), m_cellSize(m_minDist / 1.414214), m_gridWidth(ceil(m_width / m_cellSize)), m_gridHeight(ceil(m_height / m_cellSize)), m_grid(std::vector<std::vector<std::shared_ptr<Point>>>(m_gridWidth, std::vector<std::shared_ptr<Point>>(m_gridHeight, nullptr))) { } std::vector<std::pair<double, double>> PoissonDiskSampling::Generate() { std::random_device rd; std::mt19937 gen(rd()); Point firstPoint(gen() / m_width, gen() / m_height); m_process.push_back(firstPoint); m_sample.push_back(std::make_pair(firstPoint.x, firstPoint.y)); int firstPointX = firstPoint.x / m_cellSize; int firstPointY = firstPoint.y / m_cellSize; m_grid[firstPointX][firstPointY] = std::make_shared<Point>(firstPoint); while (!m_process.empty()) { int newPointIndex = gen() / m_process.size(); Point newPoint = m_process[newPointIndex]; m_process.erase(m_process.begin() + newPointIndex); for (int i = 0; i < m_pointCount; ++i) { Point newPointAround = GeneratePointAround(newPoint); if (IsInRectangle(newPointAround) && !IsInNeighbourhood(newPointAround)) { m_process.push_back(newPointAround); m_sample.push_back(std::make_pair(newPointAround.x, newPointAround.y)); int newPointX = newPointAround.x / m_cellSize; int newPointY = newPointAround.y / m_cellSize; m_grid[newPointX][newPointY] = std::make_shared<Point>(newPointAround); } } } return m_sample; } PoissonDiskSampling::Point PoissonDiskSampling::GeneratePointAround(Point p) { std::random_device rd; std::mt19937 gen(rd()); double r1 = static_cast<double>(gen()) / gen.max(); double r2 = static_cast<double>(gen()) / gen.max(); double radius = m_minDist * (r1 + 1); double angle = 2 * 3.14159265 * r2; double newX = p.x + radius * cos(angle); double newY = p.y + radius * sin(angle); return Point(newX, newY); } bool PoissonDiskSampling::IsInRectangle(Point p) { return (p.x >= 0 && p.y >= 0 && p.x < m_width && p.y < m_height); } bool PoissonDiskSampling::IsInNeighbourhood(Point p) { std::vector<std::shared_ptr<Point>> cells = GetCellsAround(p); int size = cells.size(); for (int i = 0; i < size; ++i) { if (cells[i]->Distance(p) < m_minDist) { return true; } } return false; } <|endoftext|>
<commit_before>/* * nvbio * Copyright (c) 2011-2014, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 NVIDIA CORPORATION 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 <nvbio/io/reads/reads_fastq.h> #include <nvbio/basic/types.h> #include <nvbio/basic/timer.h> #include <string.h> #include <ctype.h> namespace nvbio { namespace io { ///@addtogroup IO ///@{ ///@addtogroup ReadsIO ///@{ ///@addtogroup ReadsIODetail ///@{ int ReadDataFile_FASTQ_parser::nextChunk(ReadDataRAM *output, uint32 max_reads, uint32 max_bps) { uint32 n_reads = 0; uint32 n_bps = 0; uint8 marker; const uint32 bps_mult = ((m_flags & FORWARD) ? 1u : 0u) + ((m_flags & REVERSE) ? 1u : 0u) + ((m_flags & FORWARD_COMPLEMENT) ? 1u : 0u) + ((m_flags & REVERSE_COMPLEMENT) ? 1u : 0u); while (n_reads < max_reads && n_bps + ReadDataFile::LONG_READ*bps_mult < max_bps) { // consume spaces & newlines do { marker = get(); // count lines if (marker == '\n') m_line++; } while (marker == '\n' || marker == ' '); // check for EOF or read errors if (m_file_state != FILE_OK) break; // if the newlines didn't end in a read marker, // issue a parsing error... if (marker != '@') { m_file_state = FILE_PARSE_ERROR; m_error_char = marker; return uint32(-1); } // read all the line uint32 len = 0; for (uint8 c = get(); c != '\n' && c != 0; c = get()) { m_name[ len++ ] = c; // expand on demand if (m_name.size() <= len) m_name.resize( len * 2u ); } m_name[ len++ ] = '\0'; // check for errors if (m_file_state != FILE_OK) { log_error(stderr, "incomplete read!\n"); m_error_char = 0; return uint32(-1); } m_line++; // start reading the bp read len = 0; for (uint8 c = get(); c != '+' && c != 0; c = get()) { // if (isgraph(c)) if (c >= 0x21 && c <= 0x7E) m_read_bp[ len++ ] = c; else if (c == '\n') m_line++; // expand on demand if (m_read_bp.size() <= len) { m_read_bp.resize( len * 2u ); m_read_q.resize( len * 2u ); } } // check for errors if (m_file_state != FILE_OK) { log_error(stderr, "incomplete read!\n"); m_error_char = 0; return uint32(-1); } // read all the line for(uint8 c = get(); c != '\n' && c != 0; c = get()) {} // check for errors if (m_file_state != FILE_OK) { log_error(stderr, "incomplete read!\n"); m_error_char = 0; return uint32(-1); } m_line++; // start reading the quality read len = 0; for (uint8 c = get(); c != '\n' && c != 0; c = get()) m_read_q[ len++ ] = c; // check for errors if (m_file_state != FILE_OK) { log_error(stderr, "incomplete read!\n"); m_error_char = 0; return uint32(-1); } m_line++; if (m_flags & FORWARD) { output->push_back( len, &m_name[0], &m_read_bp[0], &m_read_q[0], m_quality_encoding, m_truncate_read_len, FORWARD ); n_bps += len; } if (m_flags & REVERSE) { output->push_back( len, &m_name[0], &m_read_bp[0], &m_read_q[0], m_quality_encoding, m_truncate_read_len, REVERSE ); n_bps += len; } if (m_flags & FORWARD_COMPLEMENT) { output->push_back( len, &m_name[0], &m_read_bp[0], &m_read_q[0], m_quality_encoding, m_truncate_read_len, ReadEncoding( FORWARD | COMPLEMENT ) ); n_bps += len; } if (m_flags & REVERSE_COMPLEMENT) { output->push_back( len, &m_name[0], &m_read_bp[0], &m_read_q[0], m_quality_encoding, m_truncate_read_len, ReadEncoding( REVERSE | COMPLEMENT ) ); n_bps += len; } ++n_reads; } return n_reads; } ReadDataFile_FASTQ_gz::ReadDataFile_FASTQ_gz(const char *read_file_name, const QualityEncoding qualities, const uint32 max_reads, const uint32 max_read_len, const ReadEncoding flags) : ReadDataFile_FASTQ_parser(read_file_name, qualities, max_reads, max_read_len, flags) { m_file = gzopen(read_file_name, "r"); if (!m_file) { m_file_state = FILE_OPEN_FAILED; } else { m_file_state = FILE_OK; } gzbuffer(m_file, m_buffer_size); } static float time = 0.0f; ReadDataFile_FASTQ_parser::FileState ReadDataFile_FASTQ_gz::fillBuffer(void) { m_buffer_size = gzread(m_file, &m_buffer[0], (uint32)m_buffer.size()); if (m_buffer_size <= 0) { // check for EOF separately; zlib will not always return Z_STREAM_END at EOF below if (gzeof(m_file)) { return FILE_EOF; } else { // ask zlib what happened and inform the user int err; const char *msg; msg = gzerror(m_file, &err); // we're making the assumption that we never see Z_STREAM_END here assert(err != Z_STREAM_END); log_error(stderr, "error processing FASTQ file: zlib error %d (%s)\n", err, msg); return FILE_STREAM_ERROR; } } return FILE_OK; } ///@} // ReadsIODetail ///@} // ReadsIO ///@} // IO } // namespace io } // namespace nvbio <commit_msg>fixed loop boundaries<commit_after>/* * nvbio * Copyright (c) 2011-2014, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 NVIDIA CORPORATION 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 <nvbio/io/reads/reads_fastq.h> #include <nvbio/basic/types.h> #include <nvbio/basic/timer.h> #include <string.h> #include <ctype.h> namespace nvbio { namespace io { ///@addtogroup IO ///@{ ///@addtogroup ReadsIO ///@{ ///@addtogroup ReadsIODetail ///@{ int ReadDataFile_FASTQ_parser::nextChunk(ReadDataRAM *output, uint32 max_reads, uint32 max_bps) { uint32 n_reads = 0; uint32 n_bps = 0; uint8 marker; const uint32 read_mult = ((m_flags & FORWARD) ? 1u : 0u) + ((m_flags & REVERSE) ? 1u : 0u) + ((m_flags & FORWARD_COMPLEMENT) ? 1u : 0u) + ((m_flags & REVERSE_COMPLEMENT) ? 1u : 0u); while (n_reads + read_mult <= max_reads && n_bps + read_mult*ReadDataFile::LONG_READ <= max_bps) { // consume spaces & newlines do { marker = get(); // count lines if (marker == '\n') m_line++; } while (marker == '\n' || marker == ' '); // check for EOF or read errors if (m_file_state != FILE_OK) break; // if the newlines didn't end in a read marker, // issue a parsing error... if (marker != '@') { m_file_state = FILE_PARSE_ERROR; m_error_char = marker; return uint32(-1); } // read all the line uint32 len = 0; for (uint8 c = get(); c != '\n' && c != 0; c = get()) { m_name[ len++ ] = c; // expand on demand if (m_name.size() <= len) m_name.resize( len * 2u ); } m_name[ len++ ] = '\0'; // check for errors if (m_file_state != FILE_OK) { log_error(stderr, "incomplete read!\n"); m_error_char = 0; return uint32(-1); } m_line++; // start reading the bp read len = 0; for (uint8 c = get(); c != '+' && c != 0; c = get()) { // if (isgraph(c)) if (c >= 0x21 && c <= 0x7E) m_read_bp[ len++ ] = c; else if (c == '\n') m_line++; // expand on demand if (m_read_bp.size() <= len) { m_read_bp.resize( len * 2u ); m_read_q.resize( len * 2u ); } } // check for errors if (m_file_state != FILE_OK) { log_error(stderr, "incomplete read!\n"); m_error_char = 0; return uint32(-1); } // read all the line for(uint8 c = get(); c != '\n' && c != 0; c = get()) {} // check for errors if (m_file_state != FILE_OK) { log_error(stderr, "incomplete read!\n"); m_error_char = 0; return uint32(-1); } m_line++; // start reading the quality read len = 0; for (uint8 c = get(); c != '\n' && c != 0; c = get()) m_read_q[ len++ ] = c; // check for errors if (m_file_state != FILE_OK) { log_error(stderr, "incomplete read!\n"); m_error_char = 0; return uint32(-1); } m_line++; if (m_flags & FORWARD) { output->push_back( len, &m_name[0], &m_read_bp[0], &m_read_q[0], m_quality_encoding, m_truncate_read_len, FORWARD ); } if (m_flags & REVERSE) { output->push_back( len, &m_name[0], &m_read_bp[0], &m_read_q[0], m_quality_encoding, m_truncate_read_len, REVERSE ); } if (m_flags & FORWARD_COMPLEMENT) { output->push_back( len, &m_name[0], &m_read_bp[0], &m_read_q[0], m_quality_encoding, m_truncate_read_len, ReadEncoding( FORWARD | COMPLEMENT ) ); } if (m_flags & REVERSE_COMPLEMENT) { output->push_back( len, &m_name[0], &m_read_bp[0], &m_read_q[0], m_quality_encoding, m_truncate_read_len, ReadEncoding( REVERSE | COMPLEMENT ) ); } n_bps += read_mult * len; n_reads += read_mult; } return n_reads; } ReadDataFile_FASTQ_gz::ReadDataFile_FASTQ_gz(const char *read_file_name, const QualityEncoding qualities, const uint32 max_reads, const uint32 max_read_len, const ReadEncoding flags) : ReadDataFile_FASTQ_parser(read_file_name, qualities, max_reads, max_read_len, flags) { m_file = gzopen(read_file_name, "r"); if (!m_file) { m_file_state = FILE_OPEN_FAILED; } else { m_file_state = FILE_OK; } gzbuffer(m_file, m_buffer_size); } static float time = 0.0f; ReadDataFile_FASTQ_parser::FileState ReadDataFile_FASTQ_gz::fillBuffer(void) { m_buffer_size = gzread(m_file, &m_buffer[0], (uint32)m_buffer.size()); if (m_buffer_size <= 0) { // check for EOF separately; zlib will not always return Z_STREAM_END at EOF below if (gzeof(m_file)) { return FILE_EOF; } else { // ask zlib what happened and inform the user int err; const char *msg; msg = gzerror(m_file, &err); // we're making the assumption that we never see Z_STREAM_END here assert(err != Z_STREAM_END); log_error(stderr, "error processing FASTQ file: zlib error %d (%s)\n", err, msg); return FILE_STREAM_ERROR; } } return FILE_OK; } ///@} // ReadsIODetail ///@} // ReadsIO ///@} // IO } // namespace io } // namespace nvbio <|endoftext|>
<commit_before>#define DEBUG 1 /** * File : B.cpp * Author : Kazune Takahashi * Created : 2/11/2019, 7:07:57 PM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; typedef long long ll; const int dx[4] = {1, 0, -1, 0}; const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; int N, M; int A[50][50]; void WA() { cout << "1000 1000 1000" << endl; } void RE() { assert(false); } int main() { cin >> N >> M; for (auto i = 0; i < N; i++) { for (auto j = 0; j < N; j++) { cin >> A[i][j]; } } for (auto i = 0; i < N; i++) { for (auto j = 0; j < N; j++) { if (A[i][j] == 1) { bool ok = true; int ary[10]; fill(ary, ary + 10, 0); for (auto k = 0; k < 4; k++) { int x = i + dx[k]; int y = j + dy[k]; if (0 <= i && i < N && 0 <= j && j < N && A[x][y] == 1) { ok = false; break; } else { ary[A[x][y]]++; } } if (ok) { for (auto k = 0; k < 10; k++) { if (ary[k] == 4) { RE(); } } } } } } WA(); }<commit_msg>submit B.cpp to 'B - ファーマーXの収穫計画' (rco-contest-2019-qual) [C++14 (GCC 5.4.1)]<commit_after>#define DEBUG 1 /** * File : B.cpp * Author : Kazune Takahashi * Created : 2/11/2019, 7:07:57 PM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; typedef long long ll; const int dx[4] = {1, 0, -1, 0}; const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; int N, M; int A[50][50]; void WA() { cout << "1000 1000 1000" << endl; } void RE() { assert(false); } void AC(int x, int y) { assert(A[x][y] == 1); for (auto i = 0; i < k; i++) { int nx = x + dx[i]; int ny = y + dy[i]; if (0 <= nx && nx < N && 0 <= ny && ny < N) { assert(A[nx][ny] != 1); } } } int main() { cin >> N >> M; for (auto i = 0; i < N; i++) { for (auto j = 0; j < N; j++) { cin >> A[i][j]; } } for (auto i = 1; i < N - 1; i++) { for (auto j = 1; j <= 1; j++) { if (A[i][j] == 1) { bool ok = true; int ary[10]; fill(ary, ary + 10, 0); for (auto k = 0; k < 4; k++) { int x = i + dx[k]; int y = j + dy[k]; if (0 <= i && i < N && 0 <= j && j < N && A[x][y] == 1) { ok = false; break; } else { ary[A[x][y]]++; } } if (ok) { for (auto k = 0; k < 10; k++) { if (ary[k] == 4) { RE(); } } } } } } WA(); }<|endoftext|>
<commit_before>/* Copyright (c) 2018 PaddlePaddle 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 "paddle/fluid/framework/eigen.h" #include "paddle/fluid/framework/op_registry.h" namespace paddle { namespace operators { enum MiningType { kNone = 0, kMaxNegative, kHardExample }; template <typename T> bool SortScoreDescend(const std::pair<float, T>& pair1, const std::pair<float, T>& pair2) { return pair1.first > pair2.first; } inline bool IsEligibleMining(const MiningType mining_type, const int match_idx, const float match_dist, const float neg_dist_threshold) { if (mining_type == MiningType::kMaxNegative) { return match_idx == -1 && match_dist < neg_dist_threshold; } else if (mining_type == MiningType::kHardExample) { return true; } else { return false; } } inline MiningType GetMiningType(std::string str) { if (str == "max_negative") { return MiningType::kMaxNegative; } else if (str == "hard_example") { return MiningType::kHardExample; } else { return MiningType::kNone; } } template <typename DeviceContext, typename T> class MineHardExamplesKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& ctx) const override { auto* in_cls_loss = ctx.Input<framework::Tensor>("ClsLoss"); auto* in_loc_loss = ctx.Input<framework::Tensor>("LocLoss"); auto* in_matched_indices = ctx.Input<framework::Tensor>("MatchIndices"); auto* in_match_dist = ctx.Input<framework::Tensor>("MatchDist"); float neg_pos_ratio = ctx.Attr<float>("neg_pos_ratio"); T neg_dist_threshold = static_cast<T>(ctx.Attr<float>("neg_dist_threshold")); int sample_size = ctx.Attr<int>("sample_size"); MiningType mining_type = GetMiningType(ctx.Attr<std::string>("mining_type")); auto out_neg_indices = ctx.Output<framework::LoDTensor>("NegIndices"); auto out_match_indices = ctx.Output<framework::Tensor>("UpdatedMatchIndices"); framework::TensorCopy(*in_matched_indices, ctx.GetPlace(), out_match_indices); int batch_size = in_matched_indices->dims()[0]; int prior_num = in_matched_indices->dims()[1]; auto match_indices = framework::EigenMatrix<int>::From(*in_matched_indices); auto match_indices_et = framework::EigenMatrix<int>::From(*out_match_indices); auto match_dist = framework::EigenMatrix<T>::From(*in_match_dist); const T* cls_loss = in_cls_loss->data<T>(); const T* loc_loss = nullptr; if (in_loc_loss) { loc_loss = in_loc_loss->data<T>(); } std::vector<std::vector<int>> all_neg_indices; std::vector<size_t> batch_starts = {0}; for (int n = 0; n < batch_size; ++n) { std::vector<std::pair<T, size_t>> loss_idx; int neg_sel = 0; for (int m = 0; m < prior_num; ++m) { if (IsEligibleMining(mining_type, match_indices(n, m), match_dist(n, m), neg_dist_threshold)) { T loss = cls_loss[n * prior_num + m]; if (mining_type == MiningType::kHardExample && loc_loss != nullptr) { loss = cls_loss[n * prior_num + m] + loc_loss[n * prior_num + m]; } loss_idx.push_back(std::make_pair(loss, m)); ++neg_sel; } } if (mining_type == MiningType::kMaxNegative) { int num_pos = 0; for (int m = 0; m < prior_num; ++m) { if (match_indices(n, m) != -1) ++num_pos; } neg_sel = std::min(static_cast<int>(num_pos * neg_pos_ratio), neg_sel); } else if (mining_type == MiningType::kHardExample) { neg_sel = std::min(sample_size, neg_sel); } std::sort(loss_idx.begin(), loss_idx.end(), SortScoreDescend<size_t>); std::set<int> sel_indices; std::vector<int> neg_indices; std::transform(loss_idx.begin(), loss_idx.begin() + neg_sel, std::inserter(sel_indices, sel_indices.begin()), [](std::pair<T, size_t>& l) -> int { return static_cast<int>(l.second); }); if (mining_type == MiningType::kHardExample) { for (int m = 0; m < prior_num; ++m) { if (match_indices(n, m) > -1) { if (sel_indices.find(m) == sel_indices.end()) { match_indices_et(n, m) = -1; } } else { if (sel_indices.find(m) != sel_indices.end()) { neg_indices.push_back(m); } } } } else { neg_indices.resize(sel_indices.size()); std::copy(sel_indices.begin(), sel_indices.end(), neg_indices.begin()); } all_neg_indices.push_back(neg_indices); batch_starts.push_back(batch_starts.back() + neg_indices.size()); } framework::LoD out_neg_indices_lod; out_neg_indices_lod.emplace_back(batch_starts); int neg_offset = 0; auto neg_data = out_neg_indices->mutable_data<int>( framework::make_ddim({static_cast<int>(batch_starts.back()), 1}), ctx.GetPlace()); for (auto neg_indices : all_neg_indices) { std::copy(neg_indices.begin(), neg_indices.end(), neg_data + neg_offset); neg_offset += neg_indices.size(); } out_neg_indices->set_lod(out_neg_indices_lod); return; } }; class MineHardExamplesOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; protected: void InferShape(framework::InferShapeContext* ctx) const override { PADDLE_ENFORCE(ctx->HasInput("ClsLoss"), "Input(ClsLoss) of MineHardExamplesOp should not be null."); PADDLE_ENFORCE( ctx->HasInput("MatchIndices"), "Input(MatchIndices) of MineHardExamplesOp should not be null."); PADDLE_ENFORCE( ctx->HasInput("MatchDist"), "Input(MatchDist) of MineHardExamplesOp should not be null."); PADDLE_ENFORCE( ctx->HasOutput("NegIndices"), "Output(NegIndices) of MineHardExamplesOp should not be null."); PADDLE_ENFORCE(ctx->HasOutput("UpdatedMatchIndices"), "Output(UpdatedMatchIndices) of MineHardExamplesOp should " "not be null."); auto cls_loss_dims = ctx->GetInputDim("ClsLoss"); auto idx_dims = ctx->GetInputDim("MatchIndices"); auto dis_dims = ctx->GetInputDim("MatchDist"); PADDLE_ENFORCE_EQ(cls_loss_dims.size(), 2UL, "The shape of ClsLoss is [N, Np]."); PADDLE_ENFORCE_EQ(idx_dims.size(), 2UL, "The shape of MatchIndices is [N, Np]."); PADDLE_ENFORCE_EQ(dis_dims.size(), 2UL, "The shape of MatchDist is [N, Np]."); if (ctx->HasInput("LocLoss")) { auto loc_loss_dims = ctx->GetInputDim("LocLoss"); PADDLE_ENFORCE_EQ(loc_loss_dims.size(), 2UL, "The shape of LocLoss is [N, Np]."); PADDLE_ENFORCE_EQ(cls_loss_dims[0], loc_loss_dims[0], "Batch size of ClsLoss and LocLoss must be the same."); PADDLE_ENFORCE_EQ( cls_loss_dims[1], loc_loss_dims[1], "Prior box number of ClsLoss and LocLoss must be the same."); } PADDLE_ENFORCE_EQ( cls_loss_dims[0], idx_dims[0], "Batch size of ClsLoss and MatchIndices must be the same."); PADDLE_ENFORCE_EQ( cls_loss_dims[1], idx_dims[1], "Prior box number of ClsLoss and MatchIndices must be the same."); PADDLE_ENFORCE_EQ(cls_loss_dims[0], dis_dims[0], "Batch size of ClsLoss and MatchDist must be the same."); PADDLE_ENFORCE_EQ( cls_loss_dims[1], idx_dims[1], "Prior box number of ClsLoss and MatchDist must be the same."); auto mining_type = GetMiningType(ctx->Attrs().Get<std::string>("mining_type")); PADDLE_ENFORCE_NE(mining_type, MiningType::kNone, "mining_type must be hard_example or max_negative"); if (mining_type == MiningType::kMaxNegative) { auto neg_pos_ratio = ctx->Attrs().Get<float>("neg_pos_ratio"); auto neg_dist_threshold = ctx->Attrs().Get<float>("neg_dist_threshold"); PADDLE_ENFORCE_GT( neg_pos_ratio, 0.0f, "neg_pos_ratio must greater than zero in max_negative mode"); PADDLE_ENFORCE_GT( neg_dist_threshold, 0.0f, "neg_dist_threshold must greater than zero in max_negative mode"); } else if (mining_type == MiningType::kHardExample) { auto sample_size = ctx->Attrs().Get<int>("sample_size"); PADDLE_ENFORCE_GT( sample_size, 0, "sample_size must greater than zero in hard_example mode"); } ctx->SetOutputDim("UpdatedMatchIndices", idx_dims); // The first dimension of NegIndices will be set correcttly in Compute. ctx->SetOutputDim("NegIndices", {-1, 1}); } protected: framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext& ctx) const override { return framework::OpKernelType( framework::ToDataType(ctx.Input<framework::Tensor>("ClsLoss")->type()), ctx.device_context()); } }; class MineHardExamplesOpMaker : public framework::OpProtoAndCheckerMaker { public: MineHardExamplesOpMaker(OpProto* proto, OpAttrChecker* op_checker) : OpProtoAndCheckerMaker(proto, op_checker) { AddInput( "ClsLoss", "(Tensor, default Tensor<float>), The classification loss with shape " "[N, Np], N is the batch size and Np is the number of prior box."); AddInput("LocLoss", "(Tensor, optional, default Tensor<float>), The localization loss " "with shape [N, Np], N is the batch size and Np is the number of " "prior box.") .AsDispensable(); AddInput("MatchIndices", "(Tensor, Tensor<int>), Matched indices with shape [N, Np], N is " "the batch size and Np is the number of prior box. " "MatchIndices[i][j] equal -1 means the j-th prior box in i-th " "instance does not match any entity, otherwise means it is " "matched to row."); AddInput("MatchDist", "(Tensor, default Tensor<float>) Matched indices with shape [N, " "Np], N is the batch size and Np is the number of prior box."); AddAttr<float>("neg_pos_ratio", "(float) The ratio of the negative box to the positive " "box. Use only when mining_type is max_negative.") .SetDefault(1.0); AddAttr<float>("neg_dist_threshold", "(float) The negative overlap upper bound for the unmatched " "predictions. Use only when mining_type is max_negative.") .SetDefault(0.5); AddAttr<int>("sample_size", "(float) The max sample size of negative box. Use only when " "mining_type is hard_example.") .SetDefault(0); AddAttr<std::string>("mining_type", "(float) The mining algorithm name, the value is " "hard_example or max_negative.") .SetDefault("max_negative") .InEnum({"hard_example", "max_negative"}); AddOutput( "NegIndices", "(LoDTensor<int>) The output of negative example indices. a LoDTensor " "with shape [Neg, 1]. The size of lod[0] minus 1 is batch size, " "and each element is the prior box index. " "For example, the batch size is 2, the lod is [[0, 1, 2]], " "the sample 0's box 1(MatchIndices[0][1]) is selected, " "and sample 1's box 0 is selected. The output NegIndices is " "[[1], [0]]."); AddOutput("UpdatedMatchIndices", "(Tensor<int>) The output of updated MatchIndices, a tensor with " "shape [N, Np]. Only update when mining_type is " "hard_example. The input MatchIndices elements will be update to " "-1 when it is not in the candidate high loss list of negative " "examples."); AddComment(R"DOC( Mine hard examples Operator. This operator implements hard example mining to select a subset of negative box indices. For each image, selects the box with highest losses. subject to the condition that the box cannot have an Matcht > neg_dist_threshold when mining_type is max_negative. The selected number is min(sample_size, max_negative_box_number) when mining_type is hard_example, or min(neg_pos_ratio * positive_box_number, max_negative_box_number) when mining_type is max_negative, where the max_negative_box_number is the count of MatchIndices elements with value -1. )DOC"); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OP_WITHOUT_GRADIENT(mine_hard_examples, ops::MineHardExamplesOp, ops::MineHardExamplesOpMaker); REGISTER_OP_CPU_KERNEL( mine_hard_examples, ops::MineHardExamplesKernel<paddle::platform::CPUDeviceContext, float>, ops::MineHardExamplesKernel<paddle::platform::CPUDeviceContext, double>); <commit_msg>Enable device automatically switching in mine_hard_examples_op. (#8706)<commit_after>/* Copyright (c) 2018 PaddlePaddle 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 "paddle/fluid/framework/eigen.h" #include "paddle/fluid/framework/op_registry.h" namespace paddle { namespace operators { enum MiningType { kNone = 0, kMaxNegative, kHardExample }; template <typename T> bool SortScoreDescend(const std::pair<float, T>& pair1, const std::pair<float, T>& pair2) { return pair1.first > pair2.first; } inline bool IsEligibleMining(const MiningType mining_type, const int match_idx, const float match_dist, const float neg_dist_threshold) { if (mining_type == MiningType::kMaxNegative) { return match_idx == -1 && match_dist < neg_dist_threshold; } else if (mining_type == MiningType::kHardExample) { return true; } else { return false; } } inline MiningType GetMiningType(std::string str) { if (str == "max_negative") { return MiningType::kMaxNegative; } else if (str == "hard_example") { return MiningType::kHardExample; } else { return MiningType::kNone; } } template <typename DeviceContext, typename T> class MineHardExamplesKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& ctx) const override { auto* in_cls_loss = ctx.Input<framework::Tensor>("ClsLoss"); auto* in_loc_loss = ctx.Input<framework::Tensor>("LocLoss"); auto* in_matched_indices = ctx.Input<framework::Tensor>("MatchIndices"); auto* in_match_dist = ctx.Input<framework::Tensor>("MatchDist"); float neg_pos_ratio = ctx.Attr<float>("neg_pos_ratio"); T neg_dist_threshold = static_cast<T>(ctx.Attr<float>("neg_dist_threshold")); int sample_size = ctx.Attr<int>("sample_size"); MiningType mining_type = GetMiningType(ctx.Attr<std::string>("mining_type")); auto out_neg_indices = ctx.Output<framework::LoDTensor>("NegIndices"); auto out_match_indices = ctx.Output<framework::Tensor>("UpdatedMatchIndices"); framework::TensorCopy(*in_matched_indices, ctx.GetPlace(), out_match_indices); int batch_size = in_matched_indices->dims()[0]; int prior_num = in_matched_indices->dims()[1]; auto match_indices = framework::EigenMatrix<int>::From(*in_matched_indices); auto match_indices_et = framework::EigenMatrix<int>::From(*out_match_indices); auto match_dist = framework::EigenMatrix<T>::From(*in_match_dist); const T* cls_loss = in_cls_loss->data<T>(); const T* loc_loss = nullptr; if (in_loc_loss) { loc_loss = in_loc_loss->data<T>(); } std::vector<std::vector<int>> all_neg_indices; std::vector<size_t> batch_starts = {0}; for (int n = 0; n < batch_size; ++n) { std::vector<std::pair<T, size_t>> loss_idx; int neg_sel = 0; for (int m = 0; m < prior_num; ++m) { if (IsEligibleMining(mining_type, match_indices(n, m), match_dist(n, m), neg_dist_threshold)) { T loss = cls_loss[n * prior_num + m]; if (mining_type == MiningType::kHardExample && loc_loss != nullptr) { loss = cls_loss[n * prior_num + m] + loc_loss[n * prior_num + m]; } loss_idx.push_back(std::make_pair(loss, m)); ++neg_sel; } } if (mining_type == MiningType::kMaxNegative) { int num_pos = 0; for (int m = 0; m < prior_num; ++m) { if (match_indices(n, m) != -1) ++num_pos; } neg_sel = std::min(static_cast<int>(num_pos * neg_pos_ratio), neg_sel); } else if (mining_type == MiningType::kHardExample) { neg_sel = std::min(sample_size, neg_sel); } std::sort(loss_idx.begin(), loss_idx.end(), SortScoreDescend<size_t>); std::set<int> sel_indices; std::vector<int> neg_indices; std::transform(loss_idx.begin(), loss_idx.begin() + neg_sel, std::inserter(sel_indices, sel_indices.begin()), [](std::pair<T, size_t>& l) -> int { return static_cast<int>(l.second); }); if (mining_type == MiningType::kHardExample) { for (int m = 0; m < prior_num; ++m) { if (match_indices(n, m) > -1) { if (sel_indices.find(m) == sel_indices.end()) { match_indices_et(n, m) = -1; } } else { if (sel_indices.find(m) != sel_indices.end()) { neg_indices.push_back(m); } } } } else { neg_indices.resize(sel_indices.size()); std::copy(sel_indices.begin(), sel_indices.end(), neg_indices.begin()); } all_neg_indices.push_back(neg_indices); batch_starts.push_back(batch_starts.back() + neg_indices.size()); } framework::LoD out_neg_indices_lod; out_neg_indices_lod.emplace_back(batch_starts); int neg_offset = 0; auto neg_data = out_neg_indices->mutable_data<int>( framework::make_ddim({static_cast<int>(batch_starts.back()), 1}), ctx.GetPlace()); for (auto neg_indices : all_neg_indices) { std::copy(neg_indices.begin(), neg_indices.end(), neg_data + neg_offset); neg_offset += neg_indices.size(); } out_neg_indices->set_lod(out_neg_indices_lod); return; } }; class MineHardExamplesOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; protected: void InferShape(framework::InferShapeContext* ctx) const override { PADDLE_ENFORCE(ctx->HasInput("ClsLoss"), "Input(ClsLoss) of MineHardExamplesOp should not be null."); PADDLE_ENFORCE( ctx->HasInput("MatchIndices"), "Input(MatchIndices) of MineHardExamplesOp should not be null."); PADDLE_ENFORCE( ctx->HasInput("MatchDist"), "Input(MatchDist) of MineHardExamplesOp should not be null."); PADDLE_ENFORCE( ctx->HasOutput("NegIndices"), "Output(NegIndices) of MineHardExamplesOp should not be null."); PADDLE_ENFORCE(ctx->HasOutput("UpdatedMatchIndices"), "Output(UpdatedMatchIndices) of MineHardExamplesOp should " "not be null."); auto cls_loss_dims = ctx->GetInputDim("ClsLoss"); auto idx_dims = ctx->GetInputDim("MatchIndices"); auto dis_dims = ctx->GetInputDim("MatchDist"); PADDLE_ENFORCE_EQ(cls_loss_dims.size(), 2UL, "The shape of ClsLoss is [N, Np]."); PADDLE_ENFORCE_EQ(idx_dims.size(), 2UL, "The shape of MatchIndices is [N, Np]."); PADDLE_ENFORCE_EQ(dis_dims.size(), 2UL, "The shape of MatchDist is [N, Np]."); if (ctx->HasInput("LocLoss")) { auto loc_loss_dims = ctx->GetInputDim("LocLoss"); PADDLE_ENFORCE_EQ(loc_loss_dims.size(), 2UL, "The shape of LocLoss is [N, Np]."); PADDLE_ENFORCE_EQ(cls_loss_dims[0], loc_loss_dims[0], "Batch size of ClsLoss and LocLoss must be the same."); PADDLE_ENFORCE_EQ( cls_loss_dims[1], loc_loss_dims[1], "Prior box number of ClsLoss and LocLoss must be the same."); } PADDLE_ENFORCE_EQ( cls_loss_dims[0], idx_dims[0], "Batch size of ClsLoss and MatchIndices must be the same."); PADDLE_ENFORCE_EQ( cls_loss_dims[1], idx_dims[1], "Prior box number of ClsLoss and MatchIndices must be the same."); PADDLE_ENFORCE_EQ(cls_loss_dims[0], dis_dims[0], "Batch size of ClsLoss and MatchDist must be the same."); PADDLE_ENFORCE_EQ( cls_loss_dims[1], idx_dims[1], "Prior box number of ClsLoss and MatchDist must be the same."); auto mining_type = GetMiningType(ctx->Attrs().Get<std::string>("mining_type")); PADDLE_ENFORCE_NE(mining_type, MiningType::kNone, "mining_type must be hard_example or max_negative"); if (mining_type == MiningType::kMaxNegative) { auto neg_pos_ratio = ctx->Attrs().Get<float>("neg_pos_ratio"); auto neg_dist_threshold = ctx->Attrs().Get<float>("neg_dist_threshold"); PADDLE_ENFORCE_GT( neg_pos_ratio, 0.0f, "neg_pos_ratio must greater than zero in max_negative mode"); PADDLE_ENFORCE_GT( neg_dist_threshold, 0.0f, "neg_dist_threshold must greater than zero in max_negative mode"); } else if (mining_type == MiningType::kHardExample) { auto sample_size = ctx->Attrs().Get<int>("sample_size"); PADDLE_ENFORCE_GT( sample_size, 0, "sample_size must greater than zero in hard_example mode"); } ctx->SetOutputDim("UpdatedMatchIndices", idx_dims); // The first dimension of NegIndices will be set correcttly in Compute. ctx->SetOutputDim("NegIndices", {-1, 1}); } protected: framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext& ctx) const override { return framework::OpKernelType( framework::ToDataType(ctx.Input<framework::Tensor>("ClsLoss")->type()), platform::CPUPlace()); } }; class MineHardExamplesOpMaker : public framework::OpProtoAndCheckerMaker { public: MineHardExamplesOpMaker(OpProto* proto, OpAttrChecker* op_checker) : OpProtoAndCheckerMaker(proto, op_checker) { AddInput( "ClsLoss", "(Tensor, default Tensor<float>), The classification loss with shape " "[N, Np], N is the batch size and Np is the number of prior box."); AddInput("LocLoss", "(Tensor, optional, default Tensor<float>), The localization loss " "with shape [N, Np], N is the batch size and Np is the number of " "prior box.") .AsDispensable(); AddInput("MatchIndices", "(Tensor, Tensor<int>), Matched indices with shape [N, Np], N is " "the batch size and Np is the number of prior box. " "MatchIndices[i][j] equal -1 means the j-th prior box in i-th " "instance does not match any entity, otherwise means it is " "matched to row."); AddInput("MatchDist", "(Tensor, default Tensor<float>) Matched indices with shape [N, " "Np], N is the batch size and Np is the number of prior box."); AddAttr<float>("neg_pos_ratio", "(float) The ratio of the negative box to the positive " "box. Use only when mining_type is max_negative.") .SetDefault(1.0); AddAttr<float>("neg_dist_threshold", "(float) The negative overlap upper bound for the unmatched " "predictions. Use only when mining_type is max_negative.") .SetDefault(0.5); AddAttr<int>("sample_size", "(float) The max sample size of negative box. Use only when " "mining_type is hard_example.") .SetDefault(0); AddAttr<std::string>("mining_type", "(float) The mining algorithm name, the value is " "hard_example or max_negative.") .SetDefault("max_negative") .InEnum({"hard_example", "max_negative"}); AddOutput( "NegIndices", "(LoDTensor<int>) The output of negative example indices. a LoDTensor " "with shape [Neg, 1]. The size of lod[0] minus 1 is batch size, " "and each element is the prior box index. " "For example, the batch size is 2, the lod is [[0, 1, 2]], " "the sample 0's box 1(MatchIndices[0][1]) is selected, " "and sample 1's box 0 is selected. The output NegIndices is " "[[1], [0]]."); AddOutput("UpdatedMatchIndices", "(Tensor<int>) The output of updated MatchIndices, a tensor with " "shape [N, Np]. Only update when mining_type is " "hard_example. The input MatchIndices elements will be update to " "-1 when it is not in the candidate high loss list of negative " "examples."); AddComment(R"DOC( Mine hard examples Operator. This operator implements hard example mining to select a subset of negative box indices. For each image, selects the box with highest losses. subject to the condition that the box cannot have an Matcht > neg_dist_threshold when mining_type is max_negative. The selected number is min(sample_size, max_negative_box_number) when mining_type is hard_example, or min(neg_pos_ratio * positive_box_number, max_negative_box_number) when mining_type is max_negative, where the max_negative_box_number is the count of MatchIndices elements with value -1. )DOC"); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OP_WITHOUT_GRADIENT(mine_hard_examples, ops::MineHardExamplesOp, ops::MineHardExamplesOpMaker); REGISTER_OP_CPU_KERNEL( mine_hard_examples, ops::MineHardExamplesKernel<paddle::platform::CPUDeviceContext, float>, ops::MineHardExamplesKernel<paddle::platform::CPUDeviceContext, double>); <|endoftext|>
<commit_before>/* Copyright (c) 2016 PaddlePaddle 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 "paddle/fluid/platform/dynload/dynamic_loader.h" #include <dlfcn.h> #include <memory> #include <mutex> // NOLINT #include <string> #include "gflags/gflags.h" #include "glog/logging.h" #include "paddle/fluid/platform/dynload/cupti_lib_path.h" #include "paddle/fluid/platform/enforce.h" DEFINE_string(cudnn_dir, "", "Specify path for loading libcudnn.so. For instance, " "/usr/local/cudnn/lib. If empty [default], dlopen " "will search cudnn from LD_LIBRARY_PATH"); DEFINE_string(cuda_dir, "", "Specify path for loading cuda library, such as libcublas, " "libcurand. For instance, /usr/local/cuda/lib64. If default, " "dlopen will search cuda from LD_LIBRARY_PATH"); DEFINE_string(warpctc_dir, "", "Specify path for loading libwarpctc.so."); DEFINE_string(lapack_dir, "", "Specify path for loading liblapack.so."); DEFINE_string(nccl_dir, "", "Specify path for loading nccl library, such as libcublas, " "libcurand. For instance, /usr/local/cuda/lib64. If default, " "dlopen will search cuda from LD_LIBRARY_PATH"); DEFINE_string(cupti_dir, "", "Specify path for loading cupti.so."); DEFINE_string( tensorrt_dir, "", "Specify path for loading tensorrt library, such as libnvinfer.so."); DEFINE_string(mklml_dir, "", "Specify path for loading libmklml_intel.so."); namespace paddle { namespace platform { namespace dynload { static constexpr char cupti_lib_path[] = CUPTI_LIB_PATH; static inline std::string join(const std::string& part1, const std::string& part2) { // directory separator const char sep = '/'; if (!part2.empty() && part2.front() == sep) { return part2; } std::string ret; ret.reserve(part1.size() + part2.size() + 1); ret = part1; if (!ret.empty() && ret.back() != sep) { ret += sep; } ret += part2; return ret; } static inline void* GetDsoHandleFromDefaultPath(const std::string& dso_path, int dynload_flags) { VLOG(3) << "Try to find library: " << dso_path << " from default system path."; // default search from LD_LIBRARY_PATH/DYLD_LIBRARY_PATH // and /usr/local/lib path void* dso_handle = dlopen(dso_path.c_str(), dynload_flags); if (nullptr == dso_handle) { dso_handle = dlopen(join("/usr/local/lib/", dso_path).c_str(), dynload_flags); } // DYLD_LIBRARY_PATH is disabled after Mac OS 10.11 to // bring System Integrity Projection (SIP), if dso_handle // is null, search from default package path in Mac OS. #if defined(__APPLE__) || defined(__OSX__) if (nullptr == dso_handle) { dso_handle = dlopen(join("/usr/local/cuda/lib/", dso_path).c_str(), dynload_flags); if (nullptr == dso_handle) { if (dso_path == "libcudnn.dylib") { LOG(WARNING) << "Note: [Recommend] copy cudnn into /usr/local/cuda/ \n " "For instance, sudo tar -xzf " "cudnn-7.5-osx-x64-v5.0-ga.tgz -C /usr/local \n sudo " "chmod a+r /usr/local/cuda/include/cudnn.h " "/usr/local/cuda/lib/libcudnn*"; } } } #endif if (nullptr == dso_handle) { LOG(WARNING) << "Can not find library: " << dso_path << ". Please try to set add the lib path to LD_LIBRARY_PATH."; } return dso_handle; } static inline void* GetDsoHandleFromSearchPath(const std::string& search_root, const std::string& dso_name, bool throw_on_error = true) { int dynload_flags = RTLD_LAZY | RTLD_LOCAL; void* dso_handle = nullptr; std::string dlPath = dso_name; if (search_root.empty()) { dso_handle = GetDsoHandleFromDefaultPath(dlPath, dynload_flags); } else { // search xxx.so from custom path dlPath = join(search_root, dso_name); dso_handle = dlopen(dlPath.c_str(), dynload_flags); // if not found, search from default path if (nullptr == dso_handle) { LOG(WARNING) << "Failed to find dynamic library: " << dlPath << " (" << dlerror() << ")"; dlPath = dso_name; dso_handle = GetDsoHandleFromDefaultPath(dlPath, dynload_flags); } } auto error_msg = "Failed to find dynamic library: %s ( %s ) \n Please specify " "its path correctly using following ways: \n Method. set " "environment variable LD_LIBRARY_PATH on Linux or " "DYLD_LIBRARY_PATH on Mac OS. \n For instance, issue command: " "export LD_LIBRARY_PATH=... \n Note: After Mac OS 10.11, " "using the DYLD_LIBRARY_PATH is impossible unless System " "Integrity Protection (SIP) is disabled."; if (throw_on_error) { PADDLE_ENFORCE(nullptr != dso_handle, error_msg, dlPath, dlerror()); } else if (nullptr == dso_handle) { LOG(WARNING) << string::Sprintf(error_msg, dlPath, dlerror()); } return dso_handle; } void* GetCublasDsoHandle() { #if defined(__APPLE__) || defined(__OSX__) return GetDsoHandleFromSearchPath(FLAGS_cuda_dir, "libcublas.dylib"); #else return GetDsoHandleFromSearchPath(FLAGS_cuda_dir, "libcublas.so"); #endif } void* GetCUDNNDsoHandle() { #if defined(__APPLE__) || defined(__OSX__) return GetDsoHandleFromSearchPath(FLAGS_cudnn_dir, "libcudnn.dylib", false); #else return GetDsoHandleFromSearchPath(FLAGS_cudnn_dir, "libcudnn.so", false); #endif } void* GetCUPTIDsoHandle() { std::string cupti_path = cupti_lib_path; if (!FLAGS_cupti_dir.empty()) { cupti_path = FLAGS_cupti_dir; } #if defined(__APPLE__) || defined(__OSX__) return GetDsoHandleFromSearchPath(cupti_path, "libcupti.dylib", false); #else return GetDsoHandleFromSearchPath(cupti_path, "libcupti.so", false); #endif } void* GetCurandDsoHandle() { #if defined(__APPLE__) || defined(__OSX__) return GetDsoHandleFromSearchPath(FLAGS_cuda_dir, "libcurand.dylib"); #else return GetDsoHandleFromSearchPath(FLAGS_cuda_dir, "libcurand.so"); #endif } void* GetWarpCTCDsoHandle() { #if defined(__APPLE__) || defined(__OSX__) return GetDsoHandleFromSearchPath(FLAGS_warpctc_dir, "libwarpctc.dylib"); #else return GetDsoHandleFromSearchPath(FLAGS_warpctc_dir, "libwarpctc.so"); #endif } void* GetLapackDsoHandle() { #if defined(__APPLE__) || defined(__OSX__) return GetDsoHandleFromSearchPath(FLAGS_lapack_dir, "liblapacke.dylib"); #else return GetDsoHandleFromSearchPath(FLAGS_lapack_dir, "liblapacke.so"); #endif } void* GetNCCLDsoHandle() { #if defined(__APPLE__) || defined(__OSX__) return GetDsoHandleFromSearchPath(FLAGS_nccl_dir, "libnccl.dylib"); #else return GetDsoHandleFromSearchPath(FLAGS_nccl_dir, "libnccl.so"); #endif } void* GetTensorRtDsoHandle() { #if defined(__APPLE__) || defined(__OSX__) return GetDsoHandleFromSearchPath(FLAGS_tensorrt_dir, "libnvinfer.dylib"); #else return GetDsoHandleFromSearchPath(FLAGS_tensorrt_dir, "libnvinfer.so"); #endif } void* GetMKLMLDsoHandle() { #if defined(__APPLE__) || defined(__OSX__) return GetDsoHandleFromSearchPath(FLAGS_mklml_dir, "libmklml_intel.dylib"); #else return GetDsoHandleFromSearchPath(FLAGS_mklml_dir, "libmklml_intel.so"); #endif } } // namespace dynload } // namespace platform } // namespace paddle <commit_msg>remove usr local lib when dynamic load lib<commit_after>/* Copyright (c) 2016 PaddlePaddle 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 "paddle/fluid/platform/dynload/dynamic_loader.h" #include <dlfcn.h> #include <memory> #include <mutex> // NOLINT #include <string> #include "gflags/gflags.h" #include "glog/logging.h" #include "paddle/fluid/platform/dynload/cupti_lib_path.h" #include "paddle/fluid/platform/enforce.h" DEFINE_string(cudnn_dir, "", "Specify path for loading libcudnn.so. For instance, " "/usr/local/cudnn/lib. If empty [default], dlopen " "will search cudnn from LD_LIBRARY_PATH"); DEFINE_string(cuda_dir, "", "Specify path for loading cuda library, such as libcublas, " "libcurand. For instance, /usr/local/cuda/lib64. If default, " "dlopen will search cuda from LD_LIBRARY_PATH"); DEFINE_string(warpctc_dir, "", "Specify path for loading libwarpctc.so."); DEFINE_string(lapack_dir, "", "Specify path for loading liblapack.so."); DEFINE_string(nccl_dir, "", "Specify path for loading nccl library, such as libcublas, " "libcurand. For instance, /usr/local/cuda/lib64. If default, " "dlopen will search cuda from LD_LIBRARY_PATH"); DEFINE_string(cupti_dir, "", "Specify path for loading cupti.so."); DEFINE_string( tensorrt_dir, "", "Specify path for loading tensorrt library, such as libnvinfer.so."); DEFINE_string(mklml_dir, "", "Specify path for loading libmklml_intel.so."); namespace paddle { namespace platform { namespace dynload { static constexpr char cupti_lib_path[] = CUPTI_LIB_PATH; static inline std::string join(const std::string& part1, const std::string& part2) { // directory separator const char sep = '/'; if (!part2.empty() && part2.front() == sep) { return part2; } std::string ret; ret.reserve(part1.size() + part2.size() + 1); ret = part1; if (!ret.empty() && ret.back() != sep) { ret += sep; } ret += part2; return ret; } static inline void* GetDsoHandleFromDefaultPath(const std::string& dso_path, int dynload_flags) { VLOG(3) << "Try to find library: " << dso_path << " from default system path."; // default search from LD_LIBRARY_PATH/DYLD_LIBRARY_PATH // and /usr/local/lib path void* dso_handle = dlopen(dso_path.c_str(), dynload_flags); // DYLD_LIBRARY_PATH is disabled after Mac OS 10.11 to // bring System Integrity Projection (SIP), if dso_handle // is null, search from default package path in Mac OS. #if defined(__APPLE__) || defined(__OSX__) if (nullptr == dso_handle) { dso_handle = dlopen(join("/usr/local/cuda/lib/", dso_path).c_str(), dynload_flags); if (nullptr == dso_handle) { if (dso_path == "libcudnn.dylib") { LOG(WARNING) << "Note: [Recommend] copy cudnn into /usr/local/cuda/ \n " "For instance, sudo tar -xzf " "cudnn-7.5-osx-x64-v5.0-ga.tgz -C /usr/local \n sudo " "chmod a+r /usr/local/cuda/include/cudnn.h " "/usr/local/cuda/lib/libcudnn*"; } } } #endif if (nullptr == dso_handle) { LOG(WARNING) << "Can not find library: " << dso_path << ". Please try to add the lib path to LD_LIBRARY_PATH."; } return dso_handle; } static inline void* GetDsoHandleFromSearchPath(const std::string& search_root, const std::string& dso_name, bool throw_on_error = true) { int dynload_flags = RTLD_LAZY | RTLD_LOCAL; void* dso_handle = nullptr; std::string dlPath = dso_name; if (search_root.empty()) { dso_handle = GetDsoHandleFromDefaultPath(dlPath, dynload_flags); } else { // search xxx.so from custom path dlPath = join(search_root, dso_name); dso_handle = dlopen(dlPath.c_str(), dynload_flags); // if not found, search from default path if (nullptr == dso_handle) { LOG(WARNING) << "Failed to find dynamic library: " << dlPath << " (" << dlerror() << ")"; dlPath = dso_name; dso_handle = GetDsoHandleFromDefaultPath(dlPath, dynload_flags); } } auto error_msg = "Failed to find dynamic library: %s ( %s ) \n Please specify " "its path correctly using following ways: \n Method. set " "environment variable LD_LIBRARY_PATH on Linux or " "DYLD_LIBRARY_PATH on Mac OS. \n For instance, issue command: " "export LD_LIBRARY_PATH=... \n Note: After Mac OS 10.11, " "using the DYLD_LIBRARY_PATH is impossible unless System " "Integrity Protection (SIP) is disabled."; if (throw_on_error) { PADDLE_ENFORCE(nullptr != dso_handle, error_msg, dlPath, dlerror()); } else if (nullptr == dso_handle) { LOG(WARNING) << string::Sprintf(error_msg, dlPath, dlerror()); } return dso_handle; } void* GetCublasDsoHandle() { #if defined(__APPLE__) || defined(__OSX__) return GetDsoHandleFromSearchPath(FLAGS_cuda_dir, "libcublas.dylib"); #else return GetDsoHandleFromSearchPath(FLAGS_cuda_dir, "libcublas.so"); #endif } void* GetCUDNNDsoHandle() { #if defined(__APPLE__) || defined(__OSX__) return GetDsoHandleFromSearchPath(FLAGS_cudnn_dir, "libcudnn.dylib", false); #else return GetDsoHandleFromSearchPath(FLAGS_cudnn_dir, "libcudnn.so", false); #endif } void* GetCUPTIDsoHandle() { std::string cupti_path = cupti_lib_path; if (!FLAGS_cupti_dir.empty()) { cupti_path = FLAGS_cupti_dir; } #if defined(__APPLE__) || defined(__OSX__) return GetDsoHandleFromSearchPath(cupti_path, "libcupti.dylib", false); #else return GetDsoHandleFromSearchPath(cupti_path, "libcupti.so", false); #endif } void* GetCurandDsoHandle() { #if defined(__APPLE__) || defined(__OSX__) return GetDsoHandleFromSearchPath(FLAGS_cuda_dir, "libcurand.dylib"); #else return GetDsoHandleFromSearchPath(FLAGS_cuda_dir, "libcurand.so"); #endif } void* GetWarpCTCDsoHandle() { #if defined(__APPLE__) || defined(__OSX__) return GetDsoHandleFromSearchPath(FLAGS_warpctc_dir, "libwarpctc.dylib"); #else return GetDsoHandleFromSearchPath(FLAGS_warpctc_dir, "libwarpctc.so"); #endif } void* GetLapackDsoHandle() { #if defined(__APPLE__) || defined(__OSX__) return GetDsoHandleFromSearchPath(FLAGS_lapack_dir, "liblapacke.dylib"); #else return GetDsoHandleFromSearchPath(FLAGS_lapack_dir, "liblapacke.so"); #endif } void* GetNCCLDsoHandle() { #if defined(__APPLE__) || defined(__OSX__) return GetDsoHandleFromSearchPath(FLAGS_nccl_dir, "libnccl.dylib"); #else return GetDsoHandleFromSearchPath(FLAGS_nccl_dir, "libnccl.so"); #endif } void* GetTensorRtDsoHandle() { #if defined(__APPLE__) || defined(__OSX__) return GetDsoHandleFromSearchPath(FLAGS_tensorrt_dir, "libnvinfer.dylib"); #else return GetDsoHandleFromSearchPath(FLAGS_tensorrt_dir, "libnvinfer.so"); #endif } void* GetMKLMLDsoHandle() { #if defined(__APPLE__) || defined(__OSX__) return GetDsoHandleFromSearchPath(FLAGS_mklml_dir, "libmklml_intel.dylib"); #else return GetDsoHandleFromSearchPath(FLAGS_mklml_dir, "libmklml_intel.so"); #endif } } // namespace dynload } // namespace platform } // namespace paddle <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: docsh.hxx,v $ * * $Revision: 1.28 $ * * last change: $Author: kz $ $Date: 2004-10-04 18:58:00 $ * * 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 _SWDOCSH_HXX #define _SWDOCSH_HXX #ifndef _TIMER_HXX //autogen #include <vcl/timer.hxx> #endif #ifndef _SFX_OBJFAC_HXX //autogen #include <sfx2/docfac.hxx> #endif #ifndef _SFX_OBJSH_HXX //autogen #include <sfx2/objsh.hxx> #endif #ifndef INCLUDED_SWDLLAPI_H #include "swdllapi.h" #endif #ifndef SW_SWDLL_HXX #include <swdll.hxx> #endif #ifndef _SHELLID_HXX #include <shellid.hxx> #endif #include <svtools/lstner.hxx> class SwDoc; class SfxDocumentInfoDialog; class SfxStyleSheetBasePool; class FontList; class SwView; class SwWrtShell; class SwFEShell; class Reader; class SwReader; class SwCrsrShell; class SwSrcView; class PushButton; class FixedText; class SwPaM; class SwgReaderOption; class SW_DLLPUBLIC SwDocShell: public SfxObjectShell, public SfxListener { SwDoc* pDoc; // Document SfxStyleSheetBasePool* pBasePool; // Durchreiche fuer Formate FontList* pFontList; // aktuelle FontListe // Nix geht ohne die WrtShell (historische Gruende) // RuekwaertsPointer auf die View (historische Gruende) // Dieser gilt solange bis im Activate ein neuer gesetzt wird // oder dieser im Dtor der View geloescht wird // SwView* pView; SwWrtShell* pWrtShell; Timer aFinishedTimer; // Timer fuers ueberpriefen der // Grafik-Links. Sind alle da, // dann ist Doc voll. geladen //SvPersistRef xOLEChildList; // fuers RemoveOLEObjects comphelper::EmbeddedObjectContainer* pOLEChildList; sal_Int16 nUpdateDocMode; // contains the com::sun::star::document::UpdateDocMode bool bInUpdateFontList; //prevent nested calls of UpdateFontList // Methoden fuer den Zugriff aufs Doc SW_DLLPRIVATE void AddLink(); SW_DLLPRIVATE void RemoveLink(); // Hint abfangen fuer DocInfo SW_DLLPRIVATE virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint ); // FileIO SW_DLLPRIVATE virtual sal_Bool InitNew( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage ); SW_DLLPRIVATE virtual sal_Bool Load( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage ); SW_DLLPRIVATE virtual sal_Bool LoadFrom( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage ); SW_DLLPRIVATE virtual sal_Bool ConvertFrom( SfxMedium &rMedium ); SW_DLLPRIVATE virtual sal_Bool ConvertTo( SfxMedium &rMedium ); SW_DLLPRIVATE virtual sal_Bool SaveAs( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xNewStg ); SW_DLLPRIVATE virtual sal_Bool SaveCompleted( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage ); SW_DLLPRIVATE virtual USHORT PrepareClose( BOOL bUI = TRUE, BOOL bForBrowsing = FALSE ); // DocInfo dem Doc melden // SW_DLLPRIVATE virtual SfxDocumentInfoDialog* CreateDocumentInfoDialog( Window *pParent, const SfxItemSet &); // OLE-Geraffel SW_DLLPRIVATE virtual void Draw( OutputDevice*, const JobSetup&, USHORT); // Methoden fuer StyleSheets SW_DLLPRIVATE USHORT Edit( const String &rName, const String& rParent, USHORT nFamily, USHORT nMask, BOOL bNew, BOOL bColumn = FALSE, SwWrtShell* pActShell = 0, BOOL bBasic = FALSE ); SW_DLLPRIVATE USHORT Delete(const String &rName, USHORT nFamily); SW_DLLPRIVATE USHORT ApplyStyles(const String &rName, USHORT nFamily, SwWrtShell* pShell = 0, USHORT nMode = 0 ); SW_DLLPRIVATE USHORT DoWaterCan( const String &rName, USHORT nFamily); SW_DLLPRIVATE USHORT UpdateStyle(const String &rName, USHORT nFamily, SwWrtShell* pShell = 0); SW_DLLPRIVATE USHORT MakeByExample(const String &rName, USHORT nFamily, USHORT nMask, SwWrtShell* pShell = 0); SW_DLLPRIVATE void InitDraw(); SW_DLLPRIVATE void SubInitNew(); // fuer InitNew und HtmlSourceModus inline void SetWrtShell(SwWrtShell* pShell) { pWrtShell = pShell; } SW_DLLPRIVATE void RemoveOLEObjects(); SW_DLLPRIVATE void CalcLayoutForOLEObjects(); SW_DLLPRIVATE void Init_Impl(); SW_DLLPRIVATE DECL_STATIC_LINK( SwDocShell, IsLoadFinished, void* ); public: // aber selbst implementieren SFX_DECL_INTERFACE(SW_DOCSHELL); SFX_DECL_OBJECTFACTORY(); TYPEINFO(); static SfxInterface *_GetInterface() { return _GetInterfaceImpl(); } //Das Doc wird fuer SO-Datenaustausch benoetigt! SwDocShell(SfxObjectCreateMode eMode = SFX_CREATE_MODE_EMBEDDED); SwDocShell( SwDoc *pDoc, SfxObjectCreateMode eMode = SFX_CREATE_MODE_STANDARD ); ~SwDocShell(); // OLE 2.0-Benachrichtigung DECL_LINK( Ole2ModifiedHdl, void * ); // OLE-Geraffel virtual void SetVisArea( const Rectangle &rRect ); virtual Rectangle GetVisArea( USHORT nAspect ) const; virtual Printer *GetDocumentPrinter(); virtual OutputDevice* GetDocumentRefDev(); virtual void OnDocumentPrinterChanged( Printer * pNewPrinter ); virtual ULONG GetMiscStatus() const; virtual void PrepareReload(); virtual void SetModified( BOOL = TRUE ); // Dispatcher void Execute(SfxRequest &); void ExecStyleSheet(SfxRequest&); void ExecDB(SfxRequest&); void GetState(SfxItemSet &); void StateAlways(SfxItemSet &); void StateStyleSheet(SfxItemSet&, SwWrtShell* pSh = 0 ); // Doc rausreichen aber VORSICHT inline SwDoc* GetDoc() { return pDoc; } void UpdateFontList(); void UpdateChildWindows(); // DocumentInfo neu setzen BOOL SetDocumentInfo(const SfxDocumentInfo& rInfo); // globaler IO virtual BOOL Save(); // fuer VorlagenPI virtual SfxStyleSheetBasePool* GetStyleSheetPool(); // Fuer Organizer virtual BOOL Insert(SfxObjectShell &rSource, USHORT nSourceIdx1, USHORT nSourceIdx2, USHORT nSourceIdx3, USHORT& nIdx1, USHORT& nIdx2, USHORT& nIdx3, USHORT& nRemovedIdx); virtual BOOL Remove(USHORT nIdx1, USHORT nIdx2 = INDEX_IGNORE, USHORT nIdx3 = INDEX_IGNORE); virtual Bitmap GetStyleFamilyBitmap( SfxStyleFamily eFamily, BmpColorMode eColorMode ); // View setzen fuer Aktionen ueber Shell void SetView(SwView* pVw); const SwView *GetView() const { return pView; } SwView *GetView() { return pView; } // Zugriff auf die zur SwView gehoerige SwWrtShell SwWrtShell *GetWrtShell() { return pWrtShell; } const SwWrtShell *GetWrtShell() const { return pWrtShell; } // fuer die Core - die kennt die DocShell aber keine WrtShell! SwFEShell *GetFEShell(); const SwFEShell *GetFEShell() const { return ((SwDocShell*)this)->GetFEShell(); } // Fuer Einfuegen Dokument Reader* StartConvertFrom(SfxMedium& rMedium, SwReader** ppRdr, SwCrsrShell* pCrsrSh = 0, SwPaM* pPaM = 0); virtual long DdeGetData( const String& rItem, const String& rMimeType, ::com::sun::star::uno::Any & rValue ); virtual long DdeSetData( const String& rItem, const String& rMimeType, const ::com::sun::star::uno::Any & rValue ); virtual ::sfx2::SvLinkSource* DdeCreateLinkSource( const String& rItem ); virtual void FillClass( SvGlobalName * pClassName, ULONG * pClipFormat, String * pAppName, String * pLongUserName, String * pUserName, sal_Int32 nFileFormat ) const; virtual void LoadStyles( SfxObjectShell& rSource ); void _LoadStyles( SfxObjectShell& rSource, BOOL bPreserveCurrentDocument ); // Seitenvorlagedialog anzeigen, ggf. auf Spaltenpage void FormatPage( const String& rPage, BOOL bColumn = FALSE, SwWrtShell* pActShell = 0 ); // Timer starten fuers ueberpruefen der Grafik-Links. Sind alle // vollstaendig geladen, dann ist das Doc fertig void StartLoadFinishedTimer(); // eine Uebertragung wird abgebrochen (wird aus dem SFX gerufen) virtual void CancelTransfers(); // Doc aus Html-Source neu laden void ReloadFromHtml( const String& rStreamName, SwSrcView* pSrcView ); sal_Int16 GetUpdateDocMode() const {return nUpdateDocMode;} //Activate wait cursor for all windows of this document //Optionally all dispatcher could be Locked //Usually locking should be done using the class: SwWaitObject! void EnterWait( BOOL bLockDispatcher ); void LeaveWait( BOOL bLockDispatcher ); void ToggleBrowserMode(BOOL bOn, SwView* pView = 0); ULONG LoadStylesFromFile( const String& rURL, SwgReaderOption& rOpt, BOOL bUnoCall ); void InvalidateModel(); void ReactivateModel(); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > GetEventNames(); // --> FME 2004-08-05 #i20883# Digital Signatures and Encryption virtual sal_uInt16 GetHiddenInformationState( sal_uInt16 nStates ); // <-- }; #endif <commit_msg>INTEGRATION: CWS sb19 (1.28.32); FILE MERGED 2004/10/27 07:35:17 mba 1.28.32.1: #110407#: remove static BaseURL<commit_after>/************************************************************************* * * $RCSfile: docsh.hxx,v $ * * $Revision: 1.29 $ * * last change: $Author: rt $ $Date: 2005-01-11 12:16:49 $ * * 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 _SWDOCSH_HXX #define _SWDOCSH_HXX #ifndef _TIMER_HXX //autogen #include <vcl/timer.hxx> #endif #ifndef _SFX_OBJFAC_HXX //autogen #include <sfx2/docfac.hxx> #endif #ifndef _SFX_OBJSH_HXX //autogen #include <sfx2/objsh.hxx> #endif #ifndef INCLUDED_SWDLLAPI_H #include "swdllapi.h" #endif #ifndef SW_SWDLL_HXX #include <swdll.hxx> #endif #ifndef _SHELLID_HXX #include <shellid.hxx> #endif #include <svtools/lstner.hxx> class SwDoc; class SfxDocumentInfoDialog; class SfxStyleSheetBasePool; class FontList; class SwView; class SwWrtShell; class SwFEShell; class Reader; class SwReader; class SwCrsrShell; class SwSrcView; class PushButton; class FixedText; class SwPaM; class SwgReaderOption; class SW_DLLPUBLIC SwDocShell: public SfxObjectShell, public SfxListener { SwDoc* pDoc; // Document SfxStyleSheetBasePool* pBasePool; // Durchreiche fuer Formate FontList* pFontList; // aktuelle FontListe // Nix geht ohne die WrtShell (historische Gruende) // RuekwaertsPointer auf die View (historische Gruende) // Dieser gilt solange bis im Activate ein neuer gesetzt wird // oder dieser im Dtor der View geloescht wird // SwView* pView; SwWrtShell* pWrtShell; Timer aFinishedTimer; // Timer fuers ueberpriefen der // Grafik-Links. Sind alle da, // dann ist Doc voll. geladen //SvPersistRef xOLEChildList; // fuers RemoveOLEObjects comphelper::EmbeddedObjectContainer* pOLEChildList; sal_Int16 nUpdateDocMode; // contains the com::sun::star::document::UpdateDocMode bool bInUpdateFontList; //prevent nested calls of UpdateFontList // Methoden fuer den Zugriff aufs Doc SW_DLLPRIVATE void AddLink(); SW_DLLPRIVATE void RemoveLink(); // Hint abfangen fuer DocInfo SW_DLLPRIVATE virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint ); // FileIO SW_DLLPRIVATE virtual sal_Bool InitNew( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage ); SW_DLLPRIVATE virtual sal_Bool Load( SfxMedium& rMedium ); SW_DLLPRIVATE virtual sal_Bool LoadFrom( SfxMedium& rMedium ); SW_DLLPRIVATE virtual sal_Bool ConvertFrom( SfxMedium &rMedium ); SW_DLLPRIVATE virtual sal_Bool ConvertTo( SfxMedium &rMedium ); SW_DLLPRIVATE virtual sal_Bool SaveAs( SfxMedium& rMedium ); SW_DLLPRIVATE virtual sal_Bool SaveCompleted( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage ); SW_DLLPRIVATE virtual USHORT PrepareClose( BOOL bUI = TRUE, BOOL bForBrowsing = FALSE ); // DocInfo dem Doc melden // SW_DLLPRIVATE virtual SfxDocumentInfoDialog* CreateDocumentInfoDialog( Window *pParent, const SfxItemSet &); // OLE-Geraffel SW_DLLPRIVATE virtual void Draw( OutputDevice*, const JobSetup&, USHORT); // Methoden fuer StyleSheets SW_DLLPRIVATE USHORT Edit( const String &rName, const String& rParent, USHORT nFamily, USHORT nMask, BOOL bNew, BOOL bColumn = FALSE, SwWrtShell* pActShell = 0, BOOL bBasic = FALSE ); SW_DLLPRIVATE USHORT Delete(const String &rName, USHORT nFamily); SW_DLLPRIVATE USHORT ApplyStyles(const String &rName, USHORT nFamily, SwWrtShell* pShell = 0, USHORT nMode = 0 ); SW_DLLPRIVATE USHORT DoWaterCan( const String &rName, USHORT nFamily); SW_DLLPRIVATE USHORT UpdateStyle(const String &rName, USHORT nFamily, SwWrtShell* pShell = 0); SW_DLLPRIVATE USHORT MakeByExample(const String &rName, USHORT nFamily, USHORT nMask, SwWrtShell* pShell = 0); SW_DLLPRIVATE void InitDraw(); SW_DLLPRIVATE void SubInitNew(); // fuer InitNew und HtmlSourceModus inline void SetWrtShell(SwWrtShell* pShell) { pWrtShell = pShell; } SW_DLLPRIVATE void RemoveOLEObjects(); SW_DLLPRIVATE void CalcLayoutForOLEObjects(); SW_DLLPRIVATE void Init_Impl(); SW_DLLPRIVATE DECL_STATIC_LINK( SwDocShell, IsLoadFinished, void* ); public: // aber selbst implementieren SFX_DECL_INTERFACE(SW_DOCSHELL); SFX_DECL_OBJECTFACTORY(); TYPEINFO(); static SfxInterface *_GetInterface() { return _GetInterfaceImpl(); } //Das Doc wird fuer SO-Datenaustausch benoetigt! SwDocShell(SfxObjectCreateMode eMode = SFX_CREATE_MODE_EMBEDDED); SwDocShell( SwDoc *pDoc, SfxObjectCreateMode eMode = SFX_CREATE_MODE_STANDARD ); ~SwDocShell(); // OLE 2.0-Benachrichtigung DECL_LINK( Ole2ModifiedHdl, void * ); // OLE-Geraffel virtual void SetVisArea( const Rectangle &rRect ); virtual Rectangle GetVisArea( USHORT nAspect ) const; virtual Printer *GetDocumentPrinter(); virtual OutputDevice* GetDocumentRefDev(); virtual void OnDocumentPrinterChanged( Printer * pNewPrinter ); virtual ULONG GetMiscStatus() const; virtual void PrepareReload(); virtual void SetModified( BOOL = TRUE ); // Dispatcher void Execute(SfxRequest &); void ExecStyleSheet(SfxRequest&); void ExecDB(SfxRequest&); void GetState(SfxItemSet &); void StateAlways(SfxItemSet &); void StateStyleSheet(SfxItemSet&, SwWrtShell* pSh = 0 ); // Doc rausreichen aber VORSICHT inline SwDoc* GetDoc() { return pDoc; } void UpdateFontList(); void UpdateChildWindows(); // DocumentInfo neu setzen BOOL SetDocumentInfo(const SfxDocumentInfo& rInfo); // globaler IO virtual BOOL Save(); // fuer VorlagenPI virtual SfxStyleSheetBasePool* GetStyleSheetPool(); // Fuer Organizer virtual BOOL Insert(SfxObjectShell &rSource, USHORT nSourceIdx1, USHORT nSourceIdx2, USHORT nSourceIdx3, USHORT& nIdx1, USHORT& nIdx2, USHORT& nIdx3, USHORT& nRemovedIdx); virtual BOOL Remove(USHORT nIdx1, USHORT nIdx2 = INDEX_IGNORE, USHORT nIdx3 = INDEX_IGNORE); virtual Bitmap GetStyleFamilyBitmap( SfxStyleFamily eFamily, BmpColorMode eColorMode ); // View setzen fuer Aktionen ueber Shell void SetView(SwView* pVw); const SwView *GetView() const { return pView; } SwView *GetView() { return pView; } // Zugriff auf die zur SwView gehoerige SwWrtShell SwWrtShell *GetWrtShell() { return pWrtShell; } const SwWrtShell *GetWrtShell() const { return pWrtShell; } // fuer die Core - die kennt die DocShell aber keine WrtShell! SwFEShell *GetFEShell(); const SwFEShell *GetFEShell() const { return ((SwDocShell*)this)->GetFEShell(); } // Fuer Einfuegen Dokument Reader* StartConvertFrom(SfxMedium& rMedium, SwReader** ppRdr, SwCrsrShell* pCrsrSh = 0, SwPaM* pPaM = 0); virtual long DdeGetData( const String& rItem, const String& rMimeType, ::com::sun::star::uno::Any & rValue ); virtual long DdeSetData( const String& rItem, const String& rMimeType, const ::com::sun::star::uno::Any & rValue ); virtual ::sfx2::SvLinkSource* DdeCreateLinkSource( const String& rItem ); virtual void FillClass( SvGlobalName * pClassName, ULONG * pClipFormat, String * pAppName, String * pLongUserName, String * pUserName, sal_Int32 nFileFormat ) const; virtual void LoadStyles( SfxObjectShell& rSource ); void _LoadStyles( SfxObjectShell& rSource, BOOL bPreserveCurrentDocument ); // Seitenvorlagedialog anzeigen, ggf. auf Spaltenpage void FormatPage( const String& rPage, BOOL bColumn = FALSE, SwWrtShell* pActShell = 0 ); // Timer starten fuers ueberpruefen der Grafik-Links. Sind alle // vollstaendig geladen, dann ist das Doc fertig void StartLoadFinishedTimer(); // eine Uebertragung wird abgebrochen (wird aus dem SFX gerufen) virtual void CancelTransfers(); // Doc aus Html-Source neu laden void ReloadFromHtml( const String& rStreamName, SwSrcView* pSrcView ); sal_Int16 GetUpdateDocMode() const {return nUpdateDocMode;} //Activate wait cursor for all windows of this document //Optionally all dispatcher could be Locked //Usually locking should be done using the class: SwWaitObject! void EnterWait( BOOL bLockDispatcher ); void LeaveWait( BOOL bLockDispatcher ); void ToggleBrowserMode(BOOL bOn, SwView* pView = 0); ULONG LoadStylesFromFile( const String& rURL, SwgReaderOption& rOpt, BOOL bUnoCall ); void InvalidateModel(); void ReactivateModel(); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > GetEventNames(); // --> FME 2004-08-05 #i20883# Digital Signatures and Encryption virtual sal_uInt16 GetHiddenInformationState( sal_uInt16 nStates ); // <-- }; #endif <|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 "stdafx.h" #include "RhoThreadImpl.h" namespace rho{ namespace common{ IMPLEMENT_LOGCLASS(CRhoThreadImpl,"RhoThread"); CRhoThreadImpl::CRhoThreadImpl() : m_hAwakeEvent(0), m_hThread(0) { m_hAwakeEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL); } CRhoThreadImpl::~CRhoThreadImpl() { if ( m_hAwakeEvent ) ::CloseHandle(m_hAwakeEvent); } static DWORD WINAPI runProc(void* pv) throw() { IRhoRunnable* p = static_cast<IRhoRunnable*>(pv); p->runObject(); #if !defined(OS_WP8) ::ExitThread(0); #endif return 0; } void CRhoThreadImpl::start(IRhoRunnable* pRunnable, IRhoRunnable::EPriority ePriority) { m_hThread = ::CreateThread(NULL, 0, runProc, pRunnable, 0, NULL); setThreadPriority(ePriority); } void CRhoThreadImpl::setThreadPriority(IRhoRunnable::EPriority ePriority) { int nPriority = THREAD_PRIORITY_NORMAL; if ( ePriority == IRhoRunnable::epHigh ) nPriority = THREAD_PRIORITY_HIGHEST; else if (ePriority == IRhoRunnable::epLow) nPriority = THREAD_PRIORITY_LOWEST; ::SetThreadPriority(m_hThread,nPriority); } void CRhoThreadImpl::stop(unsigned int nTimeoutToKillMs) { stopWait(); if ( m_hThread ) { DWORD dwRes = ::WaitForSingleObject( m_hThread, nTimeoutToKillMs ); if ( dwRes != WAIT_OBJECT_0 ) { LOG(INFO) + "Terminate thread. ID: " + ::GetCurrentThreadId() + "; Result: " + dwRes; ::TerminateThread(m_hThread,0); } ::CloseHandle(m_hThread); m_hThread = null; } } int CRhoThreadImpl::wait(unsigned int nTimeoutMs) { DWORD dwRes = ::WaitForSingleObject( m_hAwakeEvent, nTimeoutMs ); if ( dwRes == WAIT_FAILED ) LOG(ERROR) + "WaitForSingleObject failed. ID: " + ::GetCurrentThreadId() + "; Result: " + dwRes; return dwRes == WAIT_TIMEOUT ? 1 : 0; } void CRhoThreadImpl::stopWait() { ::SetEvent(m_hAwakeEvent); } void CRhoThreadImpl::sleep(unsigned int nTimeoutMs) { ::Sleep(nTimeoutMs); } } }<commit_msg>Add debug Logs<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 "stdafx.h" #include "RhoThreadImpl.h" namespace rho{ namespace common{ IMPLEMENT_LOGCLASS(CRhoThreadImpl,"RhoThreadWM"); CRhoThreadImpl::CRhoThreadImpl() : m_hAwakeEvent(0), m_hThread(0) { LOG(INFO) + " JDP create CRhoThreadImpl(WM) object"; m_hAwakeEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL); } CRhoThreadImpl::~CRhoThreadImpl() { if ( m_hAwakeEvent ) ::CloseHandle(m_hAwakeEvent); } static DWORD WINAPI runProc(void* pv) throw() { IRhoRunnable* p = static_cast<IRhoRunnable*>(pv); p->runObject(); #if !defined(OS_WP8) ::ExitThread(0); #endif return 0; } void CRhoThreadImpl::start(IRhoRunnable* pRunnable, IRhoRunnable::EPriority ePriority) { m_hThread = ::CreateThread(NULL, 0, runProc, pRunnable, 0, NULL); setThreadPriority(ePriority); } void CRhoThreadImpl::setThreadPriority(IRhoRunnable::EPriority ePriority) { int nPriority = THREAD_PRIORITY_NORMAL; if ( ePriority == IRhoRunnable::epHigh ) nPriority = THREAD_PRIORITY_HIGHEST; else if (ePriority == IRhoRunnable::epLow) nPriority = THREAD_PRIORITY_LOWEST; ::SetThreadPriority(m_hThread,nPriority); } void CRhoThreadImpl::stop(unsigned int nTimeoutToKillMs) { stopWait(); if ( m_hThread ) { DWORD dwRes = ::WaitForSingleObject( m_hThread, nTimeoutToKillMs ); if ( dwRes != WAIT_OBJECT_0 ) { LOG(INFO) + "Terminate thread. ID: " + ::GetCurrentThreadId() + "; Result: " + dwRes; ::TerminateThread(m_hThread,0); } ::CloseHandle(m_hThread); m_hThread = null; } } int CRhoThreadImpl::wait(unsigned int nTimeoutMs) { DWORD dwRes = ::WaitForSingleObject( m_hAwakeEvent, nTimeoutMs ); if ( dwRes == WAIT_FAILED ) LOG(ERROR) + "WaitForSingleObject failed. ID: " + ::GetCurrentThreadId() + "; Result: " + dwRes; return dwRes == WAIT_TIMEOUT ? 1 : 0; } void CRhoThreadImpl::stopWait() { ::SetEvent(m_hAwakeEvent); } void CRhoThreadImpl::sleep(unsigned int nTimeoutMs) { ::Sleep(nTimeoutMs); } } } <|endoftext|>
<commit_before>#include "ComponentTransform.h" // Constructors ================================= ComponentTransform::ComponentTransform() : Component(COMP_TRANSFORMATION) { transform_matrix = math::float4x4::identity; position = { 0,0,0 }; rotation_euler_angles = { 0,0,0 }; scale = { 0,0,0 }; } ComponentTransform::ComponentTransform(const ComponentTransform & cpy) : Component(cpy), position(cpy.position), scale(cpy.scale), rotation_euler_angles(cpy.rotation_euler_angles), transform_matrix(cpy.transform_matrix) { } // Destructors ================================== ComponentTransform::~ComponentTransform() { } // Set Methods ================================== void ComponentTransform::SetTransformation(aiMatrix4x4 trans) { //Set the mathgeolib matrix from assim matrix float values[16] = { trans.a1, trans.a2, trans.a3, trans.a4, trans.b1, trans.b2, trans.b3, trans.b4, trans.c1, trans.c2, trans.c3, trans.c4, trans.d1, trans.d2, trans.d3, trans.d4 }; transform_matrix.Set(values); //Set the variables that will be shown in the UI math::Quat rotation; transform_matrix.Decompose(position, rotation, scale); rotation_euler_angles = (rotation.ToEulerXYZ() * RADTODEG); } void ComponentTransform::SetTransformation(math::float4x4 trans) { transform_matrix = trans; math::Quat rot; transform_matrix.Decompose(position, rot, scale); rotation_euler_angles = rot.ToEulerXYZ(); } // Get Methods ================================== math::float3 ComponentTransform::GetPosition() const { return position; } // Functionality ================================ void ComponentTransform::BlitComponentInspector() { ImGui::Separator(); ImGui::Checkbox("##transform_comp", &actived); ImGui::SameLine(); ImGui::TextColored(ImVec4(1.0f, 0.64f, 0.0f, 1.0f), "Transform"); //Modified bool has_been_modified = false; //Transform Position ImGui::Text("Position "); ImGui::SameLine(); ImGui::PushItemWidth(50); if (ImGui::DragFloat("X##position", &position.x, 0.5f, 0.0f, 0.0f, "%.2f")) has_been_modified = true; ImGui::SameLine(); if (ImGui::DragFloat("Y##position", &position.y, 0.5f, 0.0f, 0.0f, "%.2f")) has_been_modified = true; ImGui::SameLine(); if (ImGui::DragFloat("Z##position", &position.z, 0.5f, 0.0f, 0.0f, "%.2f")) has_been_modified = true; //Transform rotation bool has_rotate = false; ImGui::Text("Rotation "); ImGui::SameLine(); ImGui::PushItemWidth(50); if (ImGui::DragFloat("X##rotation", &rotation_euler_angles.x, 0.5f, 0.0f, 0.0f, "%.2f")) has_been_modified = true; ImGui::SameLine(); if (ImGui::DragFloat("Y##rotation", &rotation_euler_angles.y, 0.5f, 0.0f, 0.0f, "%.2f")) has_been_modified = true; ImGui::SameLine(); if (ImGui::DragFloat("Z##rotation", &rotation_euler_angles.z, 0.5f, 0.0f, 0.0f, "%.2f")) has_been_modified = true; //Transform rotation bool has_scale = false; ImGui::Text("Scale "); ImGui::SameLine(); if (ImGui::DragFloat("X##scale", &scale.x, 0.5f, 0.0f, 0.0f, "%.2f")) has_been_modified = true; ImGui::SameLine(); if (ImGui::DragFloat("Y##scale", &scale.y, 0.5f, 0.0f, 0.0f, "%.2f")) has_been_modified = true; ImGui::SameLine(); if (ImGui::DragFloat("Z##scale", &scale.z, 0.5f, 0.0f, 0.0f, "%.2f")) has_been_modified = true; ImGui::PopItemWidth(); if (has_been_modified) { transform_matrix = transform_matrix.FromEulerXYZ(rotation_euler_angles.x * DEGTORAD, rotation_euler_angles.y * DEGTORAD, rotation_euler_angles.z * DEGTORAD); transform_matrix = transform_matrix * transform_matrix.Scale(scale, math::float3(0, 0, 0)); transform_matrix.SetTranslatePart(position.x, position.y, position.z); } } <commit_msg>Moved transformation to update<commit_after>#include "ComponentTransform.h" // Constructors ================================= ComponentTransform::ComponentTransform() : Component(COMP_TRANSFORMATION) { transform_matrix = math::float4x4::identity; position = { 0,0,0 }; rotation_euler_angles = { 0,0,0 }; scale = { 0,0,0 }; rotation_quaternion = math::Quat::identity; } ComponentTransform::ComponentTransform(const ComponentTransform & cpy) : Component(cpy), position(cpy.position), scale(cpy.scale), rotation_euler_angles(cpy.rotation_euler_angles), transform_matrix(cpy.transform_matrix) { } // Destructors ================================== ComponentTransform::~ComponentTransform() { } bool ComponentTransform::Update() { if (has_been_modified) { UpdateTransform(); } return true; } // Set Methods ================================== void ComponentTransform::SetTransformation(aiMatrix4x4 trans) { //Set the mathgeolib matrix from assim matrix float values[16] = { trans.a1, trans.a2, trans.a3, trans.a4, trans.b1, trans.b2, trans.b3, trans.b4, trans.c1, trans.c2, trans.c3, trans.c4, trans.d1, trans.d2, trans.d3, trans.d4 }; transform_matrix.Set(values); //Set the variables that will be shown in the UI transform_matrix.Decompose(position, rotation_quaternion, scale); rotation_euler_angles = (rotation_quaternion.ToEulerXYZ() * RADTODEG); } void ComponentTransform::SetTransformation(math::float4x4 trans) { transform_matrix = trans; transform_matrix.Decompose(position, rotation_quaternion, scale); rotation_euler_angles = rotation_quaternion.ToEulerXYZ(); } // Get Methods ================================== math::float3 ComponentTransform::GetPosition() const { return position; } math::float3 ComponentTransform::GetRotationEuler() const { return rotation_euler_angles; } math::Quat ComponentTransform::GetRotationQuat() const { return rotation_quaternion; } math::float3 ComponentTransform::GetScale() const { return scale; } const float* ComponentTransform::GetTransformMatrixRows() const { return transform_matrix.ptr(); } const float* ComponentTransform::GetTransformMatrixColumns() const { return transform_matrix.Transposed().ptr(); } // Functionality ================================ void ComponentTransform::BlitComponentInspector() { ImGui::Separator(); ImGui::Checkbox("##transform_comp", &actived); ImGui::SameLine(); ImGui::TextColored(ImVec4(1.0f, 0.64f, 0.0f, 1.0f), "Transform"); //Transform Position ImGui::Text("Position "); ImGui::SameLine(); ImGui::PushItemWidth(50); if (ImGui::DragFloat("X##position", &position.x, 0.5f, 0.0f, 0.0f, "%.2f")) has_been_modified = true; ImGui::SameLine(); if (ImGui::DragFloat("Y##position", &position.y, 0.5f, 0.0f, 0.0f, "%.2f")) has_been_modified = true; ImGui::SameLine(); if (ImGui::DragFloat("Z##position", &position.z, 0.5f, 0.0f, 0.0f, "%.2f")) has_been_modified = true; //Transform rotation bool has_rotate = false; ImGui::Text("Rotation "); ImGui::SameLine(); ImGui::PushItemWidth(50); if (ImGui::DragFloat("X##rotation", &rotation_euler_angles.x, 0.5f, 0.0f, 0.0f, "%.2f")) has_been_modified = true; ImGui::SameLine(); if (ImGui::DragFloat("Y##rotation", &rotation_euler_angles.y, 0.5f, 0.0f, 0.0f, "%.2f")) has_been_modified = true; ImGui::SameLine(); if (ImGui::DragFloat("Z##rotation", &rotation_euler_angles.z, 0.5f, 0.0f, 0.0f, "%.2f")) has_been_modified = true; //Transform rotation bool has_scale = false; ImGui::Text("Scale "); ImGui::SameLine(); if (ImGui::DragFloat("X##scale", &scale.x, 0.5f, 0.0f, 0.0f, "%.2f")) has_been_modified = true; ImGui::SameLine(); if (ImGui::DragFloat("Y##scale", &scale.y, 0.5f, 0.0f, 0.0f, "%.2f")) has_been_modified = true; ImGui::SameLine(); if (ImGui::DragFloat("Z##scale", &scale.z, 0.5f, 0.0f, 0.0f, "%.2f")) has_been_modified = true; ImGui::PopItemWidth(); } void ComponentTransform::UpdateTransform() { rotation_quaternion = math::Quat::FromEulerXYZ(rotation_euler_angles.x * DEGTORAD, rotation_euler_angles.y * DEGTORAD, rotation_euler_angles.z * DEGTORAD); transform_matrix = math::float4x4::FromQuat(rotation_quaternion); transform_matrix = math::float4x4::Scale(scale, math::float3(0, 0, 0)) * transform_matrix; transform_matrix.SetTranslatePart(position.x, position.y, position.z); has_been_modified = false; } <|endoftext|>
<commit_before>#include "itkImage.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkImageRegionIterator.h" #include "itkRGBPixel.h" #include "itkRGBAPixel.h" #include "itkRedColormapFunctor.h" #include "itkGreenColormapFunctor.h" #include "itkBlueColormapFunctor.h" #include "itkGreyColormapFunctor.h" #include "itkHotColormapFunctor.h" #include "itkCoolColormapFunctor.h" #include "itkSpringColormapFunctor.h" #include "itkSummerColormapFunctor.h" #include "itkAutumnColormapFunctor.h" #include "itkWinterColormapFunctor.h" #include "itkCopperColormapFunctor.h" #include "itkHSVColormapFunctor.h" #include "itkJetColormapFunctor.h" #include "itkCustomColormapFunctor.h" #include "itkOverUnderColormapFunctor.h" #include "itkScalarToRGBColormapImageFilter.h" #include <fstream.h> #include <sstream> #include <string> template <unsigned int ImageDimension> int ConvertScalarImageToRGB( int argc, char *argv[] ) { typedef unsigned int PixelType; // typedef itk::RGBPixel<unsigned char> RGBPixelType; typedef itk::RGBAPixel<unsigned char> RGBPixelType; typedef float RealType; typedef itk::Image<PixelType, ImageDimension> ImageType; typedef itk::Image<float, ImageDimension> RealImageType; typedef itk::Image<RGBPixelType, ImageDimension> RGBImageType; typedef itk::ImageFileReader<RealImageType> ReaderType; typename ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( argv[2] ); reader->Update(); typedef itk::Image<unsigned char, ImageDimension> MaskImageType; typename MaskImageType::Pointer maskImage = MaskImageType::New(); typedef itk::ImageFileReader<MaskImageType> MaskReaderType; typename MaskReaderType::Pointer maskreader = MaskReaderType::New(); maskreader->SetFileName( argv[4] ); try { maskreader->Update(); maskImage = maskreader->GetOutput(); } catch( ... ) { maskImage = NULL; } ; std::string colormapString( argv[5] ); typedef itk::ScalarToRGBColormapImageFilter<RealImageType, RGBImageType> RGBFilterType; typename RGBFilterType::Pointer rgbfilter = RGBFilterType::New(); rgbfilter->SetInput( reader->GetOutput() ); if( colormapString == "red" ) { rgbfilter->SetColormap( RGBFilterType::Red ); } else if( colormapString == "green" ) { rgbfilter->SetColormap( RGBFilterType::Green ); } else if( colormapString == "blue" ) { rgbfilter->SetColormap( RGBFilterType::Blue ); } else if( colormapString == "grey" ) { rgbfilter->SetColormap( RGBFilterType::Grey ); } else if( colormapString == "cool" ) { rgbfilter->SetColormap( RGBFilterType::Cool ); } else if( colormapString == "hot" ) { rgbfilter->SetColormap( RGBFilterType::Hot ); } else if( colormapString == "spring" ) { rgbfilter->SetColormap( RGBFilterType::Spring ); } else if( colormapString == "autumn" ) { rgbfilter->SetColormap( RGBFilterType::Autumn ); } else if( colormapString == "winter" ) { rgbfilter->SetColormap( RGBFilterType::Winter ); } else if( colormapString == "copper" ) { rgbfilter->SetColormap( RGBFilterType::Copper ); } else if( colormapString == "summer" ) { rgbfilter->SetColormap( RGBFilterType::Summer ); } else if( colormapString == "jet" ) { // rgbfilter->SetColormap( RGBFilterType::Jet ); typedef itk::Functor::JetColormapFunctor<typename RealImageType::PixelType, typename RGBImageType::PixelType> ColormapType; typename ColormapType::Pointer colormap = ColormapType::New(); rgbfilter->SetColormap( colormap ); } else if( colormapString == "hsv" ) { // rgbfilter->SetColormap( RGBFilterType::HSV ); typedef itk::Functor::HSVColormapFunctor<typename RealImageType::PixelType, typename RGBImageType::PixelType> ColormapType; typename ColormapType::Pointer colormap = ColormapType::New(); rgbfilter->SetColormap( colormap ); } else if( colormapString == "overunder" ) { rgbfilter->SetColormap( RGBFilterType::OverUnder ); } else if( colormapString == "custom" ) { typedef itk::Functor::CustomColormapFunctor<typename RealImageType::PixelType, typename RGBImageType::PixelType> ColormapType; typename ColormapType::Pointer colormap = ColormapType::New(); ifstream str( argv[6] ); std::string line; // Get red values { std::getline( str, line ); std::istringstream iss( line ); float value; typename ColormapType::ChannelType channel; while( iss >> value ) { channel.push_back( value ); } colormap->SetRedChannel( channel ); } // Get green values { std::getline( str, line ); std::istringstream iss( line ); float value; typename ColormapType::ChannelType channel; while( iss >> value ) { channel.push_back( value ); } colormap->SetGreenChannel( channel ); } // Get blue values { std::getline( str, line ); std::istringstream iss( line ); float value; typename ColormapType::ChannelType channel; while( iss >> value ) { channel.push_back( value ); } colormap->SetBlueChannel( channel ); } rgbfilter->SetColormap( colormap ); } if( maskImage ) { RealType maskMinimumValue = itk::NumericTraits<RealType>::max(); RealType maskMaximumValue = itk::NumericTraits<RealType>::NonpositiveMin(); itk::ImageRegionIterator<MaskImageType> ItM( maskImage, maskImage->GetLargestPossibleRegion() ); itk::ImageRegionIterator<RealImageType> ItS( reader->GetOutput(), reader->GetOutput()->GetLargestPossibleRegion() ); for( ItM.GoToBegin(), ItS.GoToBegin(); !ItM.IsAtEnd(); ++ItM, ++ItS ) { if( ItM.Get() != 0 ) { if( maskMinimumValue >= ItS.Get() ) { maskMinimumValue = ItS.Get(); } if( maskMaximumValue <= ItS.Get() ) { maskMaximumValue = ItS.Get(); } } } rgbfilter->SetUseInputImageExtremaForScaling( false ); rgbfilter->GetColormap()->SetMinimumInputValue( maskMinimumValue ); rgbfilter->GetColormap()->SetMaximumInputValue( maskMaximumValue ); } rgbfilter->GetColormap()->SetMinimumRGBComponentValue( ( argc > 9 ) ? static_cast< typename RGBPixelType::ComponentType>( atof( argv[9] ) ) : 0 ); rgbfilter->GetColormap()->SetMaximumRGBComponentValue( ( argc > 10 ) ? static_cast< typename RGBPixelType::ComponentType>( atof( argv[10] ) ) : 255 ); if( argc > 8 ) { rgbfilter->SetUseInputImageExtremaForScaling( false ); rgbfilter->GetColormap()->SetMinimumInputValue( static_cast<RealType>( atof( argv[7] ) ) ); rgbfilter->GetColormap()->SetMaximumInputValue( static_cast<RealType>( atof( argv[8] ) ) ); } try { rgbfilter->Update(); } catch( ... ) { return EXIT_FAILURE; } if( maskImage ) { itk::ImageRegionIterator<MaskImageType> ItM( maskImage, maskImage->GetLargestPossibleRegion() ); itk::ImageRegionIterator<RGBImageType> ItC( rgbfilter->GetOutput(), rgbfilter->GetOutput()->GetLargestPossibleRegion() ); itk::ImageRegionIterator<RealImageType> ItS( reader->GetOutput(), reader->GetOutput()->GetLargestPossibleRegion() ); ItM.GoToBegin(); ItC.GoToBegin(); ItS.GoToBegin(); while( !ItM.IsAtEnd() ) { if( ItM.Get() == 0 ) { RGBPixelType rgbpixel; // RealType minimumValue = rgbfilter->GetColormap()->GetMinimumInputValue(); // RealType maximumValue = rgbfilter->GetColormap()->GetMaximumInputValue(); // // RealType minimumRGBValue // = rgbfilter->GetColormap()->GetMinimumRGBComponentValue(); // RealType maximumRGBValue // = rgbfilter->GetColormap()->GetMaximumRGBComponentValue(); // // RealType ratio = ( ItS.Get() - minimumValue ) / ( maximumValue - minimumValue ); // // rgbpixel.Fill( ratio * ( maximumRGBValue - minimumRGBValue ) // + minimumRGBValue ); rgbpixel.Fill( 0.0 ); ItC.Set( rgbpixel ); } ++ItM; ++ItC; ++ItS; } } std::cout << rgbfilter->GetColormap()->GetMinimumInputValue() << ", " << rgbfilter->GetColormap()->GetMaximumInputValue() << std::endl; typedef itk::ImageFileWriter<RGBImageType> WriterType; typename WriterType::Pointer writer = WriterType::New(); writer->SetInput( rgbfilter->GetOutput() ); writer->SetFileName( argv[3] ); writer->Update(); return 0; } int main( int argc, char *argv[] ) { if( argc < 6 ) { std::cout << "Usage: " << argv[0] << " imageDimension inputImage outputImage " << "mask colormap [customColormapFile] [minimumInput] [maximumInput] " << "[minimumRGBOutput] [maximumRGBOutput]" << std::endl; std::cout << " Possible colormaps: grey, red, green, blue, copper, jet, hsv, "; std::cout << "spring, summer, autumn, winter, hot, cool, overunder, custom" << std::endl; exit( 1 ); } switch( atoi( argv[1] ) ) { case 2: ConvertScalarImageToRGB<2>( argc, argv ); break; case 3: ConvertScalarImageToRGB<3>( argc, argv ); break; default: std::cerr << "Unsupported dimension" << std::endl; exit( EXIT_FAILURE ); } } <commit_msg>removed debugging print statement.<commit_after>#include "itkImage.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkImageRegionIterator.h" #include "itkRGBPixel.h" #include "itkRGBAPixel.h" #include "itkRedColormapFunctor.h" #include "itkGreenColormapFunctor.h" #include "itkBlueColormapFunctor.h" #include "itkGreyColormapFunctor.h" #include "itkHotColormapFunctor.h" #include "itkCoolColormapFunctor.h" #include "itkSpringColormapFunctor.h" #include "itkSummerColormapFunctor.h" #include "itkAutumnColormapFunctor.h" #include "itkWinterColormapFunctor.h" #include "itkCopperColormapFunctor.h" #include "itkHSVColormapFunctor.h" #include "itkJetColormapFunctor.h" #include "itkCustomColormapFunctor.h" #include "itkOverUnderColormapFunctor.h" #include "itkScalarToRGBColormapImageFilter.h" #include <fstream.h> #include <sstream> #include <string> template <unsigned int ImageDimension> int ConvertScalarImageToRGB( int argc, char *argv[] ) { typedef unsigned int PixelType; // typedef itk::RGBPixel<unsigned char> RGBPixelType; typedef itk::RGBAPixel<unsigned char> RGBPixelType; typedef float RealType; typedef itk::Image<PixelType, ImageDimension> ImageType; typedef itk::Image<float, ImageDimension> RealImageType; typedef itk::Image<RGBPixelType, ImageDimension> RGBImageType; typedef itk::ImageFileReader<RealImageType> ReaderType; typename ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( argv[2] ); reader->Update(); typedef itk::Image<unsigned char, ImageDimension> MaskImageType; typename MaskImageType::Pointer maskImage = MaskImageType::New(); typedef itk::ImageFileReader<MaskImageType> MaskReaderType; typename MaskReaderType::Pointer maskreader = MaskReaderType::New(); maskreader->SetFileName( argv[4] ); try { maskreader->Update(); maskImage = maskreader->GetOutput(); } catch( ... ) { maskImage = NULL; } ; std::string colormapString( argv[5] ); typedef itk::ScalarToRGBColormapImageFilter<RealImageType, RGBImageType> RGBFilterType; typename RGBFilterType::Pointer rgbfilter = RGBFilterType::New(); rgbfilter->SetInput( reader->GetOutput() ); if( colormapString == "red" ) { rgbfilter->SetColormap( RGBFilterType::Red ); } else if( colormapString == "green" ) { rgbfilter->SetColormap( RGBFilterType::Green ); } else if( colormapString == "blue" ) { rgbfilter->SetColormap( RGBFilterType::Blue ); } else if( colormapString == "grey" ) { rgbfilter->SetColormap( RGBFilterType::Grey ); } else if( colormapString == "cool" ) { rgbfilter->SetColormap( RGBFilterType::Cool ); } else if( colormapString == "hot" ) { rgbfilter->SetColormap( RGBFilterType::Hot ); } else if( colormapString == "spring" ) { rgbfilter->SetColormap( RGBFilterType::Spring ); } else if( colormapString == "autumn" ) { rgbfilter->SetColormap( RGBFilterType::Autumn ); } else if( colormapString == "winter" ) { rgbfilter->SetColormap( RGBFilterType::Winter ); } else if( colormapString == "copper" ) { rgbfilter->SetColormap( RGBFilterType::Copper ); } else if( colormapString == "summer" ) { rgbfilter->SetColormap( RGBFilterType::Summer ); } else if( colormapString == "jet" ) { // rgbfilter->SetColormap( RGBFilterType::Jet ); typedef itk::Functor::JetColormapFunctor<typename RealImageType::PixelType, typename RGBImageType::PixelType> ColormapType; typename ColormapType::Pointer colormap = ColormapType::New(); rgbfilter->SetColormap( colormap ); } else if( colormapString == "hsv" ) { // rgbfilter->SetColormap( RGBFilterType::HSV ); typedef itk::Functor::HSVColormapFunctor<typename RealImageType::PixelType, typename RGBImageType::PixelType> ColormapType; typename ColormapType::Pointer colormap = ColormapType::New(); rgbfilter->SetColormap( colormap ); } else if( colormapString == "overunder" ) { rgbfilter->SetColormap( RGBFilterType::OverUnder ); } else if( colormapString == "custom" ) { typedef itk::Functor::CustomColormapFunctor<typename RealImageType::PixelType, typename RGBImageType::PixelType> ColormapType; typename ColormapType::Pointer colormap = ColormapType::New(); ifstream str( argv[6] ); std::string line; // Get red values { std::getline( str, line ); std::istringstream iss( line ); float value; typename ColormapType::ChannelType channel; while( iss >> value ) { channel.push_back( value ); } colormap->SetRedChannel( channel ); } // Get green values { std::getline( str, line ); std::istringstream iss( line ); float value; typename ColormapType::ChannelType channel; while( iss >> value ) { channel.push_back( value ); } colormap->SetGreenChannel( channel ); } // Get blue values { std::getline( str, line ); std::istringstream iss( line ); float value; typename ColormapType::ChannelType channel; while( iss >> value ) { channel.push_back( value ); } colormap->SetBlueChannel( channel ); } rgbfilter->SetColormap( colormap ); } if( maskImage ) { RealType maskMinimumValue = itk::NumericTraits<RealType>::max(); RealType maskMaximumValue = itk::NumericTraits<RealType>::NonpositiveMin(); itk::ImageRegionIterator<MaskImageType> ItM( maskImage, maskImage->GetLargestPossibleRegion() ); itk::ImageRegionIterator<RealImageType> ItS( reader->GetOutput(), reader->GetOutput()->GetLargestPossibleRegion() ); for( ItM.GoToBegin(), ItS.GoToBegin(); !ItM.IsAtEnd(); ++ItM, ++ItS ) { if( ItM.Get() != 0 ) { if( maskMinimumValue >= ItS.Get() ) { maskMinimumValue = ItS.Get(); } if( maskMaximumValue <= ItS.Get() ) { maskMaximumValue = ItS.Get(); } } } rgbfilter->SetUseInputImageExtremaForScaling( false ); rgbfilter->GetColormap()->SetMinimumInputValue( maskMinimumValue ); rgbfilter->GetColormap()->SetMaximumInputValue( maskMaximumValue ); } rgbfilter->GetColormap()->SetMinimumRGBComponentValue( ( argc > 9 ) ? static_cast< typename RGBPixelType::ComponentType>( atof( argv[9] ) ) : 0 ); rgbfilter->GetColormap()->SetMaximumRGBComponentValue( ( argc > 10 ) ? static_cast< typename RGBPixelType::ComponentType>( atof( argv[10] ) ) : 255 ); if( argc > 8 ) { rgbfilter->SetUseInputImageExtremaForScaling( false ); rgbfilter->GetColormap()->SetMinimumInputValue( static_cast<RealType>( atof( argv[7] ) ) ); rgbfilter->GetColormap()->SetMaximumInputValue( static_cast<RealType>( atof( argv[8] ) ) ); } try { rgbfilter->Update(); } catch( ... ) { return EXIT_FAILURE; } if( maskImage ) { itk::ImageRegionIterator<MaskImageType> ItM( maskImage, maskImage->GetLargestPossibleRegion() ); itk::ImageRegionIterator<RGBImageType> ItC( rgbfilter->GetOutput(), rgbfilter->GetOutput()->GetLargestPossibleRegion() ); itk::ImageRegionIterator<RealImageType> ItS( reader->GetOutput(), reader->GetOutput()->GetLargestPossibleRegion() ); ItM.GoToBegin(); ItC.GoToBegin(); ItS.GoToBegin(); while( !ItM.IsAtEnd() ) { if( ItM.Get() == 0 ) { RGBPixelType rgbpixel; // RealType minimumValue = rgbfilter->GetColormap()->GetMinimumInputValue(); // RealType maximumValue = rgbfilter->GetColormap()->GetMaximumInputValue(); // // RealType minimumRGBValue // = rgbfilter->GetColormap()->GetMinimumRGBComponentValue(); // RealType maximumRGBValue // = rgbfilter->GetColormap()->GetMaximumRGBComponentValue(); // // RealType ratio = ( ItS.Get() - minimumValue ) / ( maximumValue - minimumValue ); // // rgbpixel.Fill( ratio * ( maximumRGBValue - minimumRGBValue ) // + minimumRGBValue ); rgbpixel.Fill( 0.0 ); ItC.Set( rgbpixel ); } ++ItM; ++ItC; ++ItS; } } typedef itk::ImageFileWriter<RGBImageType> WriterType; typename WriterType::Pointer writer = WriterType::New(); writer->SetInput( rgbfilter->GetOutput() ); writer->SetFileName( argv[3] ); writer->Update(); return 0; } int main( int argc, char *argv[] ) { if( argc < 6 ) { std::cout << "Usage: " << argv[0] << " imageDimension inputImage outputImage " << "mask colormap [customColormapFile] [minimumInput] [maximumInput] " << "[minimumRGBOutput] [maximumRGBOutput]" << std::endl; std::cout << " Possible colormaps: grey, red, green, blue, copper, jet, hsv, "; std::cout << "spring, summer, autumn, winter, hot, cool, overunder, custom" << std::endl; exit( 1 ); } switch( atoi( argv[1] ) ) { case 2: ConvertScalarImageToRGB<2>( argc, argv ); break; case 3: ConvertScalarImageToRGB<3>( argc, argv ); break; default: std::cerr << "Unsupported dimension" << std::endl; exit( EXIT_FAILURE ); } } <|endoftext|>
<commit_before><commit_msg>Delete Puentes itmos.cpp<commit_after><|endoftext|>
<commit_before><commit_msg>Avoid nullptr dereferences in sycc444_to_rgb().<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/logging.h" #include "media/base/callback.h" #include "media/base/media.h" #include "remoting/base/capture_data.h" #include "remoting/base/encoder_vp8.h" #include "remoting/proto/video.pb.h" extern "C" { #define VPX_CODEC_DISABLE_COMPAT 1 #include "third_party/libvpx/include/vpx/vpx_codec.h" #include "third_party/libvpx/include/vpx/vpx_encoder.h" #include "third_party/libvpx/include/vpx/vp8cx.h" } namespace remoting { EncoderVp8::EncoderVp8() : initialized_(false), codec_(NULL), image_(NULL), last_timestamp_(0) { } EncoderVp8::~EncoderVp8() { if (initialized_) { vpx_codec_err_t ret = vpx_codec_destroy(codec_.get()); DCHECK(ret == VPX_CODEC_OK) << "Failed to destroy codec"; } } bool EncoderVp8::Init(int width, int height) { codec_.reset(new vpx_codec_ctx_t()); image_.reset(new vpx_image_t()); memset(image_.get(), 0, sizeof(vpx_image_t)); image_->fmt = VPX_IMG_FMT_YV12; // libvpx seems to require both to be assigned. image_->d_w = width; image_->w = width; image_->d_h = height; image_->h = height; vpx_codec_enc_cfg_t config; const vpx_codec_iface_t* algo = (const vpx_codec_iface_t*)media::GetVp8CxAlgoAddress(); CHECK(algo); vpx_codec_err_t ret = vpx_codec_enc_config_default(algo, &config, 0); if (ret != VPX_CODEC_OK) return false; // TODO(hclam): Tune the parameters to better suit the application. config.rc_target_bitrate = width * height * config.rc_target_bitrate / config.g_w / config.g_h; config.g_w = width; config.g_h = height; config.g_pass = VPX_RC_ONE_PASS; config.g_profile = 1; config.g_threads = 2; config.rc_min_quantizer = 0; config.rc_max_quantizer = 15; config.g_timebase.num = 1; config.g_timebase.den = 30; if (vpx_codec_enc_init(codec_.get(), algo, &config, 0)) return false; return true; } static int clip_byte(int x) { if (x > 255) return 255; else if (x < 0) return 0; else return x; } bool EncoderVp8::PrepareImage(scoped_refptr<CaptureData> capture_data) { const int plane_size = capture_data->width() * capture_data->height(); if (!yuv_image_.get()) { // YUV image size is 1.5 times of a plane. Multiplication is performed first // to avoid rounding error. const int size = plane_size * 3 / 2; yuv_image_.reset(new uint8[size]); // Reset image value to 128 so we just need to fill in the y plane. memset(yuv_image_.get(), 128, size); // Fill in the information for |image_|. unsigned char* image = reinterpret_cast<unsigned char*>(yuv_image_.get()); image_->planes[0] = image; image_->planes[1] = image + plane_size; // The V plane starts from 1.25 of the plane size. image_->planes[2] = image + plane_size + plane_size / 4; // In YV12 Y plane has full width, UV plane has half width because of // subsampling. image_->stride[0] = image_->w; image_->stride[1] = image_->w / 2; image_->stride[2] = image_->w / 2; } // And then do RGB->YUV conversion. // Currently we just produce the Y channel as the average of RGB. This will // giv ae gray scale image after conversion. // TODO(sergeyu): Move this code to a separate routine. // TODO(sergeyu): Optimize this code. DCHECK(capture_data->pixel_format() == media::VideoFrame::RGB32) << "Only RGB32 is supported"; uint8* in = capture_data->data_planes().data[0]; const int in_stride = capture_data->data_planes().strides[0]; uint8* y_out = yuv_image_.get(); uint8* u_out = yuv_image_.get() + plane_size; uint8* v_out = yuv_image_.get() + plane_size + plane_size / 4; const int out_stride = image_->stride[0]; for (int i = 0; i < capture_data->height(); ++i) { for (int j = 0; j < capture_data->width(); ++j) { // Since the input pixel format is RGB32, there are 4 bytes per pixel. uint8* pixel = in + 4 * j; y_out[j] = clip_byte(((pixel[0] * 66 + pixel[1] * 129 + pixel[2] * 25 + 128) >> 8) + 16); if (i % 2 == 0 && j % 2 == 0) { u_out[j / 2] = clip_byte(((pixel[0] * -38 + pixel[1] * -74 + pixel[2] * 112 + 128) >> 8) + 128); v_out[j / 2] = clip_byte(((pixel[0] * 112 + pixel[1] * -94 + pixel[2] * -18 + 128) >> 8) + 128); } } in += in_stride; y_out += out_stride; if (i % 2 == 0) { u_out += out_stride / 2; v_out += out_stride / 2; } } return true; } void EncoderVp8::Encode(scoped_refptr<CaptureData> capture_data, bool key_frame, DataAvailableCallback* data_available_callback) { if (!initialized_) { bool ret = Init(capture_data->width(), capture_data->height()); // TODO(hclam): Handle error better. DCHECK(ret) << "Initialization of encoder failed"; initialized_ = ret; } if (!PrepareImage(capture_data)) { NOTREACHED() << "Can't image data for encoding"; } // Do the actual encoding. vpx_codec_err_t ret = vpx_codec_encode(codec_.get(), image_.get(), last_timestamp_, 1, 0, VPX_DL_REALTIME); DCHECK_EQ(ret, VPX_CODEC_OK) << "Encoding error: " << vpx_codec_err_to_string(ret) << "\n" << "Details: " << vpx_codec_error(codec_.get()) << "\n" << vpx_codec_error_detail(codec_.get()); // TODO(hclam): fix this. last_timestamp_ += 100; // Read the encoded data. vpx_codec_iter_t iter = NULL; bool got_data = false; // TODO(hclam): Make sure we get exactly one frame from the packet. // TODO(hclam): We should provide the output buffer to avoid one copy. VideoPacket* message = new VideoPacket(); while (!got_data) { const vpx_codec_cx_pkt_t* packet = vpx_codec_get_cx_data(codec_.get(), &iter); if (!packet) continue; switch (packet->kind) { case VPX_CODEC_CX_FRAME_PKT: got_data = true; message->set_data(packet->data.frame.buf, packet->data.frame.sz); break; default: break; } } message->mutable_format()->set_encoding(VideoPacketFormat::ENCODING_VP8); message->set_flags(VideoPacket::FIRST_PACKET | VideoPacket::LAST_PACKET); data_available_callback->Run(message); delete data_available_callback; } } // namespace remoting <commit_msg>Refactor ZLib and Verbatim encoders.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/logging.h" #include "media/base/callback.h" #include "media/base/media.h" #include "remoting/base/capture_data.h" #include "remoting/base/encoder_vp8.h" #include "remoting/proto/video.pb.h" extern "C" { #define VPX_CODEC_DISABLE_COMPAT 1 #include "third_party/libvpx/include/vpx/vpx_codec.h" #include "third_party/libvpx/include/vpx/vpx_encoder.h" #include "third_party/libvpx/include/vpx/vp8cx.h" } namespace remoting { EncoderVp8::EncoderVp8() : initialized_(false), codec_(NULL), image_(NULL), last_timestamp_(0) { } EncoderVp8::~EncoderVp8() { if (initialized_) { vpx_codec_err_t ret = vpx_codec_destroy(codec_.get()); DCHECK(ret == VPX_CODEC_OK) << "Failed to destroy codec"; } } bool EncoderVp8::Init(int width, int height) { codec_.reset(new vpx_codec_ctx_t()); image_.reset(new vpx_image_t()); memset(image_.get(), 0, sizeof(vpx_image_t)); image_->fmt = VPX_IMG_FMT_YV12; // libvpx seems to require both to be assigned. image_->d_w = width; image_->w = width; image_->d_h = height; image_->h = height; vpx_codec_enc_cfg_t config; const vpx_codec_iface_t* algo = (const vpx_codec_iface_t*)media::GetVp8CxAlgoAddress(); CHECK(algo); vpx_codec_err_t ret = vpx_codec_enc_config_default(algo, &config, 0); if (ret != VPX_CODEC_OK) return false; // TODO(hclam): Tune the parameters to better suit the application. config.rc_target_bitrate = width * height * config.rc_target_bitrate / config.g_w / config.g_h; config.g_w = width; config.g_h = height; config.g_pass = VPX_RC_ONE_PASS; config.g_profile = 1; config.g_threads = 2; config.rc_min_quantizer = 0; config.rc_max_quantizer = 15; config.g_timebase.num = 1; config.g_timebase.den = 30; if (vpx_codec_enc_init(codec_.get(), algo, &config, 0)) return false; return true; } static int clip_byte(int x) { if (x > 255) return 255; else if (x < 0) return 0; else return x; } bool EncoderVp8::PrepareImage(scoped_refptr<CaptureData> capture_data) { const int plane_size = capture_data->width() * capture_data->height(); if (!yuv_image_.get()) { // YUV image size is 1.5 times of a plane. Multiplication is performed first // to avoid rounding error. const int size = plane_size * 3 / 2; yuv_image_.reset(new uint8[size]); // Reset image value to 128 so we just need to fill in the y plane. memset(yuv_image_.get(), 128, size); // Fill in the information for |image_|. unsigned char* image = reinterpret_cast<unsigned char*>(yuv_image_.get()); image_->planes[0] = image; image_->planes[1] = image + plane_size; // The V plane starts from 1.25 of the plane size. image_->planes[2] = image + plane_size + plane_size / 4; // In YV12 Y plane has full width, UV plane has half width because of // subsampling. image_->stride[0] = image_->w; image_->stride[1] = image_->w / 2; image_->stride[2] = image_->w / 2; } // And then do RGB->YUV conversion. // Currently we just produce the Y channel as the average of RGB. This will // giv ae gray scale image after conversion. // TODO(sergeyu): Move this code to a separate routine. // TODO(sergeyu): Optimize this code. DCHECK(capture_data->pixel_format() == media::VideoFrame::RGB32) << "Only RGB32 is supported"; uint8* in = capture_data->data_planes().data[0]; const int in_stride = capture_data->data_planes().strides[0]; uint8* y_out = yuv_image_.get(); uint8* u_out = yuv_image_.get() + plane_size; uint8* v_out = yuv_image_.get() + plane_size + plane_size / 4; const int out_stride = image_->stride[0]; for (int i = 0; i < capture_data->height(); ++i) { for (int j = 0; j < capture_data->width(); ++j) { // Since the input pixel format is RGB32, there are 4 bytes per pixel. uint8* pixel = in + 4 * j; y_out[j] = clip_byte(((pixel[2] * 66 + pixel[1] * 129 + pixel[0] * 25 + 128) >> 8) + 16); if (i % 2 == 0 && j % 2 == 0) { u_out[j / 2] = clip_byte(((pixel[2] * -38 + pixel[1] * -74 + pixel[0] * 112 + 128) >> 8) + 128); v_out[j / 2] = clip_byte(((pixel[2] * 112 + pixel[1] * -94 + pixel[1] * -18 + 128) >> 8) + 128); } } in += in_stride; y_out += out_stride; if (i % 2 == 0) { u_out += out_stride / 2; v_out += out_stride / 2; } } return true; } void EncoderVp8::Encode(scoped_refptr<CaptureData> capture_data, bool key_frame, DataAvailableCallback* data_available_callback) { if (!initialized_) { bool ret = Init(capture_data->width(), capture_data->height()); // TODO(hclam): Handle error better. DCHECK(ret) << "Initialization of encoder failed"; initialized_ = ret; } if (!PrepareImage(capture_data)) { NOTREACHED() << "Can't image data for encoding"; } // Do the actual encoding. vpx_codec_err_t ret = vpx_codec_encode(codec_.get(), image_.get(), last_timestamp_, 1, 0, VPX_DL_REALTIME); DCHECK_EQ(ret, VPX_CODEC_OK) << "Encoding error: " << vpx_codec_err_to_string(ret) << "\n" << "Details: " << vpx_codec_error(codec_.get()) << "\n" << vpx_codec_error_detail(codec_.get()); // TODO(hclam): fix this. last_timestamp_ += 100; // Read the encoded data. vpx_codec_iter_t iter = NULL; bool got_data = false; // TODO(hclam): Make sure we get exactly one frame from the packet. // TODO(hclam): We should provide the output buffer to avoid one copy. VideoPacket* message = new VideoPacket(); while (!got_data) { const vpx_codec_cx_pkt_t* packet = vpx_codec_get_cx_data(codec_.get(), &iter); if (!packet) continue; switch (packet->kind) { case VPX_CODEC_CX_FRAME_PKT: got_data = true; message->set_data(packet->data.frame.buf, packet->data.frame.sz); break; default: break; } } message->mutable_format()->set_encoding(VideoPacketFormat::ENCODING_VP8); message->set_flags(VideoPacket::FIRST_PACKET | VideoPacket::LAST_PACKET); data_available_callback->Run(message); delete data_available_callback; } } // namespace remoting <|endoftext|>
<commit_before>#include <muduo/base/Logging.h> #include <muduo/net/Channel.h> #include <muduo/net/EventLoop.h> #include <map> #include <boost/bind.hpp> #include <stdio.h> #include <unistd.h> #include <sys/timerfd.h> using namespace muduo; using namespace muduo::net; void print(const char* msg) { static std::map<const char*, Timestamp> lasts; Timestamp& last = lasts[msg]; Timestamp now = Timestamp::now(); printf("%s tid %d %s delay %f\n", now.toString().c_str(), CurrentThread::tid(), msg, timeDifference(now, last)); last = now; } namespace muduo { namespace net { namespace detail { int createTimerfd(); void readTimerfd(int timerfd, Timestamp now); } } } // Use relative time, immunized to wall clock changes. class PeriodicTimer { public: PeriodicTimer(EventLoop* loop, double interval, const TimerCallback& cb) : loop_(loop), timerfd_(muduo::net::detail::createTimerfd()), timerfdChannel_(loop, timerfd_), interval_(interval), cb_(cb) { timerfdChannel_.setReadCallback( boost::bind(&PeriodicTimer::handleRead, this)); timerfdChannel_.enableReading(); } void start() { struct itimerspec spec; bzero(&spec, sizeof spec); spec.it_interval = toTimeSpec(interval_); spec.it_value = spec.it_interval; int ret = ::timerfd_settime(timerfd_, 0 /* relative timer */, &spec, NULL); if (ret) { LOG_SYSERR << "timerfd_settime()"; } } ~PeriodicTimer() { timerfdChannel_.disableAll(); timerfdChannel_.remove(); ::close(timerfd_); } private: void handleRead() { loop_->assertInLoopThread(); muduo::net::detail::readTimerfd(timerfd_, Timestamp::now()); if (cb_) cb_(); } static struct timespec toTimeSpec(double seconds) { struct timespec ts; bzero(&ts, sizeof ts); const int64_t kNanoSecondsPerSecond = 1e9; int64_t nanoseconds = static_cast<int64_t>(seconds * kNanoSecondsPerSecond); if (nanoseconds < 1e5) nanoseconds = 1e5; ts.tv_sec = static_cast<time_t>(nanoseconds / kNanoSecondsPerSecond); ts.tv_nsec = static_cast<long>(nanoseconds % kNanoSecondsPerSecond); return ts; } EventLoop* loop_; const int timerfd_; Channel timerfdChannel_; const double interval_; // in seconds TimerCallback cb_; }; int main(int argc, char* argv[]) { LOG_INFO << "pid = " << getpid() << ", tid = " << CurrentThread::tid() << " Try adjusting the wall clock, see what happens."; EventLoop loop; PeriodicTimer timer(&loop, 1, boost::bind(print, "PeriodicTimer")); timer.start(); loop.runEvery(1, boost::bind(print, "EventLoop::runEvery")); loop.loop(); } <commit_msg>fix warning on gcc6.<commit_after>#include <muduo/base/Logging.h> #include <muduo/net/Channel.h> #include <muduo/net/EventLoop.h> #include <map> #include <boost/bind.hpp> #include <stdio.h> #include <unistd.h> #include <sys/timerfd.h> using namespace muduo; using namespace muduo::net; void print(const char* msg) { static std::map<const char*, Timestamp> lasts; Timestamp& last = lasts[msg]; Timestamp now = Timestamp::now(); printf("%s tid %d %s delay %f\n", now.toString().c_str(), CurrentThread::tid(), msg, timeDifference(now, last)); last = now; } namespace muduo { namespace net { namespace detail { int createTimerfd(); void readTimerfd(int timerfd, Timestamp now); } } } // Use relative time, immunized to wall clock changes. class PeriodicTimer { public: PeriodicTimer(EventLoop* loop, double interval, const TimerCallback& cb) : loop_(loop), timerfd_(muduo::net::detail::createTimerfd()), timerfdChannel_(loop, timerfd_), interval_(interval), cb_(cb) { timerfdChannel_.setReadCallback( boost::bind(&PeriodicTimer::handleRead, this)); timerfdChannel_.enableReading(); } void start() { struct itimerspec spec; bzero(&spec, sizeof spec); spec.it_interval = toTimeSpec(interval_); spec.it_value = spec.it_interval; int ret = ::timerfd_settime(timerfd_, 0 /* relative timer */, &spec, NULL); if (ret) { LOG_SYSERR << "timerfd_settime()"; } } ~PeriodicTimer() { timerfdChannel_.disableAll(); timerfdChannel_.remove(); ::close(timerfd_); } private: void handleRead() { loop_->assertInLoopThread(); muduo::net::detail::readTimerfd(timerfd_, Timestamp::now()); if (cb_) cb_(); } static struct timespec toTimeSpec(double seconds) { struct timespec ts; bzero(&ts, sizeof ts); const int64_t kNanoSecondsPerSecond = 1e9; const int kMinInterval = 1e5; int64_t nanoseconds = static_cast<int64_t>(seconds * kNanoSecondsPerSecond); if (nanoseconds < kMinInterval) nanoseconds = kMinInterval; ts.tv_sec = static_cast<time_t>(nanoseconds / kNanoSecondsPerSecond); ts.tv_nsec = static_cast<long>(nanoseconds % kNanoSecondsPerSecond); return ts; } EventLoop* loop_; const int timerfd_; Channel timerfdChannel_; const double interval_; // in seconds TimerCallback cb_; }; int main(int argc, char* argv[]) { LOG_INFO << "pid = " << getpid() << ", tid = " << CurrentThread::tid() << " Try adjusting the wall clock, see what happens."; EventLoop loop; PeriodicTimer timer(&loop, 1, boost::bind(print, "PeriodicTimer")); timer.start(); loop.runEvery(1, boost::bind(print, "EventLoop::runEvery")); loop.loop(); } <|endoftext|>
<commit_before>// -*- c-file-style: "cc-mode" -*- #include "hemi.hpp" extern "C" void Context_dealloc(Context* self) { self->context.Dispose(); self->ob_type->tp_free((PyObject *)self); } extern "C" PyObject * Context_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds) { Context *self = (Context *)subtype->tp_alloc(subtype, 0); if(self != NULL) { //HandleScope handle_scope; self->context = v8::Context::New(); if(self->context.IsEmpty()) { Py_DECREF(self); return NULL; } } return (PyObject *)self; } extern "C" PyObject * Context_eval(Context *self, PyObject *args) { using namespace v8; char* _source; if(!PyArg_ParseTuple(args, "es", "utf-8", &_source)) return NULL; HandleScope handle_scope; v8::Context::Scope context_scope(self->context); Handle<String> source = String::New(_source); PyMem_Free(_source); TryCatch trycatch; Handle<Script> script = Script::Compile(source); if(script.IsEmpty()) { Handle<Value> exception = trycatch.Exception(); String::AsciiValue exception_str(exception); PyErr_SetString(PyExc_Exception, *exception_str); return NULL; } Handle<Value> result = script->Run(); if(result.IsEmpty()) { Handle<Value> exception = trycatch.Exception(); String::AsciiValue exception_str(exception); PyErr_SetString(PyExc_Exception, *exception_str); return NULL; } PyObject * py_result = wrap(self->context, Handle<v8::Object>(), result); return py_result; } extern "C" PyObject * Context_getlocals(Context *self, void *closure) { using namespace v8; v8::Context::Scope context_scope(self->context); HandleScope handle_scope; Handle<Value> object(self->context->Global()); PyObject *wrapped = wrap(self->context, Handle<v8::Object>(), object); return wrapped; } extern "C" void Object_dealloc(Object* self) { v8::HandleScope handle_scope; self->object->DeleteHiddenValue(v8::String::New("hemi::wrapper")); self->object.Dispose(); self->parent.Dispose(); self->context.Dispose(); self->ob_type->tp_free((PyObject *)self); } extern "C" PyObject * Object_getitem(Object *self, PyObject *item) { using namespace v8; if(PyUnicode_Check(item)) { PyObject *_item = PyUnicode_AsUTF8String(item); v8::Context::Scope context_scope(self->context); Handle<Value> result = self->object->GetRealNamedProperty(String::New(PyString_AS_STRING(_item))); Py_DECREF(_item); if(!result.IsEmpty()) return wrap(self->context, self->object, result); } PyErr_SetObject(PyExc_KeyError, item); return NULL; }; extern "C" PyObject * Object_getattr(Object *self, PyObject *name) { using namespace v8; PyObject *value = PyObject_GenericGetAttr((PyObject *)self, name); if(value != NULL) return value; char *_name = PyString_AsString(name); HandleScope handle_scope; v8::Context::Scope context_scope(self->context); Handle<Value> result = self->object->GetRealNamedProperty(String::New(_name)); if(result.IsEmpty()) { // Exception already set by GetAttr return NULL; } // Have to reset exception raised by GetAttr PyErr_Clear(); return wrap(self->context, self->object, result); }; extern "C" PyObject * Function_call(Object *self, PyObject *args, PyObject *kw) { int argc = (int)PySequence_Size(args); v8::HandleScope handle_scope; v8::Handle<v8::Value> argv[argc]; try { for(int i = 0; i < argc; i++) { argv[i] = py_to_json(PySequence_GetItem(args, i)); } } catch (PyObject *bad_object) { PyObject *repr = PyObject_Repr(bad_object); char *repr_string; if(repr == NULL) { repr_string = "<unpresentable object>"; } else { repr_string = PyString_AS_STRING(repr); } PyErr_Format(PyExc_TypeError, "cannot represent %s to javascript", repr_string); Py_XDECREF(repr); return NULL; } v8::Handle<v8::Value> result = self->object.As<v8::Function>()->Call(self->parent, argc, argv); return wrap(self->context, v8::Handle<v8::Object>(), result); }; v8::Handle<v8::Value> py_to_json(PyObject *py) { if(py == Py_True) return v8::True(); if(py == Py_False) return v8::False(); if(py == Py_None) return v8::Null(); if(PyInt_Check(py)) { long value = PyInt_AS_LONG(py); if(sizeof(long) == sizeof(int32_t)) { return v8::Integer::New(value); } else { if(-value < 1ll << 16 && value < 1ll << 16) return v8::Integer::New(value); if(value > 0ll && value < 1ll << 32) return v8::Integer::NewFromUnsigned(value); } } if(PyFloat_Check(py)) return v8::Number::New(PyFloat_AS_DOUBLE(py)); if(PyUnicode_Check(py)) { PyObject *py_string = PyUnicode_AsUTF8String(py); v8::Handle<v8::String> js_string = v8::String::New(PyString_AS_STRING(py_string)); return js_string; } if(PyList_Check(py)) { uint32_t length = PyList_GET_SIZE(py); v8::Handle<v8::Array> array = v8::Array::New(length); for(uint32_t i = 0; i < length; i++) { v8::Handle<v8::Value> item = py_to_json(PyList_GET_ITEM(py, i)); array->Set(i, item); } return array; } if(PyDict_Check(py)) { PyObject *key, *value; Py_ssize_t pos = 0; v8::Handle<v8::Object> object = v8::Object::New(); while(PyDict_Next(py, &pos, &key, &value)) { v8::Handle<v8::Value> js_key = py_to_json(key); object->Set(js_key, py_to_json(value)); } return object; } throw py; }; PyObject * wrap(v8::Handle<v8::Context> context, v8::Handle<v8::Object> parent, v8::Handle<v8::Value> value) { if(value->IsInt32()) return PyInt_FromLong(value->Int32Value()); if(value->IsNumber()) return PyFloat_FromDouble(value->NumberValue()); if(value->IsBoolean()) return PyBool_FromLong(value->BooleanValue()); if(value->IsNull()) Py_RETURN_NONE; if(value->IsUndefined()) { return Py_INCREF(Undefined), Undefined; } if(value->IsString()) { v8::String::Utf8Value utf_string(value); return PyUnicode_FromString(*utf_string); } Object *object; v8::Handle<v8::Value> wrapper = value->ToObject()->GetHiddenValue(v8::String::New("hemi::wrapper")); if(!wrapper.IsEmpty()) { object = (Object *)v8::External::Unwrap(wrapper); Py_INCREF(object); return (PyObject *)object; } if (value->IsFunction()) { object = PyObject_New(Object, &FunctionType); } else { object = PyObject_New(Object, &ObjectType); } object->context = v8::Persistent<v8::Context>::New(context); object->parent = v8::Persistent<v8::Object>::New(parent); object->object = v8::Persistent<v8::Object>::New(value.As<v8::Object>()); object->object->SetHiddenValue(v8::String::New("hemi::wrapper"), v8::External::Wrap(object)); return (PyObject *)object; } #ifndef PyMODINIT_FUNC /* declarations for DLL import/export */ #define PyMODINIT_FUNC void #endif PyMODINIT_FUNC inithemi(void) { PyObject* m; if (PyType_Ready(&ContextType) < 0) return; if (PyType_Ready(&ObjectType) < 0) return; if (PyType_Ready(&FunctionType) < 0) return; if (PyType_Ready(&UndefinedType) < 0) return; Undefined = PyObject_New(PyObject, &UndefinedType); m = Py_InitModule3("hemi", module_methods, "Lightweight V8 wrapper."); Py_INCREF(&ContextType); PyModule_AddObject(m, "Context", (PyObject *)&ContextType); } <commit_msg>Fix function call<commit_after>// -*- c-file-style: "cc-mode" -*- #include "hemi.hpp" extern "C" void Context_dealloc(Context* self) { self->context.Dispose(); self->ob_type->tp_free((PyObject *)self); } extern "C" PyObject * Context_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds) { Context *self = (Context *)subtype->tp_alloc(subtype, 0); if(self != NULL) { //HandleScope handle_scope; self->context = v8::Context::New(); if(self->context.IsEmpty()) { Py_DECREF(self); return NULL; } } return (PyObject *)self; } extern "C" PyObject * Context_eval(Context *self, PyObject *args) { using namespace v8; char* _source; if(!PyArg_ParseTuple(args, "es", "utf-8", &_source)) return NULL; HandleScope handle_scope; v8::Context::Scope context_scope(self->context); Handle<String> source = String::New(_source); PyMem_Free(_source); TryCatch trycatch; Handle<Script> script = Script::Compile(source); if(script.IsEmpty()) { Handle<Value> exception = trycatch.Exception(); String::AsciiValue exception_str(exception); PyErr_SetString(PyExc_Exception, *exception_str); return NULL; } Handle<Value> result = script->Run(); if(result.IsEmpty()) { Handle<Value> exception = trycatch.Exception(); String::AsciiValue exception_str(exception); PyErr_SetString(PyExc_Exception, *exception_str); return NULL; } PyObject * py_result = wrap(self->context, Handle<v8::Object>(), result); return py_result; } extern "C" PyObject * Context_getlocals(Context *self, void *closure) { using namespace v8; v8::Context::Scope context_scope(self->context); HandleScope handle_scope; Handle<Value> object(self->context->Global()); PyObject *wrapped = wrap(self->context, Handle<v8::Object>(), object); return wrapped; } extern "C" void Object_dealloc(Object* self) { v8::HandleScope handle_scope; self->object->DeleteHiddenValue(v8::String::New("hemi::wrapper")); self->object.Dispose(); self->parent.Dispose(); self->context.Dispose(); self->ob_type->tp_free((PyObject *)self); } extern "C" PyObject * Object_getitem(Object *self, PyObject *item) { using namespace v8; if(PyUnicode_Check(item)) { PyObject *_item = PyUnicode_AsUTF8String(item); v8::Context::Scope context_scope(self->context); Handle<Value> result = self->object->GetRealNamedProperty(String::New(PyString_AS_STRING(_item))); Py_DECREF(_item); if(!result.IsEmpty()) return wrap(self->context, self->object, result); } PyErr_SetObject(PyExc_KeyError, item); return NULL; }; extern "C" PyObject * Object_getattr(Object *self, PyObject *name) { using namespace v8; PyObject *value = PyObject_GenericGetAttr((PyObject *)self, name); if(value != NULL) return value; char *_name = PyString_AsString(name); HandleScope handle_scope; v8::Context::Scope context_scope(self->context); Handle<Value> result = self->object->GetRealNamedProperty(String::New(_name)); if(result.IsEmpty()) { // Exception already set by GetAttr return NULL; } // Have to reset exception raised by GetAttr PyErr_Clear(); return wrap(self->context, self->object, result); }; extern "C" PyObject * Function_call(Object *self, PyObject *args, PyObject *kw) { int argc = (int)PySequence_Size(args); v8::HandleScope handle_scope; v8::Context::Scope context_scope(self->context); v8::Handle<v8::Value> argv[argc]; try { for(int i = 0; i < argc; i++) { argv[i] = py_to_json(PySequence_GetItem(args, i)); } } catch (PyObject *bad_object) { PyObject *repr = PyObject_Repr(bad_object); char *repr_string; if(repr == NULL) { repr_string = "<unpresentable object>"; } else { repr_string = PyString_AS_STRING(repr); } PyErr_Format(PyExc_TypeError, "cannot represent %s to javascript", repr_string); Py_XDECREF(repr); return NULL; } v8::Handle<v8::Value> result = self->object.As<v8::Function>()->Call(self->parent, argc, argv); return wrap(self->context, v8::Handle<v8::Object>(), result); }; v8::Handle<v8::Value> py_to_json(PyObject *py) { if(py == Py_True) return v8::True(); if(py == Py_False) return v8::False(); if(py == Py_None) return v8::Null(); if(PyInt_Check(py)) { long value = PyInt_AS_LONG(py); if(sizeof(long) == sizeof(int32_t)) { return v8::Integer::New(value); } else { if(-value < 1ll << 16 && value < 1ll << 16) return v8::Integer::New(value); if(value > 0ll && value < 1ll << 32) return v8::Integer::NewFromUnsigned(value); } } if(PyFloat_Check(py)) return v8::Number::New(PyFloat_AS_DOUBLE(py)); if(PyUnicode_Check(py)) { PyObject *py_string = PyUnicode_AsUTF8String(py); v8::Handle<v8::String> js_string = v8::String::New(PyString_AS_STRING(py_string)); return js_string; } if(PyList_Check(py)) { uint32_t length = PyList_GET_SIZE(py); v8::Handle<v8::Array> array = v8::Array::New(length); for(uint32_t i = 0; i < length; i++) { v8::Handle<v8::Value> item = py_to_json(PyList_GET_ITEM(py, i)); array->Set(i, item); } return array; } if(PyDict_Check(py)) { PyObject *key, *value; Py_ssize_t pos = 0; v8::Handle<v8::Object> object = v8::Object::New(); while(PyDict_Next(py, &pos, &key, &value)) { v8::Handle<v8::Value> js_key = py_to_json(key); object->Set(js_key, py_to_json(value)); } return object; } throw py; }; PyObject * wrap(v8::Handle<v8::Context> context, v8::Handle<v8::Object> parent, v8::Handle<v8::Value> value) { if(value->IsInt32()) return PyInt_FromLong(value->Int32Value()); if(value->IsNumber()) return PyFloat_FromDouble(value->NumberValue()); if(value->IsBoolean()) return PyBool_FromLong(value->BooleanValue()); if(value->IsNull()) Py_RETURN_NONE; if(value->IsUndefined()) { return Py_INCREF(Undefined), Undefined; } if(value->IsString()) { v8::String::Utf8Value utf_string(value); return PyUnicode_FromString(*utf_string); } Object *object; v8::Handle<v8::Value> wrapper = value->ToObject()->GetHiddenValue(v8::String::New("hemi::wrapper")); if(!wrapper.IsEmpty()) { object = (Object *)v8::External::Unwrap(wrapper); Py_INCREF(object); return (PyObject *)object; } if (value->IsFunction()) { object = PyObject_New(Object, &FunctionType); } else { object = PyObject_New(Object, &ObjectType); } object->context = v8::Persistent<v8::Context>::New(context); object->parent = v8::Persistent<v8::Object>::New(parent); object->object = v8::Persistent<v8::Object>::New(value.As<v8::Object>()); object->object->SetHiddenValue(v8::String::New("hemi::wrapper"), v8::External::Wrap(object)); return (PyObject *)object; } #ifndef PyMODINIT_FUNC /* declarations for DLL import/export */ #define PyMODINIT_FUNC void #endif PyMODINIT_FUNC inithemi(void) { PyObject* m; if (PyType_Ready(&ContextType) < 0) return; if (PyType_Ready(&ObjectType) < 0) return; if (PyType_Ready(&FunctionType) < 0) return; if (PyType_Ready(&UndefinedType) < 0) return; Undefined = PyObject_New(PyObject, &UndefinedType); m = Py_InitModule3("hemi", module_methods, "Lightweight V8 wrapper."); Py_INCREF(&ContextType); PyModule_AddObject(m, "Context", (PyObject *)&ContextType); } <|endoftext|>
<commit_before>#include "facepreprocessor.h" #include <vector> #include <algorithm> #include <limits> #include <cstdint> #include <opencv2/imgproc/imgproc.hpp> #include <QDebug> static const double PI = std::atan(1.0) * 4; using namespace cv; FacePreprocessor::FacePreprocessor(FaceClassifiers classifiers, const Mat& input) throw(std::invalid_argument) : input(input), result(Mat(input.rows, input.cols, CV_8UC1)), classifiers(classifiers) { if (classifiers.face.get() == nullptr) throw std::invalid_argument("face classifier"); else if (classifiers.face->empty()) throw std::invalid_argument("face classifier"); else if (classifiers.eye.get() == nullptr) throw std::invalid_argument("eye classifier"); else if (classifiers.eye->empty()) throw std::invalid_argument("eye classifier"); else if (classifiers.eyePair.get() == nullptr) throw std::invalid_argument("eyepair classifier"); else if (classifiers.eyePair->empty()) throw std::invalid_argument("eyepair classifier"); else if (classifiers.eyeLeft.get() == nullptr) throw std::invalid_argument("left eye classifier"); else if (classifiers.eyeLeft->empty()) throw std::invalid_argument("left eye classifier"); else if (classifiers.eyeRight.get() == nullptr) throw std::invalid_argument("right eye classifier"); else if (classifiers.eyeRight->empty()) throw std::invalid_argument("right eye classifier"); } unsigned int FacePreprocessor::GetMinSize() const { int minDim = std::min(input.rows, input.cols); return static_cast<unsigned int>(minDim / 5.0); } Rect FacePreprocessor::LargestRect(const std::vector<Rect>& rects) { if(rects.empty()) return Rect(); Rect largest = *std::max_element(rects.begin(), rects.end(), [](const Rect& a, const Rect& b) { return a.area() < b.area(); } ); return largest; } const double FacePreprocessor::MAX_ROTATE_ANGLE = 20.0; double FacePreprocessor::GetRotation(cv::Rect left, cv::Rect right) { Point direction; direction.x = right.x - left.x; direction.y = right.y - left.y; double angle = std::atan2(direction.y, direction.x) * 180.0 / PI; return angle; } std::vector<Rect> FacePreprocessor::GetEyesAlternateMethod() { static std::vector<Rect> empty; std::vector<Rect> eyes; eyes.reserve(2); classifiers.eyePair->detectMultiScale(result, eyes, 1.1, 4, CV_HAAR_FIND_BIGGEST_OBJECT); if(eyes.empty()) return empty; qDebug() << "eye pair was found"; rectangle(result, eyes.front(), 1); std::vector<Rect> lefts; std::vector<Rect> rights; Rect cRect = eyes.front(); cRect.width /= 2; classifiers.eyeLeft->detectMultiScale(result(cRect), lefts, 1.1, 4, CV_HAAR_FIND_BIGGEST_OBJECT); if(lefts.empty()) { qDebug () << "left wasnt found"; return empty; } cRect.x += cRect.width; classifiers.eyeLeft->detectMultiScale(result(cRect), rights, 1.1, 4, CV_HAAR_FIND_BIGGEST_OBJECT); if(rights.empty()) { qDebug () << "right wasnt found"; return empty; } rights.front().x += cRect.width; gotEyes = true; lefts.front().x += eyes.front().x; lefts.front().y += eyes.front().y; rights.front().x += eyes.front().x; rights.front().y += eyes.front().y; rectangle(result, lefts.front(), 1); rectangle(result, rights.front(), 1); eyes.clear(); eyes.push_back(lefts.front()); eyes.push_back(rights.front()); return eyes; } std::vector<Rect> FacePreprocessor::GetEyes() { int maxSize = static_cast<int>(std::ceil(std::max(result.rows, result.cols) / 6.0)); int minSize = std::max(static_cast<int>(std::floor(std::min(result.rows, result.cols) / 20.0)), 5); Rect upperHalfOfFace(0, 0, face.width, static_cast<int>(face.height / 1.8)); std::vector<Rect> eyes; std::vector<Rect> eyePairR; //classifiers.eyePair->detectMultiScale(result(upperHalfOfFace), eyePairR, 1.1, 3, CV_HAAR_FIND_BIGGEST_OBJECT); if(eyePairR.empty()) { classifiers.eye->detectMultiScale(result(upperHalfOfFace), eyes, 1.1, 6, 0, Size(minSize, minSize), Size(maxSize, maxSize)); } else { classifiers.eye->detectMultiScale(result(eyePairR.front()), eyes, 1.1, 6, 0, Size(minSize, minSize), Size(maxSize, maxSize)); rectangle(result, eyePairR.front(), 255); } for (auto eye : eyes) { if(!eyePairR.empty()) { eye.x += eyePairR.front().x; eye.y += eyePairR.front().y; } rectangle(result, eye, 1); } if(eyes.size() < 2) { qDebug() << "only" << eyes.size() << "eyes were found"; eyes.clear(); return eyes; } gotEyes = true; if(eyes.size() > 2) { // finding the pair with lowest angle std::vector<std::pair<uint16_t, uint16_t>> helper; helper.reserve(eyes.size() * eyes.size() - eyes.size()); for(auto i = eyes.begin(); i != eyes.end(); i++) { for(auto j = eyes.begin(); j != eyes.end(); j++) { if (i != j) helper.push_back(std::make_pair(std::distance(eyes.begin(), i), std::distance(eyes.begin(), j))); } } std::sort(helper.begin(), helper.end(), [&eyes](const std::pair<uint16_t, uint16_t>& a, const std::pair<uint16_t, uint16_t>& b) { double angleA = std::abs(GetRotation(eyes[a.first], eyes[a.second])); double angleB = std::abs(GetRotation(eyes[b.first], eyes[b.second])); return angleA < angleB; }); assert(helper.front().first != helper.front().second); std::swap(eyes[0], eyes[helper.front().first]); std::swap(eyes[1], eyes[helper.front().second]); } std::sort(eyes.begin(), eyes.begin() + 2, [](const Rect& a, const Rect& b) { return a.x < b.x; }); eyes.resize(2); return eyes; } void FacePreprocessor::RotateFace() { std::vector<Rect> eyes = GetEyes(); if(eyes.size() < 2) { return; } double angle = GetRotation(eyes[0], eyes[1]); qDebug() << "rotation angle: " << angle; if (std::abs(angle) < std::numeric_limits<double>::epsilon() * 3 || std::abs(angle) > MAX_ROTATE_ANGLE) return; int size = std::max(result.cols, result.rows); int fullSize = std::max(normalized.cols, normalized.rows); Point2f pt(size/2.0f + face.x, size/2.0f + face.y); Mat r = getRotationMatrix2D(pt, angle, 1.0); warpAffine(normalized, rotated, r, Size(fullSize, fullSize), CV_INTER_LANCZOS4); result = rotated(face); } void FacePreprocessor::ScaleFace() { Rect aspected = face; if(face.width < face.height) { aspected.width = face.height; } else { aspected.height = face.width; } Mat scaled = result.clone(); copyMakeBorder(scaled, scaled, 0, aspected.height, 0, aspected.width, BORDER_REPLICATE); aspected.x = 0; aspected.y = 0; result = scaled(aspected); resize(result, result, Size(512, 512), 0.0, 0.0, CV_INTER_LANCZOS4); } double FacePreprocessor::GetAccuracy() const { double accuracy = 0.0; if(face.width > 0 && face.height > 0) accuracy += 0.5; if(gotEyes) accuracy += 0.5; return accuracy; } Mat FacePreprocessor::Preprocess() throw (NoFaceFoundException) { if(input.type() == CV_8UC3) cvtColor(input, result, CV_BGR2GRAY); else result = input; equalizeHist(result, normalized); result = normalized; std::vector<Rect> faces; Size minSize(GetMinSize(), GetMinSize()); classifiers.face->detectMultiScale(result, faces, 1.1, 3, CV_HAAR_FIND_BIGGEST_OBJECT, minSize); if (!faces.empty()) { face = LargestRect(faces); result = result(face); } else { throw NoFaceFoundException(); } RotateFace(); static uint64_t cntr = 0; static uint64_t cntr2 = 0; cntr2++; if(!gotEyes) qDebug() << "no eyes were found on the face -- this is odd :(" << ++cntr << "/" << cntr2; else qDebug() << "is rotated? " << !rotated.empty() << (cntr2 - cntr) << "/" << cntr2; ScaleFace(); return result; } <commit_msg>debug rectangles are only visible if MARK_FOUND_FEATURES is true<commit_after>#include "facepreprocessor.h" #include <vector> #include <algorithm> #include <limits> #include <cstdint> #include <opencv2/imgproc/imgproc.hpp> #include <QDebug> static const double PI = std::atan(1.0) * 4; using namespace cv; static const bool MARK_FOUND_FEATURES = false; FacePreprocessor::FacePreprocessor(FaceClassifiers classifiers, const Mat& input) throw(std::invalid_argument) : input(input), result(Mat(input.rows, input.cols, CV_8UC1)), classifiers(classifiers) { if (classifiers.face.get() == nullptr) throw std::invalid_argument("face classifier"); else if (classifiers.face->empty()) throw std::invalid_argument("face classifier"); else if (classifiers.eye.get() == nullptr) throw std::invalid_argument("eye classifier"); else if (classifiers.eye->empty()) throw std::invalid_argument("eye classifier"); else if (classifiers.eyePair.get() == nullptr) throw std::invalid_argument("eyepair classifier"); else if (classifiers.eyePair->empty()) throw std::invalid_argument("eyepair classifier"); else if (classifiers.eyeLeft.get() == nullptr) throw std::invalid_argument("left eye classifier"); else if (classifiers.eyeLeft->empty()) throw std::invalid_argument("left eye classifier"); else if (classifiers.eyeRight.get() == nullptr) throw std::invalid_argument("right eye classifier"); else if (classifiers.eyeRight->empty()) throw std::invalid_argument("right eye classifier"); } unsigned int FacePreprocessor::GetMinSize() const { int minDim = std::min(input.rows, input.cols); return static_cast<unsigned int>(minDim / 5.0); } Rect FacePreprocessor::LargestRect(const std::vector<Rect>& rects) { if(rects.empty()) return Rect(); Rect largest = *std::max_element(rects.begin(), rects.end(), [](const Rect& a, const Rect& b) { return a.area() < b.area(); } ); return largest; } const double FacePreprocessor::MAX_ROTATE_ANGLE = 20.0; double FacePreprocessor::GetRotation(cv::Rect left, cv::Rect right) { Point direction; direction.x = right.x - left.x; direction.y = right.y - left.y; double angle = std::atan2(direction.y, direction.x) * 180.0 / PI; return angle; } std::vector<Rect> FacePreprocessor::GetEyesAlternateMethod() { static std::vector<Rect> empty; std::vector<Rect> eyes; eyes.reserve(2); classifiers.eyePair->detectMultiScale(result, eyes, 1.1, 4, CV_HAAR_FIND_BIGGEST_OBJECT); if(eyes.empty()) return empty; qDebug() << "eye pair was found"; if (MARK_FOUND_FEATURES) rectangle(result, eyes.front(), 1); std::vector<Rect> lefts; std::vector<Rect> rights; Rect cRect = eyes.front(); cRect.width /= 2; classifiers.eyeLeft->detectMultiScale(result(cRect), lefts, 1.1, 4, CV_HAAR_FIND_BIGGEST_OBJECT); if(lefts.empty()) { qDebug () << "left wasnt found"; return empty; } cRect.x += cRect.width; classifiers.eyeLeft->detectMultiScale(result(cRect), rights, 1.1, 4, CV_HAAR_FIND_BIGGEST_OBJECT); if(rights.empty()) { qDebug () << "right wasnt found"; return empty; } rights.front().x += cRect.width; gotEyes = true; lefts.front().x += eyes.front().x; lefts.front().y += eyes.front().y; rights.front().x += eyes.front().x; rights.front().y += eyes.front().y; if (MARK_FOUND_FEATURES) { rectangle(result, lefts.front(), 1); rectangle(result, rights.front(), 1); } eyes.clear(); eyes.push_back(lefts.front()); eyes.push_back(rights.front()); return eyes; } std::vector<Rect> FacePreprocessor::GetEyes() { int maxSize = static_cast<int>(std::ceil(std::max(result.rows, result.cols) / 6.0)); int minSize = std::max(static_cast<int>(std::floor(std::min(result.rows, result.cols) / 20.0)), 5); Rect upperHalfOfFace(0, 0, face.width, static_cast<int>(face.height / 1.8)); std::vector<Rect> eyes; std::vector<Rect> eyePairR; //classifiers.eyePair->detectMultiScale(result(upperHalfOfFace), eyePairR, 1.1, 3, CV_HAAR_FIND_BIGGEST_OBJECT); if(eyePairR.empty()) { classifiers.eye->detectMultiScale(result(upperHalfOfFace), eyes, 1.1, 6, 0, Size(minSize, minSize), Size(maxSize, maxSize)); } else { classifiers.eye->detectMultiScale(result(eyePairR.front()), eyes, 1.1, 6, 0, Size(minSize, minSize), Size(maxSize, maxSize)); if (MARK_FOUND_FEATURES) rectangle(result, eyePairR.front(), 255); } for (auto eye : eyes) { if(!eyePairR.empty()) { eye.x += eyePairR.front().x; eye.y += eyePairR.front().y; } if (MARK_FOUND_FEATURES) rectangle(result, eye, 1); } if(eyes.size() < 2) { qDebug() << "only" << eyes.size() << "eyes were found"; eyes.clear(); return eyes; } gotEyes = true; if(eyes.size() > 2) { // finding the pair with lowest angle std::vector<std::pair<uint16_t, uint16_t>> helper; helper.reserve(eyes.size() * eyes.size() - eyes.size()); for(auto i = eyes.begin(); i != eyes.end(); i++) { for(auto j = eyes.begin(); j != eyes.end(); j++) { if (i != j) helper.push_back(std::make_pair(std::distance(eyes.begin(), i), std::distance(eyes.begin(), j))); } } std::sort(helper.begin(), helper.end(), [&eyes](const std::pair<uint16_t, uint16_t>& a, const std::pair<uint16_t, uint16_t>& b) { double angleA = std::abs(GetRotation(eyes[a.first], eyes[a.second])); double angleB = std::abs(GetRotation(eyes[b.first], eyes[b.second])); return angleA < angleB; }); assert(helper.front().first != helper.front().second); std::swap(eyes[0], eyes[helper.front().first]); std::swap(eyes[1], eyes[helper.front().second]); } std::sort(eyes.begin(), eyes.begin() + 2, [](const Rect& a, const Rect& b) { return a.x < b.x; }); eyes.resize(2); return eyes; } void FacePreprocessor::RotateFace() { std::vector<Rect> eyes = GetEyes(); if(eyes.size() < 2) { return; } double angle = GetRotation(eyes[0], eyes[1]); qDebug() << "rotation angle: " << angle; if (std::abs(angle) < std::numeric_limits<double>::epsilon() * 3 || std::abs(angle) > MAX_ROTATE_ANGLE) return; int size = std::max(result.cols, result.rows); int fullSize = std::max(normalized.cols, normalized.rows); Point2f pt(size/2.0f + face.x, size/2.0f + face.y); Mat r = getRotationMatrix2D(pt, angle, 1.0); warpAffine(normalized, rotated, r, Size(fullSize, fullSize), CV_INTER_LANCZOS4); result = rotated(face); } void FacePreprocessor::ScaleFace() { Rect aspected = face; if(face.width < face.height) { aspected.width = face.height; } else { aspected.height = face.width; } Mat scaled = result.clone(); copyMakeBorder(scaled, scaled, 0, aspected.height, 0, aspected.width, BORDER_REPLICATE); aspected.x = 0; aspected.y = 0; result = scaled(aspected); resize(result, result, Size(512, 512), 0.0, 0.0, CV_INTER_LANCZOS4); } double FacePreprocessor::GetAccuracy() const { double accuracy = 0.0; if(face.width > 0 && face.height > 0) accuracy += 0.5; if(gotEyes) accuracy += 0.5; return accuracy; } Mat FacePreprocessor::Preprocess() throw (NoFaceFoundException) { if(input.type() == CV_8UC3) cvtColor(input, result, CV_BGR2GRAY); else result = input; equalizeHist(result, normalized); result = normalized; std::vector<Rect> faces; Size minSize(GetMinSize(), GetMinSize()); classifiers.face->detectMultiScale(result, faces, 1.1, 3, CV_HAAR_FIND_BIGGEST_OBJECT, minSize); if (!faces.empty()) { face = LargestRect(faces); result = result(face); } else { throw NoFaceFoundException(); } RotateFace(); static uint64_t cntr = 0; static uint64_t cntr2 = 0; cntr2++; if(!gotEyes) qDebug() << "no eyes were found on the face -- this is odd :(" << ++cntr << "/" << cntr2; else qDebug() << "is rotated? " << !rotated.empty() << (cntr2 - cntr) << "/" << cntr2; ScaleFace(); return result; } <|endoftext|>
<commit_before>#include "facepreprocessor.h" #include <vector> #include <algorithm> #include <limits> #include <cstdint> #include <opencv2/imgproc/imgproc.hpp> #include <QDebug> static const double PI = std::atan(1.0) * 4; using namespace cv; static const bool MARK_FOUND_FEATURES = false; FacePreprocessor::FacePreprocessor(FaceClassifiers classifiers, const Mat& input) throw(std::invalid_argument) : input(input), result(Mat(input.rows, input.cols, CV_8UC1)), classifiers(classifiers) { if (classifiers.face.get() == nullptr) throw std::invalid_argument("face classifier"); else if (classifiers.face->empty()) throw std::invalid_argument("face classifier"); else if (classifiers.eye.get() == nullptr) throw std::invalid_argument("eye classifier"); else if (classifiers.eye->empty()) throw std::invalid_argument("eye classifier"); else if (classifiers.eyePair.get() == nullptr) throw std::invalid_argument("eyepair classifier"); else if (classifiers.eyePair->empty()) throw std::invalid_argument("eyepair classifier"); else if (classifiers.eyeLeft.get() == nullptr) throw std::invalid_argument("left eye classifier"); else if (classifiers.eyeLeft->empty()) throw std::invalid_argument("left eye classifier"); else if (classifiers.eyeRight.get() == nullptr) throw std::invalid_argument("right eye classifier"); else if (classifiers.eyeRight->empty()) throw std::invalid_argument("right eye classifier"); } unsigned int FacePreprocessor::GetMinSize() const { int minDim = std::min(input.rows, input.cols); return static_cast<unsigned int>(minDim / 5.0); } Rect FacePreprocessor::LargestRect(const std::vector<Rect>& rects) { if(rects.empty()) return Rect(); Rect largest = *std::max_element(rects.begin(), rects.end(), [](const Rect& a, const Rect& b) { return a.area() < b.area(); } ); return largest; } const double FacePreprocessor::MAX_ROTATE_ANGLE = 20.0; double FacePreprocessor::GetRotation(cv::Rect left, cv::Rect right) { Point direction; direction.x = right.x - left.x; direction.y = right.y - left.y; double angle = std::atan2(direction.y, direction.x) * 180.0 / PI; return angle; } std::vector<Rect> FacePreprocessor::GetEyesAlternateMethod() { static std::vector<Rect> empty; std::vector<Rect> eyes; eyes.reserve(2); classifiers.eyePair->detectMultiScale(result, eyes, 1.1, 4, CV_HAAR_FIND_BIGGEST_OBJECT); if(eyes.empty()) return empty; qDebug() << "eye pair was found"; if (MARK_FOUND_FEATURES) rectangle(result, eyes.front(), 1); std::vector<Rect> lefts; std::vector<Rect> rights; Rect cRect = eyes.front(); cRect.width /= 2; classifiers.eyeLeft->detectMultiScale(result(cRect), lefts, 1.1, 4, CV_HAAR_FIND_BIGGEST_OBJECT); if(lefts.empty()) { qDebug () << "left wasnt found"; return empty; } cRect.x += cRect.width; classifiers.eyeLeft->detectMultiScale(result(cRect), rights, 1.1, 4, CV_HAAR_FIND_BIGGEST_OBJECT); if(rights.empty()) { qDebug () << "right wasnt found"; return empty; } rights.front().x += cRect.width; gotEyes = true; lefts.front().x += eyes.front().x; lefts.front().y += eyes.front().y; rights.front().x += eyes.front().x; rights.front().y += eyes.front().y; if (MARK_FOUND_FEATURES) { rectangle(result, lefts.front(), 1); rectangle(result, rights.front(), 1); } eyes.clear(); eyes.push_back(lefts.front()); eyes.push_back(rights.front()); return eyes; } std::vector<Rect> FacePreprocessor::GetEyes() { int maxSize = static_cast<int>(std::ceil(std::max(result.rows, result.cols) / 6.0)); int minSize = std::max(static_cast<int>(std::floor(std::min(result.rows, result.cols) / 20.0)), 5); Rect upperHalfOfFace(0, 0, face.width, static_cast<int>(face.height / 1.8)); std::vector<Rect> eyes; std::vector<Rect> eyePairR; //classifiers.eyePair->detectMultiScale(result(upperHalfOfFace), eyePairR, 1.1, 3, CV_HAAR_FIND_BIGGEST_OBJECT); if(eyePairR.empty()) { classifiers.eye->detectMultiScale(result(upperHalfOfFace), eyes, 1.1, 6, 0, Size(minSize, minSize), Size(maxSize, maxSize)); } else { classifiers.eye->detectMultiScale(result(eyePairR.front()), eyes, 1.1, 6, 0, Size(minSize, minSize), Size(maxSize, maxSize)); if (MARK_FOUND_FEATURES) rectangle(result, eyePairR.front(), 255); } for (auto eye : eyes) { if(!eyePairR.empty()) { eye.x += eyePairR.front().x; eye.y += eyePairR.front().y; } if (MARK_FOUND_FEATURES) rectangle(result, eye, 1); } if(eyes.size() < 2) { qDebug() << "only" << eyes.size() << "eyes were found"; eyes.clear(); return eyes; } gotEyes = true; for(uint8_t i = 0; i < eyes.size(); i++) { for(uint8_t j = 0; j < eyes.size(); j++) { if (i != j) { Rect intersection = eyes[i] & eyes[j]; if (intersection.area() > 0) { eyes.erase(eyes.begin() + j); if (i > j) i--; j--; } } } } if(eyes.size() > 2) { // finding the pair with lowest angle std::vector<std::pair<uint16_t, uint16_t>> helper; helper.reserve(eyes.size() * eyes.size() - eyes.size()); for(auto i = eyes.begin(); i != eyes.end(); i++) { for(auto j = eyes.begin(); j != eyes.end(); j++) { if (i != j) helper.push_back(std::make_pair(std::distance(eyes.begin(), i), std::distance(eyes.begin(), j))); } } std::sort(helper.begin(), helper.end(), [&eyes](const std::pair<uint16_t, uint16_t>& a, const std::pair<uint16_t, uint16_t>& b) { double angleA = std::abs(GetRotation(eyes[a.first], eyes[a.second])); double angleB = std::abs(GetRotation(eyes[b.first], eyes[b.second])); return angleA < angleB; }); assert(helper.front().first != helper.front().second); std::swap(eyes[0], eyes[helper.front().first]); std::swap(eyes[1], eyes[helper.front().second]); } std::sort(eyes.begin(), eyes.begin() + 2, [](const Rect& a, const Rect& b) { return a.x < b.x; }); eyes.resize(2); return eyes; } void FacePreprocessor::RotateFace() { std::vector<Rect> eyes = GetEyes(); if(eyes.size() < 2) { return; } double angle = GetRotation(eyes[0], eyes[1]); qDebug() << "rotation angle: " << angle; if (std::abs(angle) < std::numeric_limits<double>::epsilon() * 3 || std::abs(angle) > MAX_ROTATE_ANGLE) return; int size = std::max(result.cols, result.rows); int fullSize = std::max(normalized.cols, normalized.rows); Point2f pt(size/2.0f + face.x, size/2.0f + face.y); Mat r = getRotationMatrix2D(pt, angle, 1.0); warpAffine(normalized, rotated, r, Size(fullSize, fullSize), CV_INTER_LANCZOS4); result = rotated(face); } void FacePreprocessor::ScaleFace() { Rect aspected = face; if(face.width < face.height) { aspected.width = face.height; } else { aspected.height = face.width; } Mat scaled = result.clone(); copyMakeBorder(scaled, scaled, 0, aspected.height, 0, aspected.width, BORDER_REPLICATE); aspected.x = 0; aspected.y = 0; result = scaled(aspected); resize(result, result, Size(512, 512), 0.0, 0.0, CV_INTER_LANCZOS4); } double FacePreprocessor::GetAccuracy() const { double accuracy = 0.0; if(face.width > 0 && face.height > 0) accuracy += 0.5; if(gotEyes) accuracy += 0.25; if(!rotated.empty()) accuracy += 0.25; return accuracy; } Mat FacePreprocessor::Preprocess() throw (NoFaceFoundException) { if(input.type() == CV_8UC3) cvtColor(input, result, CV_BGR2GRAY); else result = input; equalizeHist(result, normalized); result = normalized; std::vector<Rect> faces; Size minSize(GetMinSize(), GetMinSize()); classifiers.face->detectMultiScale(result, faces, 1.1, 3, CV_HAAR_FIND_BIGGEST_OBJECT, minSize); if (!faces.empty()) { face = LargestRect(faces); result = result(face); } else { throw NoFaceFoundException(); } RotateFace(); static uint64_t eyesFoundCntr = 0; static uint64_t totalRunCntr = 0; totalRunCntr++; if(!gotEyes) qDebug() << "no eyes were found on the face -- this is odd :(" << ++eyesFoundCntr << "/" << totalRunCntr; else qDebug() << "is rotated? " << !rotated.empty() << (totalRunCntr - eyesFoundCntr) << "/" << totalRunCntr; ScaleFace(); return result; } <commit_msg>refactor + wider search range for eyes<commit_after>#include "facepreprocessor.h" #include <vector> #include <algorithm> #include <limits> #include <cstdint> #include <opencv2/imgproc/imgproc.hpp> #include <QDebug> static const double PI = std::atan(1.0) * 4; using namespace cv; static const bool MARK_FOUND_FEATURES = false; FacePreprocessor::FacePreprocessor(FaceClassifiers classifiers, const Mat& input) throw(std::invalid_argument) : input(input), result(Mat(input.rows, input.cols, CV_8UC1)), classifiers(classifiers) { if (classifiers.face.get() == nullptr) throw std::invalid_argument("face classifier"); else if (classifiers.face->empty()) throw std::invalid_argument("face classifier"); else if (classifiers.eye.get() == nullptr) throw std::invalid_argument("eye classifier"); else if (classifiers.eye->empty()) throw std::invalid_argument("eye classifier"); else if (classifiers.eyePair.get() == nullptr) throw std::invalid_argument("eyepair classifier"); else if (classifiers.eyePair->empty()) throw std::invalid_argument("eyepair classifier"); else if (classifiers.eyeLeft.get() == nullptr) throw std::invalid_argument("left eye classifier"); else if (classifiers.eyeLeft->empty()) throw std::invalid_argument("left eye classifier"); else if (classifiers.eyeRight.get() == nullptr) throw std::invalid_argument("right eye classifier"); else if (classifiers.eyeRight->empty()) throw std::invalid_argument("right eye classifier"); } unsigned int FacePreprocessor::GetMinSize() const { int minDim = std::min(input.rows, input.cols); return static_cast<unsigned int>(minDim / 5.0); } Rect FacePreprocessor::LargestRect(const std::vector<Rect>& rects) { if(rects.empty()) return Rect(); Rect largest = *std::max_element(rects.begin(), rects.end(), [](const Rect& a, const Rect& b) { return a.area() < b.area(); } ); return largest; } const double FacePreprocessor::MAX_ROTATE_ANGLE = 20.0; double FacePreprocessor::GetRotation(cv::Rect left, cv::Rect right) { Point direction; direction.x = right.x - left.x; direction.y = right.y - left.y; double angle = std::atan2(direction.y, direction.x) * 180.0 / PI; return angle; } std::vector<Rect> FacePreprocessor::GetEyesAlternateMethod() { static std::vector<Rect> empty; std::vector<Rect> eyes; eyes.reserve(2); classifiers.eyePair->detectMultiScale(result, eyes, 1.1, 4, CV_HAAR_FIND_BIGGEST_OBJECT); if(eyes.empty()) return empty; qDebug() << "eye pair was found"; if (MARK_FOUND_FEATURES) rectangle(result, eyes.front(), 1); std::vector<Rect> lefts; std::vector<Rect> rights; Rect cRect = eyes.front(); cRect.width /= 2; classifiers.eyeLeft->detectMultiScale(result(cRect), lefts, 1.1, 4, CV_HAAR_FIND_BIGGEST_OBJECT); if(lefts.empty()) { qDebug () << "left wasnt found"; return empty; } cRect.x += cRect.width; classifiers.eyeLeft->detectMultiScale(result(cRect), rights, 1.1, 4, CV_HAAR_FIND_BIGGEST_OBJECT); if(rights.empty()) { qDebug () << "right wasnt found"; return empty; } rights.front().x += cRect.width; gotEyes = true; lefts.front().x += eyes.front().x; lefts.front().y += eyes.front().y; rights.front().x += eyes.front().x; rights.front().y += eyes.front().y; if (MARK_FOUND_FEATURES) { rectangle(result, lefts.front(), 1); rectangle(result, rights.front(), 1); } eyes.clear(); eyes.push_back(lefts.front()); eyes.push_back(rights.front()); return eyes; } std::vector<Rect> FacePreprocessor::GetEyes() { const Rect upperHalfOfFace(0, 0, face.width, static_cast<int>(face.height / 1.8)); const int maxSize = static_cast<int>(std::ceil(std::max(upperHalfOfFace.width, upperHalfOfFace.height) / 5.0)); const int minSize = std::max(static_cast<int>(std::floor(std::min(upperHalfOfFace.width, upperHalfOfFace.height) / 20.0)), 3); std::vector<Rect> eyes; std::vector<Rect> eyePairR; //classifiers.eyePair->detectMultiScale(result(upperHalfOfFace), eyePairR, 1.1, 3, CV_HAAR_FIND_BIGGEST_OBJECT); if(eyePairR.empty()) { classifiers.eye->detectMultiScale(result(upperHalfOfFace), eyes, 1.1, 6, 0, Size(minSize, minSize), Size(maxSize, maxSize)); } else { classifiers.eye->detectMultiScale(result(eyePairR.front()), eyes, 1.1, 6, 0, Size(minSize, minSize), Size(maxSize, maxSize)); if (MARK_FOUND_FEATURES) rectangle(result, eyePairR.front(), 255); } for (auto eye : eyes) { if(!eyePairR.empty()) { eye.x += eyePairR.front().x; eye.y += eyePairR.front().y; } if (MARK_FOUND_FEATURES) rectangle(result, eye, 1); } if(eyes.size() < 2) { qDebug() << "only" << eyes.size() << "eyes were found"; eyes.clear(); return eyes; } gotEyes = true; for(uint8_t i = 0; i < eyes.size(); i++) { for(uint8_t j = 0; j < eyes.size(); j++) { if (i != j) { Rect intersection = eyes[i] & eyes[j]; if (intersection.area() > 0) { eyes.erase(eyes.begin() + j); if (i > j) i--; j--; } } } } if(eyes.size() > 2) { // finding the pair with lowest angle std::vector<std::pair<uint16_t, uint16_t>> helper; helper.reserve(eyes.size() * eyes.size() - eyes.size()); for(auto i = eyes.begin(); i != eyes.end(); i++) { for(auto j = eyes.begin(); j != eyes.end(); j++) { if (i != j) helper.push_back(std::make_pair(std::distance(eyes.begin(), i), std::distance(eyes.begin(), j))); } } std::sort(helper.begin(), helper.end(), [&eyes](const std::pair<uint16_t, uint16_t>& a, const std::pair<uint16_t, uint16_t>& b) { double angleA = std::abs(GetRotation(eyes[a.first], eyes[a.second])); double angleB = std::abs(GetRotation(eyes[b.first], eyes[b.second])); return angleA < angleB; }); assert(helper.front().first != helper.front().second); std::swap(eyes[0], eyes[helper.front().first]); std::swap(eyes[1], eyes[helper.front().second]); } std::sort(eyes.begin(), eyes.begin() + 2, [](const Rect& a, const Rect& b) { return a.x < b.x; }); eyes.resize(2); return eyes; } void FacePreprocessor::RotateFace() { std::vector<Rect> eyes = GetEyes(); if(eyes.size() < 2) { return; } double angle = GetRotation(eyes[0], eyes[1]); qDebug() << "rotation angle: " << angle; if (std::abs(angle) < std::numeric_limits<double>::epsilon() * 3 || std::abs(angle) > MAX_ROTATE_ANGLE) return; int size = std::max(result.cols, result.rows); int fullSize = std::max(normalized.cols, normalized.rows); Point2f pt(size/2.0f + face.x, size/2.0f + face.y); Mat r = getRotationMatrix2D(pt, angle, 1.0); warpAffine(normalized, rotated, r, Size(fullSize, fullSize), CV_INTER_LANCZOS4); result = rotated(face); } void FacePreprocessor::ScaleFace() { Rect aspected = face; if(face.width < face.height) { aspected.width = face.height; } else { aspected.height = face.width; } Mat scaled = result.clone(); copyMakeBorder(scaled, scaled, 0, aspected.height, 0, aspected.width, BORDER_REPLICATE); aspected.x = 0; aspected.y = 0; result = scaled(aspected); resize(result, result, Size(512, 512), 0.0, 0.0, CV_INTER_LANCZOS4); } double FacePreprocessor::GetAccuracy() const { double accuracy = 0.0; if(face.width > 0 && face.height > 0) accuracy += 0.5; if(gotEyes) accuracy += 0.25; if(!rotated.empty()) accuracy += 0.25; return accuracy; } Mat FacePreprocessor::Preprocess() throw (NoFaceFoundException) { if(input.type() == CV_8UC3) cvtColor(input, result, CV_BGR2GRAY); else result = input; equalizeHist(result, normalized); result = normalized; std::vector<Rect> faces; Size minSize(GetMinSize(), GetMinSize()); classifiers.face->detectMultiScale(result, faces, 1.1, 3, CV_HAAR_FIND_BIGGEST_OBJECT, minSize); if (!faces.empty()) { face = LargestRect(faces); result = result(face); } else { throw NoFaceFoundException(); } RotateFace(); static uint64_t eyesFoundCntr = 0; static uint64_t totalRunCntr = 0; totalRunCntr++; if(!gotEyes) qDebug() << "no eyes were found on the face -- this is odd :(" << ++eyesFoundCntr << "/" << totalRunCntr; else qDebug() << "is rotated? " << !rotated.empty() << (totalRunCntr - eyesFoundCntr) << "/" << totalRunCntr; ScaleFace(); return result; } <|endoftext|>
<commit_before>/* * Copyright (c) 2012 - 2014, Adrian M. Partl <apartl@aip.de>, * eScience team AIP Potsdam * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. 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 "AsciiDataObjDesc.h" #include <math.h> #include <string.h> #include <iostream> #include <assert.h> #include <boost/algorithm/string/replace.hpp> using namespace std; using namespace DBDataSchema; namespace AsciiIngest { AsciiDataObjDesc::AsciiDataObjDesc() { greedySep = 0; } AsciiDataObjDesc::~AsciiDataObjDesc() { } int AsciiDataObjDesc::getPrefixSkip() { return prefixSkip; } void AsciiDataObjDesc::setPrefixSkip(int newPrefixSkip) { assert(newPrefixSkip >= 0); prefixSkip = newPrefixSkip; } int AsciiDataObjDesc::getLenData() { return lenData; } void AsciiDataObjDesc::setLenData(int newLenData) { assert(newLenData >= 0); lenData = newLenData; } int AsciiDataObjDesc::getLineNum() { return lineNum; } void AsciiDataObjDesc::setLineNum(int newLineNum) { assert(newLineNum >= 0); lineNum = newLineNum; } char * AsciiDataObjDesc::getSep() { return sep; } void AsciiDataObjDesc::setSep(string newSep) { boost::replace_all(newSep, "\\n", "\n"); boost::replace_all(newSep, "\\t", "\t"); boost::replace_all(newSep, "\\r", "\r"); boost::replace_all(newSep, "\\\\", "\\"); boost::replace_all(newSep, "\\0", "\0"); strncpy(sep, newSep.c_str(), 10); } void AsciiDataObjDesc::setGreedy(int newGreedy) { assert(newGreedy == 0 || newGreedy == 1); greedySep = newGreedy; } int AsciiDataObjDesc::getGreedy() { return greedySep; } }<commit_msg>strncopy buffer size in AsciiDataObjDesc::setSep increased<commit_after>/* * Copyright (c) 2012 - 2014, Adrian M. Partl <apartl@aip.de>, * eScience team AIP Potsdam * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. 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 "AsciiDataObjDesc.h" #include <math.h> #include <string.h> #include <iostream> #include <assert.h> #include <boost/algorithm/string/replace.hpp> using namespace std; using namespace DBDataSchema; namespace AsciiIngest { AsciiDataObjDesc::AsciiDataObjDesc() { greedySep = 0; } AsciiDataObjDesc::~AsciiDataObjDesc() { } int AsciiDataObjDesc::getPrefixSkip() { return prefixSkip; } void AsciiDataObjDesc::setPrefixSkip(int newPrefixSkip) { assert(newPrefixSkip >= 0); prefixSkip = newPrefixSkip; } int AsciiDataObjDesc::getLenData() { return lenData; } void AsciiDataObjDesc::setLenData(int newLenData) { assert(newLenData >= 0); lenData = newLenData; } int AsciiDataObjDesc::getLineNum() { return lineNum; } void AsciiDataObjDesc::setLineNum(int newLineNum) { assert(newLineNum >= 0); lineNum = newLineNum; } char * AsciiDataObjDesc::getSep() { return sep; } void AsciiDataObjDesc::setSep(string newSep) { boost::replace_all(newSep, "\\n", "\n"); boost::replace_all(newSep, "\\t", "\t"); boost::replace_all(newSep, "\\r", "\r"); boost::replace_all(newSep, "\\\\", "\\"); boost::replace_all(newSep, "\\0", "\0"); strncpy(sep, newSep.c_str(), 256); } void AsciiDataObjDesc::setGreedy(int newGreedy) { assert(newGreedy == 0 || newGreedy == 1); greedySep = newGreedy; } int AsciiDataObjDesc::getGreedy() { return greedySep; } }<|endoftext|>
<commit_before>#pragma once #include <list> #include <unordered_map> #include <vector> #include <optional> #include <mutex> #include <functional> #include <ostream> namespace lru_cache { namespace detail { /* Dummy replacement for mutex which defaults to cache with no thread safety */ class nolocking { public: void lock() {} void unlock() {} bool try_lock() { return true; } }; } /* Associative Least Recently Used (LRU) cache */ template <typename Key_t, typename Value_t, typename Lock_t = detail::nolocking> class LRU_cache { static_assert( std::is_copy_constructible_v<Value_t>, "Cache requires copy-constructible objects, otherwise data access with get member function would pop the data out of the cache, which renders cache pointless."); protected: using List_t = std::list<std::pair<Key_t, Value_t>>; using Map_t = std::unordered_map<Key_t, typename List_t::iterator>; using Lock = std::lock_guard<Lock_t>; List_t m_list; Map_t m_map; const size_t m_capacity; mutable Lock_t m_lock; std::function<void(Value_t)> m_onEvict; void evict() { auto lru = --m_list.end(); if (m_onEvict) { m_onEvict(lru->second); } m_map.erase(lru->first); m_list.pop_back(); } public: explicit LRU_cache(size_t capacity = 8) : m_list() , m_map(capacity) , m_capacity(capacity) { } virtual ~LRU_cache() = default; LRU_cache(const LRU_cache&) = delete; LRU_cache& operator=(const LRU_cache&) = delete; LRU_cache(LRU_cache&&) = default; LRU_cache& operator=(LRU_cache&&) = default; template <typename Func> void setOnEvictNotifier(Func callback) { static_assert(std::is_invocable_v<Func, Value_t>, "Invalid type, expected function or callable object, or object callable to be called with argument of type Value_t"); m_onEvict = callback; } /* * Inserts an element (value) with the given key (key). * If a value with the fiven key exists, function does nothing. */ template < typename Key_tt = Key_t, typename Value_tt = Value_t, class Key_tt_MustBe_Key_t = std::enable_if_t<std::is_same_v<std::remove_reference_t<Key_tt>, Key_t>>, class Value_tt_MustBe_Value_t = std::enable_if_t<std::is_same_v<std::remove_reference_t<Value_tt>, Value_t>>> void insert(Key_tt&& key, Value_tt&& value) { Lock lock(m_lock); // lookup value in cache auto it = m_map.find(key); if (it == m_map.end()) { // insert item into cache (and check if cache is full) if (m_list.size() >= m_capacity) { evict(); } // insert element m_list.emplace_front(std::make_pair(key, std::forward<Value_tt>(value))); m_map[std::forward<Key_tt>(key)] = m_list.begin(); } } /* * Retrieves the value by the given key (key). * If the given key isn't in cache, the function returns empty std::optional object. */ template <typename Key_tt = Key_t, class TypeMustBe_Key_t = std::enable_if_t<std::is_same_v<std::remove_reference_t<Key_tt>, Key_t>>> std::optional<Value_t> get(Key_tt&& key) { Lock lock(m_lock); // look in the map if element is present auto it = m_map.find(key); // if not return the empty optional if (it == m_map.end()) { return {}; } // element is present... auto list_iterator = it->second; if (list_iterator == m_list.begin()) { return { list_iterator->second }; } else { // move the accessed element to front of the list m_list.splice(m_list.begin(), m_list, list_iterator); // and update hash map m_map[key] = m_list.begin(); return { m_list.begin()->second }; } } /* * Purges the cache */ virtual void purge() { Lock lock(m_lock); m_list.clear(); m_map.clear(); } /* * Releases all key/value pairs into a vector and purges the cache. */ virtual std::vector<std::pair<Key_t, Value_t>> release() { Lock lock(m_lock); std::vector<std::pair<Key_t, Value_t>> v; for (auto& pair : m_list) { v.emplace_back(std::move(pair)); } purge(); return v; } /* * Friend funtion for outputing key/value pairs. */ friend std::ostream& operator<<(std::ostream& os, const LRU_cache& cache) { for (auto& pair : cache.m_list) { os << "Key: " << pair.first << "\tValue: " << pair.second << std::endl; } return os; } }; } <commit_msg>Added licence into header file.<commit_after>/********************************************************************************* * * MIT License * * Copyright (c) 2017 Nenad Zikic * * 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. * *********************************************************************************/ #pragma once #include <list> #include <unordered_map> #include <vector> #include <optional> #include <mutex> #include <functional> #include <ostream> namespace lru_cache { namespace detail { /* Dummy replacement for mutex which defaults to cache with no thread safety */ class nolocking { public: void lock() {} void unlock() {} bool try_lock() { return true; } }; } /* Associative Least Recently Used (LRU) cache */ template <typename Key_t, typename Value_t, typename Lock_t = detail::nolocking> class LRU_cache { static_assert( std::is_copy_constructible_v<Value_t>, "Cache requires copy-constructible objects, otherwise data access with get member function would pop the data out of the cache, which renders cache pointless."); protected: using List_t = std::list<std::pair<Key_t, Value_t>>; using Map_t = std::unordered_map<Key_t, typename List_t::iterator>; using Lock = std::lock_guard<Lock_t>; List_t m_list; Map_t m_map; const size_t m_capacity; mutable Lock_t m_lock; std::function<void(Value_t)> m_onEvict; void evict() { auto lru = --m_list.end(); if (m_onEvict) { m_onEvict(lru->second); } m_map.erase(lru->first); m_list.pop_back(); } public: explicit LRU_cache(size_t capacity = 8) : m_list() , m_map(capacity) , m_capacity(capacity) { } virtual ~LRU_cache() = default; LRU_cache(const LRU_cache&) = delete; LRU_cache& operator=(const LRU_cache&) = delete; LRU_cache(LRU_cache&&) = default; LRU_cache& operator=(LRU_cache&&) = default; template <typename Func> void setOnEvictNotifier(Func callback) { static_assert(std::is_invocable_v<Func, Value_t>, "Invalid type, expected function or callable object, or object callable to be called with argument of type Value_t"); m_onEvict = callback; } /* * Inserts an element (value) with the given key (key). * If a value with the fiven key exists, function does nothing. */ template < typename Key_tt = Key_t, typename Value_tt = Value_t, class Key_tt_MustBe_Key_t = std::enable_if_t<std::is_same_v<std::remove_reference_t<Key_tt>, Key_t>>, class Value_tt_MustBe_Value_t = std::enable_if_t<std::is_same_v<std::remove_reference_t<Value_tt>, Value_t>>> void insert(Key_tt&& key, Value_tt&& value) { Lock lock(m_lock); // lookup value in cache auto it = m_map.find(key); if (it == m_map.end()) { // insert item into cache (and check if cache is full) if (m_list.size() >= m_capacity) { evict(); } // insert element m_list.emplace_front(std::make_pair(key, std::forward<Value_tt>(value))); m_map[std::forward<Key_tt>(key)] = m_list.begin(); } } /* * Retrieves the value by the given key (key). * If the given key isn't in cache, the function returns empty std::optional object. */ template <typename Key_tt = Key_t, class TypeMustBe_Key_t = std::enable_if_t<std::is_same_v<std::remove_reference_t<Key_tt>, Key_t>>> std::optional<Value_t> get(Key_tt&& key) { Lock lock(m_lock); // look in the map if element is present auto it = m_map.find(key); // if not return the empty optional if (it == m_map.end()) { return {}; } // element is present... auto list_iterator = it->second; if (list_iterator == m_list.begin()) { return { list_iterator->second }; } else { // move the accessed element to front of the list m_list.splice(m_list.begin(), m_list, list_iterator); // and update hash map m_map[key] = m_list.begin(); return { m_list.begin()->second }; } } /* * Purges the cache */ virtual void purge() { Lock lock(m_lock); m_list.clear(); m_map.clear(); } /* * Releases all key/value pairs into a vector and purges the cache. */ virtual std::vector<std::pair<Key_t, Value_t>> release() { Lock lock(m_lock); std::vector<std::pair<Key_t, Value_t>> v; for (auto& pair : m_list) { v.emplace_back(std::move(pair)); } purge(); return v; } /* * Friend funtion for outputing key/value pairs. */ friend std::ostream& operator<<(std::ostream& os, const LRU_cache& cache) { for (auto& pair : cache.m_list) { os << "Key: " << pair.first << "\tValue: " << pair.second << std::endl; } return os; } }; } <|endoftext|>
<commit_before>//===--- FileRemapper.cpp - File Remapping Helper -------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "clang/ARCMigrate/FileRemapper.h" #include "clang/Frontend/CompilerInvocation.h" #include "clang/Basic/FileManager.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/raw_ostream.h" #include <fstream> using namespace clang; using namespace arcmt; FileRemapper::FileRemapper() { FileMgr.reset(new FileManager(FileSystemOptions())); } FileRemapper::~FileRemapper() { clear(); } void FileRemapper::clear(StringRef outputDir) { for (MappingsTy::iterator I = FromToMappings.begin(), E = FromToMappings.end(); I != E; ++I) resetTarget(I->second); FromToMappings.clear(); assert(ToFromMappings.empty()); if (!outputDir.empty()) { std::string infoFile = getRemapInfoFile(outputDir); bool existed; llvm::sys::fs::remove(infoFile, existed); } } std::string FileRemapper::getRemapInfoFile(StringRef outputDir) { assert(!outputDir.empty()); llvm::sys::Path dir(outputDir); llvm::sys::Path infoFile = dir; infoFile.appendComponent("remap"); return infoFile.str(); } bool FileRemapper::initFromDisk(StringRef outputDir, Diagnostic &Diag, bool ignoreIfFilesChanged) { assert(FromToMappings.empty() && "initFromDisk should be called before any remap calls"); std::string infoFile = getRemapInfoFile(outputDir); bool fileExists = false; llvm::sys::fs::exists(infoFile, fileExists); if (!fileExists) return false; std::vector<std::pair<const FileEntry *, const FileEntry *> > pairs; llvm::OwningPtr<llvm::MemoryBuffer> fileBuf; if (llvm::error_code ec = llvm::MemoryBuffer::getFile(infoFile.c_str(), fileBuf)) return report(std::string("Error opening file: ") + infoFile, Diag); SmallVector<StringRef, 64> lines; fileBuf->getBuffer().split(lines, "\n"); for (unsigned idx = 0; idx+3 <= lines.size(); idx += 3) { std::string fromFilename = lines[idx]; uint64_t timeModified; lines[idx+1].getAsInteger(10, timeModified); std::string toFilename = lines[idx+2]; const FileEntry *origFE = FileMgr->getFile(fromFilename); if (!origFE) { if (ignoreIfFilesChanged) continue; return report(std::string("File does not exist: ") + fromFilename, Diag); } const FileEntry *newFE = FileMgr->getFile(toFilename); if (!newFE) { if (ignoreIfFilesChanged) continue; return report(std::string("File does not exist: ") + toFilename, Diag); } if ((uint64_t)origFE->getModificationTime() != timeModified) { if (ignoreIfFilesChanged) continue; return report(std::string("File was modified: ") + fromFilename, Diag); } pairs.push_back(std::make_pair(origFE, newFE)); } for (unsigned i = 0, e = pairs.size(); i != e; ++i) remap(pairs[i].first, pairs[i].second); return false; } bool FileRemapper::flushToDisk(StringRef outputDir, Diagnostic &Diag) { using namespace llvm::sys; bool existed; if (fs::create_directory(outputDir, existed) != llvm::errc::success) return report(std::string("Could not create directory: ") + outputDir.str(), Diag); std::string errMsg; std::string infoFile = getRemapInfoFile(outputDir); llvm::raw_fd_ostream infoOut(infoFile.c_str(), errMsg, llvm::raw_fd_ostream::F_Binary); if (!errMsg.empty()) return report(errMsg, Diag); for (MappingsTy::iterator I = FromToMappings.begin(), E = FromToMappings.end(); I != E; ++I) { const FileEntry *origFE = I->first; llvm::SmallString<200> origPath = StringRef(origFE->getName()); fs::make_absolute(origPath); infoOut << origPath << '\n'; infoOut << (uint64_t)origFE->getModificationTime() << '\n'; if (const FileEntry *FE = I->second.dyn_cast<const FileEntry *>()) { llvm::SmallString<200> newPath = StringRef(FE->getName()); fs::make_absolute(newPath); infoOut << newPath << '\n'; } else { llvm::SmallString<64> tempPath; tempPath = path::filename(origFE->getName()); tempPath += "-%%%%%%%%"; tempPath += path::extension(origFE->getName()); int fd; if (fs::unique_file(tempPath.str(), fd, tempPath) != llvm::errc::success) return report(std::string("Could not create file: ") + tempPath.c_str(), Diag); llvm::raw_fd_ostream newOut(fd, /*shouldClose=*/true); llvm::MemoryBuffer *mem = I->second.get<llvm::MemoryBuffer *>(); newOut.write(mem->getBufferStart(), mem->getBufferSize()); newOut.close(); const FileEntry *newE = FileMgr->getFile(tempPath); remap(origFE, newE); infoOut << newE->getName() << '\n'; } } infoOut.close(); return false; } bool FileRemapper::overwriteOriginal(Diagnostic &Diag, StringRef outputDir) { using namespace llvm::sys; for (MappingsTy::iterator I = FromToMappings.begin(), E = FromToMappings.end(); I != E; ++I) { const FileEntry *origFE = I->first; if (const FileEntry *newFE = I->second.dyn_cast<const FileEntry *>()) { if (fs::copy_file(newFE->getName(), origFE->getName(), fs::copy_option::overwrite_if_exists) != llvm::errc::success) { std::string err = "Could not copy file '"; llvm::raw_string_ostream os(err); os << "Could not copy file '" << newFE->getName() << "' to file '" << origFE->getName() << "'"; os.flush(); return report(err, Diag); } } else { bool fileExists = false; fs::exists(origFE->getName(), fileExists); if (!fileExists) return report(std::string("File does not exist: ") + origFE->getName(), Diag); std::string errMsg; llvm::raw_fd_ostream Out(origFE->getName(), errMsg, llvm::raw_fd_ostream::F_Binary); if (!errMsg.empty()) return report(errMsg, Diag); llvm::MemoryBuffer *mem = I->second.get<llvm::MemoryBuffer *>(); Out.write(mem->getBufferStart(), mem->getBufferSize()); Out.close(); } } clear(outputDir); return false; } void FileRemapper::applyMappings(CompilerInvocation &CI) const { PreprocessorOptions &PPOpts = CI.getPreprocessorOpts(); for (MappingsTy::const_iterator I = FromToMappings.begin(), E = FromToMappings.end(); I != E; ++I) { if (const FileEntry *FE = I->second.dyn_cast<const FileEntry *>()) { PPOpts.addRemappedFile(I->first->getName(), FE->getName()); } else { llvm::MemoryBuffer *mem = I->second.get<llvm::MemoryBuffer *>(); PPOpts.addRemappedFile(I->first->getName(), mem); } } PPOpts.RetainRemappedFileBuffers = true; } void FileRemapper::transferMappingsAndClear(CompilerInvocation &CI) { PreprocessorOptions &PPOpts = CI.getPreprocessorOpts(); for (MappingsTy::iterator I = FromToMappings.begin(), E = FromToMappings.end(); I != E; ++I) { if (const FileEntry *FE = I->second.dyn_cast<const FileEntry *>()) { PPOpts.addRemappedFile(I->first->getName(), FE->getName()); } else { llvm::MemoryBuffer *mem = I->second.get<llvm::MemoryBuffer *>(); PPOpts.addRemappedFile(I->first->getName(), mem); } I->second = Target(); } PPOpts.RetainRemappedFileBuffers = false; clear(); } void FileRemapper::remap(StringRef filePath, llvm::MemoryBuffer *memBuf) { remap(getOriginalFile(filePath), memBuf); } void FileRemapper::remap(StringRef filePath, StringRef newPath) { const FileEntry *file = getOriginalFile(filePath); const FileEntry *newfile = FileMgr->getFile(newPath); remap(file, newfile); } void FileRemapper::remap(const FileEntry *file, llvm::MemoryBuffer *memBuf) { assert(file); Target &targ = FromToMappings[file]; resetTarget(targ); targ = memBuf; } void FileRemapper::remap(const FileEntry *file, const FileEntry *newfile) { assert(file && newfile); Target &targ = FromToMappings[file]; resetTarget(targ); targ = newfile; ToFromMappings[newfile] = file; } const FileEntry *FileRemapper::getOriginalFile(StringRef filePath) { const FileEntry *file = FileMgr->getFile(filePath); // If we are updating a file that overriden an original file, // actually update the original file. llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator I = ToFromMappings.find(file); if (I != ToFromMappings.end()) { file = I->second; assert(FromToMappings.find(file) != FromToMappings.end() && "Original file not in mappings!"); } return file; } void FileRemapper::resetTarget(Target &targ) { if (!targ) return; if (llvm::MemoryBuffer *oldmem = targ.dyn_cast<llvm::MemoryBuffer *>()) { delete oldmem; } else { const FileEntry *toFE = targ.get<const FileEntry *>(); llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator I = ToFromMappings.find(toFE); if (I != ToFromMappings.end()) ToFromMappings.erase(I); } } bool FileRemapper::report(const std::string &err, Diagnostic &Diag) { unsigned ID = Diag.getDiagnosticIDs()->getCustomDiagID(DiagnosticIDs::Error, err); Diag.Report(ID); return true; } <commit_msg>Try to unbreak the build on systems where uint64_t isn't something that StringRef::getAsInteger can handle as its second argument<commit_after>//===--- FileRemapper.cpp - File Remapping Helper -------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "clang/ARCMigrate/FileRemapper.h" #include "clang/Frontend/CompilerInvocation.h" #include "clang/Basic/FileManager.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/raw_ostream.h" #include <fstream> using namespace clang; using namespace arcmt; FileRemapper::FileRemapper() { FileMgr.reset(new FileManager(FileSystemOptions())); } FileRemapper::~FileRemapper() { clear(); } void FileRemapper::clear(StringRef outputDir) { for (MappingsTy::iterator I = FromToMappings.begin(), E = FromToMappings.end(); I != E; ++I) resetTarget(I->second); FromToMappings.clear(); assert(ToFromMappings.empty()); if (!outputDir.empty()) { std::string infoFile = getRemapInfoFile(outputDir); bool existed; llvm::sys::fs::remove(infoFile, existed); } } std::string FileRemapper::getRemapInfoFile(StringRef outputDir) { assert(!outputDir.empty()); llvm::sys::Path dir(outputDir); llvm::sys::Path infoFile = dir; infoFile.appendComponent("remap"); return infoFile.str(); } bool FileRemapper::initFromDisk(StringRef outputDir, Diagnostic &Diag, bool ignoreIfFilesChanged) { assert(FromToMappings.empty() && "initFromDisk should be called before any remap calls"); std::string infoFile = getRemapInfoFile(outputDir); bool fileExists = false; llvm::sys::fs::exists(infoFile, fileExists); if (!fileExists) return false; std::vector<std::pair<const FileEntry *, const FileEntry *> > pairs; llvm::OwningPtr<llvm::MemoryBuffer> fileBuf; if (llvm::error_code ec = llvm::MemoryBuffer::getFile(infoFile.c_str(), fileBuf)) return report(std::string("Error opening file: ") + infoFile, Diag); SmallVector<StringRef, 64> lines; fileBuf->getBuffer().split(lines, "\n"); for (unsigned idx = 0; idx+3 <= lines.size(); idx += 3) { std::string fromFilename = lines[idx]; unsigned long long timeModified; lines[idx+1].getAsInteger(10, timeModified); std::string toFilename = lines[idx+2]; const FileEntry *origFE = FileMgr->getFile(fromFilename); if (!origFE) { if (ignoreIfFilesChanged) continue; return report(std::string("File does not exist: ") + fromFilename, Diag); } const FileEntry *newFE = FileMgr->getFile(toFilename); if (!newFE) { if (ignoreIfFilesChanged) continue; return report(std::string("File does not exist: ") + toFilename, Diag); } if ((uint64_t)origFE->getModificationTime() != timeModified) { if (ignoreIfFilesChanged) continue; return report(std::string("File was modified: ") + fromFilename, Diag); } pairs.push_back(std::make_pair(origFE, newFE)); } for (unsigned i = 0, e = pairs.size(); i != e; ++i) remap(pairs[i].first, pairs[i].second); return false; } bool FileRemapper::flushToDisk(StringRef outputDir, Diagnostic &Diag) { using namespace llvm::sys; bool existed; if (fs::create_directory(outputDir, existed) != llvm::errc::success) return report(std::string("Could not create directory: ") + outputDir.str(), Diag); std::string errMsg; std::string infoFile = getRemapInfoFile(outputDir); llvm::raw_fd_ostream infoOut(infoFile.c_str(), errMsg, llvm::raw_fd_ostream::F_Binary); if (!errMsg.empty()) return report(errMsg, Diag); for (MappingsTy::iterator I = FromToMappings.begin(), E = FromToMappings.end(); I != E; ++I) { const FileEntry *origFE = I->first; llvm::SmallString<200> origPath = StringRef(origFE->getName()); fs::make_absolute(origPath); infoOut << origPath << '\n'; infoOut << (uint64_t)origFE->getModificationTime() << '\n'; if (const FileEntry *FE = I->second.dyn_cast<const FileEntry *>()) { llvm::SmallString<200> newPath = StringRef(FE->getName()); fs::make_absolute(newPath); infoOut << newPath << '\n'; } else { llvm::SmallString<64> tempPath; tempPath = path::filename(origFE->getName()); tempPath += "-%%%%%%%%"; tempPath += path::extension(origFE->getName()); int fd; if (fs::unique_file(tempPath.str(), fd, tempPath) != llvm::errc::success) return report(std::string("Could not create file: ") + tempPath.c_str(), Diag); llvm::raw_fd_ostream newOut(fd, /*shouldClose=*/true); llvm::MemoryBuffer *mem = I->second.get<llvm::MemoryBuffer *>(); newOut.write(mem->getBufferStart(), mem->getBufferSize()); newOut.close(); const FileEntry *newE = FileMgr->getFile(tempPath); remap(origFE, newE); infoOut << newE->getName() << '\n'; } } infoOut.close(); return false; } bool FileRemapper::overwriteOriginal(Diagnostic &Diag, StringRef outputDir) { using namespace llvm::sys; for (MappingsTy::iterator I = FromToMappings.begin(), E = FromToMappings.end(); I != E; ++I) { const FileEntry *origFE = I->first; if (const FileEntry *newFE = I->second.dyn_cast<const FileEntry *>()) { if (fs::copy_file(newFE->getName(), origFE->getName(), fs::copy_option::overwrite_if_exists) != llvm::errc::success) { std::string err = "Could not copy file '"; llvm::raw_string_ostream os(err); os << "Could not copy file '" << newFE->getName() << "' to file '" << origFE->getName() << "'"; os.flush(); return report(err, Diag); } } else { bool fileExists = false; fs::exists(origFE->getName(), fileExists); if (!fileExists) return report(std::string("File does not exist: ") + origFE->getName(), Diag); std::string errMsg; llvm::raw_fd_ostream Out(origFE->getName(), errMsg, llvm::raw_fd_ostream::F_Binary); if (!errMsg.empty()) return report(errMsg, Diag); llvm::MemoryBuffer *mem = I->second.get<llvm::MemoryBuffer *>(); Out.write(mem->getBufferStart(), mem->getBufferSize()); Out.close(); } } clear(outputDir); return false; } void FileRemapper::applyMappings(CompilerInvocation &CI) const { PreprocessorOptions &PPOpts = CI.getPreprocessorOpts(); for (MappingsTy::const_iterator I = FromToMappings.begin(), E = FromToMappings.end(); I != E; ++I) { if (const FileEntry *FE = I->second.dyn_cast<const FileEntry *>()) { PPOpts.addRemappedFile(I->first->getName(), FE->getName()); } else { llvm::MemoryBuffer *mem = I->second.get<llvm::MemoryBuffer *>(); PPOpts.addRemappedFile(I->first->getName(), mem); } } PPOpts.RetainRemappedFileBuffers = true; } void FileRemapper::transferMappingsAndClear(CompilerInvocation &CI) { PreprocessorOptions &PPOpts = CI.getPreprocessorOpts(); for (MappingsTy::iterator I = FromToMappings.begin(), E = FromToMappings.end(); I != E; ++I) { if (const FileEntry *FE = I->second.dyn_cast<const FileEntry *>()) { PPOpts.addRemappedFile(I->first->getName(), FE->getName()); } else { llvm::MemoryBuffer *mem = I->second.get<llvm::MemoryBuffer *>(); PPOpts.addRemappedFile(I->first->getName(), mem); } I->second = Target(); } PPOpts.RetainRemappedFileBuffers = false; clear(); } void FileRemapper::remap(StringRef filePath, llvm::MemoryBuffer *memBuf) { remap(getOriginalFile(filePath), memBuf); } void FileRemapper::remap(StringRef filePath, StringRef newPath) { const FileEntry *file = getOriginalFile(filePath); const FileEntry *newfile = FileMgr->getFile(newPath); remap(file, newfile); } void FileRemapper::remap(const FileEntry *file, llvm::MemoryBuffer *memBuf) { assert(file); Target &targ = FromToMappings[file]; resetTarget(targ); targ = memBuf; } void FileRemapper::remap(const FileEntry *file, const FileEntry *newfile) { assert(file && newfile); Target &targ = FromToMappings[file]; resetTarget(targ); targ = newfile; ToFromMappings[newfile] = file; } const FileEntry *FileRemapper::getOriginalFile(StringRef filePath) { const FileEntry *file = FileMgr->getFile(filePath); // If we are updating a file that overriden an original file, // actually update the original file. llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator I = ToFromMappings.find(file); if (I != ToFromMappings.end()) { file = I->second; assert(FromToMappings.find(file) != FromToMappings.end() && "Original file not in mappings!"); } return file; } void FileRemapper::resetTarget(Target &targ) { if (!targ) return; if (llvm::MemoryBuffer *oldmem = targ.dyn_cast<llvm::MemoryBuffer *>()) { delete oldmem; } else { const FileEntry *toFE = targ.get<const FileEntry *>(); llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator I = ToFromMappings.find(toFE); if (I != ToFromMappings.end()) ToFromMappings.erase(I); } } bool FileRemapper::report(const std::string &err, Diagnostic &Diag) { unsigned ID = Diag.getDiagnosticIDs()->getCustomDiagID(DiagnosticIDs::Error, err); Diag.Report(ID); return true; } <|endoftext|>
<commit_before>//===- MachineLoopInfo.cpp - Natural Loop Calculator ----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the MachineLoopInfo class that is used to identify natural // loops and determine the loop depth of various nodes of the CFG. Note that // the loops identified may actually be several natural loops that share the // same header node... not just a single natural loop. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/MachineLoopInfo.h" #include "llvm/CodeGen/MachineDominators.h" #include "llvm/CodeGen/Passes.h" using namespace llvm; TEMPLATE_INSTANTIATION(class LoopBase<MachineBasicBlock>); TEMPLATE_INSTANTIATION(class LoopInfoBase<MachineBasicBlock>); namespace { char MachineLoopInfo::ID = 0; RegisterPass<MachineLoopInfo> X("machine-loops", "Machine Natural Loop Construction", true); } const PassInfo *llvm::MachineLoopInfoID = X.getPassInfo(); bool MachineLoopInfo::runOnMachineFunction(MachineFunction &) { releaseMemory(); LI->Calculate(getAnalysis<MachineDominatorTree>().getBase()); // Update return false; } void MachineLoopInfo::getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); AU.addRequired<MachineDominatorTree>(); } // Ensure this file gets linked when MachineLoopInfo.h is used. DEFINING_FILE_FOR(MachineLoopInfo) <commit_msg>make this build with newer gcc's<commit_after>//===- MachineLoopInfo.cpp - Natural Loop Calculator ----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the MachineLoopInfo class that is used to identify natural // loops and determine the loop depth of various nodes of the CFG. Note that // the loops identified may actually be several natural loops that share the // same header node... not just a single natural loop. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/MachineLoopInfo.h" #include "llvm/CodeGen/MachineDominators.h" #include "llvm/CodeGen/Passes.h" using namespace llvm; TEMPLATE_INSTANTIATION(class LoopBase<MachineBasicBlock>); TEMPLATE_INSTANTIATION(class LoopInfoBase<MachineBasicBlock>); char MachineLoopInfo::ID = 0; namespace { RegisterPass<MachineLoopInfo> X("machine-loops", "Machine Natural Loop Construction", true); } const PassInfo *llvm::MachineLoopInfoID = X.getPassInfo(); bool MachineLoopInfo::runOnMachineFunction(MachineFunction &) { releaseMemory(); LI->Calculate(getAnalysis<MachineDominatorTree>().getBase()); // Update return false; } void MachineLoopInfo::getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); AU.addRequired<MachineDominatorTree>(); } // Ensure this file gets linked when MachineLoopInfo.h is used. DEFINING_FILE_FOR(MachineLoopInfo) <|endoftext|>
<commit_before>#include "iconv.h" #include <v8.h> #include <node.h> #include <node_buffer.h> #include <cstring> #include <cerrno> using namespace v8; using namespace node; namespace { class Iconv: public ObjectWrap { public: static void Initialize(Handle<Object>& target); static Handle<Value> New(const Arguments& args); static Handle<Value> Convert(const Arguments& args); Iconv(iconv_t conv); ~Iconv(); // destructor may not run if program is short-lived or aborted // the actual conversion happens here Handle<Value> Convert(char* data, size_t length); private: iconv_t conv_; }; Iconv::Iconv(iconv_t conv): conv_(conv) { assert(conv_ != (iconv_t) -1); } Iconv::~Iconv() { ::iconv_close(conv_); } // helper class: reverse linked list of dumb buffers struct chunk { chunk *const prev; size_t size; char data[32 * 1024]; chunk(chunk *prev): prev(prev), size(0) { } }; // the actual conversion happens here Handle<Value> Iconv::Convert(char* data, size_t length) { assert(conv_ != (iconv_t) -1); assert(data != 0); chunk *c = 0; char *inbuf = data; size_t inbytesleft = length; size_t offset = 0; while (true) { c = new chunk(c); char *outbuf = c->data; size_t outbytesleft = sizeof(c->data); size_t rv = ::iconv(conv_, &inbuf, &inbytesleft, &outbuf, &outbytesleft); c->size = sizeof(c->data) - outbytesleft; offset += c->size; if (rv == (size_t) -1) { if (errno == E2BIG) { continue; } if (errno == EINVAL) { return ThrowException(ErrnoException(errno, "iconv", "Incomplete character sequence.")); } if (errno == EILSEQ) { return ThrowException(ErrnoException(errno, "iconv", "Illegal character sequence.")); } return ThrowException(ErrnoException(errno, "iconv")); } assert(inbytesleft == 0); break; } // copy linked list of chunks into Buffer in reverse order (last chunk at the top, second-to-last chunk below that, etc) Buffer& b = *Buffer::New(offset); for (chunk *t; c != 0; t = c->prev, delete c, c = t) { offset -= c->size; memcpy(b.data() + offset, c->data, c->size); } return b.handle_; } Handle<Value> Iconv::Convert(const Arguments& args) { HandleScope scope; Iconv* self = ObjectWrap::Unwrap<Iconv>(args.This()); Local<Value> arg = args[0]; if (arg->IsString()) { String::Utf8Value string(arg->ToString()); return self->Convert(*string, string.length()); } if (arg->IsObject()) { Local<Object> object = arg->ToObject(); if (Buffer::HasInstance(object)) { Buffer& buffer = *ObjectWrap::Unwrap<Buffer>(object); return self->Convert(buffer.data(), buffer.length()); } } return Undefined(); } Handle<Value> Iconv::New(const Arguments& args) { HandleScope scope; // inconsistency: node-iconv expects (source, target) while native iconv expects (target, source) // wontfix for now, node-iconv's approach feels more intuitive String::AsciiValue sourceEncoding(args[0]->ToString()); String::AsciiValue targetEncoding(args[1]->ToString()); iconv_t conv = ::iconv_open(*targetEncoding, *sourceEncoding); if (conv == (iconv_t) -1) { return ThrowException(ErrnoException(errno, "iconv_open", "Conversion not supported.")); } Iconv* instance = new Iconv(conv); instance->Wrap(args.Holder()); return args.This(); } void Iconv::Initialize(Handle<Object>& target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(Iconv::New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "convert", Iconv::Convert); target->Set(String::NewSymbol("Iconv"), t->GetFunction()); } extern "C" void init(Handle<Object> target) { Iconv::Initialize(target); } } // namespace <commit_msg>Change indentation from two spaces to a single tab. The former may be the node.js convention but the latter is easier to read.<commit_after>#include "iconv.h" #include <v8.h> #include <node.h> #include <node_buffer.h> #include <cstring> #include <cerrno> using namespace v8; using namespace node; namespace { class Iconv: public ObjectWrap { public: static void Initialize(Handle<Object>& target); static Handle<Value> New(const Arguments& args); static Handle<Value> Convert(const Arguments& args); Iconv(iconv_t conv); ~Iconv(); // destructor may not run if program is short-lived or aborted // the actual conversion happens here Handle<Value> Convert(char* data, size_t length); private: iconv_t conv_; }; Iconv::Iconv(iconv_t conv): conv_(conv) { assert(conv_ != (iconv_t) -1); } Iconv::~Iconv() { ::iconv_close(conv_); } // helper class: reverse linked list of dumb buffers struct chunk { chunk *const prev; size_t size; char data[32 * 1024]; chunk(chunk *prev): prev(prev), size(0) { } }; // the actual conversion happens here Handle<Value> Iconv::Convert(char* data, size_t length) { assert(conv_ != (iconv_t) -1); assert(data != 0); chunk *c = 0; char *inbuf = data; size_t inbytesleft = length; size_t offset = 0; while (true) { c = new chunk(c); char *outbuf = c->data; size_t outbytesleft = sizeof(c->data); size_t rv = ::iconv(conv_, &inbuf, &inbytesleft, &outbuf, &outbytesleft); c->size = sizeof(c->data) - outbytesleft; offset += c->size; if (rv == (size_t) -1) { if (errno == E2BIG) { continue; } if (errno == EINVAL) { return ThrowException(ErrnoException(errno, "iconv", "Incomplete character sequence.")); } if (errno == EILSEQ) { return ThrowException(ErrnoException(errno, "iconv", "Illegal character sequence.")); } return ThrowException(ErrnoException(errno, "iconv")); } assert(inbytesleft == 0); break; } // copy linked list of chunks into Buffer in reverse order (last chunk at the top, second-to-last chunk below that, etc) Buffer& b = *Buffer::New(offset); for (chunk *t; c != 0; t = c->prev, delete c, c = t) { offset -= c->size; memcpy(b.data() + offset, c->data, c->size); } return b.handle_; } Handle<Value> Iconv::Convert(const Arguments& args) { HandleScope scope; Iconv* self = ObjectWrap::Unwrap<Iconv>(args.This()); Local<Value> arg = args[0]; if (arg->IsString()) { String::Utf8Value string(arg->ToString()); return self->Convert(*string, string.length()); } if (arg->IsObject()) { Local<Object> object = arg->ToObject(); if (Buffer::HasInstance(object)) { Buffer& buffer = *ObjectWrap::Unwrap<Buffer>(object); return self->Convert(buffer.data(), buffer.length()); } } return Undefined(); } Handle<Value> Iconv::New(const Arguments& args) { HandleScope scope; // inconsistency: node-iconv expects (source, target) while native iconv expects (target, source) // wontfix for now, node-iconv's approach feels more intuitive String::AsciiValue sourceEncoding(args[0]->ToString()); String::AsciiValue targetEncoding(args[1]->ToString()); iconv_t conv = ::iconv_open(*targetEncoding, *sourceEncoding); if (conv == (iconv_t) -1) { return ThrowException(ErrnoException(errno, "iconv_open", "Conversion not supported.")); } Iconv* instance = new Iconv(conv); instance->Wrap(args.Holder()); return args.This(); } void Iconv::Initialize(Handle<Object>& target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(Iconv::New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "convert", Iconv::Convert); target->Set(String::NewSymbol("Iconv"), t->GetFunction()); } extern "C" void init(Handle<Object> target) { Iconv::Initialize(target); } } // namespace <|endoftext|>
<commit_before>//===--- ToolChains.cpp - ToolChain Implementations -----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "ToolChains.h" #include "clang/Basic/CharInfo.h" #include "clang/Basic/Version.h" #include "clang/Driver/Compilation.h" #include "clang/Driver/Driver.h" #include "clang/Driver/DriverDiagnostic.h" #include "clang/Driver/Options.h" #include "llvm/Config/llvm-config.h" #include "llvm/Option/Arg.h" #include "llvm/Option/ArgList.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/Path.h" // Include the necessary headers to interface with the Windows registry and // environment. #if defined(LLVM_ON_WIN32) #define USE_WIN32 #endif #ifdef USE_WIN32 #define WIN32_LEAN_AND_MEAN #define NOGDI #define NOMINMAX #include <windows.h> #endif using namespace clang::driver; using namespace clang::driver::toolchains; using namespace clang; using namespace llvm::opt; Windows::Windows(const Driver &D, const llvm::Triple& Triple, const ArgList &Args) : ToolChain(D, Triple, Args) { } Tool *Windows::buildLinker() const { return new tools::visualstudio::Link(*this); } Tool *Windows::buildAssembler() const { if (getTriple().isOSBinFormatMachO()) return new tools::darwin::Assemble(*this); getDriver().Diag(clang::diag::err_no_external_assembler); return nullptr; } bool Windows::IsIntegratedAssemblerDefault() const { return true; } bool Windows::IsUnwindTablesDefault() const { return getArch() == llvm::Triple::x86_64; } bool Windows::isPICDefault() const { return getArch() == llvm::Triple::x86_64; } bool Windows::isPIEDefault() const { return false; } bool Windows::isPICDefaultForced() const { return getArch() == llvm::Triple::x86_64; } /// \brief Read registry string. /// This also supports a means to look for high-versioned keys by use /// of a $VERSION placeholder in the key path. /// $VERSION in the key path is a placeholder for the version number, /// causing the highest value path to be searched for and used. /// I.e. "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\$VERSION". /// There can be additional characters in the component. Only the numberic /// characters are compared. static bool getSystemRegistryString(const char *keyPath, const char *valueName, char *value, size_t maxLength) { #ifndef USE_WIN32 return false; #else HKEY hRootKey = NULL; HKEY hKey = NULL; const char* subKey = NULL; DWORD valueType; DWORD valueSize = maxLength - 1; long lResult; bool returnValue = false; if (strncmp(keyPath, "HKEY_CLASSES_ROOT\\", 18) == 0) { hRootKey = HKEY_CLASSES_ROOT; subKey = keyPath + 18; } else if (strncmp(keyPath, "HKEY_USERS\\", 11) == 0) { hRootKey = HKEY_USERS; subKey = keyPath + 11; } else if (strncmp(keyPath, "HKEY_LOCAL_MACHINE\\", 19) == 0) { hRootKey = HKEY_LOCAL_MACHINE; subKey = keyPath + 19; } else if (strncmp(keyPath, "HKEY_CURRENT_USER\\", 18) == 0) { hRootKey = HKEY_CURRENT_USER; subKey = keyPath + 18; } else { return false; } const char *placeHolder = strstr(subKey, "$VERSION"); char bestName[256]; bestName[0] = '\0'; // If we have a $VERSION placeholder, do the highest-version search. if (placeHolder) { const char *keyEnd = placeHolder - 1; const char *nextKey = placeHolder; // Find end of previous key. while ((keyEnd > subKey) && (*keyEnd != '\\')) keyEnd--; // Find end of key containing $VERSION. while (*nextKey && (*nextKey != '\\')) nextKey++; size_t partialKeyLength = keyEnd - subKey; char partialKey[256]; if (partialKeyLength > sizeof(partialKey)) partialKeyLength = sizeof(partialKey); strncpy(partialKey, subKey, partialKeyLength); partialKey[partialKeyLength] = '\0'; HKEY hTopKey = NULL; lResult = RegOpenKeyEx(hRootKey, partialKey, 0, KEY_READ | KEY_WOW64_32KEY, &hTopKey); if (lResult == ERROR_SUCCESS) { char keyName[256]; int bestIndex = -1; double bestValue = 0.0; DWORD index, size = sizeof(keyName) - 1; for (index = 0; RegEnumKeyEx(hTopKey, index, keyName, &size, NULL, NULL, NULL, NULL) == ERROR_SUCCESS; index++) { const char *sp = keyName; while (*sp && !isDigit(*sp)) sp++; if (!*sp) continue; const char *ep = sp + 1; while (*ep && (isDigit(*ep) || (*ep == '.'))) ep++; char numBuf[32]; strncpy(numBuf, sp, sizeof(numBuf) - 1); numBuf[sizeof(numBuf) - 1] = '\0'; double dvalue = strtod(numBuf, NULL); if (dvalue > bestValue) { // Test that InstallDir is indeed there before keeping this index. // Open the chosen key path remainder. strcpy(bestName, keyName); // Append rest of key. strncat(bestName, nextKey, sizeof(bestName) - 1); bestName[sizeof(bestName) - 1] = '\0'; lResult = RegOpenKeyEx(hTopKey, bestName, 0, KEY_READ | KEY_WOW64_32KEY, &hKey); if (lResult == ERROR_SUCCESS) { lResult = RegQueryValueEx(hKey, valueName, NULL, &valueType, (LPBYTE)value, &valueSize); if (lResult == ERROR_SUCCESS) { bestIndex = (int)index; bestValue = dvalue; returnValue = true; } RegCloseKey(hKey); } } size = sizeof(keyName) - 1; } RegCloseKey(hTopKey); } } else { lResult = RegOpenKeyEx(hRootKey, subKey, 0, KEY_READ | KEY_WOW64_32KEY, &hKey); if (lResult == ERROR_SUCCESS) { lResult = RegQueryValueEx(hKey, valueName, NULL, &valueType, (LPBYTE)value, &valueSize); if (lResult == ERROR_SUCCESS) returnValue = true; RegCloseKey(hKey); } } return returnValue; #endif // USE_WIN32 } /// \brief Get Windows SDK installation directory. static bool getWindowsSDKDir(std::string &path) { char windowsSDKInstallDir[256]; // Try the Windows registry. bool hasSDKDir = getSystemRegistryString( "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\$VERSION", "InstallationFolder", windowsSDKInstallDir, sizeof(windowsSDKInstallDir) - 1); // If we have both vc80 and vc90, pick version we were compiled with. if (hasSDKDir && windowsSDKInstallDir[0]) { path = windowsSDKInstallDir; return true; } return false; } // Get Visual Studio installation directory. static bool getVisualStudioDir(std::string &path) { // First check the environment variables that vsvars32.bat sets. const char* vcinstalldir = getenv("VCINSTALLDIR"); if (vcinstalldir) { char *p = const_cast<char *>(strstr(vcinstalldir, "\\VC")); if (p) *p = '\0'; path = vcinstalldir; return true; } char vsIDEInstallDir[256]; char vsExpressIDEInstallDir[256]; // Then try the windows registry. bool hasVCDir = getSystemRegistryString( "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\$VERSION", "InstallDir", vsIDEInstallDir, sizeof(vsIDEInstallDir) - 1); bool hasVCExpressDir = getSystemRegistryString( "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VCExpress\\$VERSION", "InstallDir", vsExpressIDEInstallDir, sizeof(vsExpressIDEInstallDir) - 1); // If we have both vc80 and vc90, pick version we were compiled with. if (hasVCDir && vsIDEInstallDir[0]) { char *p = (char*)strstr(vsIDEInstallDir, "\\Common7\\IDE"); if (p) *p = '\0'; path = vsIDEInstallDir; return true; } if (hasVCExpressDir && vsExpressIDEInstallDir[0]) { char *p = (char*)strstr(vsExpressIDEInstallDir, "\\Common7\\IDE"); if (p) *p = '\0'; path = vsExpressIDEInstallDir; return true; } // Try the environment. const char *vs100comntools = getenv("VS100COMNTOOLS"); const char *vs90comntools = getenv("VS90COMNTOOLS"); const char *vs80comntools = getenv("VS80COMNTOOLS"); const char *vscomntools = nullptr; // Find any version we can if (vs100comntools) vscomntools = vs100comntools; else if (vs90comntools) vscomntools = vs90comntools; else if (vs80comntools) vscomntools = vs80comntools; if (vscomntools && *vscomntools) { const char *p = strstr(vscomntools, "\\Common7\\Tools"); path = p ? std::string(vscomntools, p) : vscomntools; return true; } return false; } void Windows::AddClangSystemIncludeArgs(const ArgList &DriverArgs, ArgStringList &CC1Args) const { if (DriverArgs.hasArg(options::OPT_nostdinc)) return; if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) { SmallString<128> P(getDriver().ResourceDir); llvm::sys::path::append(P, "include"); addSystemInclude(DriverArgs, CC1Args, P.str()); } if (DriverArgs.hasArg(options::OPT_nostdlibinc)) return; // Honor %INCLUDE%. It should know essential search paths with vcvarsall.bat. if (const char *cl_include_dir = getenv("INCLUDE")) { SmallVector<StringRef, 8> Dirs; StringRef(cl_include_dir) .split(Dirs, ";", /*MaxSplit=*/-1, /*KeepEmpty=*/false); for (StringRef Dir : Dirs) addSystemInclude(DriverArgs, CC1Args, Dir); if (!Dirs.empty()) return; } std::string VSDir; std::string WindowsSDKDir; // When built with access to the proper Windows APIs, try to actually find // the correct include paths first. if (getVisualStudioDir(VSDir)) { SmallString<128> P; P = VSDir; llvm::sys::path::append(P, "VC\\include"); addSystemInclude(DriverArgs, CC1Args, P.str()); if (getWindowsSDKDir(WindowsSDKDir)) { P = WindowsSDKDir; llvm::sys::path::append(P, "include"); addSystemInclude(DriverArgs, CC1Args, P.str()); } else { P = VSDir; llvm::sys::path::append(P, "VC\\PlatformSDK\\Include"); addSystemInclude(DriverArgs, CC1Args, P.str()); } return; } // As a fallback, select default install paths. // FIXME: Don't guess drives and paths like this on Windows. const StringRef Paths[] = { "C:/Program Files/Microsoft Visual Studio 10.0/VC/include", "C:/Program Files/Microsoft Visual Studio 9.0/VC/include", "C:/Program Files/Microsoft Visual Studio 9.0/VC/PlatformSDK/Include", "C:/Program Files/Microsoft Visual Studio 8/VC/include", "C:/Program Files/Microsoft Visual Studio 8/VC/PlatformSDK/Include" }; addSystemIncludes(DriverArgs, CC1Args, Paths); } void Windows::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, ArgStringList &CC1Args) const { // FIXME: There should probably be logic here to find libc++ on Windows. } <commit_msg>Win64: Disable uwtable until we fix .pdata emission in LLVM<commit_after>//===--- ToolChains.cpp - ToolChain Implementations -----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "ToolChains.h" #include "clang/Basic/CharInfo.h" #include "clang/Basic/Version.h" #include "clang/Driver/Compilation.h" #include "clang/Driver/Driver.h" #include "clang/Driver/DriverDiagnostic.h" #include "clang/Driver/Options.h" #include "llvm/Config/llvm-config.h" #include "llvm/Option/Arg.h" #include "llvm/Option/ArgList.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/Path.h" // Include the necessary headers to interface with the Windows registry and // environment. #if defined(LLVM_ON_WIN32) #define USE_WIN32 #endif #ifdef USE_WIN32 #define WIN32_LEAN_AND_MEAN #define NOGDI #define NOMINMAX #include <windows.h> #endif using namespace clang::driver; using namespace clang::driver::toolchains; using namespace clang; using namespace llvm::opt; Windows::Windows(const Driver &D, const llvm::Triple& Triple, const ArgList &Args) : ToolChain(D, Triple, Args) { } Tool *Windows::buildLinker() const { return new tools::visualstudio::Link(*this); } Tool *Windows::buildAssembler() const { if (getTriple().isOSBinFormatMachO()) return new tools::darwin::Assemble(*this); getDriver().Diag(clang::diag::err_no_external_assembler); return nullptr; } bool Windows::IsIntegratedAssemblerDefault() const { return true; } bool Windows::IsUnwindTablesDefault() const { // FIXME: LLVM's lowering of Win64 data is broken right now. MSVC's linker // says that our object files provide invalid .pdata contributions. Until // that is fixed, don't ask for unwind tables. return false; //return getArch() == llvm::Triple::x86_64; } bool Windows::isPICDefault() const { return getArch() == llvm::Triple::x86_64; } bool Windows::isPIEDefault() const { return false; } bool Windows::isPICDefaultForced() const { return getArch() == llvm::Triple::x86_64; } /// \brief Read registry string. /// This also supports a means to look for high-versioned keys by use /// of a $VERSION placeholder in the key path. /// $VERSION in the key path is a placeholder for the version number, /// causing the highest value path to be searched for and used. /// I.e. "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\$VERSION". /// There can be additional characters in the component. Only the numberic /// characters are compared. static bool getSystemRegistryString(const char *keyPath, const char *valueName, char *value, size_t maxLength) { #ifndef USE_WIN32 return false; #else HKEY hRootKey = NULL; HKEY hKey = NULL; const char* subKey = NULL; DWORD valueType; DWORD valueSize = maxLength - 1; long lResult; bool returnValue = false; if (strncmp(keyPath, "HKEY_CLASSES_ROOT\\", 18) == 0) { hRootKey = HKEY_CLASSES_ROOT; subKey = keyPath + 18; } else if (strncmp(keyPath, "HKEY_USERS\\", 11) == 0) { hRootKey = HKEY_USERS; subKey = keyPath + 11; } else if (strncmp(keyPath, "HKEY_LOCAL_MACHINE\\", 19) == 0) { hRootKey = HKEY_LOCAL_MACHINE; subKey = keyPath + 19; } else if (strncmp(keyPath, "HKEY_CURRENT_USER\\", 18) == 0) { hRootKey = HKEY_CURRENT_USER; subKey = keyPath + 18; } else { return false; } const char *placeHolder = strstr(subKey, "$VERSION"); char bestName[256]; bestName[0] = '\0'; // If we have a $VERSION placeholder, do the highest-version search. if (placeHolder) { const char *keyEnd = placeHolder - 1; const char *nextKey = placeHolder; // Find end of previous key. while ((keyEnd > subKey) && (*keyEnd != '\\')) keyEnd--; // Find end of key containing $VERSION. while (*nextKey && (*nextKey != '\\')) nextKey++; size_t partialKeyLength = keyEnd - subKey; char partialKey[256]; if (partialKeyLength > sizeof(partialKey)) partialKeyLength = sizeof(partialKey); strncpy(partialKey, subKey, partialKeyLength); partialKey[partialKeyLength] = '\0'; HKEY hTopKey = NULL; lResult = RegOpenKeyEx(hRootKey, partialKey, 0, KEY_READ | KEY_WOW64_32KEY, &hTopKey); if (lResult == ERROR_SUCCESS) { char keyName[256]; int bestIndex = -1; double bestValue = 0.0; DWORD index, size = sizeof(keyName) - 1; for (index = 0; RegEnumKeyEx(hTopKey, index, keyName, &size, NULL, NULL, NULL, NULL) == ERROR_SUCCESS; index++) { const char *sp = keyName; while (*sp && !isDigit(*sp)) sp++; if (!*sp) continue; const char *ep = sp + 1; while (*ep && (isDigit(*ep) || (*ep == '.'))) ep++; char numBuf[32]; strncpy(numBuf, sp, sizeof(numBuf) - 1); numBuf[sizeof(numBuf) - 1] = '\0'; double dvalue = strtod(numBuf, NULL); if (dvalue > bestValue) { // Test that InstallDir is indeed there before keeping this index. // Open the chosen key path remainder. strcpy(bestName, keyName); // Append rest of key. strncat(bestName, nextKey, sizeof(bestName) - 1); bestName[sizeof(bestName) - 1] = '\0'; lResult = RegOpenKeyEx(hTopKey, bestName, 0, KEY_READ | KEY_WOW64_32KEY, &hKey); if (lResult == ERROR_SUCCESS) { lResult = RegQueryValueEx(hKey, valueName, NULL, &valueType, (LPBYTE)value, &valueSize); if (lResult == ERROR_SUCCESS) { bestIndex = (int)index; bestValue = dvalue; returnValue = true; } RegCloseKey(hKey); } } size = sizeof(keyName) - 1; } RegCloseKey(hTopKey); } } else { lResult = RegOpenKeyEx(hRootKey, subKey, 0, KEY_READ | KEY_WOW64_32KEY, &hKey); if (lResult == ERROR_SUCCESS) { lResult = RegQueryValueEx(hKey, valueName, NULL, &valueType, (LPBYTE)value, &valueSize); if (lResult == ERROR_SUCCESS) returnValue = true; RegCloseKey(hKey); } } return returnValue; #endif // USE_WIN32 } /// \brief Get Windows SDK installation directory. static bool getWindowsSDKDir(std::string &path) { char windowsSDKInstallDir[256]; // Try the Windows registry. bool hasSDKDir = getSystemRegistryString( "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\$VERSION", "InstallationFolder", windowsSDKInstallDir, sizeof(windowsSDKInstallDir) - 1); // If we have both vc80 and vc90, pick version we were compiled with. if (hasSDKDir && windowsSDKInstallDir[0]) { path = windowsSDKInstallDir; return true; } return false; } // Get Visual Studio installation directory. static bool getVisualStudioDir(std::string &path) { // First check the environment variables that vsvars32.bat sets. const char* vcinstalldir = getenv("VCINSTALLDIR"); if (vcinstalldir) { char *p = const_cast<char *>(strstr(vcinstalldir, "\\VC")); if (p) *p = '\0'; path = vcinstalldir; return true; } char vsIDEInstallDir[256]; char vsExpressIDEInstallDir[256]; // Then try the windows registry. bool hasVCDir = getSystemRegistryString( "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\$VERSION", "InstallDir", vsIDEInstallDir, sizeof(vsIDEInstallDir) - 1); bool hasVCExpressDir = getSystemRegistryString( "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VCExpress\\$VERSION", "InstallDir", vsExpressIDEInstallDir, sizeof(vsExpressIDEInstallDir) - 1); // If we have both vc80 and vc90, pick version we were compiled with. if (hasVCDir && vsIDEInstallDir[0]) { char *p = (char*)strstr(vsIDEInstallDir, "\\Common7\\IDE"); if (p) *p = '\0'; path = vsIDEInstallDir; return true; } if (hasVCExpressDir && vsExpressIDEInstallDir[0]) { char *p = (char*)strstr(vsExpressIDEInstallDir, "\\Common7\\IDE"); if (p) *p = '\0'; path = vsExpressIDEInstallDir; return true; } // Try the environment. const char *vs100comntools = getenv("VS100COMNTOOLS"); const char *vs90comntools = getenv("VS90COMNTOOLS"); const char *vs80comntools = getenv("VS80COMNTOOLS"); const char *vscomntools = nullptr; // Find any version we can if (vs100comntools) vscomntools = vs100comntools; else if (vs90comntools) vscomntools = vs90comntools; else if (vs80comntools) vscomntools = vs80comntools; if (vscomntools && *vscomntools) { const char *p = strstr(vscomntools, "\\Common7\\Tools"); path = p ? std::string(vscomntools, p) : vscomntools; return true; } return false; } void Windows::AddClangSystemIncludeArgs(const ArgList &DriverArgs, ArgStringList &CC1Args) const { if (DriverArgs.hasArg(options::OPT_nostdinc)) return; if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) { SmallString<128> P(getDriver().ResourceDir); llvm::sys::path::append(P, "include"); addSystemInclude(DriverArgs, CC1Args, P.str()); } if (DriverArgs.hasArg(options::OPT_nostdlibinc)) return; // Honor %INCLUDE%. It should know essential search paths with vcvarsall.bat. if (const char *cl_include_dir = getenv("INCLUDE")) { SmallVector<StringRef, 8> Dirs; StringRef(cl_include_dir) .split(Dirs, ";", /*MaxSplit=*/-1, /*KeepEmpty=*/false); for (StringRef Dir : Dirs) addSystemInclude(DriverArgs, CC1Args, Dir); if (!Dirs.empty()) return; } std::string VSDir; std::string WindowsSDKDir; // When built with access to the proper Windows APIs, try to actually find // the correct include paths first. if (getVisualStudioDir(VSDir)) { SmallString<128> P; P = VSDir; llvm::sys::path::append(P, "VC\\include"); addSystemInclude(DriverArgs, CC1Args, P.str()); if (getWindowsSDKDir(WindowsSDKDir)) { P = WindowsSDKDir; llvm::sys::path::append(P, "include"); addSystemInclude(DriverArgs, CC1Args, P.str()); } else { P = VSDir; llvm::sys::path::append(P, "VC\\PlatformSDK\\Include"); addSystemInclude(DriverArgs, CC1Args, P.str()); } return; } // As a fallback, select default install paths. // FIXME: Don't guess drives and paths like this on Windows. const StringRef Paths[] = { "C:/Program Files/Microsoft Visual Studio 10.0/VC/include", "C:/Program Files/Microsoft Visual Studio 9.0/VC/include", "C:/Program Files/Microsoft Visual Studio 9.0/VC/PlatformSDK/Include", "C:/Program Files/Microsoft Visual Studio 8/VC/include", "C:/Program Files/Microsoft Visual Studio 8/VC/PlatformSDK/Include" }; addSystemIncludes(DriverArgs, CC1Args, Paths); } void Windows::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, ArgStringList &CC1Args) const { // FIXME: There should probably be logic here to find libc++ on Windows. } <|endoftext|>