<commit_before>#include <cctag/ImageCenterOptimizer.hpp>
#include <cctag/identification.hpp>
#include <cctag/visualDebug.hpp>
#include <cctag/geometry/point.hpp>
#include <cctag/algebra/invert.hpp>
#include <cctag/optimization/conditioner.hpp>
#include <cctag/geometry/distance.hpp>
#include <cctag/progBase/exceptions.hpp>
#include <cctag/global.hpp>

#include <OptQNewton.h>

#include <terry/sampler/all.hpp>

#include <boost/bind.hpp>
#include <boost/math/special_functions/pow.hpp>
#include <boost/math/constants/constants.hpp>

#include <cmath>
#include <ostream>

namespace cctag {

ImageCenterOptimizer::ImageCenterOptimizer( const VecExtPoints & vecExtPoints )
: Parent( 2, &ImageCenterOptimizer::optimizePointFun, NULL, this )
, _vecExtPoints( vecExtPoints )
{
}

void ImageCenterOptimizer::initOpt( int ndim, NEWMAT::ColumnVector& x )
{
  if ( ndim != 2 )
  {
          BOOST_THROW_EXCEPTION( exception::Bug() << exception::dev() + "Unable to init minimizer!" );
  }

  x(1) = _pToRefine.x();// todo@Lilian: why not (0) and (1) instead ?!
  x(2) = _pToRefine.y();
}

/**
 * Fonction de coût (fct à minimiser)
 *
 * @param[int] n nombre de paramètres à minimiser
 * @param[in] x les paramètres à estimer
 * @param[out] fx un scalaire, le résultat
 * @param[out] result, un truc de optpp, je sais pas pour l'instant à quoi ça sert
 * @param[in] objPtr
 */
void ImageCenterOptimizer::optimizePointFun( int n, const NEWMAT::ColumnVector& x, double& fx, int& result, void *objPtr )
{
	using namespace OPTPP;

	if( n != 2 )
	{
		return;
	}

	This *this_ptr = static_cast<This*>( objPtr );

	cctag::Point2dN<double> centerExtEllipse( x(1), x(2) );

	cctag::numerical::optimization::condition(centerExtEllipse, this_ptr->_mInvT);

	//CCTAG_TCOUT_VAR( centerExtEllipse );

	//CCTagVisualDebug::instance().drawText( centerExtEllipse, boost::lexical_cast<std::string>(this_ptr->_numIter), cctag::color_white );
	CCTagVisualDebug::instance().drawPoint( centerExtEllipse, cctag::color_blue );

	cctag::numerical::BoundedMatrix3x3d mH;
	VecSignals vecSig;
	if ( !getSignals( mH, vecSig, this_ptr->_lengthSig, centerExtEllipse, this_ptr->_vecExtPoints, this_ptr->_src, this_ptr->_ellipse.matrix() ) )
	{
		// We are diverging
		CCTAG_COUT_DEBUG("divergence!");
		return;
	}

	double res = 0;
        std::size_t resSize = 0;
	for( std::size_t i = 0; i < vecSig.size() - 1; ++i )
	{
		//CCTAG_TCOUT_VAR(vecSig[i]._imgSignal);
		for( std::size_t j = i+1; j < vecSig.size(); ++j )
		{
			res += std::pow( norm_2( vecSig[i]._imgSignal - vecSig[j]._imgSignal ), 4 );
                        //res += norm_2( vecSig[i]._imgSignal - vecSig[j]._imgSignal );
                        ++resSize;
		}
	}
        res /= resSize;

	++this_ptr->_numIter;

	//double penalty = 0;
	//double distanceToCentre = cctag::numerical::distancePoints2D( centerExtEllipse, this_ptr->_ellipse.center() );
	//if ( distanceToCentre > 0.2*std::min(this_ptr->_ellipse.a(), this_ptr->_ellipse.b()) )
	//{
	//	penalty += 1000000*distanceToCentre/std::min(this_ptr->_ellipse.a(), this_ptr->_ellipse.b());
	//}

	fx = res;//+penalty;
	result = NLPFunction;
}

Point2dN<double> ImageCenterOptimizer::operator()( const cctag::Point2dN<double> & pToRefine, const std::size_t lengthSig, const cv::Mat & src, const cctag::numerical::geometry::Ellipse & outerEllipse, const cctag::numerical::BoundedMatrix3x3d & mT)
{
	using namespace OPTPP;
	using namespace NEWMAT;

	Point2dN<double> res;

	//  Create a Nonlinear problem object
	_pToRefine = pToRefine;
	cctag::numerical::optimization::condition(_pToRefine, mT);

	_lengthSig = lengthSig;
	_src = src;
	_ellipse = outerEllipse;
	_numIter = 0;
	// 2D conditioning matrix
	_mT = mT;

	cctag::numerical::invert_3x3(mT,_mInvT);

	OptQNewton objfcn( this );

	objfcn.setSearchStrategy( TrustRegion );//LineSearch ); //TrustRegion );
	objfcn.setMaxFeval( 200 );
	objfcn.setFcnTol( 1.0e-4 );

#if defined(DEBUG)
	if ( !objfcn.setOutputFile("example1.out", 0) )
	{
		CCTAG_COUT_ERROR( "main: output file open failed" );
	}
#endif

	objfcn.optimize();

	//objfcn.printStatus( "Solution from quasi-newton" );
	objfcn.cleanup();

	//#ifdef REG_TEST
	ColumnVector x_sol = getXc();
	// Point raffiné à retourner :
	res.setX( x_sol( 1 ) );
	res.setY( x_sol( 2 ) );

	cctag::numerical::optimization::condition(res, _mInvT);

	objfcn.cleanup();

	return res;
}

} // namespace cctag
<commit_msg>Nice option in opt++<commit_after>#include <cctag/ImageCenterOptimizer.hpp>
#include <cctag/identification.hpp>
#include <cctag/visualDebug.hpp>
#include <cctag/geometry/point.hpp>
#include <cctag/algebra/invert.hpp>
#include <cctag/optimization/conditioner.hpp>
#include <cctag/geometry/distance.hpp>
#include <cctag/progBase/exceptions.hpp>
#include <cctag/global.hpp>

#include <OptQNewton.h>

#include <terry/sampler/all.hpp>

#include <boost/bind.hpp>
#include <boost/math/special_functions/pow.hpp>
#include <boost/math/constants/constants.hpp>

#include <cmath>
#include <ostream>

namespace cctag {

ImageCenterOptimizer::ImageCenterOptimizer( const VecExtPoints & vecExtPoints )
: Parent( 2, &ImageCenterOptimizer::optimizePointFun, NULL, this )
, _vecExtPoints( vecExtPoints )
{
}

void ImageCenterOptimizer::initOpt( int ndim, NEWMAT::ColumnVector& x )
{
  if ( ndim != 2 )
  {
          BOOST_THROW_EXCEPTION( exception::Bug() << exception::dev() + "Unable to init minimizer!" );
  }

  x(1) = _pToRefine.x();// todo@Lilian: why not (0) and (1) instead ?!
  x(2) = _pToRefine.y();
}

/**
 * Fonction de coût (fct à minimiser)
 *
 * @param[int] n nombre de paramètres à minimiser
 * @param[in] x les paramètres à estimer
 * @param[out] fx un scalaire, le résultat
 * @param[out] result, un truc de optpp, je sais pas pour l'instant à quoi ça sert
 * @param[in] objPtr
 */
void ImageCenterOptimizer::optimizePointFun( int n, const NEWMAT::ColumnVector& x, double& fx, int& result, void *objPtr )
{
	using namespace OPTPP;

	if( n != 2 )
	{
		return;
	}

	This *this_ptr = static_cast<This*>( objPtr );

	cctag::Point2dN<double> centerExtEllipse( x(1), x(2) );

	cctag::numerical::optimization::condition(centerExtEllipse, this_ptr->_mInvT);

	//CCTAG_TCOUT_VAR( centerExtEllipse );

	//CCTagVisualDebug::instance().drawText( centerExtEllipse, boost::lexical_cast<std::string>(this_ptr->_numIter), cctag::color_white );
	CCTagVisualDebug::instance().drawPoint( centerExtEllipse, cctag::color_blue );

	cctag::numerical::BoundedMatrix3x3d mH;
	VecSignals vecSig;
	if ( !getSignals( mH, vecSig, this_ptr->_lengthSig, centerExtEllipse, this_ptr->_vecExtPoints, this_ptr->_src, this_ptr->_ellipse.matrix() ) )
	{
		// We are diverging
		CCTAG_COUT_DEBUG("divergence!");
		return;
	}

	double res = 0;
        std::size_t resSize = 0;
	for( std::size_t i = 0; i < vecSig.size() - 1; ++i )
	{
		//CCTAG_TCOUT_VAR(vecSig[i]._imgSignal);
		for( std::size_t j = i+1; j < vecSig.size(); ++j )
		{
			res += std::pow( norm_2( vecSig[i]._imgSignal - vecSig[j]._imgSignal ), 4 );
                        //res += norm_2( vecSig[i]._imgSignal - vecSig[j]._imgSignal );
                        ++resSize;
		}
	}
        res /= resSize;

	++this_ptr->_numIter;

	//double penalty = 0;
	//double distanceToCentre = cctag::numerical::distancePoints2D( centerExtEllipse, this_ptr->_ellipse.center() );
	//if ( distanceToCentre > 0.2*std::min(this_ptr->_ellipse.a(), this_ptr->_ellipse.b()) )
	//{
	//	penalty += 1000000*distanceToCentre/std::min(this_ptr->_ellipse.a(), this_ptr->_ellipse.b());
	//}

	fx = res;//+penalty;
	result = NLPFunction;
}

Point2dN<double> ImageCenterOptimizer::operator()( const cctag::Point2dN<double> & pToRefine, const std::size_t lengthSig, const cv::Mat & src, const cctag::numerical::geometry::Ellipse & outerEllipse, const cctag::numerical::BoundedMatrix3x3d & mT)
{
	using namespace OPTPP;
	using namespace NEWMAT;

	Point2dN<double> res;

	//  Create a Nonlinear problem object
	_pToRefine = pToRefine;
	cctag::numerical::optimization::condition(_pToRefine, mT);

	_lengthSig = lengthSig;
	_src = src;
	_ellipse = outerEllipse;
	_numIter = 0;
	// 2D conditioning matrix
	_mT = mT;

	cctag::numerical::invert_3x3(mT,_mInvT);

	OptQNewton objfcn( this );

	objfcn.setSearchStrategy( TrustRegion );//LineSearch ); //TrustRegion );
	objfcn.setMaxFeval( 200 );
	objfcn.setFcnTol( 1.0e-4 );
    //objfcn.setMaxStep(0.2);
#if defined(DEBUG)
	if ( !objfcn.setOutputFile("example1.out", 0) )
	{
		CCTAG_COUT_ERROR( "main: output file open failed" );
	}
#endif

	objfcn.optimize();

	//objfcn.printStatus( "Solution from quasi-newton" );
	objfcn.cleanup();

	//#ifdef REG_TEST
	ColumnVector x_sol = getXc();
	// Point raffiné à retourner :
	res.setX( x_sol( 1 ) );
	res.setY( x_sol( 2 ) );

	cctag::numerical::optimization::condition(res, _mInvT);

	objfcn.cleanup();

	return res;
}

} // namespace cctag
<|endoftext|>


