#ifndef _ViewCellBsp_H__ #define _ViewCellBsp_H__ #include "Mesh.h" #include "Containers.h" #include "Polygon3.h" #include #include "Statistics.h" class ViewCell; class BspViewCell; class Plane3; class BspTree; class BspInterior; //class Polygon3; class AxisAlignedBox3; class Ray; class BspNodeGeometry { public: BspNodeGeometry() {}; ~BspNodeGeometry(); float GetArea() const; /** Computes new cell based on the old cell definition and a new split plane @param side indicates which side of the halfspace */ void SplitGeometry(BspNodeGeometry &front, BspNodeGeometry &back, const BspTree &tree, const Plane3 &splitPlane) const; Polygon3 *SplitPolygon(Polygon3 *poly, const BspTree &tree) const; PolygonContainer mPolys; }; /** Data structure used for optimized ray casting. */ struct BspRayTraversalData { BspNode *mNode; Vector3 mExitPoint; float mMaxT; BspRayTraversalData() {} BspRayTraversalData(BspNode *n, const Vector3 &extp, const float maxt): mNode(n), mExitPoint(extp), mMaxT(maxt) {} }; /** Data used for passing ray data down the tree. */ struct BoundedRay { Ray *mRay; float mMinT; float mMaxT; BoundedRay(): mMinT(0), mMaxT(1e6), mRay(NULL) {} BoundedRay(Ray *r, float minT, float maxT): mRay(r), mMinT(minT), mMaxT(maxT) {} }; typedef vector BoundedRayContainer; class BspTreeStatistics: public StatisticsBase { public: // total number of nodes int nodes; // number of splits int splits; // totals number of rays int rays; // maximal reached depth int maxDepth; // minimal depth int minDepth; // max depth nodes int maxDepthNodes; // max number of rays per node int maxObjectRefs; // accumulated depth (used to compute average) int accumDepth; // number of initial polygons int polys; /// samples contributing to pvs int contributingSamples; /// sample contributions to pvs int sampleContributions; /// largest pvs int largestPvs; // Constructor BspTreeStatistics() { Reset(); } int Nodes() const {return nodes;} int Interior() const { return nodes / 2; } int Leaves() const { return (nodes / 2) + 1; } // TODO: computation wrong double AvgDepth() const { return accumDepth / (double)Leaves();}; void Reset() { nodes = 0; splits = 0; maxDepthNodes = 0; maxDepth = 0; minDepth = 99999; polys = 0; accumDepth = 0; contributingSamples = 0; sampleContributions = 0; } void Print(ostream &app) const; friend ostream &operator<<(ostream &s, const BspTreeStatistics &stat) { stat.Print(s); return s; } }; class BspViewCellsStatistics: public StatisticsBase { public: /// number of view cells int viewCells; /// size of the PVS int pvs; /// largest PVS of all view cells int maxPvs; /// smallest PVS of all view cells int minPvs; /// view cells with empty PVS int emptyPvs; /// number of bsp leaves covering the view space int bspLeaves; /// largest number of leaves covered by one view cell int maxBspLeaves; // Constructor BspViewCellsStatistics() { Reset(); } double AvgBspLeaves() const {return (double)bspLeaves / (double)viewCells;}; double AvgPvs() const {return (double)pvs / (double)viewCells;}; void Reset() { viewCells = 0; pvs = 0; maxPvs = 0; minPvs = 999999; emptyPvs = 0; bspLeaves = 0; maxBspLeaves = 0; } void Print(ostream &app) const; friend ostream &operator<<(ostream &s, const BspViewCellsStatistics &stat) { stat.Print(s); return s; } }; /** BspNode abstract class serving for interior and leaf node implementation */ class BspNode { friend class BspTree; public: BspNode(); virtual ~BspNode(){}; BspNode(BspInterior *parent); /** Determines whether this node is a leaf or not @return true if leaf */ virtual bool IsLeaf() const = 0; /** Determines whether this node is a root @return true if root */ virtual bool IsRoot() const; /** Returns parent node. */ BspInterior *GetParent(); /** Sets parent node. */ void SetParent(BspInterior *parent); static int sMailId; int mMailbox; void Mail() { mMailbox = sMailId; } static void NewMail() { ++ sMailId; } bool Mailed() const { return mMailbox == sMailId; } protected: /// parent of this node BspInterior *mParent; }; /** BSP interior node implementation */ class BspInterior : public BspNode { friend class BspTree; public: /** Standard contructor taking split plane as argument. */ BspInterior(const Plane3 &plane); ~BspInterior(); /** @return false since it is an interior node */ bool IsLeaf() const; BspNode *GetBack(); BspNode *GetFront(); Plane3 *GetPlane(); void ReplaceChildLink(BspNode *oldChild, BspNode *newChild); void SetupChildLinks(BspNode *b, BspNode *f); /** Splits polygons with respect to the split plane. @param polys the polygons to be split. the polygons are consumed and distributed to the containers frontPolys, backPolys, coincident. @param frontPolys returns the polygons in the front of the split plane @param backPolys returns the polygons in the back of the split plane @param coincident returns the polygons coincident to the split plane @returns the number of splits */ int SplitPolygons(PolygonContainer &polys, PolygonContainer &frontPolys, PolygonContainer &backPolys, PolygonContainer &coincident); friend ostream &operator<<(ostream &s, const BspInterior &A) { return s << A.mPlane; } protected: /// Splitting plane corresponding to this node Plane3 mPlane; /// back node BspNode *mBack; /// front node BspNode *mFront; }; /** BSP leaf node implementation. */ class BspLeaf : public BspNode { friend class BspTree; public: BspLeaf(); BspLeaf(BspViewCell *viewCell); BspLeaf(BspInterior *parent); BspLeaf(BspInterior *parent, BspViewCell *viewCell); /** @return true since it is an interior node */ bool IsLeaf() const; /** Returns pointer of view cell. */ BspViewCell *GetViewCell() const; /** Sets pointer to view cell. */ void SetViewCell(BspViewCell *viewCell); /** Adds rays to the PVS. @param sampleContributions the number contributions of the sampels @param contributingSampels the number of contributing rays */ void AddToPvs(const BoundedRayContainer &rays, int &sampleContributions, int &contributingSamples, bool storeLeavesWithRays = false); protected: /// if NULL this does not correspond to feasible viewcell BspViewCell *mViewCell; }; /** Implementation of the view cell BSP tree. */ class BspTree { public: /** Additional data which is passed down the BSP tree during traversal. */ struct BspTraversalData { /// the current node BspNode *mNode; /// polygonal data for splitting PolygonContainer *mPolygons; /// current depth int mDepth; /// the view cell associated with this subdivsion ViewCell *mViewCell; /// rays piercing this node BoundedRayContainer *mRays; /// area of current node float mArea; BspNodeGeometry *mGeometry; /// pvs size int mPvs; BspTraversalData(): mNode(NULL), mPolygons(NULL), mDepth(0), mViewCell(NULL), mRays(NULL), mPvs(0), mArea(0.0), mGeometry(NULL) {} BspTraversalData(BspNode *node, PolygonContainer *polys, const int depth, ViewCell *viewCell, BoundedRayContainer *rays, int pvs, float area, BspNodeGeometry *cell): mNode(node), mPolygons(polys), mDepth(depth), mViewCell(viewCell), mRays(rays), mPvs(pvs), mArea(area), mGeometry(cell) {} }; typedef std::stack BspTraversalStack; /** Default constructor creating an empty tree. @param viewCell view cell corresponding to unbounded space */ BspTree(BspViewCell *viewCell); ~BspTree(); const BspTreeStatistics &GetStatistics() const; /** Constructs tree using the given list of view cells. For this type of construction we filter all view cells down the tree. If there is no polygon left, the last split plane decides inside or outside of the viewcell. A pointer to the appropriate view cell is stored within each leaf. Many leafs can point to the same viewcell. */ void Construct(const ViewCellContainer &viewCells); /** Constructs tree using the given list of objects. @note the objects are not taken as view cells, but the view cells are constructed from the subdivision: Each leaf is taken as one viewcell. @param objects list of objects */ void Construct(const ObjectContainer &objects); /** Constructs the tree from a given set of rays. @param sampleRays the set of sample rays the construction is based on @param viewCells if not NULL, new view cells are created in the leafs and stored in the conatainer */ void Construct(const RayContainer &sampleRays); /** Returns list of BSP leaves. */ void CollectLeaves(vector &leaves) const; /** Returns box which bounds the whole tree. */ AxisAlignedBox3 GetBoundingBox()const; /** Returns root of BSP tree. */ BspNode *GetRoot() const; /** Exports Bsp tree to file. */ bool Export(const string filename); /** Collects the leaf view cells of the tree @param viewCells returns the view cells */ void CollectViewCells(ViewCellContainer &viewCells) const; /** A ray is cast possible intersecting the tree. @param the ray that is cast. @returns the number of intersections with objects stored in the tree. */ int CastRay(Ray &ray); /** Set to true if new view cells shall be generated in each leaf. */ void SetGenerateViewCells(int generateViewCells); /// bsp tree construction types enum {FROM_INPUT_VIEW_CELLS, FROM_SCENE_GEOMETRY, FROM_SAMPLES}; /** Returns statistics. */ BspTreeStatistics &GetStat(); /** finds neighbouring leaves of this tree node. */ int FindNeighbors(BspNode *n, vector &neighbors, const bool onlyUnmailed) const; /** Constructs geometry associated with the half space intersections leading to this node. */ void ConstructGeometry(BspNode *n, PolygonContainer &cell) const; /** Construct geometry of view cell. */ void ConstructGeometry(BspViewCell *vc, PolygonContainer &cell) const; void ConstructGeometry(BspNode *n, BspNodeGeometry &cell) const; /** Returns random leaf of BSP tree. @param halfspace defines the halfspace from which the leaf is taken. */ BspLeaf *GetRandomLeaf(const Plane3 &halfspace); /** Returns random leaf of BSP tree. @param onlyUnmailed if only unmailed leaves should be returned. */ BspLeaf *GetRandomLeaf(const bool onlyUnmailed = false); /** Returns true if merge criteria are reached. */ bool ShouldMerge(BspLeaf *front, BspLeaf *back) const; /** Merges view cells based on some criteria E.g., empty view cells can pe purged, view cells which have a very similar PVS can be merged to one larger view cell. @returns true if merge was successful. */ bool MergeViewCells(BspLeaf *front, BspLeaf *back) const; /** Traverses tree and counts all view cells as well as their PVS size. */ void EvaluateViewCellsStats(BspViewCellsStatistics &stat) const; /** Parses the environment and stores the global BSP tree parameters */ static void ParseEnvironment(); /// BSP tree construction method static int sConstructionMethod; protected: // -------------------------------------------------------------- // For sorting objects // -------------------------------------------------------------- struct SortableEntry { enum {POLY_MIN, POLY_MAX}; int type; float value; Polygon3 *poly; SortableEntry() {} SortableEntry(const int t, const float v, Polygon3 *poly): type(t), value(v), poly(poly) {} bool operator<(const SortableEntry &b) const { return value < b.value; } }; /** Evaluates tree stats in the BSP tree leafs. */ void EvaluateLeafStats(const BspTraversalData &data); /** Subdivides node with respect to the traversal data. @param tStack current traversal stack @param tData traversal data also holding node to be subdivided @returns new root of the subtree */ BspNode *Subdivide(BspTraversalStack &tStack, BspTraversalData &tData); /** Constructs the tree from the given list of polygons and rays. @param polys stores set of polygons on which subdivision may be based @param rays storesset of rays on which subdivision may be based */ void Construct(PolygonContainer *polys, BoundedRayContainer *rays); /** Selects the best possible splitting plane. @param leaf the leaf to be split @param polys the polygon list on which the split decition is based @param rays ray container on which selection may be based @note the polygons can be reordered in the process @returns the split plane */ Plane3 SelectPlane(BspLeaf *leaf, BspTraversalData &data); /** Evaluates the contribution of the candidate split plane. @param candidatePlane the candidate split plane @param polys the polygons the split can be based on @param rays the rays the split can be based on @returns the cost of the candidate split plane */ float SplitPlaneCost(const Plane3 &candidatePlane, BspTraversalData &data) const; /** Strategies where the effect of the split plane is tested on all input rays. @returns the cost of the candidate split plane */ float SplitPlaneCost(const Plane3 &candidatePlane, const PolygonContainer &polys) const; /** Strategies where the effect of the split plane is tested on all input rays. @returns the cost of the candidate split plane */ float SplitPlaneCost(const Plane3 &candidatePlane, const BoundedRayContainer &rays, const int pvs, const float area, const BspNodeGeometry &cell) const; /** Filters next view cell down the tree and inserts it into the appropriate leaves (i.e., possibly more than one leaf). */ void InsertViewCell(ViewCell *viewCell); /** Inserts polygons down the tree. The polygons are filtered until a leaf is reached, then further subdivided. */ void InsertPolygons(PolygonContainer *polys); /** Subdivide leaf. @param leaf the leaf to be subdivided @param polys the polygons to be split @param frontPolys returns the polygons in front of the split plane @param backPolys returns the polygons in the back of the split plane @param rays the polygons to be filtered @param frontRays returns the polygons in front of the split plane @param backRays returns the polygons in the back of the split plane @returns the root of the subdivision */ BspInterior *SubdivideNode(BspTraversalData &tData, BspTraversalData &frontData, BspTraversalData &backData, PolygonContainer &coincident); /** Filters polygons down the tree. @param node the current BSP node @param polys the polygons to be filtered @param frontPolys returns the polygons in front of the split plane @param backPolys returns the polygons in the back of the split plane */ void FilterPolygons(BspInterior *node, PolygonContainer *polys, PolygonContainer *frontPolys, PolygonContainer *backPolys); /** Selects the split plane in order to construct a tree with certain characteristics (e.g., balanced tree, least splits, 2.5d aligned) @param polygons container of polygons @param rays bundle of rays on which the split can be based */ Plane3 SelectPlaneHeuristics(BspLeaf *leaf, BspTraversalData &data); /** Extracts the meshes of the objects and adds them to polygons. Adds object aabb to the aabb of the tree. @param maxPolys the maximal number of objects to be stored as polygons @returns the number of polygons */ int AddToPolygonSoup(const ObjectContainer &objects, PolygonContainer &polys, int maxObjects = 0); /** Extracts the meshes of the view cells and and adds them to polygons. Adds view cell aabb to the aabb of the tree. @param maxPolys the maximal number of objects to be stored as polygons @returns the number of polygons */ int AddToPolygonSoup(const ViewCellContainer &viewCells, PolygonContainer &polys, int maxObjects = 0); /** Extract polygons of this mesh and add to polygon container. @param mesh the mesh that drives the polygon construction @param parent the parent intersectable this polygon is constructed from @returns number of polygons */ int AddMeshToPolygons(Mesh *mesh, PolygonContainer &polys, MeshInstance *parent); /** returns next candidate index and reorders polygons so no candidate is chosen two times @param the current candidate index @param max the range of candidates */ int GetNextCandidateIdx(int currentIdx, PolygonContainer &polys); /** Helper function which extracts a view cell on the front and the back of the split plane. @param backViewCell returns view cell on the back of the split plane @param frontViewCell returns a view cell on the front of the split plane @param coincident container of polygons coincident to the split plane @param splitPlane the split plane which decides about back and front @param extractBack if a back view cell is extracted @param extractFront if a front view cell is extracted */ void ExtractViewCells(BspTraversalData &frontData, BspTraversalData &backData, const PolygonContainer &coincident, const Plane3 splitPlane) const; /** Computes best cost ratio for the suface area heuristics for axis aligned splits. This heuristics minimizes the cost for ray traversal. @param polys the polygons guiding the ratio computation @param box the bounding box of the leaf @param axis the current split axis @param position returns the split position @param objectsBack the number of objects in the back of the split plane @param objectsFront the number of objects in the front of the split plane */ float BestCostRatio(const PolygonContainer &polys, const AxisAlignedBox3 &box, const int axis, float &position, int &objectsBack, int &objectsFront) const; /** Sorts split candidates for surface area heuristics for axis aligned splits. @param polys the input for choosing split candidates @param axis the current split axis @param splitCandidates returns sorted list of split candidates */ void SortSplitCandidates(const PolygonContainer &polys, const int axis, vector &splitCandidates) const; /** Selects an axis aligned split plane. Returns true if split is valied */ bool SelectAxisAlignedPlane(Plane3 &plane, const PolygonContainer &polys) const; /** Bounds ray and returns minT and maxT. @returns true if ray hits BSP tree bounding box */ bool BoundRay(const Ray &ray, float &minT, float &maxT) const; /** Subdivides the rays into front and back rays according to the split plane. @param plane the split plane @param rays contains the rays to be split. The rays are distributed into front and back rays. @param frontRays returns rays on the front side of the plane @param backRays returns rays on the back side of the plane @returns the number of splits */ int SplitRays(const Plane3 &plane, BoundedRayContainer &rays, BoundedRayContainer &frontRays, BoundedRayContainer &backRays); /** Extracts the split planes representing the space bounded by node n. */ void ExtractHalfSpaces(BspNode *n, vector &halfSpaces) const; /** Computes the pvs of the front and back leaf with a given classification. */ void IncPvs(Intersectable &obj, int &frontPvs, int &backPvs, const int cf, const int frontId, const int backId, const int frontAndBackId) const; int ComputePvsSize(const BoundedRayContainer &rays) const; inline bool TerminationCriteriaMet(const BspTraversalData &data) const; float AccumulatedRayLength(BoundedRayContainer &rays) const; /// Pointer to the root of the tree BspNode *mRoot; BspTreeStatistics mStat; /// Strategies for choosing next split plane. enum {NO_STRATEGY = 0, RANDOM_POLYGON = 1, AXIS_ALIGNED = 2, LEAST_SPLITS = 4, BALANCED_POLYS = 8, BALANCED_VIEW_CELLS = 16, LARGEST_POLY_AREA = 32, VERTICAL_AXIS = 64, BLOCKED_RAYS = 128, LEAST_RAY_SPLITS = 256, BALANCED_RAYS = 512, PVS = 1024 }; /// box around the whole view domain AxisAlignedBox3 mBox; /// view cell corresponding to unbounded space BspViewCell *mRootCell; /// should view cells be stored or generated in the leaves? bool mGenerateViewCells; /// maximal number of polygons before subdivision termination int mTermMaxPolygons; /// maximal number of rays before subdivision termination int mTermMaxRays; /// maximal possible depth int mTermMaxDepth; /// mininum area float mTermMinArea; /// mininum PVS int mTermMinPvs; /// strategy to get the best split plane int mSplitPlaneStrategy; /// number of candidates evaluated for the next split plane int mMaxPolyCandidates; /// number of candidates for split planes evaluated using the rays int mMaxRayCandidates; /// maximal number of polygons for axis aligned split int mTermMaxPolysForAxisAligned; /// maximal number of rays for axis aligned split int mTermMaxRaysForAxisAligned; /// maximal number of objects for axis aligned split int mTermMaxObjectsForAxisAligned; /// maximal contribution per ray float mTermMaxRayContribution; /// maximal accumulated ray length float mTermMaxAccRayLength; bool mStoreLeavesWithRays; /// axis aligned split criteria float mCtDivCi; float mSplitBorder; float mMaxCostRatio; // factors guiding the split plane heuristics float mLeastSplitsFactor; float mBalancedPolysFactor; float mBalancedViewCellsFactor; float mVerticalSplitsFactor; float mLargestPolyAreaFactor; float mBlockedRaysFactor; float mLeastRaySplitsFactor; float mBalancedRaysFactor; float mPvsFactor; //-- thresholds used for view cells merge int mMinPvsDif; int mMinPvs; int mMaxPvs; /// if area or accumulated ray lenght should be used for PVS heuristics bool mPvsUseArea; private: /** Evaluates split plane classification with respect to the plane's contribution for a balanced tree. */ static const float sLeastPolySplitsTable[4]; /** Evaluates split plane classification with respect to the plane's contribution for a minimum number splits in the tree. */ static const float sBalancedPolysTable[4]; /** Evaluates split plane classification with respect to the plane's contribution for a minimum number of ray splits. */ static const float sLeastRaySplitsTable[5]; /** Evaluates split plane classification with respect to the plane's contribution for balanced rays. */ static const float sBalancedRaysTable[5]; }; #endif