<commit_before>// Copyright (C) 2007-2013  CEA/DEN, EDF R&D
//
// 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.
//
// 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
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
// Author : Anthony Geay (CEA/DEN)

#ifndef __PARAMEDMEM_MEDCOUPLINGPOINTSET_HXX__
#define __PARAMEDMEM_MEDCOUPLINGPOINTSET_HXX__

#include "MEDCoupling.hxx"
#include "MEDCouplingMesh.hxx"

#include <vector>

namespace INTERP_KERNEL
{
  class DirectedBoundingBox;
}

namespace ParaMEDMEM
{
  class DataArrayInt;
  class DataArrayDouble;

  /*!
   * This class is abstract and not instanciable.
   * ParaMEDMEM::MEDCouplingUMesh class inherits from this class.
   * This class aggregates an array '_coords' containing nodes coordinates.
   * So all operations on coordinates are managed by this class.
   * This is the case for example for following methods :
   * rotation, translation, scaling, getNodeIdsNearPoint, boundingbox...
   */
  class MEDCOUPLING_EXPORT MEDCouplingPointSet : public MEDCouplingMesh
  {
  protected:
    MEDCouplingPointSet();
    MEDCouplingPointSet(const MEDCouplingPointSet& other, bool deepCopy);
    ~MEDCouplingPointSet();
  public:
    void updateTime() const;
    std::size_t getHeapMemorySize() const;
    int getNumberOfNodes() const;
    int getSpaceDimension() const;
    void setCoords(const DataArrayDouble *coords);
    const DataArrayDouble *getCoords() const { return _coords; }
    DataArrayDouble *getCoords() { return _coords; }
    DataArrayDouble *getCoordinatesAndOwner() const;
    void copyTinyStringsFrom(const MEDCouplingMesh *other) throw(INTERP_KERNEL::Exception);
    bool isEqualIfNotWhy(const MEDCouplingMesh *other, double prec, std::string& reason) const throw(INTERP_KERNEL::Exception);
    bool isEqualWithoutConsideringStr(const MEDCouplingMesh *other, double prec) const;
    void checkFastEquivalWith(const MEDCouplingMesh *other, double prec) const throw(INTERP_KERNEL::Exception);
    void checkDeepEquivalWith(const MEDCouplingMesh *other, int cellCompPol, double prec,
                              DataArrayInt *&cellCor, DataArrayInt *&nodeCor) const throw(INTERP_KERNEL::Exception);
    void checkDeepEquivalOnSameNodesWith(const MEDCouplingMesh *other, int cellCompPol, double prec,
                                         DataArrayInt *&cellCor) const throw(INTERP_KERNEL::Exception);
    bool areCoordsEqualIfNotWhy(const MEDCouplingPointSet& other, double prec, std::string& reason) const;
    bool areCoordsEqual(const MEDCouplingPointSet& other, double prec) const;
    bool areCoordsEqualWithoutConsideringStr(const MEDCouplingPointSet& other, double prec) const;
    virtual MEDCouplingPointSet *deepCpyConnectivityOnly() const throw(INTERP_KERNEL::Exception) = 0;
    virtual void shallowCopyConnectivityFrom(const MEDCouplingPointSet *other) throw(INTERP_KERNEL::Exception) = 0;
    virtual DataArrayInt *mergeNodes(double precision, bool& areNodesMerged, int& newNbOfNodes);
    virtual DataArrayInt *mergeNodes2(double precision, bool& areNodesMerged, int& newNbOfNodes);
    virtual MEDCouplingPointSet *mergeMyselfWithOnSameCoords(const MEDCouplingPointSet *other) const = 0;
    void getCoordinatesOfNode(int nodeId, std::vector<double>& coo) const throw(INTERP_KERNEL::Exception);
    DataArrayInt *buildPermArrayForMergeNode(double precision, int limitNodeId, bool& areNodesMerged, int& newNbOfNodes) const;
    DataArrayInt *getNodeIdsNearPoint(const double *pos, double eps) const throw(INTERP_KERNEL::Exception);
    void getNodeIdsNearPoints(const double *pos, int nbOfPoints, double eps, DataArrayInt *& c, DataArrayInt *& cI) const throw(INTERP_KERNEL::Exception);
    void findCommonNodes(double prec, int limitNodeId, DataArrayInt *&comm, DataArrayInt *&commIndex) const;
    virtual void findCommonCells(int compType, int startCellId, DataArrayInt *& commonCellsArr, DataArrayInt *& commonCellsIArr) const throw(INTERP_KERNEL::Exception) = 0;
    DataArrayInt *buildNewNumberingFromCommonNodesFormat(const DataArrayInt *comm, const DataArrayInt *commIndex,
                                                         int& newNbOfNodes) const;
    void getBoundingBox(double *bbox) const throw(INTERP_KERNEL::Exception);
    void zipCoords();
    double getCaracteristicDimension() const;
    void recenterForMaxPrecision(double eps) throw(INTERP_KERNEL::Exception);
    void rotate(const double *center, const double *vector, double angle);
    void translate(const double *vector);
    void scale(const double *point, double factor);
    void changeSpaceDimension(int newSpaceDim, double dftVal=0.) throw(INTERP_KERNEL::Exception);
    void tryToShareSameCoords(const MEDCouplingPointSet& other, double epsilon) throw(INTERP_KERNEL::Exception);
    void duplicateNodesInCoords(const int *nodeIdsToDuplicateBg, const int *nodeIdsToDuplicateEnd) throw(INTERP_KERNEL::Exception);
    virtual void tryToShareSameCoordsPermute(const MEDCouplingPointSet& other, double epsilon) throw(INTERP_KERNEL::Exception);
    void findNodesOnPlane(const double *pt, const double *vec, double eps, std::vector<int>& nodes) const throw(INTERP_KERNEL::Exception);
    void findNodesOnLine(const double *pt, const double *vec, double eps, std::vector<int>& nodes) const throw(INTERP_KERNEL::Exception);
    static DataArrayDouble *MergeNodesArray(const MEDCouplingPointSet *m1, const MEDCouplingPointSet *m2) throw(INTERP_KERNEL::Exception);
    static DataArrayDouble *MergeNodesArray(const std::vector<const MEDCouplingPointSet *>& ms) throw(INTERP_KERNEL::Exception);
    static MEDCouplingPointSet *BuildInstanceFromMeshType(MEDCouplingMeshType type);
    static void Rotate2DAlg(const double *center, double angle, int nbNodes, double *coords);
    static void Rotate3DAlg(const double *center, const double *vect, double angle, int nbNodes, double *coords);
    MEDCouplingMesh *buildPart(const int *start, const int *end) const;
    MEDCouplingMesh *buildPartAndReduceNodes(const int *start, const int *end, DataArrayInt*& arr) const;
    MEDCouplingMesh *buildPartRange(int beginCellIds, int endCellIds, int stepCellIds) const throw(INTERP_KERNEL::Exception);
    MEDCouplingMesh *buildPartRangeAndReduceNodes(int beginCellIds, int endCellIds, int stepCellIds, int& beginOut, int& endOut, int& stepOut, DataArrayInt*& arr) const throw(INTERP_KERNEL::Exception);
    DataArrayInt *getCellIdsFullyIncludedInNodeIds(const int *partBg, const int *partEnd) const;
    DataArrayInt *getCellIdsLyingOnNodes(const int *begin, const int *end, bool fullyIn) const;
    virtual MEDCouplingPointSet *buildPartOfMySelf(const int *start, const int *end, bool keepCoords=true) const;
    virtual MEDCouplingPointSet *buildPartOfMySelf2(int start, int end, int step, bool keepCoords=true) const throw(INTERP_KERNEL::Exception);
    virtual MEDCouplingPointSet *buildPartOfMySelfKeepCoords(const int *begin, const int *end) const = 0;
    virtual MEDCouplingPointSet *buildPartOfMySelfKeepCoords2(int start, int end, int step) const = 0;
    virtual MEDCouplingPointSet *buildPartOfMySelfNode(const int *start, const int *end, bool fullyIn) const;
    virtual MEDCouplingPointSet *buildFacePartOfMySelfNode(const int *start, const int *end, bool fullyIn) const = 0;
    virtual DataArrayInt *findBoundaryNodes() const = 0;
    virtual MEDCouplingPointSet *buildBoundaryMesh(bool keepCoords) const = 0;
    virtual DataArrayInt *getNodeIdsInUse(int& nbrOfNodesInUse) const throw(INTERP_KERNEL::Exception) = 0;
    virtual void fillCellIdsToKeepFromNodeIds(const int *begin, const int *end, bool fullyIn, DataArrayInt *&cellIdsKeptArr) const = 0;
    virtual void renumberNodesInConn(const int *newNodeNumbersO2N) = 0;
    virtual void renumberNodes(const int *newNodeNumbers, int newNbOfNodes);
    virtual void renumberNodes2(const int *newNodeNumbers, int newNbOfNodes);
    virtual bool isEmptyMesh(const std::vector<int>& tinyInfo) const = 0;
    virtual void checkFullyDefined() const throw(INTERP_KERNEL::Exception) = 0;
    void getTinySerializationInformation(std::vector<double>& tinyInfoD, std::vector<int>& tinyInfo, std::vector<std::string>& littleStrings) const;
    void resizeForUnserialization(const std::vector<int>& tinyInfo, DataArrayInt *a1, DataArrayDouble *a2, std::vector<std::string>& littleStrings) const;
    void serialize(DataArrayInt *&a1, DataArrayDouble *&a2) const;
    void unserialization(const std::vector<double>& tinyInfoD, const std::vector<int>& tinyInfo, const DataArrayInt *a1, DataArrayDouble *a2,
                         const std::vector<std::string>& littleStrings);
    virtual DataArrayInt *getCellsInBoundingBox(const double *bbox, double eps) const = 0;
    virtual DataArrayInt *getCellsInBoundingBox(const INTERP_KERNEL::DirectedBoundingBox& bbox, double eps) = 0;
    virtual DataArrayInt *zipCoordsTraducer() throw(INTERP_KERNEL::Exception);
    virtual DataArrayInt *zipConnectivityTraducer(int compType, int startCellId=0) throw(INTERP_KERNEL::Exception);
    virtual void getReverseNodalConnectivity(DataArrayInt *revNodal, DataArrayInt *revNodalIndx) const throw(INTERP_KERNEL::Exception) = 0;
    //tools
  public:
    MEDCOUPLING_EXPORT bool areCellsFrom2MeshEqual(const MEDCouplingPointSet *other, int cellId, double prec) const;
  protected:
    void checkCoherency() const throw(INTERP_KERNEL::Exception);
    static bool intersectsBoundingBox(const double* bb1, const double* bb2, int dim, double eps);
    static bool intersectsBoundingBox(const INTERP_KERNEL::DirectedBoundingBox& bb1, const double* bb2, int dim, double eps);
    void rotate2D(const double *center, double angle);
    void rotate3D(const double *center, const double *vect, double angle);
    void project2DCellOnXY(const int *startConn, const int *endConn, std::vector<double>& res) const;
    static bool isButterfly2DCell(const std::vector<double>& res, bool isQuad, double eps);
  protected:
    DataArrayDouble *_coords;
  };
}

#endif
<commit_msg>windows porting<commit_after>// Copyright (C) 2007-2013  CEA/DEN, EDF R&D
//
// 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.
//
// 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
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
// Author : Anthony Geay (CEA/DEN)

#ifndef __PARAMEDMEM_MEDCOUPLINGPOINTSET_HXX__
#define __PARAMEDMEM_MEDCOUPLINGPOINTSET_HXX__

#include "MEDCoupling.hxx"
#include "MEDCouplingMesh.hxx"

#include <vector>

namespace INTERP_KERNEL
{
  class DirectedBoundingBox;
}

namespace ParaMEDMEM
{
  class DataArrayInt;
  class DataArrayDouble;