<commit_before>// This file is distributed under the MIT license.
// See the LICENSE file for details.

namespace MATH_NAMESPACE
{

//--------------------------------------------------------------------------------------------------
// vector2 members
//

template <typename T>
MATH_FUNC
inline vector<2, T>::vector(T x, T y)
    : x(x)
    , y(y)
{
}

template <typename T>
MATH_FUNC
inline vector<2, T>::vector(T s)
    : x(s)
    , y(s)
{
}

template <typename T>
MATH_FUNC
inline vector<2, T>::vector(T const data[2])
    : x(data[0])
    , y(data[1])
{
}

template <typename T>
template <typename U>
MATH_FUNC
inline vector<2, T>::vector(vector<2, U> const& rhs)
    : x(rhs.x)
    , y(rhs.y)
{
}

template <typename T>
template <typename U>
MATH_FUNC
inline vector<2, T>::vector(vector<3, U> const& rhs)
    : x(rhs.x)
    , y(rhs.y)
{
}

template <typename T>
template <typename U>
MATH_FUNC
inline vector<2, T>::vector(vector<4, U> const& rhs)
    : x(rhs.x)
    , y(rhs.y)
{
}

template <typename T>
template <typename U>
MATH_FUNC
inline vector<2, T>& vector<2, T>::operator=(vector<2, U> const& rhs)
{

    x = rhs.x;
    y = rhs.y;
    return *this;

}

template <typename T>
MATH_FUNC
inline T* vector<2, T>::data()
{
    return reinterpret_cast<T*>(this);
}

template <typename T>
MATH_FUNC
inline T const* vector<2, T>::data() const
{
    return reinterpret_cast<T const*>(this);
}

template <typename T>
MATH_FUNC
inline T& vector<2, T>::operator[](size_t i)
{
    return data()[i];
}

template <typename T>
MATH_FUNC
inline T const& vector<2, T>::operator[](size_t i) const
{
    return data()[i];
}

//--------------------------------------------------------------------------------------------------
// Basic arithmetic
//

template <typename T>
MATH_FUNC
inline vector<2, T> operator-(vector<2, T> const& v)
{
    return vector<2, T>(-v.x, -v.y);
}

template <typename T>
MATH_FUNC
inline vector<2, T> operator+(vector<2, T> const& u, vector<2, T> const& v)
{
    return vector<2, T>(u.x + v.x, u.y + v.y);
}

template <typename T>
MATH_FUNC
inline vector<2, T> operator-(vector<2, T> const& u, vector<2, T> const& v)
{
    return vector<2, T>(u.x - v.x, u.y - v.y);
}

template <typename T>
MATH_FUNC
inline vector<2, T> operator*(vector<2, T> const& u, vector<2, T> const& v)
{
    return vector<2, T>(u.x * v.x, u.y * v.y);
}

template <typename T>
MATH_FUNC
inline vector<2, T> operator/(vector<2, T> const& u, vector<2, T> const& v)
{
    return vector<2, T>(u.x / v.x, u.y / v.y);
}

//--------------------------------------------------------------------------------------------------
// Comparisons
//

template <typename T>
MATH_FUNC
inline bool operator==(vector<2, T> const& u, vector<2, T> const& v)
{
    return u.x == v.x && u.y == v.y;
}

template <typename T>
MATH_FUNC
inline bool operator<(vector<2, T> const& u, vector<2, T> const& v)
{
    return u.x < v.x || (u.x == v.x && u.y < v.y);
}

template <typename T>
MATH_FUNC
inline bool operator!=(vector<2, T> const& u, vector<2, T> const& v)
{
    return !(u == v);
}

template <typename T>
MATH_FUNC
inline bool operator<=(vector<2, T> const& u, vector<2, T> const& v)
{
    return !(v < u);
}

template <typename T>
MATH_FUNC
inline bool operator>(vector<2, T> const& u, vector<2, T> const& v)
{
    return v < u;
}

template <typename T>
MATH_FUNC
inline bool operator>=(vector<2, T> const& u, vector<2, T> const& v)
{
    return !(u < v);
}

template <typename T>
MATH_FUNC
inline vector<2, T> operator+(vector<2, T> const& v, T const& s)
{
    return vector<2, T>(v.x + s, v.y + s);
}

template <typename T>
MATH_FUNC
inline vector<2, T> operator-(vector<2, T> const& v, T const& s)
{
    return vector<2, T>(v.x - s, v.y - s);
}

template <typename T>
MATH_FUNC
inline vector<2, T> operator*(vector<2, T> const& v, T const& s)
{
    return vector<2, T>(v.x * s, v.y * s);
}

template <typename T>
MATH_FUNC
inline vector<2, T> operator/(vector<2, T> const& v, T const& s)
{
    return vector<2, T>(v.x / s, v.y / s);
}

template <typename T>
MATH_FUNC
inline vector<2, T> operator+(T const& s, vector<2, T> const& v)
{
    return vector<2, T>(s + v.x, s + v.y);
}

template <typename T>
MATH_FUNC
inline vector<2, T> operator-(T const& s, vector<2, T> const& v)
{
    return vector<2, T>(s - v.x, s - v.y);
}

template <typename T>
MATH_FUNC
inline vector<2, T> operator*(T const& s, vector<2, T> const& v)
{
    return vector<2, T>(s * v.x, s * v.y);
}

template <typename T>
MATH_FUNC
inline vector<2, T> operator/(T const& s, vector<2, T> const& v)
{
    return vector<2, T>(s / v.x, s / v.y);
}

//--------------------------------------------------------------------------------------------------
// Geometric functions
//

template <typename T>
MATH_FUNC
inline T dot(vector<2, T> const& u, vector<2, T> const& v)
{
    return u.x * v.x + u.y * v.y;
}

template <typename T>
MATH_FUNC
inline T norm(vector<2, T>  const& v)
{
    return sqrt( dot(v, v) );
}

template <typename T>
MATH_FUNC
inline T norm2(vector<2, T> const& v)
{
    return dot(v, v);
}

template <typename T>
MATH_FUNC
inline T length(vector<2, T> const& v)
{
    return norm(v);
}

template <typename T>
MATH_FUNC
inline vector<2, T> normalize(vector<2, T> const& v)
{
    return v * rsqrt( dot(v, v) );
}

//-------------------------------------------------------------------------------------------------
// Misc.
//

template <typename M, typename T>
MATH_FUNC
inline vector<2, T> select(M const& m, vector<2, T> const& u, vector<2, T> const& v)
{
    return vector<2, T>(
            select(m, u.x, v.x),
            select(m, u.y, v.y)
            );
}

template <typename M, typename T1, typename T2>
MATH_FUNC
auto select(M const& m, vector<2, T1> const& u, vector<2, T2> const& v)
    -> vector<2, decltype(select(m, u.x, v.x))>
{
    using T3 = decltype(select(m, u.x, v.x));

    return vector<2, T3>(
            select(m, u.x, v.x),
            select(m, u.y, v.y)
            );
}

template <typename T>
MATH_FUNC
inline vector<2, T> hadd(vector<2, T> const& u)
{
    return u.x + u.y;
}

} // MATH_NAMESPACE
<commit_msg>Implement min() and max() for vec2<commit_after>// This file is distributed under the MIT license.
// See the LICENSE file for details.

namespace MATH_NAMESPACE
{

//--------------------------------------------------------------------------------------------------
// vector2 members
//

template <typename T>
MATH_FUNC
inline vector<2, T>::vector(T x, T y)
    : x(x)
    , y(y)
{
}

template <typename T>
MATH_FUNC
inline vector<2, T>::vector(T s)
    : x(s)
    , y(s)
{
}

template <typename T>
MATH_FUNC
inline vector<2, T>::vector(T const data[2])
    : x(data[0])
    , y(data[1])
{
}

template <typename T>
template <typename U>
MATH_FUNC
inline vector<2, T>::vector(vector<2, U> const& rhs)
    : x(rhs.x)
    , y(rhs.y)
{
}

template <typename T>
template <typename U>
MATH_FUNC
inline vector<2, T>::vector(vector<3, U> const& rhs)
    : x(rhs.x)
    , y(rhs.y)
{
}

template <typename T>
template <typename U>
MATH_FUNC
inline vector<2, T>::vector(vector<4, U> const& rhs)
    : x(rhs.x)
    , y(rhs.y)
{
}

template <typename T>
template <typename U>
MATH_FUNC
inline vector<2, T>& vector<2, T>::operator=(vector<2, U> const& rhs)
{

    x = rhs.x;
    y = rhs.y;
    return *this;

}

template <typename T>
MATH_FUNC
inline T* vector<2, T>::data()
{
    return reinterpret_cast<T*>(this);
}

template <typename T>
MATH_FUNC
inline T const* vector<2, T>::data() const
{
    return reinterpret_cast<T const*>(this);
}

template <typename T>
MATH_FUNC
inline T& vector<2, T>::operator[](size_t i)
{
    return data()[i];
}

template <typename T>
MATH_FUNC
inline T const& vector<2, T>::operator[](size_t i) const
{
    return data()[i];
}

//--------------------------------------------------------------------------------------------------
// Basic arithmetic
//

template <typename T>
MATH_FUNC
inline vector<2, T> operator-(vector<2, T> const& v)
{
    return vector<2, T>(-v.x, -v.y);
}

template <typename T>
MATH_FUNC
inline vector<2, T> operator+(vector<2, T> const& u, vector<2, T> const& v)
{
    return vector<2, T>(u.x + v.x, u.y + v.y);
}

template <typename T>
MATH_FUNC
inline vector<2, T> operator-(vector<2, T> const& u, vector<2, T> const& v)
{
    return vector<2, T>(u.x - v.x, u.y - v.y);
}

template <typename T>
MATH_FUNC
inline vector<2, T> operator*(vector<2, T> const& u, vector<2, T> const& v)
{
    return vector<2, T>(u.x * v.x, u.y * v.y);
}

template <typename T>
MATH_FUNC
inline vector<2, T> operator/(vector<2, T> const& u, vector<2, T> const& v)
{
    return vector<2, T>(u.x / v.x, u.y / v.y);
}

//--------------------------------------------------------------------------------------------------
// Comparisons
//

template <typename T>
MATH_FUNC
inline bool operator==(vector<2, T> const& u, vector<2, T> const& v)
{
    return u.x == v.x && u.y == v.y;
}

template <typename T>
MATH_FUNC
inline bool operator<(vector<2, T> const& u, vector<2, T> const& v)
{
    return u.x < v.x || (u.x == v.x && u.y < v.y);
}

template <typename T>
MATH_FUNC
inline bool operator!=(vector<2, T> const& u, vector<2, T> const& v)
{
    return !(u == v);
}

template <typename T>
MATH_FUNC
inline bool operator<=(vector<2, T> const& u, vector<2, T> const& v)
{
    return !(v < u);
}

template <typename T>
MATH_FUNC
inline bool operator>(vector<2, T> const& u, vector<2, T> const& v)
{
    return v < u;
}

template <typename T>
MATH_FUNC
inline bool operator>=(vector<2, T> const& u, vector<2, T> const& v)
{
    return !(u < v);
}

template <typename T>
MATH_FUNC
inline vector<2, T> operator+(vector<2, T> const& v, T const& s)
{
    return vector<2, T>(v.x + s, v.y + s);
}

template <typename T>
MATH_FUNC
inline vector<2, T> operator-(vector<2, T> const& v, T const& s)
{
    return vector<2, T>(v.x - s, v.y - s);
}

template <typename T>
MATH_FUNC
inline vector<2, T> operator*(vector<2, T> const& v, T const& s)
{
    return vector<2, T>(v.x * s, v.y * s);
}

template <typename T>
MATH_FUNC
inline vector<2, T> operator/(vector<2, T> const& v, T const& s)
{
    return vector<2, T>(v.x / s, v.y / s);
}

template <typename T>
MATH_FUNC
inline vector<2, T> operator+(T const& s, vector<2, T> const& v)
{
    return vector<2, T>(s + v.x, s + v.y);
}

template <typename T>
MATH_FUNC
inline vector<2, T> operator-(T const& s, vector<2, T> const& v)
{
    return vector<2, T>(s - v.x, s - v.y);
}

template <typename T>
MATH_FUNC
inline vector<2, T> operator*(T const& s, vector<2, T> const& v)
{
    return vector<2, T>(s * v.x, s * v.y);
}

template <typename T>
MATH_FUNC
inline vector<2, T> operator/(T const& s, vector<2, T> const& v)
{
    return vector<2, T>(s / v.x, s / v.y);
}

//--------------------------------------------------------------------------------------------------
// Geometric functions
//

template <typename T>
MATH_FUNC
inline T dot(vector<2, T> const& u, vector<2, T> const& v)
{
    return u.x * v.x + u.y * v.y;
}

template <typename T>
MATH_FUNC
inline T norm(vector<2, T>  const& v)
{
    return sqrt( dot(v, v) );
}

template <typename T>
MATH_FUNC
inline T norm2(vector<2, T> const& v)
{
    return dot(v, v);
}

template <typename T>
MATH_FUNC
inline T length(vector<2, T> const& v)
{
    return norm(v);
}

template <typename T>
MATH_FUNC
inline vector<2, T> normalize(vector<2, T> const& v)
{
    return v * rsqrt( dot(v, v) );
}

//-------------------------------------------------------------------------------------------------
// Misc.
//

template <typename M, typename T>
MATH_FUNC
inline vector<2, T> select(M const& m, vector<2, T> const& u, vector<2, T> const& v)
{
    return vector<2, T>(
            select(m, u.x, v.x),
            select(m, u.y, v.y)
            );
}

template <typename M, typename T1, typename T2>
MATH_FUNC
auto select(M const& m, vector<2, T1> const& u, vector<2, T2> const& v)
    -> vector<2, decltype(select(m, u.x, v.x))>
{
    using T3 = decltype(select(m, u.x, v.x));

    return vector<2, T3>(
            select(m, u.x, v.x),
            select(m, u.y, v.y)
            );
}

template <typename T>
MATH_FUNC
inline vector<2, T> min(vector<2, T> const& u, vector<2, T> const& v)
{
    return vector<2, T>( min(u.x, v.x), min(u.y, v.y) );
}

template <typename T>
MATH_FUNC
inline vector<2, T> max(vector<2, T> const& u, vector<2, T> const& v)
{
    return vector<2, T>( max(u.x, v.x), max(u.y, v.y) );
}

template <typename T>
MATH_FUNC
inline vector<2, T> hadd(vector<2, T> const& u)
{
    return u.x + u.y;
}

} // MATH_NAMESPACE
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_FUNCTIONALS_INTERFACES_HH
#define DUNE_GDT_FUNCTIONALS_INTERFACES_HH

#include <dune/stuff/common/crtp.hh>

#include <dune/gdt/spaces/interface.hh>
#include <dune/gdt/discretefunction/default.hh>

namespace Dune {
namespace GDT {

template <class Traits>
class FunctionalInterface : public Stuff::CRTPInterface<FunctionalInterface<Traits>, Traits>
{
  typedef typename Traits::derived_type derived_type;

public:
  typedef typename Traits::GridViewType GridViewType;
  typedef typename Traits::ScalarType ScalarType;

  template <class SourceType>
  ScalarType apply(const SourceType& source) const
  {
    CHECK_CRTP(this->as_imp().apply(source));
    return this->as_imp().apply(source);
  }
}; // class FunctionalInterface

//! \note derive from FunctionalInterface
template <class Traits>
class AssemblableFunctionalInterface : protected Stuff::CRTPInterface<AssemblableFunctionalInterface<Traits>, Traits>
{
public:
  typedef typename Traits::derived_type derived_type;
  typedef typename Traits::GridViewType GridViewType;
  typedef typename Traits::SpaceType SpaceType;
  typedef typename Traits::VectorType VectorType;
  typedef typename Traits::ScalarType ScalarType;

private:
  static_assert(is_space<SpaceType>::value, "SpaceType has to be derived from SpaceInterface!");
  static_assert(Stuff::LA::is_vector<VectorType>::value,
                "VectorType has to be derived from Stuff::LA::VectorInterface!");

public:
  const GridViewType& grid_view() const
  {
    CHECK_CRTP(this->as_imp().grid_view());
    return this->as_imp().grid_view();
  }

  const SpaceType& space() const
  {
    CHECK_CRTP(this->as_imp().space());
    return this->as_imp().space();
  }

  void assemble()
  {
    CHECK_AND_CALL_CRTP(this->as_imp().assemble());
  }

  VectorType& vector()
  {
    CHECK_CRTP(this->as_imp().vector());
    return this->as_imp().vector();
  }