  /*!
   * This class is abstract and not instanciable.
   * ParaMEDMEM::MEDCouplingUMesh class inherits from this class.
   * This class aggregates an array '_coords' containing nodes coordinates.
   * So all operations on coordinates are managed by this class.
   * This is the case for example for following methods :
   * rotation, translation, scaling, getNodeIdsNearPoint, boundingbox...
   */
  class MEDCOUPLING_EXPORT MEDCouplingPointSet : public MEDCouplingMesh
  {
  protected:
    MEDCouplingPointSet();
    MEDCouplingPointSet(const MEDCouplingPointSet& other, bool deepCopy);
    ~MEDCouplingPointSet();
  public:
    void updateTime() const;
    std::size_t getHeapMemorySize() const;
    int getNumberOfNodes() const;
    int getSpaceDimension() const;
    void setCoords(const DataArrayDouble *coords);
    const DataArrayDouble *getCoords() const { return _coords; }
    DataArrayDouble *getCoords() { return _coords; }
    DataArrayDouble *getCoordinatesAndOwner() const;
    void copyTinyStringsFrom(const MEDCouplingMesh *other) throw(INTERP_KERNEL::Exception);
    bool isEqualIfNotWhy(const MEDCouplingMesh *other, double prec, std::string& reason) const throw(INTERP_KERNEL::Exception);
    bool isEqualWithoutConsideringStr(const MEDCouplingMesh *other, double prec) const;
    void checkFastEquivalWith(const MEDCouplingMesh *other, double prec) const throw(INTERP_KERNEL::Exception);
    void checkDeepEquivalWith(const MEDCouplingMesh *other, int cellCompPol, double prec,
                              DataArrayInt *&cellCor, DataArrayInt *&nodeCor) const throw(INTERP_KERNEL::Exception);
    void checkDeepEquivalOnSameNodesWith(const MEDCouplingMesh *other, int cellCompPol, double prec,
                                         DataArrayInt *&cellCor) const throw(INTERP_KERNEL::Exception);
    bool areCoordsEqualIfNotWhy(const MEDCouplingPointSet& other, double prec, std::string& reason) const;
    bool areCoordsEqual(const MEDCouplingPointSet& other, double prec) const;
    bool areCoordsEqualWithoutConsideringStr(const MEDCouplingPointSet& other, double prec) const;
    virtual MEDCouplingPointSet *deepCpyConnectivityOnly() const throw(INTERP_KERNEL::Exception) = 0;
    virtual void shallowCopyConnectivityFrom(const MEDCouplingPointSet *other) throw(INTERP_KERNEL::Exception) = 0;
    virtual DataArrayInt *mergeNodes(double precision, bool& areNodesMerged, int& newNbOfNodes);
    virtual DataArrayInt *mergeNodes2(double precision, bool& areNodesMerged, int& newNbOfNodes);
    virtual MEDCouplingPointSet *mergeMyselfWithOnSameCoords(const MEDCouplingPointSet *other) const = 0;
    void getCoordinatesOfNode(int nodeId, std::vector<double>& coo) const throw(INTERP_KERNEL::Exception);
    DataArrayInt *buildPermArrayForMergeNode(double precision, int limitNodeId, bool& areNodesMerged, int& newNbOfNodes) const;
    DataArrayInt *getNodeIdsNearPoint(const double *pos, double eps) const throw(INTERP_KERNEL::Exception);
    void getNodeIdsNearPoints(const double *pos, int nbOfPoints, double eps, DataArrayInt *& c, DataArrayInt *& cI) const throw(INTERP_KERNEL::Exception);
    void findCommonNodes(double prec, int limitNodeId, DataArrayInt *&comm, DataArrayInt *&commIndex) const;
    virtual void findCommonCells(int compType, int startCellId, DataArrayInt *& commonCellsArr, DataArrayInt *& commonCellsIArr) const throw(INTERP_KERNEL::Exception) = 0;
    DataArrayInt *buildNewNumberingFromCommonNodesFormat(const DataArrayInt *comm, const DataArrayInt *commIndex,
                                                         int& newNbOfNodes) const;
    void getBoundingBox(double *bbox) const throw(INTERP_KERNEL::Exception);
    void zipCoords();
    double getCaracteristicDimension() const;
    void recenterForMaxPrecision(double eps) throw(INTERP_KERNEL::Exception);
    void rotate(const double *center, const double *vector, double angle);
    void translate(const double *vector);
    void scale(const double *point, double factor);
    void changeSpaceDimension(int newSpaceDim, double dftVal=0.) throw(INTERP_KERNEL::Exception);
    void tryToShareSameCoords(const MEDCouplingPointSet& other, double epsilon) throw(INTERP_KERNEL::Exception);
    void duplicateNodesInCoords(const int *nodeIdsToDuplicateBg, const int *nodeIdsToDuplicateEnd) throw(INTERP_KERNEL::Exception);
    virtual void tryToShareSameCoordsPermute(const MEDCouplingPointSet& other, double epsilon) throw(INTERP_KERNEL::Exception);
    void findNodesOnPlane(const double *pt, const double *vec, double eps, std::vector<int>& nodes) const throw(INTERP_KERNEL::Exception);
    void findNodesOnLine(const double *pt, const double *vec, double eps, std::vector<int>& nodes) const throw(INTERP_KERNEL::Exception);
    static DataArrayDouble *MergeNodesArray(const MEDCouplingPointSet *m1, const MEDCouplingPointSet *m2) throw(INTERP_KERNEL::Exception);
    static DataArrayDouble *MergeNodesArray(const std::vector<const MEDCouplingPointSet *>& ms) throw(INTERP_KERNEL::Exception);
    static MEDCouplingPointSet *BuildInstanceFromMeshType(MEDCouplingMeshType type);
    static void Rotate2DAlg(const double *center, double angle, int nbNodes, double *coords);
    static void Rotate3DAlg(const double *center, const double *vect, double angle, int nbNodes, double *coords);
    MEDCouplingMesh *buildPart(const int *start, const int *end) const;
    MEDCouplingMesh *buildPartAndReduceNodes(const int *start, const int *end, DataArrayInt*& arr) const;
    MEDCouplingMesh *buildPartRange(int beginCellIds, int endCellIds, int stepCellIds) const throw(INTERP_KERNEL::Exception);
    MEDCouplingMesh *buildPartRangeAndReduceNodes(int beginCellIds, int endCellIds, int stepCellIds, int& beginOut, int& endOut, int& stepOut, DataArrayInt*& arr) const throw(INTERP_KERNEL::Exception);
    DataArrayInt *getCellIdsFullyIncludedInNodeIds(const int *partBg, const int *partEnd) const;
    DataArrayInt *getCellIdsLyingOnNodes(const int *begin, const int *end, bool fullyIn) const;
    virtual MEDCouplingPointSet *buildPartOfMySelf(const int *start, const int *end, bool keepCoords=true) const;
    virtual MEDCouplingPointSet *buildPartOfMySelf2(int start, int end, int step, bool keepCoords=true) const throw(INTERP_KERNEL::Exception);
    virtual MEDCouplingPointSet *buildPartOfMySelfKeepCoords(const int *begin, const int *end) const = 0;
    virtual MEDCouplingPointSet *buildPartOfMySelfKeepCoords2(int start, int end, int step) const = 0;
    virtual MEDCouplingPointSet *buildPartOfMySelfNode(const int *start, const int *end, bool fullyIn) const;
    virtual MEDCouplingPointSet *buildFacePartOfMySelfNode(const int *start, const int *end, bool fullyIn) const = 0;
    virtual DataArrayInt *findBoundaryNodes() const = 0;
    virtual MEDCouplingPointSet *buildBoundaryMesh(bool keepCoords) const = 0;
    virtual DataArrayInt *getNodeIdsInUse(int& nbrOfNodesInUse) const throw(INTERP_KERNEL::Exception) = 0;
    virtual void fillCellIdsToKeepFromNodeIds(const int *begin, const int *end, bool fullyIn, DataArrayInt *&cellIdsKeptArr) const = 0;
    virtual void renumberNodesInConn(const int *newNodeNumbersO2N) = 0;
    virtual void renumberNodes(const int *newNodeNumbers, int newNbOfNodes);
    virtual void renumberNodes2(const int *newNodeNumbers, int newNbOfNodes);
    virtual bool isEmptyMesh(const std::vector<int>& tinyInfo) const = 0;
    virtual void checkFullyDefined() const throw(INTERP_KERNEL::Exception) = 0;
    void getTinySerializationInformation(std::vector<double>& tinyInfoD, std::vector<int>& tinyInfo, std::vector<std::string>& littleStrings) const;
    void resizeForUnserialization(const std::vector<int>& tinyInfo, DataArrayInt *a1, DataArrayDouble *a2, std::vector<std::string>& littleStrings) const;
    void serialize(DataArrayInt *&a1, DataArrayDouble *&a2) const;
    void unserialization(const std::vector<double>& tinyInfoD, const std::vector<int>& tinyInfo, const DataArrayInt *a1, DataArrayDouble *a2,
                         const std::vector<std::string>& littleStrings);
    virtual DataArrayInt *getCellsInBoundingBox(const double *bbox, double eps) const = 0;
    virtual DataArrayInt *getCellsInBoundingBox(const INTERP_KERNEL::DirectedBoundingBox& bbox, double eps) = 0;
    virtual DataArrayInt *zipCoordsTraducer() throw(INTERP_KERNEL::Exception);
    virtual DataArrayInt *zipConnectivityTraducer(int compType, int startCellId=0) throw(INTERP_KERNEL::Exception);
    virtual void getReverseNodalConnectivity(DataArrayInt *revNodal, DataArrayInt *revNodalIndx) const throw(INTERP_KERNEL::Exception) = 0;
    //tools
  public:
    bool areCellsFrom2MeshEqual(const MEDCouplingPointSet *other, int cellId, double prec) const;
  protected:
    void checkCoherency() const throw(INTERP_KERNEL::Exception);
    static bool intersectsBoundingBox(const double* bb1, const double* bb2, int dim, double eps);
    static bool intersectsBoundingBox(const INTERP_KERNEL::DirectedBoundingBox& bb1, const double* bb2, int dim, double eps);
    void rotate2D(const double *center, double angle);
    void rotate3D(const double *center, const double *vect, double angle);
    void project2DCellOnXY(const int *startConn, const int *endConn, std::vector<double>& res) const;
    static bool isButterfly2DCell(const std::vector<double>& res, bool isQuad, double eps);
  protected:
    DataArrayDouble *_coords;
  };
}

#endif
<|endoftext|>


<commit_before>#ifndef GAUSS_LOCALIZATION_HXX
#define GAUSS_LOCALIZATION_HXX

#include <vector>
#include "MEDMEM_define.hxx"
#include "MEDMEM_Exception.hxx"
#include "MEDMEM_ArrayInterface.hxx"
#include "MEDMEM_nArray.hxx"
#include "MEDMEM_DriversDef.hxx"
#include "MEDMEM_SetInterlacingType.hxx"

using namespace std;
using namespace MEDMEM;
using namespace MED_EN;

namespace MEDMEM {

  class GAUSS_LOCALIZATION_ {
  public:
    virtual MED_EN::medModeSwitch getInterlacingType() const {return MED_EN::MED_UNDEFINED_INTERLACE;}
    virtual ~GAUSS_LOCALIZATION_() {}; //Indispensable pour dtruire le vrai objet point
  };

  template <class INTERLACING_TAG=FullInterlace> class GAUSS_LOCALIZATION;

  template <class INTERLACING_TAG> ostream & operator<< (ostream &os,
							 const GAUSS_LOCALIZATION<INTERLACING_TAG> &loc);