  const VectorType& vector() const
  {
    CHECK_CRTP(this->as_imp().vector());
    return this->as_imp().vector();
  }

  template <class S>
  ScalarType apply(const Stuff::LA::VectorInterface<S, ScalarType>& source) const
  {
    typedef typename S::derived_type SourceType;
    assemble();
    return vector().dot(static_cast<SourceType&>(source));
  }

  template <class S>
  ScalarType apply(const ConstDiscreteFunction<SpaceType, S>& source) const
  {
    assemble();
    assert(source.vector().size() == vector().size());
    return apply(source.vector());
  }
}; // class AssemblableFunctionalInterface

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_FUNCTIONALS_INTERFACES_HH
<commit_msg>[functionals.interfaces] update FunctionalInterface<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_FUNCTIONALS_INTERFACES_HH
#define DUNE_GDT_FUNCTIONALS_INTERFACES_HH

#include <dune/stuff/common/crtp.hh>

#include <dune/gdt/spaces/interface.hh>
#include <dune/gdt/discretefunction/default.hh>

namespace Dune {
namespace GDT {

template <class Traits>
class FunctionalInterface : public Stuff::CRTPInterface<FunctionalInterface<Traits>, Traits>
{
public:
  typedef typename Traits::derived_type derived_type;
  typedef typename Traits::FieldType FieldType;

  template <class SourceType>
  FieldType apply(const SourceType& source) const
  {
    CHECK_CRTP(this->as_imp().apply(source));
    return this->as_imp().apply(source);
  }
}; // class FunctionalInterface

//! \note derive from FunctionalInterface
template <class Traits>
class AssemblableFunctionalInterface : protected Stuff::CRTPInterface<AssemblableFunctionalInterface<Traits>, Traits>
{
public:
  typedef typename Traits::derived_type derived_type;
  typedef typename Traits::GridViewType GridViewType;
  typedef typename Traits::SpaceType SpaceType;
  typedef typename Traits::VectorType VectorType;
  typedef typename Traits::ScalarType ScalarType;

private:
  static_assert(is_space<SpaceType>::value, "SpaceType has to be derived from SpaceInterface!");
  static_assert(Stuff::LA::is_vector<VectorType>::value,
                "VectorType has to be derived from Stuff::LA::VectorInterface!");

public:
  const GridViewType& grid_view() const
  {
    CHECK_CRTP(this->as_imp().grid_view());
    return this->as_imp().grid_view();
  }

  const SpaceType& space() const
  {
    CHECK_CRTP(this->as_imp().space());
    return this->as_imp().space();
  }

  void assemble()
  {
    CHECK_AND_CALL_CRTP(this->as_imp().assemble());
  }

  VectorType& vector()
  {
    CHECK_CRTP(this->as_imp().vector());
    return this->as_imp().vector();
  }

  const VectorType& vector() const
  {
    CHECK_CRTP(this->as_imp().vector());
    return this->as_imp().vector();
  }

  template <class S>
  ScalarType apply(const Stuff::LA::VectorInterface<S, ScalarType>& source) const
  {
    typedef typename S::derived_type SourceType;
    assemble();
    return vector().dot(static_cast<SourceType&>(source));
  }

  template <class S>
  ScalarType apply(const ConstDiscreteFunction<SpaceType, S>& source) const
  {
    assemble();
    assert(source.vector().size() == vector().size());
    return apply(source.vector());
  }
}; // class AssemblableFunctionalInterface

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_FUNCTIONALS_INTERFACES_HH
<|endoftext|>


<commit_before><commit_msg>add game class deconstructor ok to free member<commit_after><|endoftext|>


<commit_before><commit_msg>v1.1.1<commit_after><|endoftext|>


<commit_before>// Copyright 2012-2013 Samplecount S.L.
//
// 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 "Methcla/Audio/Engine.hpp"
#include "Methcla/Audio/Group.hpp"

using namespace Methcla::Audio;

Group::Group(Environment& env, NodeId nodeId, Group* target, Node::AddAction addAction)
    : Node(env, nodeId, target, addAction)
    , m_first(nullptr)
    , m_last(nullptr)
{
}

Group::~Group()
{
    freeAll();
}

ResourceRef<Group> Group::construct(Environment& env, NodeId nodeId, Group* target, Node::AddAction addAction)
{
    return ResourceRef<Group>(new (env.rtMem().alloc(sizeof(Group))) Group(env, nodeId, target, addAction));
}

void Group::doProcess(size_t numFrames)
{
    Node* node = m_first;
    while (node != nullptr)
    {
        node->process(numFrames);
        node = node->m_next;
    }
}

void Group::addToHead(Node* node)
{
    assert( (node != nullptr) && (node->m_prev == nullptr) && (node->m_next == nullptr) );
    node->m_next = m_first;
    m_first = node;
    if (m_last == nullptr)
        m_last = m_first;
}

void Group::addToTail(Node* node)
{
    assert( (node != nullptr) && (node->m_prev == nullptr) && (node->m_next == nullptr) );
    node->m_prev = m_last;
    m_last = node;
    if (m_first == nullptr)
        m_first = m_last;
}

void Group::remove(Node* node)
{
    assert(    (node != nullptr)
           && (   (node == m_first && node == m_last && node->m_prev == nullptr && node->m_next == nullptr)
               || !((node->m_prev == nullptr) && (node->m_next == nullptr)) )
          );

    Node* prev = node->m_prev;
    Node* next = node->m_next;

    if (node == m_first)
    {
        assert( prev == nullptr );
        m_first = next;
    }
    else
    {
        prev->m_next = next;
    }

    if (node == m_last)
    {
        assert( next == nullptr );
        m_last = prev;
    }
    else
    {
        next->m_prev = prev;
    }

    node->m_parent = nullptr;
    node->m_prev = nullptr;
    node->m_next = nullptr;
}

bool Group::isEmpty() const
{
    return m_first == nullptr;
}

void Group::freeAll()
{
    while (!isEmpty())
    {
        Node* node = m_first;
        remove(node);
        env().releaseNode(node->id());
    }
}
<commit_msg>Fix linked list insertion methods<commit_after>// Copyright 2012-2013 Samplecount S.L.
//
// 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 "Methcla/Audio/Engine.hpp"
#include "Methcla/Audio/Group.hpp"

using namespace Methcla::Audio;

Group::Group(Environment& env, NodeId nodeId, Group* target, Node::AddAction addAction)
    : Node(env, nodeId, target, addAction)
    , m_first(nullptr)
    , m_last(nullptr)
{
}

Group::~Group()
{
    freeAll();
}

ResourceRef<Group> Group::construct(Environment& env, NodeId nodeId, Group* target, Node::AddAction addAction)
{
    return ResourceRef<Group>(new (env.rtMem().alloc(sizeof(Group))) Group(env, nodeId, target, addAction));
}

void Group::doProcess(size_t numFrames)
{
    Node* node = m_first;
    while (node != nullptr)
    {
        node->process(numFrames);
        node = node->m_next;
    }
}

void Group::addToHead(Node* node)
{
    assert( (node != nullptr) && (node->m_prev == nullptr) && (node->m_next == nullptr) );
    node->m_next = m_first;

    if (m_first != nullptr)
        m_first->m_prev = node;

    m_first = node;

    if (m_last == nullptr)
        m_last = node;
}

void Group::addToTail(Node* node)
{
    assert( (node != nullptr) && (node->m_prev == nullptr) && (node->m_next == nullptr) );
    node->m_prev = m_last;

    if (m_last != nullptr)
        m_last->m_next = node;

    m_last = node;

    if (m_first == nullptr)
        m_first = node;
}

void Group::remove(Node* node)
{
    assert(    (node != nullptr)
           && (   (node == m_first && node == m_last && node->m_prev == nullptr && node->m_next == nullptr)
               || !((node->m_prev == nullptr) && (node->m_next == nullptr)) )
          );

    Node* prev = node->m_prev;
    Node* next = node->m_next;

    if (node == m_first)
    {
        assert( prev == nullptr );
        m_first = next;
    }
    else
    {
        prev->m_next = next;
    }

    if (node == m_last)
    {
        assert( next == nullptr );
        m_last = prev;
    }
    else
    {
        next->m_prev = prev;
    }

    node->m_parent = nullptr;
    node->m_prev = nullptr;
    node->m_next = nullptr;
}

bool Group::isEmpty() const
{
    return m_first == nullptr;
}

void Group::freeAll()
{
    while (!isEmpty())
    {
        Node* node = m_first;
        remove(node);
        env().releaseNode(node->id());
    }
}
<|endoftext|>


<commit_before><commit_msg>add inputstream reader/message parser<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"

#include "svtools/table/tablecontrol.hxx"

#include "tabledatawindow.hxx"
#include "tablecontrol_impl.hxx"
#include "tablegeometry.hxx"
#include "cellvalueconversion.hxx"

#include <vcl/help.hxx>

//......................................................................................................................
namespace svt { namespace table
{
//......................................................................................................................

    /** === begin UNO using === **/
    using ::com::sun::star::uno::Any;
    /** === end UNO using === **/

    //==================================================================================================================
    //= TableDataWindow
    //==================================================================================================================
    //------------------------------------------------------------------------------------------------------------------
    TableDataWindow::TableDataWindow( TableControl_Impl& _rTableControl )
        :Window( &_rTableControl.getAntiImpl() )
        ,m_rTableControl( _rTableControl )
        ,m_nTipWindowHandle( 0 )
    {
        // by default, use the background as determined by the style settings
        const Color aWindowColor( GetSettings().GetStyleSettings().GetFieldColor() );
        SetBackground( Wallpaper( aWindowColor ) );
        SetFillColor( aWindowColor );
    }

    //------------------------------------------------------------------------------------------------------------------
    TableDataWindow::~TableDataWindow()
    {
        impl_hideTipWindow();
    }

    //------------------------------------------------------------------------------------------------------------------
    void TableDataWindow::Paint( const Rectangle& rUpdateRect )
    {
        m_rTableControl.doPaintContent( rUpdateRect );
    }
    //------------------------------------------------------------------------------------------------------------------
    void TableDataWindow::SetBackground( const Wallpaper& rColor )
    {
        Window::SetBackground( rColor );
    }
    //------------------------------------------------------------------------------------------------------------------
    void TableDataWindow::SetControlBackground( const Color& rColor )
    {
        Window::SetControlBackground( rColor );
    }
    //------------------------------------------------------------------------------------------------------------------
    void TableDataWindow::SetBackground()
    {
        Window::SetBackground();
    }
    //------------------------------------------------------------------------------------------------------------------
    void TableDataWindow::SetControlBackground()
    {
        Window::SetControlBackground();
    }

    //------------------------------------------------------------------------------------------------------------------
    void TableDataWindow::RequestHelp( const HelpEvent& rHEvt )
    {
        USHORT const nHelpMode = rHEvt.GetMode();
        if ( ( nHelpMode & HELPMODE_QUICK ) != 0 )
        {
            ITableControl& rTableControl = m_rTableControl;
            PTableModel const pTableModel( rTableControl.getModel() );

            Point const aMousePos( ScreenToOutputPixel( rHEvt.GetMousePosPixel() ) );

            RowPos const hitRow = rTableControl.getRowAtPoint( aMousePos );
            ColPos const hitCol = rTableControl.getColAtPoint( aMousePos );

            ::rtl::OUString sHelpText;

            if ( ( hitCol >= 0 ) && ( hitCol < pTableModel->getColumnCount() ) )
            {
                if ( hitRow == ROW_COL_HEADERS )
                {
                    sHelpText = pTableModel->getColumnModel( hitCol )->getHelpText();
                }
                else if ( ( hitRow >= 0 ) && ( hitRow < pTableModel->getRowCount() ) )
                {
                    Any aCellToolTip;
                    pTableModel->getCellToolTip( hitCol, hitRow, aCellToolTip );
                    if ( !aCellToolTip.hasValue() )
                    {
                        // use the cell content
                        pTableModel->getCellContent( hitCol, hitRow, aCellToolTip );

                        // use the cell content as tool tip only if it doesn't fit into the cell.
                        bool const activeCell = ( hitRow == rTableControl.getCurrentRow() ) && ( hitCol == rTableControl.getCurrentColumn() );
                        bool const selectedCell = rTableControl.isRowSelected( hitRow );

                        Rectangle const aWindowRect( Point( 0, 0 ), GetOutputSizePixel() );
                        TableCellGeometry const aCell( m_rTableControl, aWindowRect, hitCol, hitRow );
                        Rectangle const aCellRect( aCell.getRect() );

                        PTableRenderer const pRenderer = pTableModel->getRenderer();
                        if ( pRenderer->FitsIntoCell( aCellToolTip, hitCol, hitRow, activeCell, selectedCell, *this, aCellRect ) )
                            aCellToolTip.clear();
                    }

                    sHelpText = CellValueConversion::convertToString( aCellToolTip );
                }
            }

            if ( sHelpText.getLength() )
            {
                Rectangle const aControlScreenRect(
                    OutputToScreenPixel( Point( 0, 0 ) ),
                    GetOutputSizePixel()
                );

                if ( m_nTipWindowHandle )
                    Help::UpdateTip( m_nTipWindowHandle, this, aControlScreenRect, sHelpText );
                else
                    m_nTipWindowHandle = Help::ShowTip( this, aControlScreenRect, sHelpText );
            }
        }
        else
        {
            Window::RequestHelp( rHEvt );
        }
    }

    //------------------------------------------------------------------------------------------------------------------
    void TableDataWindow::impl_hideTipWindow()
    {
        if ( m_nTipWindowHandle != 0 )
        {
            Help::HideTip( m_nTipWindowHandle );
            m_nTipWindowHandle = 0;
        }
    }

    //------------------------------------------------------------------------------------------------------------------
    void TableDataWindow::MouseMove( const MouseEvent& rMEvt )
    {
        if ( rMEvt.IsLeaveWindow() )
            impl_hideTipWindow();

        Point aPoint = rMEvt.GetPosPixel();
        if ( !m_rTableControl.getInputHandler()->MouseMove( m_rTableControl, rMEvt ) )
        {
            if ( m_rTableControl.getRowAtPoint( aPoint ) == ROW_COL_HEADERS )
            {
                m_rTableControl.resizeColumn( aPoint );
            }
            else
            {
                Window::MouseMove( rMEvt );
            }
        }
    }
    //------------------------------------------------------------------------------------------------------------------
    void TableDataWindow::MouseButtonDown( const MouseEvent& rMEvt )
    {
        const Point aPoint = rMEvt.GetPosPixel();
        const RowPos nCurRow = m_rTableControl.getRowAtPoint( aPoint );
        if ( !m_rTableControl.getInputHandler()->MouseButtonDown( m_rTableControl, rMEvt ) )
            Window::MouseButtonDown( rMEvt );
        else
        {
            if(nCurRow >= 0 && m_rTableControl.getSelEngine()->GetSelectionMode() != NO_SELECTION)
            {
                if( !m_rTableControl.isRowSelected( nCurRow ) )
                {
                    m_aSelectHdl.Call( NULL );
                }
            }
        }
        m_aMouseButtonDownHdl.Call((MouseEvent*) &rMEvt);
    }
    //------------------------------------------------------------------------------------------------------------------
    void TableDataWindow::MouseButtonUp( const MouseEvent& rMEvt )
    {
        if ( !m_rTableControl.getInputHandler()->MouseButtonUp( m_rTableControl, rMEvt ) )
            Window::MouseButtonUp( rMEvt );
        m_aMouseButtonUpHdl.Call((MouseEvent*) &rMEvt);
        m_rTableControl.getAntiImpl().GrabFocus();
    }
    //------------------------------------------------------------------------------------------------------------------
    void TableDataWindow::SetPointer( const Pointer& rPointer )
    {
        Window::SetPointer(rPointer);
    }
    //------------------------------------------------------------------------------------------------------------------
    void TableDataWindow::CaptureMouse()
    {
        Window::CaptureMouse();
    }
    //------------------------------------------------------------------------------------------------------------------
    void TableDataWindow::ReleaseMouse(  )
    {
        Window::ReleaseMouse();
    }
    // -----------------------------------------------------------------------
    long TableDataWindow::Notify(NotifyEvent& rNEvt )
    {
        long nDone = 0;
        if ( rNEvt.GetType() == EVENT_COMMAND )
        {
            const CommandEvent& rCEvt = *rNEvt.GetCommandEvent();
            if ( rCEvt.GetCommand() == COMMAND_WHEEL )
            {
                const CommandWheelData* pData = rCEvt.GetWheelData();
                if( !pData->GetModifier() && ( pData->GetMode() == COMMAND_WHEEL_SCROLL ) )
                {
                    nDone = HandleScrollCommand( rCEvt, m_rTableControl.getHorzScrollbar(), m_rTableControl.getVertScrollbar() );
                }
            }
        }
        return nDone ? nDone : Window::Notify( rNEvt );
    }
//......................................................................................................................
} } // namespace svt::table
//......................................................................................................................
<commit_msg>gridsort: if the tooltip text contains line breaks, force the tip style to be 'balloon' - the 'normal' style doesn't support line breaks<commit_after>/*************************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"

#include "svtools/table/tablecontrol.hxx"

#include "tabledatawindow.hxx"
#include "tablecontrol_impl.hxx"
#include "tablegeometry.hxx"
#include "cellvalueconversion.hxx"

#include <vcl/help.hxx>

//......................................................................................................................
namespace svt { namespace table
{
//......................................................................................................................

    /** === begin UNO using === **/
    using ::com::sun::star::uno::Any;
    /** === end UNO using === **/

    //==================================================================================================================
    //= TableDataWindow
    //==================================================================================================================
    //------------------------------------------------------------------------------------------------------------------
    TableDataWindow::TableDataWindow( TableControl_Impl& _rTableControl )
        :Window( &_rTableControl.getAntiImpl() )
        ,m_rTableControl( _rTableControl )
        ,m_nTipWindowHandle( 0 )
    {
        // by default, use the background as determined by the style settings
        const Color aWindowColor( GetSettings().GetStyleSettings().GetFieldColor() );
        SetBackground( Wallpaper( aWindowColor ) );
        SetFillColor( aWindowColor );
    }

    //------------------------------------------------------------------------------------------------------------------
    TableDataWindow::~TableDataWindow()
    {
        impl_hideTipWindow();
    }