  template <class INTERLACING_TAG> class GAUSS_LOCALIZATION : public GAUSS_LOCALIZATION_{
  public:
    typedef  typename MEDMEM_ArrayInterface<double,INTERLACING_TAG,NoGauss>::Array ArrayNoGauss;

  protected:

    string                      _locName;
    MED_EN::medGeometryElement  _typeGeo;
    int                         _nGauss;
    ArrayNoGauss                _cooRef;
    ArrayNoGauss                _cooGauss;
    vector<double>              _wg;
    MED_EN::medModeSwitch       _interlacingType;

  public:
    friend ostream & operator<< <INTERLACING_TAG>(ostream &os,
						  const GAUSS_LOCALIZATION<INTERLACING_TAG> &loc);

    GAUSS_LOCALIZATION() throw (MEDEXCEPTION);
    GAUSS_LOCALIZATION(const string & locName,
		       const MED_EN::medGeometryElement typeGeo,
		       const int  nGauss,
		       const ArrayNoGauss & cooRef,
		       const ArrayNoGauss & cooGauss,
		       const vector<double>  & wg) throw (MEDEXCEPTION);

    GAUSS_LOCALIZATION(const string & locName,
		       const MED_EN::medGeometryElement  typeGeo,
		       const int  nGauss,
		       const double  * const cooRef,
		       const double  * const cooGauss,
		       const double  * const wg) throw (MEDEXCEPTION);

    //GAUSS_LOCALIZATION(const GAUSS_LOCALIZATION & loc); constructeur de recopie par dfaut correct
    virtual ~GAUSS_LOCALIZATION() {};
    GAUSS_LOCALIZATION & operator=(const GAUSS_LOCALIZATION & gaussLoc);
    bool operator == (const GAUSS_LOCALIZATION &loc) const;

    string          getName()    const {return _locName;}
    MED_EN::medGeometryElement getType() const {return _typeGeo;}
    int             getNbGauss() const {return _nGauss;}
    ArrayNoGauss    getRefCoo () const {return _cooRef;}     //Ces tableaux sont petits
    ArrayNoGauss    getGsCoo  () const {return _cooGauss;}   //Ces tableaux sont petits
    vector <double> getWeight () const {return _wg;}         //Ces tableaux sont petits
    inline MED_EN::medModeSwitch  getInterlacingType() const { return _interlacingType;}

  };
  template <class INTERLACING_TAG> GAUSS_LOCALIZATION<INTERLACING_TAG>::GAUSS_LOCALIZATION() throw (MEDEXCEPTION) : _typeGeo(MED_EN::MED_NONE), _nGauss(-1),
														    _interlacingType(_interlacingType( SET_INTERLACING_TYPE<INTERLACING_TAG>::_interlacingType))  {};
  template <class INTERLACING_TAG> GAUSS_LOCALIZATION<INTERLACING_TAG>::GAUSS_LOCALIZATION(const string & locName,
											   const MED_EN::medGeometryElement typeGeo,
											   const int  nGauss,
											   const ArrayNoGauss & cooRef,
											   const ArrayNoGauss & cooGauss,
											   const vector<double>  & wg)  throw (MEDEXCEPTION) :
    _locName(locName),_typeGeo(typeGeo),_nGauss(nGauss),_cooRef(cooRef),_cooGauss(cooGauss),_wg(wg),
    _interlacingType(SET_INTERLACING_TYPE<INTERLACING_TAG>::_interlacingType)
  {
    const char * LOC = "GAUSS_LOCALIZATION(locName,typeGeo, nGauss, const ArrayNoGauss & cooRef,..) : ";
    BEGIN_OF(LOC);
    if (_cooRef.getDim() != _cooGauss.getDim() )
      throw MEDEXCEPTION( LOCALIZED( STRING(LOC) <<"cooRef and cooGaus must have the same number of components")) ;

    if (_cooRef.getArraySize() != (_typeGeo%100)*(_typeGeo/100) )
      throw MEDEXCEPTION( LOCALIZED( STRING(LOC) <<"cooRef size is " << _cooRef.getArraySize()
				     << " and should be (_typeGeo%100)*(_typeGeo/100) "
				     << (_typeGeo%100)*(_typeGeo/100))) ;

    if (_cooGauss.getArraySize() != _nGauss*(_typeGeo/100) )
      throw MEDEXCEPTION( LOCALIZED( STRING(LOC) <<"cooGauss must be of size nGauss*(_typeGeo/100) "
				     << _nGauss*(_typeGeo/100) ));
    if (_wg.size() != _nGauss )
      throw MEDEXCEPTION( LOCALIZED( STRING(LOC) <<"wg must be of size nGauss "
				     << _nGauss ));

    END_OF(LOC);
  };

  template <class INTERLACING_TAG> GAUSS_LOCALIZATION<INTERLACING_TAG>::GAUSS_LOCALIZATION(const string & locName,
											   const MED_EN::medGeometryElement  typeGeo,
											   const int  nGauss,
											   const double  * const cooRef,
											   const double  * const cooGauss,
											   const double  * const wg) throw (MEDEXCEPTION) :
    _locName(locName),_typeGeo(typeGeo),_nGauss(nGauss),
    _cooRef(ArrayNoGauss(const_cast<double *>(cooRef),typeGeo/100,typeGeo%100)),
    _cooGauss(ArrayNoGauss(const_cast<double *>(cooGauss),typeGeo/100,_nGauss)),
    _wg(vector<double>(wg,wg+nGauss)),
    _interlacingType(SET_INTERLACING_TYPE<INTERLACING_TAG>::_interlacingType)
  {
    const char * LOC = "GAUSS_LOCALIZATION(locName,typeGeo, nGauss, const double * cooRef,..) :";
    BEGIN_OF(LOC);
    if (_cooRef.getDim() != _cooGauss.getDim() )
      throw MEDEXCEPTION( LOCALIZED( STRING(LOC) <<"cooRef and cooGaus must have the same number of components")) ;

    if (_cooRef.getArraySize() != (_typeGeo%100)*(_typeGeo/100) )
      throw MEDEXCEPTION( LOCALIZED( STRING(LOC) <<"cooRef must be of size (_typeGeo%100)*(_typeGeo/100) "
				     << (_typeGeo%100)*(_typeGeo/100))) ;

    if (_cooGauss.getArraySize() != _nGauss*(_typeGeo/100) )
      throw MEDEXCEPTION( LOCALIZED( STRING(LOC) <<"cooGauss must be of size nGauss*(_typeGeo/100) "
				     << _nGauss*(_typeGeo/100) ));
    if (_wg.size() != _nGauss )
      throw MEDEXCEPTION( LOCALIZED( STRING(LOC) <<"wg must be of size nGauss "
				     << _nGauss ));
    END_OF(LOC);
  };

  template <class INTERLACING_TAG> GAUSS_LOCALIZATION<INTERLACING_TAG> &
  GAUSS_LOCALIZATION<INTERLACING_TAG>::operator=(const GAUSS_LOCALIZATION & gaussLoc)
  {
    if ( this == &gaussLoc) return *this;

    _locName  = gaussLoc._locName;
    _typeGeo  = gaussLoc._typeGeo;
    _nGauss   = gaussLoc._nGauss;
    _cooRef   = ArrayNoGauss(gaussLoc._cooRef);   //utilisation de la copie superficielle par dfaut n'est pas une bonne ide
    _cooGauss = ArrayNoGauss(gaussLoc._cooGauss);  //dans l'oprateur = de MEDnArray
    _wg       = gaussLoc._wg;

    return *this;
  }

  template <class INTERLACING_TAG> bool
  GAUSS_LOCALIZATION<INTERLACING_TAG>::operator == (const GAUSS_LOCALIZATION & gaussLoc) const {
    return (
	    _locName  == gaussLoc._locName &&
	    _typeGeo  == gaussLoc._typeGeo &&
	    _nGauss   == gaussLoc._nGauss  &&
	    _cooRef   == gaussLoc._cooRef  &&   //utilisation de la copie superficielle par dfaut n'est pas une bonne ide
	    _cooGauss == gaussLoc._cooGauss &&  //dans l'oprateur = de MEDnArray
	    _wg       == gaussLoc._wg
	    );
  }

  template <class INTERLACING_TAG> ostream & MEDMEM::operator<<(ostream &os,
								const  GAUSS_LOCALIZATION<INTERLACING_TAG> &loc) {
    os << "Localization Name     : " << loc._locName << endl;
    os << "Geometric Type        : " << MED_EN::geoNames[loc._typeGeo]<< endl;
    os << "Number Of GaussPoints : " << loc._nGauss << endl;
    os << "Ref.   Element Coords : " << endl << loc._cooRef << endl;
    os << "Gauss points Coords   : " << endl << loc._cooGauss << endl;
    os << "Gauss points weigth   : " << endl ;
    for(int i=0; i<loc._wg.size();++i)
      os << "_wg[" << i << "] = " << loc._wg[i] << endl;
    return os;
  }

} //END NAMESPACE