    //------------------------------------------------------------------------------------------------------------------
    void TableDataWindow::Paint( const Rectangle& rUpdateRect )
    {
        m_rTableControl.doPaintContent( rUpdateRect );
    }
    //------------------------------------------------------------------------------------------------------------------
    void TableDataWindow::SetBackground( const Wallpaper& rColor )
    {
        Window::SetBackground( rColor );
    }
    //------------------------------------------------------------------------------------------------------------------
    void TableDataWindow::SetControlBackground( const Color& rColor )
    {
        Window::SetControlBackground( rColor );
    }
    //------------------------------------------------------------------------------------------------------------------
    void TableDataWindow::SetBackground()
    {
        Window::SetBackground();
    }
    //------------------------------------------------------------------------------------------------------------------
    void TableDataWindow::SetControlBackground()
    {
        Window::SetControlBackground();
    }

    //------------------------------------------------------------------------------------------------------------------
    void TableDataWindow::RequestHelp( const HelpEvent& rHEvt )
    {
        USHORT const nHelpMode = rHEvt.GetMode();
        if ( ( nHelpMode & HELPMODE_QUICK ) != 0 )
        {
            ITableControl& rTableControl = m_rTableControl;
            PTableModel const pTableModel( rTableControl.getModel() );

            Point const aMousePos( ScreenToOutputPixel( rHEvt.GetMousePosPixel() ) );

            RowPos const hitRow = rTableControl.getRowAtPoint( aMousePos );
            ColPos const hitCol = rTableControl.getColAtPoint( aMousePos );

            ::rtl::OUString sHelpText;
            USHORT nHelpStyle = 0;

            if ( ( hitCol >= 0 ) && ( hitCol < pTableModel->getColumnCount() ) )
            {
                if ( hitRow == ROW_COL_HEADERS )
                {
                    sHelpText = pTableModel->getColumnModel( hitCol )->getHelpText();
                }
                else if ( ( hitRow >= 0 ) && ( hitRow < pTableModel->getRowCount() ) )
                {
                    Any aCellToolTip;
                    pTableModel->getCellToolTip( hitCol, hitRow, aCellToolTip );
                    if ( !aCellToolTip.hasValue() )
                    {
                        // use the cell content
                        pTableModel->getCellContent( hitCol, hitRow, aCellToolTip );

                        // use the cell content as tool tip only if it doesn't fit into the cell.
                        bool const activeCell = ( hitRow == rTableControl.getCurrentRow() ) && ( hitCol == rTableControl.getCurrentColumn() );
                        bool const selectedCell = rTableControl.isRowSelected( hitRow );

                        Rectangle const aWindowRect( Point( 0, 0 ), GetOutputSizePixel() );
                        TableCellGeometry const aCell( m_rTableControl, aWindowRect, hitCol, hitRow );
                        Rectangle const aCellRect( aCell.getRect() );

                        PTableRenderer const pRenderer = pTableModel->getRenderer();
                        if ( pRenderer->FitsIntoCell( aCellToolTip, hitCol, hitRow, activeCell, selectedCell, *this, aCellRect ) )
                            aCellToolTip.clear();
                    }

                    sHelpText = CellValueConversion::convertToString( aCellToolTip );

                    if ( sHelpText.indexOf( '\n' ) >= 0 )
                        nHelpStyle = QUICKHELP_TIP_STYLE_BALLOON;
                }
            }

            if ( sHelpText.getLength() )
            {
                Rectangle const aControlScreenRect(
                    OutputToScreenPixel( Point( 0, 0 ) ),
                    GetOutputSizePixel()
                );

                if ( m_nTipWindowHandle )
                    Help::UpdateTip( m_nTipWindowHandle, this, aControlScreenRect, sHelpText );
                else
                    m_nTipWindowHandle = Help::ShowTip( this, aControlScreenRect, sHelpText, nHelpStyle );
            }
        }
        else
        {
            Window::RequestHelp( rHEvt );
        }
    }

    //------------------------------------------------------------------------------------------------------------------
    void TableDataWindow::impl_hideTipWindow()
    {
        if ( m_nTipWindowHandle != 0 )
        {
            Help::HideTip( m_nTipWindowHandle );
            m_nTipWindowHandle = 0;
        }
    }