#endif
<commit_msg>Fix for compilation error with gcc4.0.1: MEDMEM_GaussLocalization.hxx:166: error: explicit qualification in declaration of `std::ostream& MEDMEM::operator<<(std::ostream&, const MEDMEM::GAUSS_LOCALIZATION<INTERLACING_TAG>&)'.<commit_after>#ifndef GAUSS_LOCALIZATION_HXX
#define GAUSS_LOCALIZATION_HXX

#include <vector>
#include "MEDMEM_define.hxx"
#include "MEDMEM_Exception.hxx"
#include "MEDMEM_ArrayInterface.hxx"
#include "MEDMEM_nArray.hxx"
#include "MEDMEM_DriversDef.hxx"
#include "MEDMEM_SetInterlacingType.hxx"

using namespace std;
using namespace MEDMEM;
using namespace MED_EN;

namespace MEDMEM {

  class GAUSS_LOCALIZATION_ {
  public:
    virtual MED_EN::medModeSwitch getInterlacingType() const {return MED_EN::MED_UNDEFINED_INTERLACE;}
    virtual ~GAUSS_LOCALIZATION_() {}; //Indispensable pour dtruire le vrai objet point
  };

  template <class INTERLACING_TAG=FullInterlace> class GAUSS_LOCALIZATION;

  template <class INTERLACING_TAG> ostream & operator<< (ostream &os,
							 const GAUSS_LOCALIZATION<INTERLACING_TAG> &loc);

  template <class INTERLACING_TAG> class GAUSS_LOCALIZATION : public GAUSS_LOCALIZATION_{
  public:
    typedef  typename MEDMEM_ArrayInterface<double,INTERLACING_TAG,NoGauss>::Array ArrayNoGauss;

  protected:

    string                      _locName;
    MED_EN::medGeometryElement  _typeGeo;
    int                         _nGauss;
    ArrayNoGauss                _cooRef;
    ArrayNoGauss                _cooGauss;
    vector<double>              _wg;
    MED_EN::medModeSwitch       _interlacingType;

  public:
    friend ostream & operator<< <INTERLACING_TAG>(ostream &os,
						  const GAUSS_LOCALIZATION<INTERLACING_TAG> &loc);

    GAUSS_LOCALIZATION() throw (MEDEXCEPTION);
    GAUSS_LOCALIZATION(const string & locName,
		       const MED_EN::medGeometryElement typeGeo,
		       const int  nGauss,
		       const ArrayNoGauss & cooRef,
		       const ArrayNoGauss & cooGauss,
		       const vector<double>  & wg) throw (MEDEXCEPTION);

    GAUSS_LOCALIZATION(const string & locName,
		       const MED_EN::medGeometryElement  typeGeo,
		       const int  nGauss,
		       const double  * const cooRef,
		       const double  * const cooGauss,
		       const double  * const wg) throw (MEDEXCEPTION);

    //GAUSS_LOCALIZATION(const GAUSS_LOCALIZATION & loc); constructeur de recopie par dfaut correct
    virtual ~GAUSS_LOCALIZATION() {};
    GAUSS_LOCALIZATION & operator=(const GAUSS_LOCALIZATION & gaussLoc);
    bool operator == (const GAUSS_LOCALIZATION &loc) const;

    string          getName()    const {return _locName;}
    MED_EN::medGeometryElement getType() const {return _typeGeo;}
    int             getNbGauss() const {return _nGauss;}
    ArrayNoGauss    getRefCoo () const {return _cooRef;}     //Ces tableaux sont petits
    ArrayNoGauss    getGsCoo  () const {return _cooGauss;}   //Ces tableaux sont petits
    vector <double> getWeight () const {return _wg;}         //Ces tableaux sont petits
    inline MED_EN::medModeSwitch  getInterlacingType() const { return _interlacingType;}

  };
  template <class INTERLACING_TAG> GAUSS_LOCALIZATION<INTERLACING_TAG>::GAUSS_LOCALIZATION() throw (MEDEXCEPTION) : _typeGeo(MED_EN::MED_NONE), _nGauss(-1),
														    _interlacingType(_interlacingType( SET_INTERLACING_TYPE<INTERLACING_TAG>::_interlacingType))  {};
  template <class INTERLACING_TAG> GAUSS_LOCALIZATION<INTERLACING_TAG>::GAUSS_LOCALIZATION(const string & locName,
											   const MED_EN::medGeometryElement typeGeo,
											   const int  nGauss,
											   const ArrayNoGauss & cooRef,
											   const ArrayNoGauss & cooGauss,
											   const vector<double>  & wg)  throw (MEDEXCEPTION) :
    _locName(locName),_typeGeo(typeGeo),_nGauss(nGauss),_cooRef(cooRef),_cooGauss(cooGauss),_wg(wg),
    _interlacingType(SET_INTERLACING_TYPE<INTERLACING_TAG>::_interlacingType)
  {
    const char * LOC = "GAUSS_LOCALIZATION(locName,typeGeo, nGauss, const ArrayNoGauss & cooRef,..) : ";
    BEGIN_OF(LOC);
    if (_cooRef.getDim() != _cooGauss.getDim() )
      throw MEDEXCEPTION( LOCALIZED( STRING(LOC) <<"cooRef and cooGaus must have the same number of components")) ;

    if (_cooRef.getArraySize() != (_typeGeo%100)*(_typeGeo/100) )
      throw MEDEXCEPTION( LOCALIZED( STRING(LOC) <<"cooRef size is " << _cooRef.getArraySize()
				     << " and should be (_typeGeo%100)*(_typeGeo/100) "
				     << (_typeGeo%100)*(_typeGeo/100))) ;

    if (_cooGauss.getArraySize() != _nGauss*(_typeGeo/100) )
      throw MEDEXCEPTION( LOCALIZED( STRING(LOC) <<"cooGauss must be of size nGauss*(_typeGeo/100) "
				     << _nGauss*(_typeGeo/100) ));
    if (_wg.size() != _nGauss )
      throw MEDEXCEPTION( LOCALIZED( STRING(LOC) <<"wg must be of size nGauss "
				     << _nGauss ));

    END_OF(LOC);
  };

  template <class INTERLACING_TAG> GAUSS_LOCALIZATION<INTERLACING_TAG>::GAUSS_LOCALIZATION(const string & locName,
											   const MED_EN::medGeometryElement  typeGeo,
											   const int  nGauss,
											   const double  * const cooRef,
											   const double  * const cooGauss,
											   const double  * const wg) throw (MEDEXCEPTION) :
    _locName(locName),_typeGeo(typeGeo),_nGauss(nGauss),
    _cooRef(ArrayNoGauss(const_cast<double *>(cooRef),typeGeo/100,typeGeo%100)),
    _cooGauss(ArrayNoGauss(const_cast<double *>(cooGauss),typeGeo/100,_nGauss)),
    _wg(vector<double>(wg,wg+nGauss)),
    _interlacingType(SET_INTERLACING_TYPE<INTERLACING_TAG>::_interlacingType)
  {
    const char * LOC = "GAUSS_LOCALIZATION(locName,typeGeo, nGauss, const double * cooRef,..) :";
    BEGIN_OF(LOC);
    if (_cooRef.getDim() != _cooGauss.getDim() )
      throw MEDEXCEPTION( LOCALIZED( STRING(LOC) <<"cooRef and cooGaus must have the same number of components")) ;

    if (_cooRef.getArraySize() != (_typeGeo%100)*(_typeGeo/100) )
      throw MEDEXCEPTION( LOCALIZED( STRING(LOC) <<"cooRef must be of size (_typeGeo%100)*(_typeGeo/100) "
				     << (_typeGeo%100)*(_typeGeo/100))) ;

    if (_cooGauss.getArraySize() != _nGauss*(_typeGeo/100) )
      throw MEDEXCEPTION( LOCALIZED( STRING(LOC) <<"cooGauss must be of size nGauss*(_typeGeo/100) "
				     << _nGauss*(_typeGeo/100) ));
    if (_wg.size() != _nGauss )
      throw MEDEXCEPTION( LOCALIZED( STRING(LOC) <<"wg must be of size nGauss "
				     << _nGauss ));
    END_OF(LOC);
  };

  template <class INTERLACING_TAG> GAUSS_LOCALIZATION<INTERLACING_TAG> &
  GAUSS_LOCALIZATION<INTERLACING_TAG>::operator=(const GAUSS_LOCALIZATION & gaussLoc)
  {
    if ( this == &gaussLoc) return *this;

    _locName  = gaussLoc._locName;
    _typeGeo  = gaussLoc._typeGeo;
    _nGauss   = gaussLoc._nGauss;
    _cooRef   = ArrayNoGauss(gaussLoc._cooRef);   //utilisation de la copie superficielle par dfaut n'est pas une bonne ide
    _cooGauss = ArrayNoGauss(gaussLoc._cooGauss);  //dans l'oprateur = de MEDnArray
    _wg       = gaussLoc._wg;

    return *this;
  }

  template <class INTERLACING_TAG> bool
  GAUSS_LOCALIZATION<INTERLACING_TAG>::operator == (const GAUSS_LOCALIZATION & gaussLoc) const {
    return (
	    _locName  == gaussLoc._locName &&
	    _typeGeo  == gaussLoc._typeGeo &&
	    _nGauss   == gaussLoc._nGauss  &&
	    _cooRef   == gaussLoc._cooRef  &&   //utilisation de la copie superficielle par dfaut n'est pas une bonne ide
	    _cooGauss == gaussLoc._cooGauss &&  //dans l'oprateur = de MEDnArray
	    _wg       == gaussLoc._wg
	    );
  }

  template <class INTERLACING_TAG> ostream & operator<<(ostream &os,
								const  GAUSS_LOCALIZATION<INTERLACING_TAG> &loc) {
    os << "Localization Name     : " << loc._locName << endl;
    os << "Geometric Type        : " << MED_EN::geoNames[loc._typeGeo]<< endl;
    os << "Number Of GaussPoints : " << loc._nGauss << endl;
    os << "Ref.   Element Coords : " << endl << loc._cooRef << endl;
    os << "Gauss points Coords   : " << endl << loc._cooGauss << endl;
    os << "Gauss points weigth   : " << endl ;
    for(int i=0; i<loc._wg.size();++i)
      os << "_wg[" << i << "] = " << loc._wg[i] << endl;
    return os;
  }

} //END NAMESPACE

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: skeletoncommon.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: vg $ $Date: 2006-03-15 09:20:08 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef INCLUDED_UNODEVTOOLS_SOURCE_SKELETONMAKER_SKELETONCOMMON_HXX
#define INCLUDED_UNODEVTOOLS_SOURCE_SKELETONMAKER_SKELETONCOMMON_HXX

#ifndef _RTL_STRING_HXX_
#include "rtl/string.hxx"
#endif
#ifndef INCLUDED_registry_reader_hxx
#include "registry/reader.hxx"
#endif
#ifndef INCLUDED_CODEMAKER_TYPEMANAGER_HXX
#include "codemaker/typemanager.hxx"
#endif
#ifndef INCLUDED_CODEMAKER_UNOTYPE_HXX
#include "codemaker/unotype.hxx"
#endif

#include <fstream>
#include <hash_set>
#include <hash_map>

namespace skeletonmaker {

struct ProgramOptions {
    ProgramOptions(): java5(true), all(false), dump(false), license(false),
                      shortnames(false), supportpropertysetmixin(false),
                      language(1), componenttype(1) {}

    bool java5;
    bool all;
    bool dump;
    bool license;
    bool shortnames;
    bool supportpropertysetmixin;
    // language specifier - is extendable
    // 1 = Java
    // 2 = C++
    short language;
    // component type
    // 1 = default UNO component - is extendable
    // 2 = calc add-in
    // 3 = add-on
    short componenttype;
    rtl::OString outputpath;
    rtl::OString implname;
};

// typedef ::std::hash_map< ::rtl::OString,
//                          ::std::pair< rtl::OString, sal_Int16 >,
//                          rtl::OStringHash > StringPairHashMap;

typedef ::std::vector< ::std::pair< rtl::OString,
                     ::std::pair< rtl::OString, sal_Int16 > > > AttributeInfo;

/**
   print the standard OpenOffice.org license header

   @param o specifies the output stream
   @param filename specifies the source file name
*/
void printLicenseHeader(std::ostream& o, rtl::OString const & filename);

/**
   create dependent on the output path, the implementation name and the
   extension a new output file. If output path is equal "stdout" the tool
   generates the output to standard out.

   @param options the program options including the output path and the
                  implementation name
   @param extension specifies the file extensions (e.g. .cxx or .java)
   @param ppOutputStream out parameter returning the output stream
   @param targetSourceFileName out parameter returning the generated file name
                               constructed on base of the output path, the
                               implementation name and the extension
   @param tmpSourceFileName out parameter returning the temporary file name based
                            on the output path and a generated temporary file name.
   @return true if output is generated to standard out or else false
*/
bool getOutputStream(ProgramOptions const & options,
                     rtl::OString const & extension,
                     std::ostream** ppOutputStream,
                     rtl::OString & targetSourceFileName,
                     rtl::OString & tmpSourceFileName);

codemaker::UnoType::Sort decomposeResolveAndCheck(
    TypeManager const & manager, rtl::OString const & type,
    bool resolveTypedefs, bool allowVoid, bool allowExtraEntities,
    RTTypeClass * typeClass, rtl::OString * name, sal_Int32 * rank,
    std::vector< rtl::OString > * arguments);

void checkType(TypeManager const & manager,
               rtl::OString const & type,
               std::hash_set< rtl::OString, rtl::OStringHash >& interfaceTypes,
               std::hash_set< rtl::OString, rtl::OStringHash >& serviceTypes,
               AttributeInfo& properties);

void checkDefaultInterfaces(
    std::hash_set< rtl::OString, rtl::OStringHash >& interfaces,
    const std::hash_set< rtl::OString, rtl::OStringHash >& services,
    const rtl::OString & propertyhelper);

rtl::OString checkPropertyHelper(
    ProgramOptions const & options, TypeManager const & manager,
    const std::hash_set< rtl::OString, rtl::OStringHash >& services,
    const std::hash_set< rtl::OString, rtl::OStringHash >& interfaces,
    AttributeInfo& attributes,
    std::hash_set< rtl::OString, rtl::OStringHash >& propinterfaces);

/**
   checks whether the return and parameters types are valid and allowed
   calc add-in type. The function throws a CannotDumpException with an
   detailed error description which type is wrong

   @param manager a type manager
   @param reader a registry type reader of an interface defining
                 calc add-in functions
*/
void checkAddInTypes(TypeManager const & manager,
                     typereg::Reader const & reader);

/**
   checks if XComponent have to be supported, if yes it removes it from the
   supported interfaces list becuase it becmoes implmented by the appropriate
   helper

   @param manager a type manager
   @param interfaces a list of interfaces which should be implemented

   @return true if XComponent have to be supported
*/
bool checkXComponentSupport(TypeManager const & manager,
         std::hash_set< rtl::OString, rtl::OStringHash >& interfaces);

sal_uInt16 checkAdditionalPropertyFlags(typereg::Reader const & reader,
                                        sal_uInt16 field, sal_uInt16 method);

void generateFunctionParameterMap(std::ostream& o,
         ProgramOptions const & options,
         TypeManager const & manager,
         const std::hash_set< ::rtl::OString, ::rtl::OStringHash >& interfaces);

}

#endif // INCLUDED_UNODEVTOOLS_SOURCE_SKELETONMAKER_SKELETONCOMMON_HXX

<commit_msg>INTEGRATION: CWS jsc12 (1.4.10); FILE MERGED 2006/07/31 14:53:23 jsc 1.4.10.1: #i67879# simplify calc add-in skeleton<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: skeletoncommon.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: ihi $ $Date: 2006-08-01 16:24:36 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef INCLUDED_UNODEVTOOLS_SOURCE_SKELETONMAKER_SKELETONCOMMON_HXX
#define INCLUDED_UNODEVTOOLS_SOURCE_SKELETONMAKER_SKELETONCOMMON_HXX

#ifndef _RTL_STRING_HXX_
#include "rtl/string.hxx"
#endif
#ifndef INCLUDED_registry_reader_hxx
#include "registry/reader.hxx"
#endif
#ifndef INCLUDED_CODEMAKER_TYPEMANAGER_HXX
#include "codemaker/typemanager.hxx"
#endif
#ifndef INCLUDED_CODEMAKER_UNOTYPE_HXX
#include "codemaker/unotype.hxx"
#endif

#include <fstream>
#include <hash_set>
#include <hash_map>

namespace skeletonmaker {

struct ProgramOptions {
    ProgramOptions(): java5(true), all(false), dump(false), license(false),
                      shortnames(false), supportpropertysetmixin(false),
                      backwardcompatible(false), language(1), componenttype(1) {}

    bool java5;
    bool all;
    bool dump;
    bool license;
    bool shortnames;
    bool supportpropertysetmixin;
    bool backwardcompatible;
    // language specifier - is extendable
    // 1 = Java
    // 2 = C++
    short language;
    // component type
    // 1 = default UNO component - is extendable
    // 2 = calc add-in
    // 3 = add-on
    short componenttype;
    rtl::OString outputpath;
    rtl::OString implname;
};

// typedef ::std::hash_map< ::rtl::OString,
//                          ::std::pair< rtl::OString, sal_Int16 >,
//                          rtl::OStringHash > StringPairHashMap;

typedef ::std::vector< ::std::pair< rtl::OString,
                     ::std::pair< rtl::OString, sal_Int16 > > > AttributeInfo;

/**
   print the standard OpenOffice.org license header

   @param o specifies the output stream
   @param filename specifies the source file name
*/
void printLicenseHeader(std::ostream& o, rtl::OString const & filename);

/**
   create dependent on the output path, the implementation name and the
   extension a new output file. If output path is equal "stdout" the tool
   generates the output to standard out.

   @param options the program options including the output path and the
                  implementation name
   @param extension specifies the file extensions (e.g. .cxx or .java)
   @param ppOutputStream out parameter returning the output stream
   @param targetSourceFileName out parameter returning the generated file name
                               constructed on base of the output path, the
                               implementation name and the extension
   @param tmpSourceFileName out parameter returning the temporary file name based
                            on the output path and a generated temporary file name.
   @return true if output is generated to standard out or else false
*/
bool getOutputStream(ProgramOptions const & options,
                     rtl::OString const & extension,
                     std::ostream** ppOutputStream,
                     rtl::OString & targetSourceFileName,
                     rtl::OString & tmpSourceFileName);

codemaker::UnoType::Sort decomposeResolveAndCheck(
    TypeManager const & manager, rtl::OString const & type,
    bool resolveTypedefs, bool allowVoid, bool allowExtraEntities,
    RTTypeClass * typeClass, rtl::OString * name, sal_Int32 * rank,
    std::vector< rtl::OString > * arguments);

void checkType(TypeManager const & manager,
               rtl::OString const & type,
               std::hash_set< rtl::OString, rtl::OStringHash >& interfaceTypes,
               std::hash_set< rtl::OString, rtl::OStringHash >& serviceTypes,
               AttributeInfo& properties);

void checkDefaultInterfaces(
    std::hash_set< rtl::OString, rtl::OStringHash >& interfaces,
    const std::hash_set< rtl::OString, rtl::OStringHash >& services,
    const rtl::OString & propertyhelper);

rtl::OString checkPropertyHelper(
    ProgramOptions const & options, TypeManager const & manager,
    const std::hash_set< rtl::OString, rtl::OStringHash >& services,
    const std::hash_set< rtl::OString, rtl::OStringHash >& interfaces,
    AttributeInfo& attributes,
    std::hash_set< rtl::OString, rtl::OStringHash >& propinterfaces);

/**
   checks whether the return and parameters types are valid and allowed
   calc add-in type. The function throws a CannotDumpException with an
   detailed error description which type is wrong

   @param manager a type manager
   @param reader a registry type reader of an interface defining
                 calc add-in functions
*/
void checkAddInTypes(TypeManager const & manager,
                     typereg::Reader const & reader);

/**
   checks if XComponent have to be supported, if yes it removes it from the
   supported interfaces list becuase it becmoes implmented by the appropriate
   helper

   @param manager a type manager
   @param interfaces a list of interfaces which should be implemented

   @return true if XComponent have to be supported
*/
bool checkXComponentSupport(TypeManager const & manager,
         std::hash_set< rtl::OString, rtl::OStringHash >& interfaces);

sal_uInt16 checkAdditionalPropertyFlags(typereg::Reader const & reader,
                                        sal_uInt16 field, sal_uInt16 method);

void generateFunctionParameterMap(std::ostream& o,
         ProgramOptions const & options,
         TypeManager const & manager,
         const std::hash_set< ::rtl::OString, ::rtl::OStringHash >& interfaces);

}

#endif // INCLUDED_UNODEVTOOLS_SOURCE_SKELETONMAKER_SKELETONCOMMON_HXX

<|endoftext|>


<commit_before>/**
 * Copyright (c) 2016 zScale Technology GmbH <legal@zscale.io>
 * Authors:
 *   - Paul Asmuth <paul@zscale.io>
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License ("the license") as
 * published by the Free Software Foundation, either version 3 of the License,
 * or any later version.
 *
 * In accordance with Section 7(e) of the license, the licensing of the Program
 * under the license does not imply a trademark license. Therefore any rights,
 * title and interest in our trademarks remain entirely with us.
 *
 * 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 license for more details.
 *
 * You can be released from the requirements of the license by purchasing a
 * commercial license. Buying such a license is mandatory as soon as you develop
 * commercial activities involving this program without disclosing the source
 * code of your own applications
 */
#include <eventql/util/stdtypes.h>
#include <eventql/util/autoref.h>
#include <eventql/util/io/fileutil.h>
#include <eventql/util/logging.h>
#include <eventql/db/LSMTableIndexCache.h>
#include "eventql/eventql.h"
#include <assert.h>

namespace eventql {

LSMTableIndexCache::LSMTableIndexCache(
    const String& base_path,
    size_t max_size /* = kDefaultMaxSize */) :
    base_path_(base_path),
    head_(nullptr),
    tail_(nullptr),
    size_(0),
    max_size_(max_size) {}

LSMTableIndexCache::~LSMTableIndexCache() {
  for (const auto& slot : map_) {
    delete slot.second;
  }
}

RefPtr<LSMTableIndex> LSMTableIndexCache::lookup(const String& filename) {
  auto file_path = FileUtil::joinPaths(base_path_, filename + ".idx");

  ScopedLock<std::mutex> lk(mutex_);
  auto& slot = map_[filename];
  if (slot) {
    if (slot->next) {
      slot->next->prev = slot->prev;
    } else {
      tail_ = slot->prev;
    }

    if (slot->prev) {
      slot->prev->next = slot->next;
    } else {
      head_ = slot->next;
    }
  } else {
    while (size_ > max_size_) {
      flushTail();
    }

    slot = new Entry();
    slot->filename = filename;
    slot->idx = new LSMTableIndex();
    slot->size =
        FileUtil::size(file_path) + filename.size() * 2 + kConstantOverhead;
    size_ += slot->size;

    logInfo(
        "evqld",
        "LSMTableIndexCache::load: $0 (size=$1/$2)",
        filename,
        size_,
        slot->size);
  }

  slot->next = head_;
  slot->prev = nullptr;
  if (head_) {
    head_->prev = slot;
  } else {
    tail_ = slot;
  }

  head_ = slot;
  auto idx = slot->idx;
  lk.unlock();

  idx->load(file_path);

  return idx;
}

void LSMTableIndexCache::flush(const String& filename) {
  ScopedLock<std::mutex> lk(mutex_);
  logInfo("evqld", "LSMTableIndexCache::flush: $0 (size=$1)", filename, size_);

  auto iter = map_.find(filename);
  if (iter == map_.end()) {
    return;
  }

  auto slot = iter->second;
  map_.erase(iter);

  if (slot->next) {
    slot->next->prev = slot->prev;
  } else {
    tail_ = slot->prev;
  }

  if (slot->prev) {
    slot->prev->next = slot->next;
  } else {
    head_ = slot->next;
  }

  size_ -= slot->size;
  assert(head_ || size_ == 0);
  delete slot;
}

// PRECONDITION: must hold mutex
void LSMTableIndexCache::flushTail() {
  auto entry = tail_;
  if (!entry) {
    return;
  }

  if (entry->prev) {
    entry->prev->next = nullptr;
  } else {
    head_ = nullptr;
  }

  tail_ = entry->prev;
  size_ -= entry->size;
  map_.erase(entry->filename);
  assert(head_ || size_ == 0);
  delete entry;
}

size_t LSMTableIndexCache::size() const {
  ScopedLock<std::mutex> lk(mutex_);
  return size_;
}

} // namespace eventql

<commit_msg>add assert<commit_after>/**
 * Copyright (c) 2016 zScale Technology GmbH <legal@zscale.io>
 * Authors:
 *   - Paul Asmuth <paul@zscale.io>
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License ("the license") as
 * published by the Free Software Foundation, either version 3 of the License,
 * or any later version.
 *
 * In accordance with Section 7(e) of the license, the licensing of the Program
 * under the license does not imply a trademark license. Therefore any rights,
 * title and interest in our trademarks remain entirely with us.
 *
 * 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 license for more details.
 *
 * You can be released from the requirements of the license by purchasing a
 * commercial license. Buying such a license is mandatory as soon as you develop
 * commercial activities involving this program without disclosing the source
 * code of your own applications
 */
#include <eventql/util/stdtypes.h>
#include <eventql/util/autoref.h>
#include <eventql/util/io/fileutil.h>
#include <eventql/util/logging.h>
#include <eventql/db/LSMTableIndexCache.h>
#include "eventql/eventql.h"
#include <assert.h>

namespace eventql {

LSMTableIndexCache::LSMTableIndexCache(
    const String& base_path,
    size_t max_size /* = kDefaultMaxSize */) :
    base_path_(base_path),
    head_(nullptr),
    tail_(nullptr),
    size_(0),
    max_size_(max_size) {}

LSMTableIndexCache::~LSMTableIndexCache() {
  for (const auto& slot : map_) {
    delete slot.second;
  }
}

RefPtr<LSMTableIndex> LSMTableIndexCache::lookup(const String& filename) {
  auto file_path = FileUtil::joinPaths(base_path_, filename + ".idx");

  ScopedLock<std::mutex> lk(mutex_);
  auto& slot = map_[filename];
  if (slot) {
    if (slot->next) {
      slot->next->prev = slot->prev;
    } else {
      tail_ = slot->prev;
    }

    if (slot->prev) {
      slot->prev->next = slot->next;
    } else {
      head_ = slot->next;
    }
  } else {
    while (size_ > max_size_) {
      flushTail();
    }

    slot = new Entry();
    slot->filename = filename;
    slot->idx = new LSMTableIndex();
    slot->size =
        FileUtil::size(file_path) + filename.size() * 2 + kConstantOverhead;
    size_ += slot->size;

    logInfo(
        "evqld",
        "LSMTableIndexCache::load: $0 (size=$1/$2)",
        filename,
        size_,
        slot->size);
  }

  slot->next = head_;
  slot->prev = nullptr;
  if (head_) {
    head_->prev = slot;
  } else {
    tail_ = slot;
  }

  head_ = slot;
  auto idx = slot->idx;
  lk.unlock();

  idx->load(file_path);

  return idx;
}

void LSMTableIndexCache::flush(const String& filename) {
  ScopedLock<std::mutex> lk(mutex_);
  logInfo("evqld", "LSMTableIndexCache::flush: $0 (size=$1)", filename, size_);

  auto iter = map_.find(filename);
  if (iter == map_.end()) {
    return;
  }

  auto slot = iter->second;
  map_.erase(iter);

  if (slot->next) {
    slot->next->prev = slot->prev;
  } else {
    tail_ = slot->prev;
  }

  if (slot->prev) {
    slot->prev->next = slot->next;
  } else {
    head_ = slot->next;
  }

  size_ -= slot->size;
  assert(head_ || size_ == 0);
  delete slot;
}

// PRECONDITION: must hold mutex
void LSMTableIndexCache::flushTail() {
  auto entry = tail_;
  assert(entry != nullptr);

  if (entry->prev) {
    entry->prev->next = nullptr;
  } else {
    head_ = nullptr;
  }

  tail_ = entry->prev;
  size_ -= entry->size;
  map_.erase(entry->filename);
  assert(head_ || size_ == 0);
  delete entry;
}

size_t LSMTableIndexCache::size() const {
  ScopedLock<std::mutex> lk(mutex_);
  return size_;
}

} // namespace eventql

<|endoftext|>


<commit_before>/*
 *  WhiteNoiseBackground.cpp
 *  WhiteNoiseBackground
 *
 *  Created by Christopher Stawarz on 12/15/10.
 *  Copyright 2010 MIT. All rights reserved.
 *
 */

#include "WhiteNoiseBackground.h"

#if TARGET_OS_OSX
#  include <OpenGL/gl3ext.h>
#endif

BEGIN_NAMESPACE_MW

void WhiteNoiseBackground::describeComponent(ComponentInfo &info) {
    Stimulus::describeComponent(info);
    info.setSignature("stimulus/white_noise_background");
}

WhiteNoiseBackground::WhiteNoiseBackground(const ParameterValueMap &parameters) :
    Stimulus(parameters),
    randGen(Clock::instance()->getSystemTimeUS()),
    randDist(std::numeric_limits<GLubyte>::min(), std::numeric_limits<GLubyte>::max())
{ }

void WhiteNoiseBackground::load(shared_ptr<StimulusDisplay> display) {
    if (loaded)
        return;

    auto ctxLock = display->setCurrent(0);

    display->getCurrentViewportSize(width, height);
    pixels.clear();
    pixels.assign(width * height, std::numeric_limits<GLuint>::max());

    auto vertexShader = gl::createShader(GL_VERTEX_SHADER, vertexShaderSource);
    auto fragmentShader = gl::createShader(GL_FRAGMENT_SHADER, fragmentShaderSource);
    program = gl::createProgram({ vertexShader.get(), fragmentShader.get() }).release();
    gl::ProgramUsage programUsage(program);

    glUniform1i(glGetUniformLocation(program, "noiseTexture"), 0);

    glGenVertexArrays(1, &vertexArray);
    gl::VertexArrayBinding vertexArrayBinding(vertexArray);

    glGenBuffers(1, &vertexPositionBuffer);
    gl::BufferBinding<GL_ARRAY_BUFFER> arrayBufferBinding(vertexPositionBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertexPositions), vertexPositions.data(), GL_STATIC_DRAW);
    GLint vertexPositionAttribLocation = glGetAttribLocation(program, "vertexPosition");
    glEnableVertexAttribArray(vertexPositionAttribLocation);
    glVertexAttribPointer(vertexPositionAttribLocation, componentsPerVertex, GL_FLOAT, GL_FALSE, 0, nullptr);

    glGenBuffers(1, &texCoordsBuffer);
    arrayBufferBinding.bind(texCoordsBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(texCoords), texCoords.data(), GL_STATIC_DRAW);
    GLint texCoordsAttribLocation = glGetAttribLocation(program, "texCoords");
    glEnableVertexAttribArray(texCoordsAttribLocation);
    glVertexAttribPointer(texCoordsAttribLocation, componentsPerVertex, GL_FLOAT, GL_FALSE, 0, nullptr);

    glGenTextures(1, &texture);
    gl::TextureBinding<GL_TEXTURE_2D> textureBinding(texture);
    glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA8, width, height);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

    Stimulus::load(display);
}

void WhiteNoiseBackground::unload(shared_ptr<StimulusDisplay> display) {
    if (!loaded)
        return;

    auto ctxLock = display->setCurrent(0);

    glDeleteTextures(1, &texture);
    glDeleteBuffers(1, &texCoordsBuffer);
    glDeleteBuffers(1, &vertexPositionBuffer);
    glDeleteVertexArrays(1, &vertexArray);
    glDeleteProgram(program);

    pixels.clear();

    Stimulus::unload(display);
}

void WhiteNoiseBackground::draw(shared_ptr<StimulusDisplay> display) {
    gl::ProgramUsage programUsage(program);
    gl::VertexArrayBinding vertexArrayBinding(vertexArray);

    gl::TextureBinding<GL_TEXTURE_2D> textureBinding(texture);

    glDrawArrays(GL_TRIANGLE_STRIP, 0, numVertices);
}

Datum WhiteNoiseBackground::getCurrentAnnounceDrawData() {
    Datum announceData = Stimulus::getCurrentAnnounceDrawData();
	announceData.addElement(STIM_TYPE, "white_noise_background");
    return announceData;
}

void WhiteNoiseBackground::randomizePixels() {
    boost::mutex::scoped_lock lock(pixelsMutex);

    for (size_t i = 0; i < pixels.size(); i++) {
        GLubyte randVal = randDist(randGen);
        GLubyte *pix = reinterpret_cast<GLubyte *>(&(pixels[i]));
        for (size_t j = 0; j < componentsPerPixel - 1; j++) {
            pix[j] = randVal;
        }
    }

    auto ctxLock = StimulusDisplay::getCurrentStimulusDisplay()->setCurrent(0);
    updateTexture();
}

void WhiteNoiseBackground::updateTexture() {
#if !MWORKS_OPENGL_ES
    glPixelStorei(GL_UNPACK_SWAP_BYTES, GL_FALSE);
    glPixelStorei(GL_UNPACK_LSB_FIRST, GL_FALSE);
#endif
    glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
    glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, 0);
    glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
    glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
    glPixelStorei(GL_UNPACK_SKIP_IMAGES, 0);
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

    gl::TextureBinding<GL_TEXTURE_2D> textureBinding(texture);

    glTexSubImage2D(GL_TEXTURE_2D,
                    0,
                    0,
                    0,
                    width,
                    height,
#if MWORKS_OPENGL_ES
                    GL_RGBA,
                    GL_UNSIGNED_BYTE,
#else
                    GL_BGRA,
                    GL_UNSIGNED_INT_8_8_8_8_REV,
#endif
                    pixels.data());
}

const std::string WhiteNoiseBackground::vertexShaderSource
(R"(
 in vec4 vertexPosition;
 in vec2 texCoords;
 out vec2 varyingTexCoords;

 void main() {
     gl_Position = vertexPosition;
     varyingTexCoords = texCoords;
 }
 )");

const std::string WhiteNoiseBackground::fragmentShaderSource
(R"(
 uniform sampler2D noiseTexture;
 in vec2 varyingTexCoords;
 out vec4 fragColor;

 void main() {
     fragColor = texture(noiseTexture, varyingTexCoords);
 }
 )");

const WhiteNoiseBackground::VertexPositionArray WhiteNoiseBackground::vertexPositions {
    -1.0f, -1.0f,
     1.0f, -1.0f,
    -1.0f,  1.0f,
     1.0f,  1.0f
};

const WhiteNoiseBackground::VertexPositionArray WhiteNoiseBackground::texCoords {
    0.0f, 0.0f,
    1.0f, 0.0f,
    0.0f, 1.0f,
    1.0f, 1.0f
};

END_NAMESPACE_MW

<commit_msg>Revert "In WhiteNoiseBackground, create texture storage only once", as it complicates the code without improving performance<commit_after>/*
 *  WhiteNoiseBackground.cpp
 *  WhiteNoiseBackground
 *
 *  Created by Christopher Stawarz on 12/15/10.
 *  Copyright 2010 MIT. All rights reserved.
 *
 */

#include "WhiteNoiseBackground.h"

BEGIN_NAMESPACE_MW

void WhiteNoiseBackground::describeComponent(ComponentInfo &info) {
    Stimulus::describeComponent(info);
    info.setSignature("stimulus/white_noise_background");
}

WhiteNoiseBackground::WhiteNoiseBackground(const ParameterValueMap &parameters) :
    Stimulus(parameters),
    randGen(Clock::instance()->getSystemTimeUS()),
    randDist(std::numeric_limits<GLubyte>::min(), std::numeric_limits<GLubyte>::max())
{ }

void WhiteNoiseBackground::load(shared_ptr<StimulusDisplay> display) {
    if (loaded)
        return;

    auto ctxLock = display->setCurrent(0);

    display->getCurrentViewportSize(width, height);
    pixels.clear();
    pixels.assign(width * height, std::numeric_limits<GLuint>::max());

    auto vertexShader = gl::createShader(GL_VERTEX_SHADER, vertexShaderSource);
    auto fragmentShader = gl::createShader(GL_FRAGMENT_SHADER, fragmentShaderSource);
    program = gl::createProgram({ vertexShader.get(), fragmentShader.get() }).release();
    gl::ProgramUsage programUsage(program);

    glUniform1i(glGetUniformLocation(program, "noiseTexture"), 0);

    glGenVertexArrays(1, &vertexArray);
    gl::VertexArrayBinding vertexArrayBinding(vertexArray);

    glGenBuffers(1, &vertexPositionBuffer);
    gl::BufferBinding<GL_ARRAY_BUFFER> arrayBufferBinding(vertexPositionBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertexPositions), vertexPositions.data(), GL_STATIC_DRAW);
    GLint vertexPositionAttribLocation = glGetAttribLocation(program, "vertexPosition");
    glEnableVertexAttribArray(vertexPositionAttribLocation);
    glVertexAttribPointer(vertexPositionAttribLocation, componentsPerVertex, GL_FLOAT, GL_FALSE, 0, nullptr);

    glGenBuffers(1, &texCoordsBuffer);
    arrayBufferBinding.bind(texCoordsBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(texCoords), texCoords.data(), GL_STATIC_DRAW);
    GLint texCoordsAttribLocation = glGetAttribLocation(program, "texCoords");
    glEnableVertexAttribArray(texCoordsAttribLocation);
    glVertexAttribPointer(texCoordsAttribLocation, componentsPerVertex, GL_FLOAT, GL_FALSE, 0, nullptr);

    glGenTextures(1, &texture);
    updateTexture();

    Stimulus::load(display);
}

void WhiteNoiseBackground::unload(shared_ptr<StimulusDisplay> display) {
    if (!loaded)
        return;

    auto ctxLock = display->setCurrent(0);

    glDeleteTextures(1, &texture);
    glDeleteBuffers(1, &texCoordsBuffer);
    glDeleteBuffers(1, &vertexPositionBuffer);
    glDeleteVertexArrays(1, &vertexArray);
    glDeleteProgram(program);

    pixels.clear();

    Stimulus::unload(display);
}

void WhiteNoiseBackground::draw(shared_ptr<StimulusDisplay> display) {
    gl::ProgramUsage programUsage(program);
    gl::VertexArrayBinding vertexArrayBinding(vertexArray);

    gl::TextureBinding<GL_TEXTURE_2D> textureBinding(texture);

    glDrawArrays(GL_TRIANGLE_STRIP, 0, numVertices);
}

Datum WhiteNoiseBackground::getCurrentAnnounceDrawData() {
    Datum announceData = Stimulus::getCurrentAnnounceDrawData();
	announceData.addElement(STIM_TYPE, "white_noise_background");
    return announceData;
}

void WhiteNoiseBackground::randomizePixels() {
    boost::mutex::scoped_lock lock(pixelsMutex);

    for (size_t i = 0; i < pixels.size(); i++) {
        GLubyte randVal = randDist(randGen);
        GLubyte *pix = reinterpret_cast<GLubyte *>(&(pixels[i]));
        for (size_t j = 0; j < componentsPerPixel - 1; j++) {
            pix[j] = randVal;
        }
    }

    auto ctxLock = StimulusDisplay::getCurrentStimulusDisplay()->setCurrent(0);
    updateTexture();
}

void WhiteNoiseBackground::updateTexture() {
#if !MWORKS_OPENGL_ES
    glPixelStorei(GL_UNPACK_SWAP_BYTES, GL_FALSE);
    glPixelStorei(GL_UNPACK_LSB_FIRST, GL_FALSE);
#endif
    glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
    glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, 0);
    glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
    glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
    glPixelStorei(GL_UNPACK_SKIP_IMAGES, 0);
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

    gl::TextureBinding<GL_TEXTURE_2D> textureBinding(texture);

    glTexImage2D(GL_TEXTURE_2D,
                 0,
                 GL_RGBA8,
                 width,
                 height,
                 0,
#if MWORKS_OPENGL_ES
                 GL_RGBA,
                 GL_UNSIGNED_BYTE,
#else
                 GL_BGRA,
                 GL_UNSIGNED_INT_8_8_8_8_REV,
#endif
                 pixels.data());

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
}

const std::string WhiteNoiseBackground::vertexShaderSource
(R"(
 in vec4 vertexPosition;
 in vec2 texCoords;
 out vec2 varyingTexCoords;

 void main() {
     gl_Position = vertexPosition;
     varyingTexCoords = texCoords;
 }
 )");

const std::string WhiteNoiseBackground::fragmentShaderSource
(R"(
 uniform sampler2D noiseTexture;
 in vec2 varyingTexCoords;
 out vec4 fragColor;

 void main() {
     fragColor = texture(noiseTexture, varyingTexCoords);
 }
 )");

const WhiteNoiseBackground::VertexPositionArray WhiteNoiseBackground::vertexPositions {
    -1.0f, -1.0f,
     1.0f, -1.0f,
    -1.0f,  1.0f,
     1.0f,  1.0f
};

const WhiteNoiseBackground::VertexPositionArray WhiteNoiseBackground::texCoords {
    0.0f, 0.0f,
    1.0f, 0.0f,
    0.0f, 1.0f,
    1.0f, 1.0f
};

END_NAMESPACE_MW

<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qdeclarativedisplayinfo_p.h"
#include "qsystemdisplayinfo.h"

QT_BEGIN_NAMESPACE

Q_GLOBAL_STATIC(QSystemDisplayInfo, displayInfo)

/*!
    \qmlclass NetworkInfo QDeclarativeDisplayInfo
    \brief The DisplayInfo element allows you to get information and
     receive notifications about the diplsay.
    \inherits QObject

    \ingroup qml-systeminfo

    This element is part of the \bold{QtMobility.systeminfo 1.2} module.
    It is a convience class to make QML usage easier.

    \endqml

\sa QSystemDisplayInfo
*/

/*!
    \qmlsignal DisplayInfo::orientationChanged()

    This handler is called when gui orientation has changed.
*/

/*!
  Constructs the DeviceInfo
  */
QDeclarativeDisplayInfo::QDeclarativeDisplayInfo(QObject *parent) :
    QSystemDisplayInfo(parent),currentScreen(0)
{
}

/*!
    \qmlproperty int DeviceInfo::screen

    Contains the display number of this screen.
*/
int QDeclarativeDisplayInfo::screen()
{
    return currentScreen;
}

/*!
   This function sets this DisplayInfo to use screen \a screen.

    If not set, the default is the default screen, or display 0.
*/
void QDeclarativeDisplayInfo::setCurrentScreen(int screen)
{
    currentScreen = screen;
}

/*!
    \qmlproperty int DisplayInfo::displayBrightness
   Returns the brightness of the screen.
  */
int QDeclarativeDisplayInfo::displayBrightness()
{
    return displayInfo()->displayBrightness(currentScreen);
}

/*!
    \qmlproperty int DisplayInfo::colorDepth
   Returns the color depth of the screen, in bits per pixel.
  */
int QDeclarativeDisplayInfo::colorDepth()
{
    return displayInfo()->colorDepth(currentScreen);
}

/*!
    \qmlproperty QSystemDisplayInfo::DisplayOrientation DisplayInfo::orientation
    Returns the QSystemDisplayInfo::DisplayOrientation of the UI QDesktopWidget for the screen.
  */
QSystemDisplayInfo::DisplayOrientation QDeclarativeDisplayInfo::orientation()
{
    return displayInfo()->orientation(currentScreen);
}

/*!
    \qmlproperty float DisplayInfo::contrast
   Returns the contrast of the screen, from 0 to 1.
  */
float QDeclarativeDisplayInfo::contrast()
{
    return displayInfo()->contrast(currentScreen);
}

/*!
    \qmlproperty int DisplayInfo::dpiWidth
   Returns the DPI width of the screen in millimeters.
  */
int QDeclarativeDisplayInfo::dpiWidth()
{
    return displayInfo()->getDPIWidth(currentScreen);
}

/*!
    \qmlproperty int DisplayInfo::dpiHeight
   Returns the DPI height of the screen in millimeters.
  */
int QDeclarativeDisplayInfo::dpiHeight()
{
    return displayInfo()->getDPIHeight(currentScreen);
}

/*!
    \qmlproperty int DisplayInfo::physicalHeight
   Returns the physical height of the screen in millimeters.
  */
int QDeclarativeDisplayInfo::physicalHeight()
{
    return displayInfo()->physicalHeight(currentScreen);
}

/*!
    \qmlproperty int DisplayInfo::physicalWidth
   Returns the physical width of the screen in millimeters.
  */
int QDeclarativeDisplayInfo::physicalWidth()
{
    return displayInfo()->physicalWidth(currentScreen);
}
<commit_msg>this is displayinfo not networkinfo<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qdeclarativedisplayinfo_p.h"
#include "qsystemdisplayinfo.h"

QT_BEGIN_NAMESPACE

Q_GLOBAL_STATIC(QSystemDisplayInfo, displayInfo)

/*!
    \qmlclass DisplayInfo QDeclarativeDisplayInfo
    \brief The DisplayInfo element allows you to get information and
     receive notifications about the diplsay.
    \inherits QObject

    \ingroup qml-systeminfo

    This element is part of the \bold{QtMobility.systeminfo 1.2} module.
    It is a convience class to make QML usage easier.

    \endqml

\sa QSystemDisplayInfo
*/

/*!
    \qmlsignal DisplayInfo::orientationChanged()

    This handler is called when gui orientation has changed.
*/

/*!
  Constructs the DeviceInfo
  */
QDeclarativeDisplayInfo::QDeclarativeDisplayInfo(QObject *parent) :
    QSystemDisplayInfo(parent),currentScreen(0)
{
}

/*!
    \qmlproperty int DeviceInfo::screen

    Contains the display number of this screen.
*/
int QDeclarativeDisplayInfo::screen()
{
    return currentScreen;
}

/*!
   This function sets this DisplayInfo to use screen \a screen.

    If not set, the default is the default screen, or display 0.
*/
void QDeclarativeDisplayInfo::setCurrentScreen(int screen)
{
    currentScreen = screen;
}

/*!
    \qmlproperty int DisplayInfo::displayBrightness
   Returns the brightness of the screen.
  */
int QDeclarativeDisplayInfo::displayBrightness()
{
    return displayInfo()->displayBrightness(currentScreen);
}

/*!
    \qmlproperty int DisplayInfo::colorDepth
   Returns the color depth of the screen, in bits per pixel.
  */
int QDeclarativeDisplayInfo::colorDepth()
{
    return displayInfo()->colorDepth(currentScreen);
}

/*!
    \qmlproperty QSystemDisplayInfo::DisplayOrientation DisplayInfo::orientation
    Returns the QSystemDisplayInfo::DisplayOrientation of the UI QDesktopWidget for the screen.
  */
QSystemDisplayInfo::DisplayOrientation QDeclarativeDisplayInfo::orientation()
{
    return displayInfo()->orientation(currentScreen);
}

/*!
    \qmlproperty float DisplayInfo::contrast
   Returns the contrast of the screen, from 0 to 1.
  */
float QDeclarativeDisplayInfo::contrast()
{
    return displayInfo()->contrast(currentScreen);
}

/*!
    \qmlproperty int DisplayInfo::dpiWidth
   Returns the DPI width of the screen in millimeters.
  */
int QDeclarativeDisplayInfo::dpiWidth()
{
    return displayInfo()->getDPIWidth(currentScreen);
}

/*!
    \qmlproperty int DisplayInfo::dpiHeight
   Returns the DPI height of the screen in millimeters.
  */
int QDeclarativeDisplayInfo::dpiHeight()
{
    return displayInfo()->getDPIHeight(currentScreen);
}

/*!
    \qmlproperty int DisplayInfo::physicalHeight
   Returns the physical height of the screen in millimeters.
  */
int QDeclarativeDisplayInfo::physicalHeight()
{
    return displayInfo()->physicalHeight(currentScreen);
}

/*!
    \qmlproperty int DisplayInfo::physicalWidth
   Returns the physical width of the screen in millimeters.
  */
int QDeclarativeDisplayInfo::physicalWidth()
{
    return displayInfo()->physicalWidth(currentScreen);
}
<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright (c) 2010, Howard Butler
 *
 * 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 Martin Isenburg or Iowa Department
 *       of Natural Resources 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.
 ****************************************************************************/

#pragma once

#include <sstream>

#ifndef PDAL_DLL
#define PDAL_DLL
#endif

namespace pdal
{

/*!
    \verbatim embed:rst

    Bounds is for manipulating n-dimensional ranges of data.  Typically
    used for defining the spatial extents of XYZ data, this class can also be
    used for defining bounds of other dimensions.

    \endverbatim
*/

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wfloat-equal"

class PDAL_DLL BOX3D
{
private:
    static const double LOWEST;
    static const double HIGHEST;

public:

    BOX3D()
       { clear(); }

    BOX3D(const BOX3D& box) :
        minx(box.minx), maxx(box.maxx), miny(box.miny), maxy(box.maxy),
        minz(box.minz), maxz(box.maxz)
    {}

    BOX3D(double minx, double miny, double maxx, double maxy) :
        minx(minx), maxx(maxx), miny(miny), maxy(maxy),
        minz(HIGHEST), maxz(LOWEST)
    {}

    BOX3D(double minx, double miny, double minz, double maxx, double maxy,
            double maxz) :
        minx(minx), maxx(maxx), miny(miny), maxy(maxy), minz(minz), maxz(maxz)
    {}

    double minx;
    double maxx;
    double miny;
    double maxy;
    double minz;
    double maxz;

    bool empty() const
    {
        return  minx == HIGHEST && maxx == LOWEST &&
            miny == HIGHEST && maxy == LOWEST &&
            minz == HIGHEST && maxz == LOWEST;
    }

    bool contains(double x, double y, double z) const
    {
        return minx <= x && x <= maxx &&
               miny <= y && y <= maxy &&
               minz <= z && z <= maxz;
    }

    bool contains(const BOX3D& other) const
    {
        return minx <= other.minx && other.maxx <= maxx &&
            miny <= other.miny && other.maxy <= maxy &&
            minz <= other.minz && other.maxz <= maxz;
    }

    bool equal(const BOX3D& other) const
    {
        return  minx == other.minx && maxx == other.maxx &&
            miny == other.miny && maxy == other.maxy &&
            minz == other.minz && maxz == other.maxz;
    }

    bool operator==(BOX3D const& rhs) const
    {
        return equal(rhs);
    }

    bool operator!=(BOX3D const& rhs) const
    {
        return (!equal(rhs));
    }

    void grow(double x, double y, double z=LOWEST)
    {
        if (x < minx) minx = x;
        if (x > maxx) maxx = x;

        if (y < miny) miny = y;
        if (y > maxy) maxy = y;

        if (z < minz) minz = z;
        if (z > maxz) maxz = z;

    }

    void grow(const BOX3D& other)
    {
        if (other.minx < minx) minx = other.minx;
        if (other.maxx > maxx) maxx = other.maxx;

        if (other.miny < miny) miny = other.miny;
        if (other.maxy > maxy) maxy = other.maxy;

        if (other.minz < minz) minz = other.minz;
        if (other.maxz > maxz) maxz = other.maxz;
    }

    void clip(double x, double y, double z)
    {
        if (x > minx) minx = x;
        if (x < maxx) maxx = x;

        if (y > maxy) miny = y;
        if (y < maxy) maxy = y;

        if (z > maxz) minz = z;
        if (z < maxz) maxz = z;
    }

    void clip(const BOX3D& other)
    {
        if (other.minx > minx) minx = other.minx;
        if (other.maxx < maxx) maxx = other.maxx;

        if (other.miny > miny) miny = other.miny;
        if (other.maxy < maxy) maxy = other.maxy;

        if (other.minz < minz) minz = other.minz;
        if (other.maxz > maxz) maxz = other.maxz;
    }

    bool is_z_empty() const
    {
        return ((minz == HIGHEST) && (maxz == LOWEST));
    }

    bool overlaps(const BOX3D& other)
    {
        if (is_z_empty())
            return minx <= other.maxx && maxx >= other.minx &&
                   miny <= other.maxy && maxy >= other.miny;
        return minx <= other.maxx && maxx >= other.minx &&
               miny <= other.maxy && maxy >= other.miny &&
               minz <= other.maxz && maxz >= other.minz;
    }

    void clear()
    {
        minx = HIGHEST; miny = HIGHEST; minz = HIGHEST;
        maxx = LOWEST; maxy = LOWEST; maxz = LOWEST;
    }

    std::string toBox(uint32_t precision = 8, uint32_t dimensions = 2) const
    {
        std::stringstream oss;

        oss.precision(precision);
        oss.setf(std::ios_base::fixed, std::ios_base::floatfield);

        if (dimensions == 2)
        {
            oss << "box(";
            oss << minx << " " << miny << ", ";
            oss << maxx << " " << maxy << ")";
        }

        else if (dimensions == 3)
        {
            oss << "box3d(";
            oss << minx << " " << miny << " " << minz << ", ";
            oss << maxx << " " << maxy << " " << maxz << ")";
        }
        return oss.str();
    }

    std::string toWKT(uint32_t precision = 8) const
    {
        std::stringstream oss;

        oss.precision(precision);
        oss.setf(std::ios_base::fixed, std::ios_base::floatfield);

        oss << "POLYGON ((";

        oss << minx << " " << miny << ", ";
        oss << minx << " " << maxy << ", ";
        oss << maxx << " " << maxy << ", ";
        oss << maxx << " " << miny << ", ";
        oss << minx << " " << miny;
        oss << "))";

        // Nothing happens for 3D bounds.

        return oss.str();
    }

    /// Returns a staticly-allocated Bounds extent that represents infinity
    static const BOX3D& getDefaultSpatialExtent()
    {
        static BOX3D v(LOWEST, LOWEST, LOWEST, HIGHEST, HIGHEST, HIGHEST);
        return v;
    }

};

inline std::ostream& operator << (std::ostream& ostr, const BOX3D& bounds)
{
    if (bounds.empty())
    {
        ostr << "()";
        return ostr;
    }

    ostr << "(";
    ostr << "[" << bounds.minx << ", " << bounds.maxx << "], "
         << "[" << bounds.miny << ", " << bounds.maxy <<"]";
    if (!bounds.is_z_empty())
         ostr << ", [" <<  bounds.minz << ", " << bounds.maxz << "]";
    ostr << ")";
    return ostr;
}

extern PDAL_DLL std::istream& operator>>(std::istream& istr, BOX3D& bounds);

} // namespace pdal

#pragma GCC diagnostic pop
<commit_msg>if we do not want to rely on PDAL (pdal_export.hpp) to build the Utils library, then we need to define PDAL_DLL locally<commit_after>/******************************************************************************
 * Copyright (c) 2010, Howard Butler
 *
 * 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 Martin Isenburg or Iowa Department
 *       of Natural Resources 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.
 ****************************************************************************/

#pragma once

#include <cstdint>
#include <sstream>

#ifndef PDAL_DLL
#if defined(WIN32)
#   define PDAL_DLL   __declspec(dllexport)
#else
#  if defined(USE_GCC_VISIBILITY_FLAG)
#    define PDAL_DLL     __attribute__ ((visibility("default")))
#  else
#    define PDAL_DLL
#  endif
#endif
#endif

namespace pdal
{

/*!
    \verbatim embed:rst

    Bounds is for manipulating n-dimensional ranges of data.  Typically
    used for defining the spatial extents of XYZ data, this class can also be
    used for defining bounds of other dimensions.

    \endverbatim
*/

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wfloat-equal"

class PDAL_DLL BOX3D
{
private:
    static const double LOWEST;
    static const double HIGHEST;

public:

    BOX3D()
       { clear(); }

    BOX3D(const BOX3D& box) :
        minx(box.minx), maxx(box.maxx), miny(box.miny), maxy(box.maxy),
        minz(box.minz), maxz(box.maxz)
    {}

    BOX3D(double minx, double miny, double maxx, double maxy) :
        minx(minx), maxx(maxx), miny(miny), maxy(maxy),
        minz(HIGHEST), maxz(LOWEST)
    {}

    BOX3D(double minx, double miny, double minz, double maxx, double maxy,
            double maxz) :
        minx(minx), maxx(maxx), miny(miny), maxy(maxy), minz(minz), maxz(maxz)
    {}

    double minx;
    double maxx;
    double miny;
    double maxy;
    double minz;
    double maxz;

    bool empty() const
    {
        return  minx == HIGHEST && maxx == LOWEST &&
            miny == HIGHEST && maxy == LOWEST &&
            minz == HIGHEST && maxz == LOWEST;
    }

    bool contains(double x, double y, double z) const
    {
        return minx <= x && x <= maxx &&
               miny <= y && y <= maxy &&
               minz <= z && z <= maxz;
    }

    bool contains(const BOX3D& other) const
    {
        return minx <= other.minx && other.maxx <= maxx &&
            miny <= other.miny && other.maxy <= maxy &&
            minz <= other.minz && other.maxz <= maxz;
    }

    bool equal(const BOX3D& other) const
    {
        return  minx == other.minx && maxx == other.maxx &&
            miny == other.miny && maxy == other.maxy &&
            minz == other.minz && maxz == other.maxz;
    }

    bool operator==(BOX3D const& rhs) const
    {
        return equal(rhs);
    }

    bool operator!=(BOX3D const& rhs) const
    {
        return (!equal(rhs));
    }

    void grow(double x, double y, double z=LOWEST)
    {
        if (x < minx) minx = x;
        if (x > maxx) maxx = x;

        if (y < miny) miny = y;
        if (y > maxy) maxy = y;

        if (z < minz) minz = z;
        if (z > maxz) maxz = z;

    }

    void grow(const BOX3D& other)
    {
        if (other.minx < minx) minx = other.minx;
        if (other.maxx > maxx) maxx = other.maxx;

        if (other.miny < miny) miny = other.miny;
        if (other.maxy > maxy) maxy = other.maxy;

        if (other.minz < minz) minz = other.minz;
        if (other.maxz > maxz) maxz = other.maxz;
    }

    void clip(double x, double y, double z)
    {
        if (x > minx) minx = x;
        if (x < maxx) maxx = x;

        if (y > maxy) miny = y;
        if (y < maxy) maxy = y;

        if (z > maxz) minz = z;
        if (z < maxz) maxz = z;
    }

    void clip(const BOX3D& other)
    {
        if (other.minx > minx) minx = other.minx;
        if (other.maxx < maxx) maxx = other.maxx;

        if (other.miny > miny) miny = other.miny;
        if (other.maxy < maxy) maxy = other.maxy;

        if (other.minz < minz) minz = other.minz;
        if (other.maxz > maxz) maxz = other.maxz;
    }

    bool is_z_empty() const
    {
        return ((minz == HIGHEST) && (maxz == LOWEST));
    }

    bool overlaps(const BOX3D& other)
    {
        if (is_z_empty())
            return minx <= other.maxx && maxx >= other.minx &&
                   miny <= other.maxy && maxy >= other.miny;
        return minx <= other.maxx && maxx >= other.minx &&
               miny <= other.maxy && maxy >= other.miny &&
               minz <= other.maxz && maxz >= other.minz;
    }

    void clear()
    {
        minx = HIGHEST; miny = HIGHEST; minz = HIGHEST;
        maxx = LOWEST; maxy = LOWEST; maxz = LOWEST;
    }

    std::string toBox(uint32_t precision = 8, uint32_t dimensions = 2) const
    {
        std::stringstream oss;

        oss.precision(precision);
        oss.setf(std::ios_base::fixed, std::ios_base::floatfield);

        if (dimensions == 2)
        {
            oss << "box(";
            oss << minx << " " << miny << ", ";
            oss << maxx << " " << maxy << ")";
        }

        else if (dimensions == 3)
        {
            oss << "box3d(";
            oss << minx << " " << miny << " " << minz << ", ";
            oss << maxx << " " << maxy << " " << maxz << ")";
        }
        return oss.str();
    }

    std::string toWKT(uint32_t precision = 8) const
    {
        std::stringstream oss;

        oss.precision(precision);
        oss.setf(std::ios_base::fixed, std::ios_base::floatfield);

        oss << "POLYGON ((";

        oss << minx << " " << miny << ", ";
        oss << minx << " " << maxy << ", ";
        oss << maxx << " " << maxy << ", ";
        oss << maxx << " " << miny << ", ";
        oss << minx << " " << miny;
        oss << "))";

        // Nothing happens for 3D bounds.

        return oss.str();
    }

    /// Returns a staticly-allocated Bounds extent that represents infinity
    static const BOX3D& getDefaultSpatialExtent()
    {
        static BOX3D v(LOWEST, LOWEST, LOWEST, HIGHEST, HIGHEST, HIGHEST);
        return v;
    }

};

inline std::ostream& operator << (std::ostream& ostr, const BOX3D& bounds)
{
    if (bounds.empty())
    {
        ostr << "()";
        return ostr;
    }

    ostr << "(";
    ostr << "[" << bounds.minx << ", " << bounds.maxx << "], "
         << "[" << bounds.miny << ", " << bounds.maxy <<"]";
    if (!bounds.is_z_empty())
         ostr << ", [" <<  bounds.minz << ", " << bounds.maxz << "]";
    ostr << ")";
    return ostr;
}

extern PDAL_DLL std::istream& operator>>(std::istream& istr, BOX3D& bounds);

} // namespace pdal

#pragma GCC diagnostic pop
<|endoftext|>