    //------------------------------------------------------------------------------------------------------------------
    void TableDataWindow::MouseMove( const MouseEvent& rMEvt )
    {
        if ( rMEvt.IsLeaveWindow() )
            impl_hideTipWindow();

        Point aPoint = rMEvt.GetPosPixel();
        if ( !m_rTableControl.getInputHandler()->MouseMove( m_rTableControl, rMEvt ) )
        {
            if ( m_rTableControl.getRowAtPoint( aPoint ) == ROW_COL_HEADERS )
            {
                m_rTableControl.resizeColumn( aPoint );
            }
            else
            {
                Window::MouseMove( rMEvt );
            }
        }
    }
    //------------------------------------------------------------------------------------------------------------------
    void TableDataWindow::MouseButtonDown( const MouseEvent& rMEvt )
    {
        const Point aPoint = rMEvt.GetPosPixel();
        const RowPos nCurRow = m_rTableControl.getRowAtPoint( aPoint );
        if ( !m_rTableControl.getInputHandler()->MouseButtonDown( m_rTableControl, rMEvt ) )
            Window::MouseButtonDown( rMEvt );
        else
        {
            if(nCurRow >= 0 && m_rTableControl.getSelEngine()->GetSelectionMode() != NO_SELECTION)
            {
                if( !m_rTableControl.isRowSelected( nCurRow ) )
                {
                    m_aSelectHdl.Call( NULL );
                }
            }
        }
        m_aMouseButtonDownHdl.Call((MouseEvent*) &rMEvt);
    }
    //------------------------------------------------------------------------------------------------------------------
    void TableDataWindow::MouseButtonUp( const MouseEvent& rMEvt )
    {
        if ( !m_rTableControl.getInputHandler()->MouseButtonUp( m_rTableControl, rMEvt ) )
            Window::MouseButtonUp( rMEvt );
        m_aMouseButtonUpHdl.Call((MouseEvent*) &rMEvt);
        m_rTableControl.getAntiImpl().GrabFocus();
    }
    //------------------------------------------------------------------------------------------------------------------
    void TableDataWindow::SetPointer( const Pointer& rPointer )
    {
        Window::SetPointer(rPointer);
    }
    //------------------------------------------------------------------------------------------------------------------
    void TableDataWindow::CaptureMouse()
    {
        Window::CaptureMouse();
    }
    //------------------------------------------------------------------------------------------------------------------
    void TableDataWindow::ReleaseMouse(  )
    {
        Window::ReleaseMouse();
    }
    // -----------------------------------------------------------------------
    long TableDataWindow::Notify(NotifyEvent& rNEvt )
    {
        long nDone = 0;
        if ( rNEvt.GetType() == EVENT_COMMAND )
        {
            const CommandEvent& rCEvt = *rNEvt.GetCommandEvent();
            if ( rCEvt.GetCommand() == COMMAND_WHEEL )
            {
                const CommandWheelData* pData = rCEvt.GetWheelData();
                if( !pData->GetModifier() && ( pData->GetMode() == COMMAND_WHEEL_SCROLL ) )
                {
                    nDone = HandleScrollCommand( rCEvt, m_rTableControl.getHorzScrollbar(), m_rTableControl.getVertScrollbar() );
                }
            }
        }
        return nDone ? nDone : Window::Notify( rNEvt );
    }
//......................................................................................................................
} } // namespace svt::table
//......................................................................................................................
<|endoftext|>


<commit_before>// Copyright (c) 2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <blockfilter.h>
#include <crypto/siphash.h>
#include <hash.h>
#include <primitives/transaction.h>
#include <script/script.h>
#include <streams.h>

/// SerType used to serialize parameters in GCS filter encoding.
static constexpr int GCS_SER_TYPE = SER_NETWORK;

/// Protocol version used to serialize parameters in GCS filter encoding.
static constexpr int GCS_SER_VERSION = 0;

template <typename OStream>
static void GolombRiceEncode(BitStreamWriter<OStream>& bitwriter, uint8_t P, uint64_t x)
{
    // Write quotient as unary-encoded: q 1's followed by one 0.
    uint64_t q = x >> P;
    while (q > 0) {
        int nbits = q <= 64 ? static_cast<int>(q) : 64;
        bitwriter.Write(~0ULL, nbits);
        q -= nbits;
    }
    bitwriter.Write(0, 1);

    // Write the remainder in P bits. Since the remainder is just the bottom
    // P bits of x, there is no need to mask first.
    bitwriter.Write(x, P);
}

template <typename IStream>
static uint64_t GolombRiceDecode(BitStreamReader<IStream>& bitreader, uint8_t P)
{
    // Read unary-encoded quotient: q 1's followed by one 0.
    uint64_t q = 0;
    while (bitreader.Read(1) == 1) {
        ++q;
    }

    uint64_t r = bitreader.Read(P);

    return (q << P) + r;
}

// Map a value x that is uniformly distributed in the range [0, 2^64) to a
// value uniformly distributed in [0, n) by returning the upper 64 bits of
// x * n.
//
// See: https://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/
static uint64_t MapIntoRange(uint64_t x, uint64_t n)
{
#ifdef __SIZEOF_INT128__
    return (static_cast<unsigned __int128>(x) * static_cast<unsigned __int128>(n)) >> 64;
#else
    // To perform the calculation on 64-bit numbers without losing the
    // result to overflow, split the numbers into the most significant and
    // least significant 32 bits and perform multiplication piece-wise.
    //
    // See: https://stackoverflow.com/a/26855440
    uint64_t x_hi = x >> 32;
    uint64_t x_lo = x & 0xFFFFFFFF;
    uint64_t n_hi = n >> 32;
    uint64_t n_lo = n & 0xFFFFFFFF;

    uint64_t ac = x_hi * n_hi;
    uint64_t ad = x_hi * n_lo;
    uint64_t bc = x_lo * n_hi;
    uint64_t bd = x_lo * n_lo;

    uint64_t mid34 = (bd >> 32) + (bc & 0xFFFFFFFF) + (ad & 0xFFFFFFFF);
    uint64_t upper64 = ac + (bc >> 32) + (ad >> 32) + (mid34 >> 32);
    return upper64;
#endif
}

uint64_t GCSFilter::HashToRange(const Element& element) const
{
    uint64_t hash = CSipHasher(m_params.m_siphash_k0, m_params.m_siphash_k1)
        .Write(element.data(), element.size())
        .Finalize();
    return MapIntoRange(hash, m_F);
}

std::vector<uint64_t> GCSFilter::BuildHashedSet(const ElementSet& elements) const
{
    std::vector<uint64_t> hashed_elements;
    hashed_elements.reserve(elements.size());
    for (const Element& element : elements) {
        hashed_elements.push_back(HashToRange(element));
    }
    std::sort(hashed_elements.begin(), hashed_elements.end());
    return hashed_elements;
}

GCSFilter::GCSFilter(const Params& params)
    : m_params(params), m_N(0), m_F(0), m_encoded{0}
{}

GCSFilter::GCSFilter(const Params& params, std::vector<unsigned char> encoded_filter)
    : m_params(params), m_encoded(std::move(encoded_filter))
{
    VectorReader stream(GCS_SER_TYPE, GCS_SER_VERSION, m_encoded, 0);

    uint64_t N = ReadCompactSize(stream);
    m_N = static_cast<uint32_t>(N);
    if (m_N != N) {
        throw std::ios_base::failure("N must be <2^32");
    }
    m_F = static_cast<uint64_t>(m_N) * static_cast<uint64_t>(m_params.m_M);

    // Verify that the encoded filter contains exactly N elements. If it has too much or too little
    // data, a std::ios_base::failure exception will be raised.
    BitStreamReader<VectorReader> bitreader(stream);
    for (uint64_t i = 0; i < m_N; ++i) {
        GolombRiceDecode(bitreader, m_params.m_P);
    }
    if (!stream.empty()) {
        throw std::ios_base::failure("encoded_filter contains excess data");
    }
}

GCSFilter::GCSFilter(const Params& params, const ElementSet& elements)
    : m_params(params)
{
    size_t N = elements.size();
    m_N = static_cast<uint32_t>(N);
    if (m_N != N) {
        throw std::invalid_argument("N must be <2^32");
    }
    m_F = static_cast<uint64_t>(m_N) * static_cast<uint64_t>(m_params.m_M);

    CVectorWriter stream(GCS_SER_TYPE, GCS_SER_VERSION, m_encoded, 0);

    WriteCompactSize(stream, m_N);

    if (elements.empty()) {
        return;
    }

    BitStreamWriter<CVectorWriter> bitwriter(stream);

    uint64_t last_value = 0;
    for (uint64_t value : BuildHashedSet(elements)) {
        uint64_t delta = value - last_value;
        GolombRiceEncode(bitwriter, m_params.m_P, delta);
        last_value = value;
    }

    bitwriter.Flush();
}

bool GCSFilter::MatchInternal(const uint64_t* element_hashes, size_t size) const
{
    VectorReader stream(GCS_SER_TYPE, GCS_SER_VERSION, m_encoded, 0);

    // Seek forward by size of N
    uint64_t N = ReadCompactSize(stream);
    assert(N == m_N);

    BitStreamReader<VectorReader> bitreader(stream);

    uint64_t value = 0;
    size_t hashes_index = 0;
    for (uint32_t i = 0; i < m_N; ++i) {
        uint64_t delta = GolombRiceDecode(bitreader, m_params.m_P);
        value += delta;

        while (true) {
            if (hashes_index == size) {
                return false;
            } else if (element_hashes[hashes_index] == value) {
                return true;
            } else if (element_hashes[hashes_index] > value) {
                break;
            }

            hashes_index++;
        }
    }

    return false;
}

bool GCSFilter::Match(const Element& element) const
{
    uint64_t query = HashToRange(element);
    return MatchInternal(&query, 1);
}

bool GCSFilter::MatchAny(const ElementSet& elements) const
{
    const std::vector<uint64_t> queries = BuildHashedSet(elements);
    return MatchInternal(queries.data(), queries.size());
}

static GCSFilter::ElementSet BasicFilterElements(const CBlock& block,
                                                 const CBlockUndo& block_undo)
{
    GCSFilter::ElementSet elements;

    for (const CTransactionRef& tx : block.vtx) {
        for (const CTxOut& txout : tx->vout) {
            const CScript& script = txout.scriptPubKey;
            if (script.empty() || script[0] == OP_RETURN) continue;
            elements.emplace(script.begin(), script.end());
        }
    }

    for (const CTxUndo& tx_undo : block_undo.vtxundo) {
        for (const Coin& prevout : tx_undo.vprevout) {
            const CScript& script = prevout.out.scriptPubKey;
            if (script.empty()) continue;
            elements.emplace(script.begin(), script.end());
        }
    }

    return elements;
}

BlockFilter::BlockFilter(BlockFilterType filter_type, const uint256& block_hash,
                         std::vector<unsigned char> filter)
    : m_filter_type(filter_type), m_block_hash(block_hash)
{
    GCSFilter::Params params;
    if (!BuildParams(params)) {
        throw std::invalid_argument("unknown filter_type");
    }
    m_filter = GCSFilter(params, std::move(filter));
}

BlockFilter::BlockFilter(BlockFilterType filter_type, const CBlock& block, const CBlockUndo& block_undo)
    : m_filter_type(filter_type), m_block_hash(block.GetHash())
{
    GCSFilter::Params params;
    if (!BuildParams(params)) {
        throw std::invalid_argument("unknown filter_type");
    }
    m_filter = GCSFilter(params, BasicFilterElements(block, block_undo));
}

bool BlockFilter::BuildParams(GCSFilter::Params& params) const
{
    switch (m_filter_type) {
    case BlockFilterType::BASIC:
        params.m_siphash_k0 = m_block_hash.GetUint64(0);
        params.m_siphash_k1 = m_block_hash.GetUint64(1);
        params.m_P = BASIC_FILTER_P;
        params.m_M = BASIC_FILTER_M;
        break;

    default:
        return false;
    }

    return true;
}

uint256 BlockFilter::GetHash() const
{
    const std::vector<unsigned char>& data = GetEncodedFilter();

    uint256 result;
    CHash256().Write(data.data(), data.size()).Finalize(result.begin());
    return result;
}

uint256 BlockFilter::ComputeHeader(const uint256& prev_header) const
{
    const uint256& filter_hash = GetHash();

    uint256 result;
    CHash256()
        .Write(filter_hash.begin(), filter_hash.size())
        .Write(prev_header.begin(), prev_header.size())
        .Finalize(result.begin());
    return result;
}
<commit_msg>blockfilter: Remove default clause in switch statement.<commit_after>// Copyright (c) 2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <blockfilter.h>
#include <crypto/siphash.h>
#include <hash.h>
#include <primitives/transaction.h>
#include <script/script.h>
#include <streams.h>

/// SerType used to serialize parameters in GCS filter encoding.
static constexpr int GCS_SER_TYPE = SER_NETWORK;

/// Protocol version used to serialize parameters in GCS filter encoding.
static constexpr int GCS_SER_VERSION = 0;

template <typename OStream>
static void GolombRiceEncode(BitStreamWriter<OStream>& bitwriter, uint8_t P, uint64_t x)
{
    // Write quotient as unary-encoded: q 1's followed by one 0.
    uint64_t q = x >> P;
    while (q > 0) {
        int nbits = q <= 64 ? static_cast<int>(q) : 64;
        bitwriter.Write(~0ULL, nbits);
        q -= nbits;
    }
    bitwriter.Write(0, 1);

    // Write the remainder in P bits. Since the remainder is just the bottom
    // P bits of x, there is no need to mask first.
    bitwriter.Write(x, P);
}

template <typename IStream>
static uint64_t GolombRiceDecode(BitStreamReader<IStream>& bitreader, uint8_t P)
{
    // Read unary-encoded quotient: q 1's followed by one 0.
    uint64_t q = 0;
    while (bitreader.Read(1) == 1) {
        ++q;
    }

    uint64_t r = bitreader.Read(P);

    return (q << P) + r;
}

// Map a value x that is uniformly distributed in the range [0, 2^64) to a
// value uniformly distributed in [0, n) by returning the upper 64 bits of
// x * n.
//
// See: https://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/
static uint64_t MapIntoRange(uint64_t x, uint64_t n)
{
#ifdef __SIZEOF_INT128__
    return (static_cast<unsigned __int128>(x) * static_cast<unsigned __int128>(n)) >> 64;
#else
    // To perform the calculation on 64-bit numbers without losing the
    // result to overflow, split the numbers into the most significant and
    // least significant 32 bits and perform multiplication piece-wise.
    //
    // See: https://stackoverflow.com/a/26855440
    uint64_t x_hi = x >> 32;
    uint64_t x_lo = x & 0xFFFFFFFF;
    uint64_t n_hi = n >> 32;
    uint64_t n_lo = n & 0xFFFFFFFF;

    uint64_t ac = x_hi * n_hi;
    uint64_t ad = x_hi * n_lo;
    uint64_t bc = x_lo * n_hi;
    uint64_t bd = x_lo * n_lo;

    uint64_t mid34 = (bd >> 32) + (bc & 0xFFFFFFFF) + (ad & 0xFFFFFFFF);
    uint64_t upper64 = ac + (bc >> 32) + (ad >> 32) + (mid34 >> 32);
    return upper64;
#endif
}

uint64_t GCSFilter::HashToRange(const Element& element) const
{
    uint64_t hash = CSipHasher(m_params.m_siphash_k0, m_params.m_siphash_k1)
        .Write(element.data(), element.size())
        .Finalize();
    return MapIntoRange(hash, m_F);
}

std::vector<uint64_t> GCSFilter::BuildHashedSet(const ElementSet& elements) const
{
    std::vector<uint64_t> hashed_elements;
    hashed_elements.reserve(elements.size());
    for (const Element& element : elements) {
        hashed_elements.push_back(HashToRange(element));
    }
    std::sort(hashed_elements.begin(), hashed_elements.end());
    return hashed_elements;
}

GCSFilter::GCSFilter(const Params& params)
    : m_params(params), m_N(0), m_F(0), m_encoded{0}
{}

GCSFilter::GCSFilter(const Params& params, std::vector<unsigned char> encoded_filter)
    : m_params(params), m_encoded(std::move(encoded_filter))
{
    VectorReader stream(GCS_SER_TYPE, GCS_SER_VERSION, m_encoded, 0);

    uint64_t N = ReadCompactSize(stream);
    m_N = static_cast<uint32_t>(N);
    if (m_N != N) {
        throw std::ios_base::failure("N must be <2^32");
    }
    m_F = static_cast<uint64_t>(m_N) * static_cast<uint64_t>(m_params.m_M);

    // Verify that the encoded filter contains exactly N elements. If it has too much or too little
    // data, a std::ios_base::failure exception will be raised.
    BitStreamReader<VectorReader> bitreader(stream);
    for (uint64_t i = 0; i < m_N; ++i) {
        GolombRiceDecode(bitreader, m_params.m_P);
    }
    if (!stream.empty()) {
        throw std::ios_base::failure("encoded_filter contains excess data");
    }
}

GCSFilter::GCSFilter(const Params& params, const ElementSet& elements)
    : m_params(params)
{
    size_t N = elements.size();
    m_N = static_cast<uint32_t>(N);
    if (m_N != N) {
        throw std::invalid_argument("N must be <2^32");
    }
    m_F = static_cast<uint64_t>(m_N) * static_cast<uint64_t>(m_params.m_M);

    CVectorWriter stream(GCS_SER_TYPE, GCS_SER_VERSION, m_encoded, 0);

    WriteCompactSize(stream, m_N);

    if (elements.empty()) {
        return;
    }

    BitStreamWriter<CVectorWriter> bitwriter(stream);

    uint64_t last_value = 0;
    for (uint64_t value : BuildHashedSet(elements)) {
        uint64_t delta = value - last_value;
        GolombRiceEncode(bitwriter, m_params.m_P, delta);
        last_value = value;
    }

    bitwriter.Flush();
}

bool GCSFilter::MatchInternal(const uint64_t* element_hashes, size_t size) const
{
    VectorReader stream(GCS_SER_TYPE, GCS_SER_VERSION, m_encoded, 0);

    // Seek forward by size of N
    uint64_t N = ReadCompactSize(stream);
    assert(N == m_N);

    BitStreamReader<VectorReader> bitreader(stream);

    uint64_t value = 0;
    size_t hashes_index = 0;
    for (uint32_t i = 0; i < m_N; ++i) {
        uint64_t delta = GolombRiceDecode(bitreader, m_params.m_P);
        value += delta;

        while (true) {
            if (hashes_index == size) {
                return false;
            } else if (element_hashes[hashes_index] == value) {
                return true;
            } else if (element_hashes[hashes_index] > value) {
                break;
            }

            hashes_index++;
        }
    }

    return false;
}

bool GCSFilter::Match(const Element& element) const
{
    uint64_t query = HashToRange(element);
    return MatchInternal(&query, 1);
}

bool GCSFilter::MatchAny(const ElementSet& elements) const
{
    const std::vector<uint64_t> queries = BuildHashedSet(elements);
    return MatchInternal(queries.data(), queries.size());
}

static GCSFilter::ElementSet BasicFilterElements(const CBlock& block,
                                                 const CBlockUndo& block_undo)
{
    GCSFilter::ElementSet elements;

    for (const CTransactionRef& tx : block.vtx) {
        for (const CTxOut& txout : tx->vout) {
            const CScript& script = txout.scriptPubKey;
            if (script.empty() || script[0] == OP_RETURN) continue;
            elements.emplace(script.begin(), script.end());
        }
    }

    for (const CTxUndo& tx_undo : block_undo.vtxundo) {
        for (const Coin& prevout : tx_undo.vprevout) {
            const CScript& script = prevout.out.scriptPubKey;
            if (script.empty()) continue;
            elements.emplace(script.begin(), script.end());
        }
    }

    return elements;
}

BlockFilter::BlockFilter(BlockFilterType filter_type, const uint256& block_hash,
                         std::vector<unsigned char> filter)
    : m_filter_type(filter_type), m_block_hash(block_hash)
{
    GCSFilter::Params params;
    if (!BuildParams(params)) {
        throw std::invalid_argument("unknown filter_type");
    }
    m_filter = GCSFilter(params, std::move(filter));
}

BlockFilter::BlockFilter(BlockFilterType filter_type, const CBlock& block, const CBlockUndo& block_undo)
    : m_filter_type(filter_type), m_block_hash(block.GetHash())
{
    GCSFilter::Params params;
    if (!BuildParams(params)) {
        throw std::invalid_argument("unknown filter_type");
    }
    m_filter = GCSFilter(params, BasicFilterElements(block, block_undo));
}

bool BlockFilter::BuildParams(GCSFilter::Params& params) const
{
    switch (m_filter_type) {
    case BlockFilterType::BASIC:
        params.m_siphash_k0 = m_block_hash.GetUint64(0);
        params.m_siphash_k1 = m_block_hash.GetUint64(1);
        params.m_P = BASIC_FILTER_P;
        params.m_M = BASIC_FILTER_M;
        return true;
    }

    return false;
}

uint256 BlockFilter::GetHash() const
{
    const std::vector<unsigned char>& data = GetEncodedFilter();

    uint256 result;
    CHash256().Write(data.data(), data.size()).Finalize(result.begin());
    return result;
}

uint256 BlockFilter::ComputeHeader(const uint256& prev_header) const
{
    const uint256& filter_hash = GetHash();

    uint256 result;
    CHash256()
        .Write(filter_hash.begin(), filter_hash.size())
        .Write(prev_header.begin(), prev_header.size())
        .Finalize(result.begin());
    return result;
}
<|endoftext|>


<commit_before>#include "nbind/nbind.h"
#include "nbind/api.h"
#include <X11/Xlib.h>
#include "xdisplay.h"
#include "screen.h"

ScreenInfo::Screen ScreenInfo::Screen::main() {
	Display *display = XGetMainDisplay();
	const int screen = DefaultScreen(display);

	return ScreenInfo::Screen(
		(size_t)DisplayWidth(display, screen),
		(size_t)DisplayHeight(display, screen),
		XDefaultDepth(display, screen)
	);
};

std::vector<ScreenInfo::Screen> ScreenInfo::Screen::all() {
	std::vector<ScreenInfo::Screen> result;

	Display *display = XGetMainDisplay();
	const int screenCount = XScreenCount(display);

	for (int index  = 0; index < screenCount; index++) {
		// ::Screen * screen = XScreenOfDisplay(display, index);
		result.push_back(ScreenInfo::Screen(
			(size_t) DisplayWidth(display, index),
			(size_t) DisplayHeight(display, index),
			XDefaultDepth(display, index)
		));
	}

	return result;
};
<commit_msg>base1<commit_after>#include "nbind/nbind.h"
#include "nbind/api.h"
#include <X11/Xlib.h>
#include "xdisplay.h"
#include "screen.h"

ScreenInfo::Screen ScreenInfo::Screen::main() {
	Display *display = XGetMainDisplay();
	const int screen = DefaultScreen(display);

	return ScreenInfo::Screen(
		(size_t)DisplayWidth(display, screen),
		(size_t)DisplayHeight(display, screen),
		XDefaultDepth(display, screen)
	);
};

std::vector<ScreenInfo::Screen> ScreenInfo::Screen::all() {
	std::vector<ScreenInfo::Screen> result;

	Display *display = XGetMainDisplay();
	const int screenCount = XScreenCount(display);

	for (int index  = 1; index <= screenCount; index++) {
		// ::Screen * screen = XScreenOfDisplay(display, index);
		result.push_back(ScreenInfo::Screen(
			(size_t) DisplayWidth(display, index),
			(size_t) DisplayHeight(display, index),
			XDefaultDepth(display, index)
		));
	}

	return result;
};
<|endoftext|>