#include #include #include #include "ViewCell.h" #include "Plane3.h" #include "VspTree.h" #include "Mesh.h" #include "common.h" #include "Environment.h" #include "Polygon3.h" #include "Ray.h" #include "AxisAlignedBox3.h" #include "Exporter.h" #include "Plane3.h" #include "ViewCellsManager.h" #include "Beam.h" #include "KdTree.h" #include "KdIntersectable.h" #include "HierarchyManager.h" #include "BvHierarchy.h" #include "OspTree.h" namespace GtpVisibilityPreprocessor { #define USE_FIXEDPOINT_T 0 //-- static members VspTree *VspTree::VspSubdivisionCandidate::sVspTree = NULL; // variable for debugging volume contribution for heuristics static float debugVol; int VspNode::sMailId = 1; // pvs penalty can be different from pvs size inline static float EvalPvsPenalty(const int pvs, const int lower, const int upper) { // clamp to minmax values if (pvs < lower) { return (float)lower; } else if (pvs > upper) { return (float)upper; } return (float)pvs; } static bool ViewCellHasMultipleReferences(Intersectable *obj, ViewCell *vc, bool checkOnlyMailed) { MailablePvsData *vdata = obj->mViewCellPvs.Find(vc); //return false; if (vdata) { // more than one view cell sees this object inside different kd cells if (!checkOnlyMailed || !vdata->Mailed()) { if (checkOnlyMailed) vdata->Mail(); //Debug << "sumpdf: " << vdata->mSumPdf << endl; if (vdata->mSumPdf > 1.5f) return true; } } return false; } void VspTreeStatistics::Print(ostream &app) const { app << "=========== VspTree statistics ===============\n"; app << setprecision(4); app << "#N_CTIME ( Construction time [s] )\n" << Time() << " \n"; app << "#N_NODES ( Number of nodes )\n" << nodes << "\n"; app << "#N_INTERIORS ( Number of interior nodes )\n" << Interior() << "\n"; app << "#N_LEAVES ( Number of leaves )\n" << Leaves() << "\n"; app << "#AXIS_ALIGNED_SPLITS (number of axis aligned splits)\n" << splits[0] + splits[1] + splits[2] << endl; app << "#N_SPLITS ( Number of splits in axes x y z)\n"; for (int i = 0; i < 3; ++ i) app << splits[i] << " "; app << endl; app << "#N_PMAXDEPTHLEAVES ( Percentage of leaves at maximum depth )\n" << maxDepthNodes * 100 / (double)Leaves() << endl; app << "#N_PMINPVSLEAVES ( Percentage of leaves with mininimal PVS )\n" << minPvsNodes * 100 / (double)Leaves() << endl; app << "#N_PMINRAYSLEAVES ( Percentage of leaves with minimal number of rays)\n" << minRaysNodes * 100 / (double)Leaves() << endl; app << "#N_MAXCOSTNODES ( Percentage of leaves with terminated because of max cost ratio )\n" << maxCostNodes * 100 / (double)Leaves() << endl; app << "#N_PMINPROBABILITYLEAVES ( Percentage of leaves with mininum probability )\n" << minProbabilityNodes * 100 / (double)Leaves() << endl; app << "#N_PMAXRAYCONTRIBLEAVES ( Percentage of leaves with maximal ray contribution )\n" << maxRayContribNodes * 100 / (double)Leaves() << endl; app << "#N_PMAXDEPTH ( Maximal reached depth )\n" << maxDepth << endl; app << "#N_PMINDEPTH ( Minimal reached depth )\n" << minDepth << endl; app << "#AVGDEPTH ( average depth )\n" << AvgDepth() << endl; app << "#N_INVALIDLEAVES (number of invalid leaves )\n" << invalidLeaves << endl; app << "#N_RAYS (number of rays / leaf)\n" << AvgRays() << endl; //app << "#N_PVS: " << pvs << endl; //app << "#N_MAXOBJECTREFS ( Max number of object refs / leaf )\n" << maxObjectRefs << "\n"; app << "========== END OF VspTree statistics ==========\n"; } /******************************************************************/ /* class VspNode implementation */ /******************************************************************/ VspNode::VspNode(): mParent(NULL), mTreeValid(true), mTimeStamp(0) {} VspNode::VspNode(VspInterior *parent): mParent(parent), mTreeValid(true) {} bool VspNode::IsRoot() const { return mParent == NULL; } VspInterior *VspNode::GetParent() { return mParent; } void VspNode::SetParent(VspInterior *parent) { mParent = parent; } bool VspNode::IsSibling(VspNode *n) const { return ((this != n) && mParent && (mParent->GetFront() == n) || (mParent->GetBack() == n)); } int VspNode::GetDepth() const { int depth = 0; VspNode *p = mParent; while (p) { p = p->mParent; ++ depth; } return depth; } bool VspNode::TreeValid() const { return mTreeValid; } void VspNode::SetTreeValid(const bool v) { mTreeValid = v; } /****************************************************************/ /* class VspInterior implementation */ /****************************************************************/ VspInterior::VspInterior(const AxisAlignedPlane &plane): mPlane(plane), mFront(NULL), mBack(NULL) {} VspInterior::~VspInterior() { DEL_PTR(mFront); DEL_PTR(mBack); } bool VspInterior::IsLeaf() const { return false; } VspNode *VspInterior::GetBack() { return mBack; } VspNode *VspInterior::GetFront() { return mFront; } AxisAlignedPlane VspInterior::GetPlane() const { return mPlane; } float VspInterior::GetPosition() const { return mPlane.mPosition; } int VspInterior::GetAxis() const { return mPlane.mAxis; } void VspInterior::ReplaceChildLink(VspNode *oldChild, VspNode *newChild) { if (mBack == oldChild) mBack = newChild; else mFront = newChild; } void VspInterior::SetupChildLinks(VspNode *front, VspNode *back) { mBack = back; mFront = front; } AxisAlignedBox3 VspInterior::GetBoundingBox() const { return mBoundingBox; } void VspInterior::SetBoundingBox(const AxisAlignedBox3 &box) { mBoundingBox = box; } int VspInterior::Type() const { return Interior; } /****************************************************************/ /* class VspLeaf implementation */ /****************************************************************/ VspLeaf::VspLeaf(): mViewCell(NULL), mPvs(NULL) { } VspLeaf::~VspLeaf() { DEL_PTR(mPvs); CLEAR_CONTAINER(mVssRays); } int VspLeaf::Type() const { return Leaf; } VspLeaf::VspLeaf(ViewCellLeaf *viewCell): mViewCell(viewCell) { } VspLeaf::VspLeaf(VspInterior *parent): VspNode(parent), mViewCell(NULL), mPvs(NULL) {} VspLeaf::VspLeaf(VspInterior *parent, ViewCellLeaf *viewCell): VspNode(parent), mViewCell(viewCell), mPvs(NULL) { } ViewCellLeaf *VspLeaf::GetViewCell() const { return mViewCell; } void VspLeaf::SetViewCell(ViewCellLeaf *viewCell) { mViewCell = viewCell; } bool VspLeaf::IsLeaf() const { return true; } /*************************************************************************/ /* class VspTree implementation */ /*************************************************************************/ VspTree::VspTree(): mRoot(NULL), mOutOfBoundsCell(NULL), mStoreRays(false), mTimeStamp(1), mHierarchyManager(NULL) { bool randomize = false; Environment::GetSingleton()->GetBoolValue("VspTree.Construction.randomize", randomize); if (randomize) Randomize(); // initialise random generator for heuristics //-- termination criteria for autopartition Environment::GetSingleton()->GetIntValue("VspTree.Termination.maxDepth", mTermMaxDepth); Environment::GetSingleton()->GetIntValue("VspTree.Termination.minPvs", mTermMinPvs); Environment::GetSingleton()->GetIntValue("VspTree.Termination.minRays", mTermMinRays); Environment::GetSingleton()->GetFloatValue("VspTree.Termination.minProbability", mTermMinProbability); Environment::GetSingleton()->GetFloatValue("VspTree.Termination.maxRayContribution", mTermMaxRayContribution); Environment::GetSingleton()->GetIntValue("VspTree.Termination.missTolerance", mTermMissTolerance); Environment::GetSingleton()->GetIntValue("VspTree.Termination.maxViewCells", mMaxViewCells); //-- max cost ratio for early tree termination Environment::GetSingleton()->GetFloatValue("VspTree.Termination.maxCostRatio", mTermMaxCostRatio); Environment::GetSingleton()->GetFloatValue("VspTree.Termination.minGlobalCostRatio", mTermMinGlobalCostRatio); Environment::GetSingleton()->GetIntValue("VspTree.Termination.globalCostMissTolerance", mTermGlobalCostMissTolerance); //-- factors for bsp tree split plane heuristics Environment::GetSingleton()->GetFloatValue("VspTree.Termination.ct_div_ci", mCtDivCi); //-- partition criteria Environment::GetSingleton()->GetFloatValue("VspTree.Construction.epsilon", mEpsilon); Environment::GetSingleton()->GetFloatValue("VspTree.Construction.renderCostDecreaseWeight", mRenderCostDecreaseWeight); // if only the driving axis is used for axis aligned split Environment::GetSingleton()->GetBoolValue("VspTree.splitUseOnlyDrivingAxis", mOnlyDrivingAxis); Environment::GetSingleton()->GetIntValue("VspTree.maxTests", mMaxTests); Environment::GetSingleton()->GetFloatValue("VspTree.maxStaticMemory", mMaxMemory); Environment::GetSingleton()->GetBoolValue("VspTree.useCostHeuristics", mUseCostHeuristics); Environment::GetSingleton()->GetBoolValue("VspTree.simulateOctree", mCirculatingAxis); //Environment::GetSingleton()->GetBoolValue("VspTree.useKdPvsForHeuristics", mUseKdPvsForHeuristics); char subdivisionStatsLog[100]; Environment::GetSingleton()->GetStringValue("VspTree.subdivisionStats", subdivisionStatsLog); mSubdivisionStats.open(subdivisionStatsLog); Environment::GetSingleton()->GetFloatValue("VspTree.Construction.minBand", mMinBand); Environment::GetSingleton()->GetFloatValue("VspTree.Construction.maxBand", mMaxBand); //-- debug output Debug << "******* VSP options ******** " << endl; Debug << "max depth: " << mTermMaxDepth << endl; Debug << "min PVS: " << mTermMinPvs << endl; Debug << "min probabiliy: " << mTermMinProbability << endl; Debug << "min rays: " << mTermMinRays << endl; Debug << "max ray contri: " << mTermMaxRayContribution << endl; Debug << "max cost ratio: " << mTermMaxCostRatio << endl; Debug << "miss tolerance: " << mTermMissTolerance << endl; Debug << "max view cells: " << mMaxViewCells << endl; Debug << "randomize: " << randomize << endl; Debug << "min global cost ratio: " << mTermMinGlobalCostRatio << endl; Debug << "global cost miss tolerance: " << mTermGlobalCostMissTolerance << endl; Debug << "only driving axis: " << mOnlyDrivingAxis << endl; Debug << "max memory: " << mMaxMemory << endl; Debug << "use cost heuristics: " << mUseCostHeuristics << endl; Debug << "subdivision stats log: " << subdivisionStatsLog << endl; Debug << "render cost decrease weight: " << mRenderCostDecreaseWeight << endl; Debug << "circulating axis: " << mCirculatingAxis << endl; Debug << "minband: " << mMinBand << endl; Debug << "maxband: " << mMaxBand << endl; mLocalSubdivisionCandidates = new vector; Debug << endl; } VspViewCell *VspTree::GetOutOfBoundsCell() { return mOutOfBoundsCell; } VspViewCell *VspTree::GetOrCreateOutOfBoundsCell() { if (!mOutOfBoundsCell) { mOutOfBoundsCell = new VspViewCell(); mOutOfBoundsCell->SetId(-1); mOutOfBoundsCell->SetValid(false); } return mOutOfBoundsCell; } const VspTreeStatistics &VspTree::GetStatistics() const { return mVspStats; } VspTree::~VspTree() { DEL_PTR(mRoot); DEL_PTR(mLocalSubdivisionCandidates); } void VspTree::ComputeBoundingBox(const VssRayContainer &rays, AxisAlignedBox3 *forcedBoundingBox) { if (forcedBoundingBox) { mBoundingBox = *forcedBoundingBox; } else // compute vsp tree bounding box { mBoundingBox.Initialize(); VssRayContainer::const_iterator rit, rit_end = rays.end(); //-- compute bounding box for (rit = rays.begin(); rit != rit_end; ++ rit) { VssRay *ray = *rit; // compute bounding box of view space mBoundingBox.Include(ray->GetTermination()); mBoundingBox.Include(ray->GetOrigin()); } } } void VspTree::AddSubdivisionStats(const int viewCells, const float renderCostDecr, const float totalRenderCost, const float avgRenderCost) { mSubdivisionStats << "#ViewCells\n" << viewCells << endl << "#RenderCostDecrease\n" << renderCostDecr << endl << "#TotalRenderCost\n" << totalRenderCost << endl << "#AvgRenderCost\n" << avgRenderCost << endl; } // TODO: return memory usage in MB float VspTree::GetMemUsage() const { return (float) (sizeof(VspTree) + mVspStats.Leaves() * sizeof(VspLeaf) + mCreatedViewCells * sizeof(VspViewCell) + mVspStats.pvs * sizeof(PvsData) + mVspStats.Interior() * sizeof(VspInterior) + mVspStats.accumRays * sizeof(RayInfo)) / (1024.0f * 1024.0f); } inline bool VspTree::LocalTerminationCriteriaMet(const VspTraversalData &data) const { const bool localTerminationCriteriaMet = ( ((int)data.mRays->size() <= mTermMinRays) || (data.mPvs <= mTermMinPvs) || (data.mProbability <= mTermMinProbability) || (data.GetAvgRayContribution() > mTermMaxRayContribution) || (data.mDepth >= mTermMaxDepth) ); if (0 && localTerminationCriteriaMet) { Debug << "********local termination *********" << endl; Debug << "rays: " << (int)data.mRays->size() << " " << mTermMinRays << endl; Debug << "pvs: " << data.mPvs << " " << mTermMinPvs << endl; Debug << "p: " << data.mProbability << " " << mTermMinProbability << endl; Debug << "avg contri: " << data.GetAvgRayContribution() << " " << mTermMaxRayContribution << endl; Debug << "depth " << data.mDepth << " " << mTermMaxDepth << endl; } return localTerminationCriteriaMet; } inline bool VspTree::GlobalTerminationCriteriaMet(const VspTraversalData &data) const { const bool terminationCriteriaMet = ( // mOutOfMemory || (mVspStats.Leaves() >= mMaxViewCells) || (mGlobalCostMisses >= mTermGlobalCostMissTolerance) ); if (0 && terminationCriteriaMet) { Debug << "********* terminationCriteriaMet *********" << endl; Debug << "cost misses: " << mGlobalCostMisses << " " << mTermGlobalCostMissTolerance << endl; Debug << "leaves: " << mVspStats.Leaves() << " " << mMaxViewCells << endl; } return terminationCriteriaMet; } void VspTree::CreateViewCell(VspTraversalData &tData, const bool updatePvs) { //-- create new view cell VspLeaf *leaf = dynamic_cast(tData.mNode); VspViewCell *viewCell = new VspViewCell(); leaf->SetViewCell(viewCell); int conSamp = 0; float sampCon = 0.0f; if (updatePvs) { //-- update pvs of view cell AddSamplesToPvs(leaf, *tData.mRays, sampCon, conSamp); // update scalar pvs size value ObjectPvs &pvs = viewCell->GetPvs(); mViewCellsManager->UpdateScalarPvsSize(viewCell, pvs.CountObjectsInPvs(), pvs.GetSize()); mVspStats.contributingSamples += conSamp; mVspStats.sampleContributions += (int)sampCon; } //-- store additional info if (mStoreRays) { RayInfoContainer::const_iterator it, it_end = tData.mRays->end(); for (it = tData.mRays->begin(); it != it_end; ++ it) { (*it).mRay->Ref(); leaf->mVssRays.push_back((*it).mRay); } } // set view cell values viewCell->mLeaf = leaf; viewCell->SetVolume(tData.mProbability); leaf->mProbability = tData.mProbability; } void VspTree::EvalSubdivisionStats(const SubdivisionCandidate &sc) { const float costDecr = sc.GetRenderCostDecrease(); AddSubdivisionStats(mVspStats.Leaves(), costDecr, mTotalCost, (float)mTotalPvsSize / (float)mVspStats.Leaves()); } VspNode *VspTree::Subdivide(SplitQueue &tQueue, SubdivisionCandidate *splitCandidate, const bool globalCriteriaMet) { // todo remove dynamic cast VspSubdivisionCandidate *sc = dynamic_cast(splitCandidate); VspTraversalData &tData = sc->mParentData; VspNode *newNode = tData.mNode; if (!LocalTerminationCriteriaMet(tData) && !globalCriteriaMet) { VspTraversalData tFrontData; VspTraversalData tBackData; //-- continue subdivision // create new interior node and two leaf node const AxisAlignedPlane splitPlane = sc->mSplitPlane; newNode = SubdivideNode(splitPlane, tData, tFrontData, tBackData); const int maxCostMisses = sc->mMaxCostMisses; // how often was max cost ratio missed in this branch? tFrontData.mMaxCostMisses = maxCostMisses; tBackData.mMaxCostMisses = maxCostMisses; mTotalCost -= sc->GetRenderCostDecrease(); mTotalPvsSize += tFrontData.mPvs + tBackData.mPvs - tData.mPvs; // subdivision statistics if (1) EvalSubdivisionStats(*sc); //-- evaluate new split candidates for global greedy cost heuristics VspSubdivisionCandidate *frontCandidate = new VspSubdivisionCandidate(tFrontData); VspSubdivisionCandidate *backCandidate = new VspSubdivisionCandidate(tBackData); EvalSubdivisionCandidate(*frontCandidate); EvalSubdivisionCandidate(*backCandidate); tQueue.Push(frontCandidate); tQueue.Push(backCandidate); // delete old view cell delete tData.mNode->mViewCell; // delete old leaf node DEL_PTR(tData.mNode); } if (newNode->IsLeaf()) // subdivision terminated { // view cell is created during subdivision //CreateViewCell(tData); VspLeaf *leaf = dynamic_cast(newNode); ViewCell *viewCell = leaf->GetViewCell(); int conSamp = 0; float sampCon = 0.0f; #if 0 //-- store pvs optained from rays AddSamplesToPvs(leaf, *tData.mRays, sampCon, conSamp); // update scalar pvs size value ObjectPvs &pvs = viewCell->GetPvs(); mViewCellsManager->UpdateScalarPvsSize(viewCell, pvs.CountObjectsInPvs(), pvs.GetSize()); mVspStats.contributingSamples += conSamp; mVspStats.sampleContributions += (int)sampCon; #endif //-- store additional info if (mStoreRays) { RayInfoContainer::const_iterator it, it_end = tData.mRays->end(); for (it = tData.mRays->begin(); it != it_end; ++ it) { (*it).mRay->Ref(); leaf->mVssRays.push_back((*it).mRay); } } // finally evaluate statistics for this leaf EvaluateLeafStats(tData); } //-- cleanup tData.Clear(); return newNode; } void VspTree::EvalSubdivisionCandidate(VspSubdivisionCandidate &splitCandidate) { float frontProb; float backProb; VspLeaf *leaf = dynamic_cast(splitCandidate.mParentData.mNode); // compute locally best split plane const float ratio = SelectSplitPlane( splitCandidate.mParentData, splitCandidate.mSplitPlane, frontProb, backProb); const bool success = ratio < mTermMaxCostRatio; float oldRenderCost; // compute global decrease in render cost const float renderCostDecr = EvalRenderCostDecrease(splitCandidate.mSplitPlane, splitCandidate.mParentData, oldRenderCost); splitCandidate.SetRenderCostDecrease(renderCostDecr); #if 0 const float priority = (float)-data.mDepth; #else // take render cost of node into account // otherwise danger of being stuck in a local minimum!! const float factor = mRenderCostDecreaseWeight; const float priority = factor * renderCostDecr + (1.0f - factor) * oldRenderCost; #endif splitCandidate.SetPriority(priority); // max cost threshold violated? splitCandidate.mMaxCostMisses = success ? splitCandidate.mParentData.mMaxCostMisses : splitCandidate.mParentData.mMaxCostMisses + 1; //Debug << "p: " << tData.mNode << " depth: " << tData.mDepth << endl; } VspInterior *VspTree::SubdivideNode(const AxisAlignedPlane &splitPlane, VspTraversalData &tData, VspTraversalData &frontData, VspTraversalData &backData) { VspLeaf *leaf = dynamic_cast(tData.mNode); //-- the front and back traversal data is filled with the new values frontData.mDepth = tData.mDepth + 1; backData.mDepth = tData.mDepth + 1; frontData.mRays = new RayInfoContainer(); backData.mRays = new RayInfoContainer(); //-- subdivide rays SplitRays(splitPlane, *tData.mRays, *frontData.mRays, *backData.mRays); //Debug << "f: " << frontData.mRays->size() << " b: " << backData.mRays->size() << "d: " << tData.mRays->size() << endl; //-- compute pvs frontData.mPvs = EvalPvsSize(*frontData.mRays); backData.mPvs = EvalPvsSize(*backData.mRays); // split front and back node geometry and compute area tData.mBoundingBox.Split(splitPlane.mAxis, splitPlane.mPosition, frontData.mBoundingBox, backData.mBoundingBox); frontData.mProbability = frontData.mBoundingBox.GetVolume(); backData.mProbability = tData.mProbability - frontData.mProbability; /////////////////////////////////////////// // subdivide further // store maximal and minimal depth if (tData.mDepth > mVspStats.maxDepth) { Debug << "max depth increases to " << tData.mDepth << " at " << mVspStats.Leaves() << " leaves" << endl; mVspStats.maxDepth = tData.mDepth; } // two more leaves mVspStats.nodes += 2; VspInterior *interior = new VspInterior(splitPlane); #ifdef _DEBUG Debug << interior << endl; #endif+ //-- create front and back leaf VspInterior *parent = leaf->GetParent(); // replace a link from node's parent if (parent) { parent->ReplaceChildLink(leaf, interior); interior->SetParent(parent); // remove "parent" view cell from pvs of all objects (traverse trough rays) RemoveParentViewCellReferences(tData.mNode->GetViewCell()); } else // new root { mRoot = interior; } VspLeaf *frontLeaf = new VspLeaf(interior); VspLeaf *backLeaf = new VspLeaf(interior); // and setup child links interior->SetupChildLinks(frontLeaf, backLeaf); // add bounding box interior->SetBoundingBox(tData.mBoundingBox); // set front and back leaf frontData.mNode = frontLeaf; backData.mNode = backLeaf; // explicitely create front and back view cell CreateViewCell(frontData, false); CreateViewCell(backData, false); #if WORK_WITH_VIEWCELL_PVS // create front and back view cell // add front and back view cell to "Potentially Visbilie View Cells" // of the objects in front and back pvs AddViewCellReferences(frontLeaf->GetViewCell()); AddViewCellReferences(backLeaf->GetViewCell()); #endif interior->mTimeStamp = mTimeStamp ++; return interior; } void VspTree::RemoveParentViewCellReferences(ViewCell *parent) const { KdLeaf::NewMail(); // remove the parents from the object pvss ObjectPvsMap::const_iterator oit, oit_end = parent->GetPvs().mEntries.end(); for (oit = parent->GetPvs().mEntries.begin(); oit != oit_end; ++ oit) { Intersectable *object = (*oit).first; // HACK: make sure that the view cell is removed from the pvs const float high_contri = 9999999; // remove reference count of view cells object->mViewCellPvs.RemoveSample(parent, high_contri); } } void VspTree::AddViewCellReferences(ViewCell *vc) const { KdLeaf::NewMail(); // Add front view cell to the object pvsss ObjectPvsMap::const_iterator oit, oit_end = vc->GetPvs().mEntries.end(); for (oit = vc->GetPvs().mEntries.begin(); oit != oit_end; ++ oit) { Intersectable *object = (*oit).first; // increase reference count of view cells object->mViewCellPvs.AddSample(vc, 1); } } void VspTree::AddSamplesToPvs(VspLeaf *leaf, const RayInfoContainer &rays, float &sampleContributions, int &contributingSamples) { sampleContributions = 0; contributingSamples = 0; RayInfoContainer::const_iterator it, it_end = rays.end(); ViewCellLeaf *vc = leaf->GetViewCell(); // add contributions from samples to the PVS for (it = rays.begin(); it != it_end; ++ it) { float sc = 0.0f; VssRay *ray = (*it).mRay; bool madeContrib = false; float contribution; Intersectable *obj = ray->mTerminationObject; if (obj) { madeContrib = mViewCellsManager->AddSampleToPvs( obj, ray->mTermination, vc, ray->mPdf, contribution); sc += contribution; } obj = ray->mOriginObject; if (obj) { madeContrib = mViewCellsManager->AddSampleToPvs( obj, ray->mOrigin, vc, ray->mPdf, contribution); sc += contribution; } if (madeContrib) { ++ contributingSamples; } // store rays for visualization if (0) leaf->mVssRays.push_back(new VssRay(*ray)); } } void VspTree::SortSubdivisionCandidates(const RayInfoContainer &rays, const int axis, float minBand, float maxBand) { mLocalSubdivisionCandidates->clear(); int requestedSize = 2 * (int)(rays.size()); // creates a sorted split candidates array if (mLocalSubdivisionCandidates->capacity() > 500000 && requestedSize < (int)(mLocalSubdivisionCandidates->capacity() / 10) ) { delete mLocalSubdivisionCandidates; mLocalSubdivisionCandidates = new vector; } mLocalSubdivisionCandidates->reserve(requestedSize); float pos; RayInfoContainer::const_iterator rit, rit_end = rays.end(); //-- insert all queries for (rit = rays.begin(); rit != rit_end; ++ rit) { const bool positive = (*rit).mRay->HasPosDir(axis); pos = (*rit).ExtrapOrigin(axis); mLocalSubdivisionCandidates->push_back(SortableEntry(positive ? SortableEntry::ERayMin : SortableEntry::ERayMax, pos, (*rit).mRay)); pos = (*rit).ExtrapTermination(axis); mLocalSubdivisionCandidates->push_back(SortableEntry(positive ? SortableEntry::ERayMax : SortableEntry::ERayMin, pos, (*rit).mRay)); } stable_sort(mLocalSubdivisionCandidates->begin(), mLocalSubdivisionCandidates->end()); } int VspTree::GetPvsContribution(Intersectable *object) const { int pvsContri = 0; KdPvsMap::const_iterator kit, kit_end = object->mKdPvs.mEntries.end(); Intersectable::NewMail(); // Search kd leaves this object is attached to for (kit = object->mKdPvs.mEntries.begin(); kit != kit_end; ++ kit) { KdNode *l = (*kit).first; // new object found during sweep // => increase pvs contribution of this kd node if (!l->Mailed()) { l->Mail(); ++ pvsContri; } } return pvsContri; } int VspTree::PrepareHeuristics(const VssRay &ray, const bool isTermination) { int pvsSize = 0; Intersectable *obj; Vector3 pt; KdNode *node; ray.GetSampleData(isTermination, pt, &obj, &node); if (!obj) return 0; switch (mHierarchyManager->GetObjectSpaceSubdivisonType()) { case HierarchyManager::NO_OBJ_SUBDIV: { if (!obj->Mailed()) { obj->Mail(); obj->mCounter = 1; ++ pvsSize; } else { ++ obj->mCounter; } break; } case HierarchyManager::KD_BASED_OBJ_SUBDIV: { KdLeaf *leaf = mHierarchyManager->mOspTree->GetLeaf(pt, node); pvsSize += PrepareHeuristics(leaf); break; } case HierarchyManager::BV_BASED_OBJ_SUBDIV: { BvhLeaf *leaf = mHierarchyManager->mBvHierarchy->GetLeaf(obj); if (!leaf->Mailed()) { leaf->Mail(); leaf->mCounter = 1; pvsSize += (int)leaf->mObjects.size(); } else { ++ leaf->mCounter; } break; } default: break; } return pvsSize; } int VspTree::PrepareHeuristics(KdLeaf *leaf) { int pvsSize = 0; if (!leaf->Mailed()) { leaf->Mail(); leaf->mCounter = 1; // add objects without the objects which are in several kd leaves pvsSize += (int)(leaf->mObjects.size() - leaf->mMultipleObjects.size()); //Debug << "adding " << (int)leaf->mObjects.size() << " " << leaf->mMultipleObjects.size() << endl; } else { ++ leaf->mCounter; } //-- the objects belonging to several leaves must be handled seperately ObjectContainer::const_iterator oit, oit_end = leaf->mMultipleObjects.end(); for (oit = leaf->mMultipleObjects.begin(); oit != oit_end; ++ oit) { Intersectable *object = *oit; if (!object->Mailed()) { object->Mail(); object->mCounter = 1; ++ pvsSize; } else { ++ object->mCounter; } } return pvsSize; } int VspTree::PrepareHeuristics(const RayInfoContainer &rays) { Intersectable::NewMail(); KdNode::NewMail(); int pvsSize = 0; RayInfoContainer::const_iterator ri, ri_end = rays.end(); // set all kd nodes / objects as belonging to the front pvs for (ri = rays.begin(); ri != ri_end; ++ ri) { VssRay *ray = (*ri).mRay; pvsSize += PrepareHeuristics(*ray, true); pvsSize += PrepareHeuristics(*ray, false); } return pvsSize; } int VspTree::EvalMaxEventContribution(KdLeaf *leaf) const { int pvs = 0; // leaf falls out of right pvs if (-- leaf->mCounter == 0) { pvs -= ((int)leaf->mObjects.size() - (int)leaf->mMultipleObjects.size()); } //-- separately handle objects which are in several kd leaves ObjectContainer::const_iterator oit, oit_end = leaf->mMultipleObjects.end(); for (oit = leaf->mMultipleObjects.begin(); oit != oit_end; ++ oit) { Intersectable *object = *oit; if (-- object->mCounter == 0) { ++ pvs; } } return pvs; } int VspTree::EvalMinEventContribution(KdLeaf *leaf) const { if (leaf->Mailed()) return 0; leaf->Mail(); // add objects without those which are part of several kd leaves int pvs = ((int)leaf->mObjects.size() - (int)leaf->mMultipleObjects.size()); // separately handle objects which are part of several kd leaves ObjectContainer::const_iterator oit, oit_end = leaf->mMultipleObjects.end(); for (oit = leaf->mMultipleObjects.begin(); oit != oit_end; ++ oit) { Intersectable *object = *oit; // object not previously in pvs if (!object->Mailed()) { object->Mail(); ++ pvs; } } return pvs; } int VspTree::EvalMinEventContribution(const VssRay &ray, const bool isTermination) const { Intersectable *obj; Vector3 pt; KdNode *node; ray.GetSampleData(isTermination, pt, &obj, &node); if (!obj) return 0; int pvs = 0; switch (mHierarchyManager->GetObjectSpaceSubdivisonType()) { case HierarchyManager::NO_OBJ_SUBDIV: { if (!obj->Mailed()) { obj->Mail(); ++ pvs; } break; } case HierarchyManager::KD_BASED_OBJ_SUBDIV: { KdLeaf *leaf = mHierarchyManager->mOspTree->GetLeaf(pt, node); // add contributions of the kd nodes pvs += EvalMinEventContribution(leaf); break; } case HierarchyManager::BV_BASED_OBJ_SUBDIV: { BvhLeaf *leaf = mHierarchyManager->mBvHierarchy->GetLeaf(obj); if (!leaf->Mailed()) { leaf->Mail(); pvs += (int)leaf->mObjects.size(); } break; } default: break; } return pvs; } int VspTree::EvalMaxEventContribution(const VssRay &ray, const bool isTermination) const { Intersectable *obj; Vector3 pt; KdNode *node; ray.GetSampleData(isTermination, pt, &obj, &node); if (!obj) return 0; int pvs = 0; switch (mHierarchyManager->GetObjectSpaceSubdivisonType()) { case HierarchyManager::NO_OBJ_SUBDIV: { if (-- obj->mCounter == 0) ++ pvs; break; } case HierarchyManager::KD_BASED_OBJ_SUBDIV: { KdLeaf *leaf = mHierarchyManager->mOspTree->GetLeaf(pt, node); // add contributions of the kd nodes pvs += EvalMaxEventContribution(leaf); break; } case HierarchyManager::BV_BASED_OBJ_SUBDIV: { BvhLeaf *leaf = mHierarchyManager->mBvHierarchy->GetLeaf(obj); if (-- leaf->mCounter == 0) pvs += (int)leaf->mObjects.size(); break; } default: break; } return pvs; } void VspTree::EvalHeuristicsContribution(const SortableEntry &ci, int &pvsLeft, int &pvsRight) const { VssRay *ray = ci.ray; if (ci.type == SortableEntry::ERayMin) { pvsLeft += EvalMinEventContribution(*ray, true); pvsLeft += EvalMinEventContribution(*ray, false); } else { pvsRight -= EvalMaxEventContribution(*ray, true); pvsRight -= EvalMaxEventContribution(*ray, false); } } float VspTree::EvalLocalCostHeuristics(const VspTraversalData &tData, const AxisAlignedBox3 &box, const int axis, float &position) { // get subset of rays RayInfoContainer usedRays; if (mMaxTests < (int)tData.mRays->size()) { GetRayInfoSets(*tData.mRays, mMaxTests, usedRays); } else { usedRays = *tData.mRays; } int pvsSize = tData.mPvs; const float minBox = box.Min(axis); const float maxBox = box.Max(axis); const float sizeBox = maxBox - minBox; const float minBand = minBox + mMinBand * sizeBox; const float maxBand = minBox + mMaxBand * sizeBox; SortSubdivisionCandidates(usedRays, axis, minBand, maxBand); // prepare the sweep // (note: returns pvs size, so there would be no need // to give pvs size as argument) pvsSize = PrepareHeuristics(usedRays); // go through the lists, count the number of objects left and right // and evaluate the following cost funcion: // C = ct_div_ci + (ql*rl + qr*rr)/queries int pvsl = 0; int pvsr = pvsSize; int pvsBack = pvsl; int pvsFront = pvsr; float sum = (float)pvsSize * sizeBox; float minSum = 1e20f; // if no good split can be found, take mid split position = minBox + 0.5f * sizeBox; // the relative cost ratio float ratio = 99999999.0f; bool splitPlaneFound = false; Intersectable::NewMail(); KdLeaf::NewMail(); //-- traverse through visibility events vector::const_iterator ci, ci_end = mLocalSubdivisionCandidates->end(); for (ci = mLocalSubdivisionCandidates->begin(); ci != ci_end; ++ ci) { EvalHeuristicsContribution(*ci, pvsl, pvsr); // Note: sufficient to compare size of bounding boxes of front and back side? if (((*ci).value >= minBand) && ((*ci).value <= maxBand)) { float currentPos; // HACK: current positition is BETWEEN visibility events if (0 && ((ci + 1) != ci_end)) currentPos = ((*ci).value + (*(ci + 1)).value) * 0.5f; else currentPos = (*ci).value; sum = pvsl * ((*ci).value - minBox) + pvsr * (maxBox - (*ci).value); //Debug << "pos=" << (*ci).value << "\t newpos=" << currentPos << "\t pvs=(" << pvsl << "," << pvsr << ")" << "\t cost= " << sum << endl; if (sum < minSum) { splitPlaneFound = true; minSum = sum; position = currentPos; pvsBack = pvsl; pvsFront = pvsr; } } } //-- compute cost const int lowerPvsLimit = mViewCellsManager->GetMinPvsSize(); const int upperPvsLimit = mViewCellsManager->GetMaxPvsSize(); const float pOverall = sizeBox; const float pBack = position - minBox; const float pFront = maxBox - position; const float penaltyOld = EvalPvsPenalty(pvsSize, lowerPvsLimit, upperPvsLimit); const float penaltyFront = EvalPvsPenalty(pvsFront, lowerPvsLimit, upperPvsLimit); const float penaltyBack = EvalPvsPenalty(pvsBack, lowerPvsLimit, upperPvsLimit); const float oldRenderCost = penaltyOld * pOverall + Limits::Small; const float newRenderCost = penaltyFront * pFront + penaltyBack * pBack; if (splitPlaneFound) { ratio = newRenderCost / oldRenderCost; } const float volRatio = tData.mBoundingBox.GetVolume() / (sizeBox * mBoundingBox.GetVolume()); /* //if (axis != 1) //Debug << "axis=" << axis << " costRatio=" << ratio << " pos=" << position << " t=" << (position - minBox) / (maxBox - minBox) // <<"\t pb=(" << pvsBack << ")\t pf=(" << pvsFront << ")" << endl; Debug << "\n§§§§ eval local cost §§§§" << endl << "back pvs: " << penaltyBack << " front pvs: " << penaltyFront << " total pvs: " << penaltyOld << endl << "back p: " << pBack * volRatio << " front p " << pFront * volRatio << " p: " << pOverall * volRatio << endl << "old rc: " << oldRenderCost * volRatio << " new rc: " << newRenderCost * volRatio << endl << "render cost decrease: " << oldRenderCost * volRatio - newRenderCost * volRatio << endl; */ return ratio; } float VspTree::SelectSplitPlane(const VspTraversalData &tData, AxisAlignedPlane &plane, float &pFront, float &pBack) { float nPosition[3]; float nCostRatio[3]; float nProbFront[3]; float nProbBack[3]; // create bounding box of node geometry AxisAlignedBox3 box = tData.mBoundingBox; int sAxis = 0; int bestAxis = -1; // if we use some kind of specialised fixed axis const bool useSpecialAxis = mOnlyDrivingAxis || mCirculatingAxis; //Debug << "data: " << tData.mBoundingBox << " pvs " << tData.mPvs << endl; if (mCirculatingAxis) { int parentAxis = 0; VspNode *parent = tData.mNode->GetParent(); if (parent) parentAxis = dynamic_cast(parent)->GetAxis(); sAxis = (parentAxis + 1) % 3; } else if (mOnlyDrivingAxis) { sAxis = box.Size().DrivingAxis(); } for (int axis = 0; axis < 3; ++ axis) { if (!useSpecialAxis || (axis == sAxis)) { if (mUseCostHeuristics) { //-- place split plane using heuristics nCostRatio[axis] = EvalLocalCostHeuristics(tData, box, axis, nPosition[axis]); } else { //-- split plane position is spatial median nPosition[axis] = (box.Min()[axis] + box.Max()[axis]) * 0.5f; nCostRatio[axis] = EvalLocalSplitCost(tData, box, axis, nPosition[axis], nProbFront[axis], nProbBack[axis]); } if (bestAxis == -1) { bestAxis = axis; } else if (nCostRatio[axis] < nCostRatio[bestAxis]) { bestAxis = axis; } } } //-- assign values of best split plane.mAxis = bestAxis; plane.mPosition = nPosition[bestAxis]; // split plane position pFront = nProbFront[bestAxis]; pBack = nProbBack[bestAxis]; //Debug << "val: " << nCostRatio[bestAxis] << " axis: " << bestAxis << endl; return nCostRatio[bestAxis]; } float VspTree::EvalRenderCostDecrease(const AxisAlignedPlane &candidatePlane, const VspTraversalData &data, float &normalizedOldRenderCost) const { float pvsFront = 0; float pvsBack = 0; float totalPvs = 0; // probability that view point lies in back / front node float pOverall = data.mProbability; float pFront = 0; float pBack = 0; const float viewSpaceVol = mBoundingBox.GetVolume(); // create unique ids for pvs heuristics Intersectable::NewMail(3); KdLeaf::NewMail(3); RayInfoContainer::const_iterator rit, rit_end = data.mRays->end(); for (rit = data.mRays->begin(); rit != rit_end; ++ rit) { RayInfo rayInf = *rit; float t; VssRay *ray = rayInf.mRay; const int cf = rayInf.ComputeRayIntersection(candidatePlane.mAxis, candidatePlane.mPosition, t); /* if (!mUseKdPvsForHeuristics) { // find front and back pvs for origing and termination object UpdateObjPvsContri(ray->mTerminationObject, cf, pvsFront, pvsBack, totalPvs); UpdateObjPvsContri(ray->mOriginObject, cf, pvsFront, pvsBack, totalPvs); } else { if (ray->mTerminationObject) { KdLeaf *leaf = mHierarchyManager->mOspTree->GetLeaf(ray->mTermination, ray->mTerminationNode); UpdateKdLeafPvsContri(leaf, cf, pvsFront, pvsBack, totalPvs); } if (ray->mOriginObject) { KdLeaf *leaf = mHierarchyManager->mOspTree->GetLeaf(ray->mOrigin, ray->mOriginNode); UpdateKdLeafPvsContri(leaf, cf, pvsFront, pvsBack, totalPvs); } } */ } AxisAlignedBox3 frontBox; AxisAlignedBox3 backBox; data.mBoundingBox.Split(candidatePlane.mAxis, candidatePlane.mPosition, frontBox, backBox); pFront = frontBox.GetVolume(); pBack = pOverall - pFront; //-- pvs rendering heuristics const int lowerPvsLimit = mViewCellsManager->GetMinPvsSize(); const int upperPvsLimit = mViewCellsManager->GetMaxPvsSize(); //-- only render cost heuristics or combined with standard deviation const float penaltyOld = EvalPvsPenalty((int)totalPvs, lowerPvsLimit, upperPvsLimit); const float penaltyFront = EvalPvsPenalty((int)pvsFront, lowerPvsLimit, upperPvsLimit); const float penaltyBack = EvalPvsPenalty((int)pvsBack, lowerPvsLimit, upperPvsLimit); const float oldRenderCost = pOverall * penaltyOld; const float newRenderCost = penaltyFront * pFront + penaltyBack * pBack; normalizedOldRenderCost = oldRenderCost / viewSpaceVol; const float renderCostDecrease = (oldRenderCost - newRenderCost) / viewSpaceVol; /* Debug << "\n==== eval render cost decrease ===" << endl << "back pvs: " << pvsBack << " front pvs " << pvsFront << " total pvs: " << totalPvs << endl << "back p: " << pBack / viewSpaceVol << " front p " << pFront / viewSpaceVol << " p: " << pOverall / viewSpaceVol << endl << "old rc: " << normalizedOldRenderCost << " new rc: " << newRenderCost / viewSpaceVol << endl << "render cost decrease: " << renderCostDecrease << endl; */ return renderCostDecrease; } float VspTree::EvalLocalSplitCost(const VspTraversalData &data, const AxisAlignedBox3 &box, const int axis, const float &position, float &pFront, float &pBack) const { float pvsTotal = 0; float pvsFront = 0; float pvsBack = 0; // create unique ids for pvs heuristics Intersectable::NewMail(3); const int pvsSize = data.mPvs; RayInfoContainer::const_iterator rit, rit_end = data.mRays->end(); // this is the main ray classification loop! for(rit = data.mRays->begin(); rit != rit_end; ++ rit) { // determine the side of this ray with respect to the plane float t; const int side = (*rit).ComputeRayIntersection(axis, position, t); UpdateObjPvsContri((*rit).mRay->mTerminationObject, side, pvsFront, pvsBack, pvsTotal); UpdateObjPvsContri((*rit).mRay->mOriginObject, side, pvsFront, pvsBack, pvsTotal); } //-- evaluate cost heuristics float pOverall; pOverall = data.mProbability; // we use spatial mid split => simplified computation pBack = pFront = pOverall * 0.5f; const float newCost = pvsBack * pBack + pvsFront * pFront; const float oldCost = (float)pvsSize * pOverall + Limits::Small; #ifdef _DEBUG Debug << axis << " " << pvsSize << " " << pvsBack << " " << pvsFront << endl; Debug << pFront << " " << pBack << " " << pOverall << endl; #endif return (mCtDivCi + newCost) / oldCost; } void VspTree::UpdateObjPvsContri(Intersectable *obj, const int cf, float &frontPvs, float &backPvs, float &totalPvs) const { if (!obj) return; //const float renderCost = mViewCellsManager->SimpleRay &raynderCost(obj); const int renderCost = 1; // object in no pvs => new if (!obj->Mailed() && !obj->Mailed(1) && !obj->Mailed(2)) { totalPvs += renderCost; } // QUESTION matt: is it safe to assume that // the object belongs to no pvs in this case? //if (cf == Ray::COINCIDENT) return; if (cf >= 0) // front pvs { if (!obj->Mailed() && !obj->Mailed(2)) { frontPvs += renderCost; // already in back pvs => in both pvss if (obj->Mailed(1)) obj->Mail(2); else obj->Mail(); } } if (cf <= 0) // back pvs { if (!obj->Mailed(1) && !obj->Mailed(2)) { backPvs += renderCost; // already in front pvs => in both pvss if (obj->Mailed()) obj->Mail(2); else obj->Mail(1); } } } void VspTree::UpdateKdLeafPvsContri(KdLeaf *leaf, const int cf, float &frontPvs, float &backPvs, float &totalPvs) const { if (!leaf) return; // the objects which are referenced in this and only this leaf const int contri = (int)(leaf->mObjects.size() - leaf->mMultipleObjects.size()); // newly found leaf if (!leaf->Mailed() && !leaf->Mailed(1) && !leaf->Mailed(2)) { totalPvs += contri; } // compute contribution of yet unclassified objects ObjectContainer::const_iterator oit, oit_end = leaf->mMultipleObjects.end(); for (oit = leaf->mMultipleObjects.begin(); oit != oit_end; ++ oit) { UpdateObjPvsContri(*oit, cf, frontPvs, backPvs, totalPvs); } // QUESTION matt: is it safe to assume that // the object belongs to no pvs in this case? //if (cf == Ray::COINCIDENT) return; if (cf >= 0) // front pvs { if (!leaf->Mailed() && !leaf->Mailed(2)) { frontPvs += contri; // already in back pvs => in both pvss if (leaf->Mailed(1)) leaf->Mail(2); else leaf->Mail(); } } if (cf <= 0) // back pvs { if (!leaf->Mailed(1) && !leaf->Mailed(2)) { backPvs += contri; // already in front pvs => in both pvss if (leaf->Mailed()) leaf->Mail(2); else leaf->Mail(1); } } } void VspTree::CollectLeaves(vector &leaves, const bool onlyUnmailed, const int maxPvsSize) const { stack nodeStack; nodeStack.push(mRoot); while (!nodeStack.empty()) { VspNode *node = nodeStack.top(); nodeStack.pop(); if (node->IsLeaf()) { // test if this leaf is in valid view space VspLeaf *leaf = dynamic_cast(node); if (leaf->TreeValid() && (!onlyUnmailed || !leaf->Mailed()) && ((maxPvsSize < 0) || (leaf->GetViewCell()->GetPvs().CountObjectsInPvs() <= maxPvsSize))) { leaves.push_back(leaf); } } else { VspInterior *interior = dynamic_cast(node); nodeStack.push(interior->GetBack()); nodeStack.push(interior->GetFront()); } } } AxisAlignedBox3 VspTree::GetBoundingBox() const { return mBoundingBox; } VspNode *VspTree::GetRoot() const { return mRoot; } void VspTree::EvaluateLeafStats(const VspTraversalData &data) { // the node became a leaf -> evaluate stats for leafs VspLeaf *leaf = dynamic_cast(data.mNode); if (data.mPvs > mVspStats.maxPvs) { mVspStats.maxPvs = data.mPvs; } mVspStats.pvs += data.mPvs; if (data.mDepth < mVspStats.minDepth) { mVspStats.minDepth = data.mDepth; } if (data.mDepth >= mTermMaxDepth) { ++ mVspStats.maxDepthNodes; //Debug << "new max depth: " << mVspStats.maxDepthNodes << endl; } // accumulate rays to compute rays / leaf mVspStats.accumRays += (int)data.mRays->size(); if (data.mPvs < mTermMinPvs) ++ mVspStats.minPvsNodes; if ((int)data.mRays->size() < mTermMinRays) ++ mVspStats.minRaysNodes; if (data.GetAvgRayContribution() > mTermMaxRayContribution) ++ mVspStats.maxRayContribNodes; if (data.mProbability <= mTermMinProbability) ++ mVspStats.minProbabilityNodes; // accumulate depth to compute average depth mVspStats.accumDepth += data.mDepth; ++ mCreatedViewCells; #ifdef _DEBUG Debug << "BSP stats: " << "Depth: " << data.mDepth << " (max: " << mTermMaxDepth << "), " << "PVS: " << data.mPvs << " (min: " << mTermMinPvs << "), " << "#rays: " << (int)data.mRays->size() << " (max: " << mTermMinRays << "), " << "#pvs: " << leaf->GetViewCell()->GetPvs().CountObjectsInPvs() << "), " << "#avg ray contrib (pvs): " << (float)data.mPvs / (float)data.mRays->size() << endl; #endif } void VspTree::CollectViewCells(ViewCellContainer &viewCells, bool onlyValid) const { ViewCell::NewMail(); CollectViewCells(mRoot, onlyValid, viewCells, true); } void VspTree::CollapseViewCells() { // TODO matt #if HAS_TO_BE_REDONE stack nodeStack; if (!mRoot) return; nodeStack.push(mRoot); while (!nodeStack.empty()) { VspNode *node = nodeStack.top(); nodeStack.pop(); if (node->IsLeaf()) { BspViewCell *viewCell = dynamic_cast(node)->GetViewCell(); if (!viewCell->GetValid()) { BspViewCell *viewCell = dynamic_cast(node)->GetViewCell(); ViewCellContainer leaves; mViewCellsTree->CollectLeaves(viewCell, leaves); ViewCellContainer::const_iterator it, it_end = leaves.end(); for (it = leaves.begin(); it != it_end; ++ it) { VspLeaf *l = dynamic_cast(*it)->mLeaf; l->SetViewCell(GetOrCreateOutOfBoundsCell()); ++ mVspStats.invalidLeaves; } // add to unbounded view cell GetOrCreateOutOfBoundsCell()->GetPvs().AddPvs(viewCell->GetPvs()); DEL_PTR(viewCell); } } else { VspInterior *interior = dynamic_cast(node); nodeStack.push(interior->GetFront()); nodeStack.push(interior->GetBack()); } } Debug << "invalid leaves: " << mVspStats.invalidLeaves << endl; #endif } void VspTree::CollectRays(VssRayContainer &rays) { vector leaves; CollectLeaves(leaves); vector::const_iterator lit, lit_end = leaves.end(); for (lit = leaves.begin(); lit != lit_end; ++ lit) { VspLeaf *leaf = *lit; VssRayContainer::const_iterator rit, rit_end = leaf->mVssRays.end(); for (rit = leaf->mVssRays.begin(); rit != rit_end; ++ rit) rays.push_back(*rit); } } void VspTree::SetViewCellsManager(ViewCellsManager *vcm) { mViewCellsManager = vcm; } void VspTree::ValidateTree() { mVspStats.invalidLeaves = 0; stack nodeStack; if (!mRoot) return; nodeStack.push(mRoot); while (!nodeStack.empty()) { VspNode *node = nodeStack.top(); nodeStack.pop(); if (node->IsLeaf()) { VspLeaf *leaf = dynamic_cast(node); if (!leaf->GetViewCell()->GetValid()) ++ mVspStats.invalidLeaves; // validity flags don't match => repair if (leaf->GetViewCell()->GetValid() != leaf->TreeValid()) { leaf->SetTreeValid(leaf->GetViewCell()->GetValid()); PropagateUpValidity(leaf); } } else { VspInterior *interior = dynamic_cast(node); nodeStack.push(interior->GetFront()); nodeStack.push(interior->GetBack()); } } Debug << "invalid leaves: " << mVspStats.invalidLeaves << endl; } void VspTree::CollectViewCells(VspNode *root, bool onlyValid, ViewCellContainer &viewCells, bool onlyUnmailed) const { stack nodeStack; if (!root) return; nodeStack.push(root); while (!nodeStack.empty()) { VspNode *node = nodeStack.top(); nodeStack.pop(); if (node->IsLeaf()) { if (!onlyValid || node->TreeValid()) { ViewCellLeaf *leafVc = dynamic_cast(node)->GetViewCell(); ViewCell *viewCell = mViewCellsTree->GetActiveViewCell(leafVc); if (!onlyUnmailed || !viewCell->Mailed()) { viewCell->Mail(); viewCells.push_back(viewCell); } } } else { VspInterior *interior = dynamic_cast(node); nodeStack.push(interior->GetFront()); nodeStack.push(interior->GetBack()); } } } int VspTree::FindNeighbors(VspLeaf *n, vector &neighbors, const bool onlyUnmailed) const { stack nodeStack; nodeStack.push(mRoot); const AxisAlignedBox3 box = GetBoundingBox(n); while (!nodeStack.empty()) { VspNode *node = nodeStack.top(); nodeStack.pop(); if (node->IsLeaf()) { VspLeaf *leaf = dynamic_cast(node); if (leaf != n && (!onlyUnmailed || !leaf->Mailed())) neighbors.push_back(leaf); } else { VspInterior *interior = dynamic_cast(node); if (interior->GetPosition() > box.Max(interior->GetAxis())) nodeStack.push(interior->GetBack()); else { if (interior->GetPosition() < box.Min(interior->GetAxis())) nodeStack.push(interior->GetFront()); else { // random decision nodeStack.push(interior->GetBack()); nodeStack.push(interior->GetFront()); } } } } return (int)neighbors.size(); } // Find random neighbor which was not mailed VspLeaf *VspTree::GetRandomLeaf(const Plane3 &plane) { stack nodeStack; nodeStack.push(mRoot); int mask = rand(); while (!nodeStack.empty()) { VspNode *node = nodeStack.top(); nodeStack.pop(); if (node->IsLeaf()) { return dynamic_cast(node); } else { VspInterior *interior = dynamic_cast(node); VspNode *next; if (GetBoundingBox(interior->GetBack()).Side(plane) < 0) { next = interior->GetFront(); } else { if (GetBoundingBox(interior->GetFront()).Side(plane) < 0) { next = interior->GetBack(); } else { // random decision if (mask & 1) next = interior->GetBack(); else next = interior->GetFront(); mask = mask >> 1; } } nodeStack.push(next); } } return NULL; } VspLeaf *VspTree::GetRandomLeaf(const bool onlyUnmailed) { stack nodeStack; nodeStack.push(mRoot); int mask = rand(); while (!nodeStack.empty()) { VspNode *node = nodeStack.top(); nodeStack.pop(); if (node->IsLeaf()) { if ( (!onlyUnmailed || !node->Mailed()) ) return dynamic_cast(node); } else { VspInterior *interior = dynamic_cast(node); // random decision if (mask & 1) nodeStack.push(interior->GetBack()); else nodeStack.push(interior->GetFront()); mask = mask >> 1; } } return NULL; } void VspTree::CollectPvs(const RayInfoContainer &rays, ObjectContainer &objects) const { RayInfoContainer::const_iterator rit, rit_end = rays.end(); Intersectable::NewMail(); for (rit = rays.begin(); rit != rays.end(); ++ rit) { VssRay *ray = (*rit).mRay; Intersectable *object; object = ray->mOriginObject; if (object) { if (!object->Mailed()) { object->Mail(); objects.push_back(object); } } object = ray->mTerminationObject; if (object) { if (!object->Mailed()) { object->Mail(); objects.push_back(object); } } } } int VspTree::EvalPvsContribution(const VssRay &ray, const bool isTermination) const { Intersectable *obj; Vector3 pt; KdNode *node; ray.GetSampleData(isTermination, pt, &obj, &node); if (!obj) return 0; int pvs = 0; switch(mHierarchyManager->GetObjectSpaceSubdivisonType()) { case HierarchyManager::NO_OBJ_SUBDIV: { if (!obj->Mailed()) { obj->Mail(); ++ pvs; } break; } case HierarchyManager::KD_BASED_OBJ_SUBDIV: { KdLeaf *leaf = mHierarchyManager->mOspTree->GetLeaf(pt, node); if (!leaf->Mailed()) { leaf->Mail(); pvs += (int)(leaf->mObjects.size() - leaf->mMultipleObjects.size()); ObjectContainer::const_iterator oit, oit_end = leaf->mMultipleObjects.end(); for (oit = leaf->mMultipleObjects.begin(); oit != oit_end; ++ oit) { Intersectable *obj = *oit; if (!obj->Mailed()) { obj->Mail(); ++ pvs; } } } break; } case HierarchyManager::BV_BASED_OBJ_SUBDIV: { BvhLeaf *bvhleaf = mHierarchyManager->mBvHierarchy->GetLeaf(obj); if (!bvhleaf->Mailed()) { bvhleaf->Mail(); pvs += (int)bvhleaf->mObjects.size(); } break; } default: break; } return pvs; } int VspTree::EvalPvsSize(const RayInfoContainer &rays) const { int pvsSize = 0; Intersectable::NewMail(); KdNode::NewMail(); BvhNode::NewMail(); RayInfoContainer::const_iterator rit, rit_end = rays.end(); for (rit = rays.begin(); rit != rays.end(); ++ rit) { VssRay *ray = (*rit).mRay; pvsSize += EvalPvsContribution(*ray, true); pvsSize += EvalPvsContribution(*ray, false); } return pvsSize; } float VspTree::GetEpsilon() const { return mEpsilon; } int VspTree::CastLineSegment(const Vector3 &origin, const Vector3 &termination, ViewCellContainer &viewcells) { int hits = 0; float mint = 0.0f, maxt = 1.0f; const Vector3 dir = termination - origin; stack tStack; //Intersectable::NewMail(); //ViewCell::NewMail(); Vector3 entp = origin; Vector3 extp = termination; VspNode *node = mRoot; VspNode *farChild; float position; int axis; while (1) { if (!node->IsLeaf()) { VspInterior *in = dynamic_cast(node); position = in->GetPosition(); axis = in->GetAxis(); if (entp[axis] <= position) { if (extp[axis] <= position) { node = in->GetBack(); // cases N1,N2,N3,P5,Z2,Z3 continue; } else { // case N4 node = in->GetBack(); farChild = in->GetFront(); } } else { if (position <= extp[axis]) { node = in->GetFront(); // cases P1,P2,P3,N5,Z1 continue; } else { node = in->GetFront(); farChild = in->GetBack(); // case P4 } } // $$ modification 3.5.2004 - hints from Kamil Ghais // case N4 or P4 const float tdist = (position - origin[axis]) / dir[axis]; tStack.push(LineTraversalData(farChild, extp, maxt)); //TODO extp = origin + dir * tdist; maxt = tdist; } else { // compute intersection with all objects in this leaf VspLeaf *leaf = dynamic_cast(node); ViewCell *vc = leaf->GetViewCell(); // don't have to mail because each view cell belongs to exactly one leaf //if (!vc->Mailed()) //{ // vc->Mail(); viewcells.push_back(vc); ++ hits; //} #if 0 leaf->mRays.push_back(RayInfo(new VssRay(origin, termination, NULL, NULL, 0))); #endif // get the next node from the stack if (tStack.empty()) break; entp = extp; mint = maxt; LineTraversalData &s = tStack.top(); node = s.mNode; extp = s.mExitPoint; maxt = s.mMaxT; tStack.pop(); } } return hits; } int VspTree::CastRay(Ray &ray) { int hits = 0; stack tStack; const Vector3 dir = ray.GetDir(); float maxt, mint; if (!mBoundingBox.GetRaySegment(ray, mint, maxt)) return 0; Intersectable::NewMail(); ViewCell::NewMail(); Vector3 entp = ray.Extrap(mint); Vector3 extp = ray.Extrap(maxt); const Vector3 origin = entp; VspNode *node = mRoot; VspNode *farChild = NULL; float position; int axis; while (1) { if (!node->IsLeaf()) { VspInterior *in = dynamic_cast(node); position = in->GetPosition(); axis = in->GetAxis(); if (entp[axis] <= position) { if (extp[axis] <= position) { node = in->GetBack(); // cases N1,N2,N3,P5,Z2,Z3 continue; } else { // case N4 node = in->GetBack(); farChild = in->GetFront(); } } else { if (position <= extp[axis]) { node = in->GetFront(); // cases P1,P2,P3,N5,Z1 continue; } else { node = in->GetFront(); farChild = in->GetBack(); // case P4 } } // $$ modification 3.5.2004 - hints from Kamil Ghais // case N4 or P4 const float tdist = (position - origin[axis]) / dir[axis]; tStack.push(LineTraversalData(farChild, extp, maxt)); //TODO extp = origin + dir * tdist; maxt = tdist; } else { // compute intersection with all objects in this leaf VspLeaf *leaf = dynamic_cast(node); ViewCell *vc = leaf->GetViewCell(); if (!vc->Mailed()) { vc->Mail(); // todo: add view cells to ray ++ hits; } #if 0 leaf->mRays.push_back(RayInfo(new VssRay(origin, termination, NULL, NULL, 0))); #endif // get the next node from the stack if (tStack.empty()) break; entp = extp; mint = maxt; LineTraversalData &s = tStack.top(); node = s.mNode; extp = s.mExitPoint; maxt = s.mMaxT; tStack.pop(); } } return hits; } ViewCell *VspTree::GetViewCell(const Vector3 &point, const bool active) { if (mRoot == NULL) return NULL; stack nodeStack; nodeStack.push(mRoot); ViewCellLeaf *viewcell = NULL; while (!nodeStack.empty()) { VspNode *node = nodeStack.top(); nodeStack.pop(); if (node->IsLeaf()) { viewcell = dynamic_cast(node)->GetViewCell(); break; } else { VspInterior *interior = dynamic_cast(node); // random decision if (interior->GetPosition() - point[interior->GetAxis()] < 0) nodeStack.push(interior->GetBack()); else nodeStack.push(interior->GetFront()); } } if (active) return mViewCellsTree->GetActiveViewCell(viewcell); else return viewcell; } bool VspTree::ViewPointValid(const Vector3 &viewPoint) const { VspNode *node = mRoot; while (1) { // early exit if (node->TreeValid()) return true; if (node->IsLeaf()) return false; VspInterior *in = dynamic_cast(node); if (in->GetPosition() - viewPoint[in->GetAxis()] <= 0) { node = in->GetBack(); } else { node = in->GetFront(); } } // should never come here return false; } void VspTree::PropagateUpValidity(VspNode *node) { const bool isValid = node->TreeValid(); // propagative up invalid flag until only invalid nodes exist over this node if (!isValid) { while (!node->IsRoot() && node->GetParent()->TreeValid()) { node = node->GetParent(); node->SetTreeValid(false); } } else { // propagative up valid flag until one of the subtrees is invalid while (!node->IsRoot() && !node->TreeValid()) { node = node->GetParent(); VspInterior *interior = dynamic_cast(node); // the parent is valid iff both leaves are valid node->SetTreeValid(interior->GetBack()->TreeValid() && interior->GetFront()->TreeValid()); } } } bool VspTree::Export(OUT_STREAM &stream) { ExportNode(mRoot, stream); return true; } void VspTree::ExportNode(VspNode *node, OUT_STREAM &stream) { if (node->IsLeaf()) { VspLeaf *leaf = dynamic_cast(node); ViewCell *viewCell = mViewCellsTree->GetActiveViewCell(leaf->GetViewCell()); int id = -1; if (viewCell != mOutOfBoundsCell) id = viewCell->GetId(); stream << "" << endl; } else { VspInterior *interior = dynamic_cast(node); AxisAlignedPlane plane = interior->GetPlane(); stream << "" << endl; ExportNode(interior->GetBack(), stream); ExportNode(interior->GetFront(), stream); stream << "" << endl; } } int VspTree::SplitRays(const AxisAlignedPlane &plane, RayInfoContainer &rays, RayInfoContainer &frontRays, RayInfoContainer &backRays) const { int splits = 0; RayInfoContainer::const_iterator rit, rit_end = rays.end(); for (rit = rays.begin(); rit != rit_end; ++ rit) { RayInfo bRay = *rit; VssRay *ray = bRay.mRay; float t; // get classification and receive new t // test if start point behind or in front of plane const int side = bRay.ComputeRayIntersection(plane.mAxis, plane.mPosition, t); if (side == 0) { ++ splits; if (ray->HasPosDir(plane.mAxis)) { backRays.push_back(RayInfo(ray, bRay.GetMinT(), t)); frontRays.push_back(RayInfo(ray, t, bRay.GetMaxT())); } else { frontRays.push_back(RayInfo(ray, bRay.GetMinT(), t)); backRays.push_back(RayInfo(ray, t, bRay.GetMaxT())); } } else if (side == 1) { frontRays.push_back(bRay); } else { backRays.push_back(bRay); } } return splits; } AxisAlignedBox3 VspTree::GetBoundingBox(VspNode *node) const { if (!node->GetParent()) return mBoundingBox; if (!node->IsLeaf()) { return (dynamic_cast(node))->GetBoundingBox(); } VspInterior *parent = dynamic_cast(node->GetParent()); AxisAlignedBox3 box(parent->GetBoundingBox()); if (parent->GetFront() == node) box.SetMin(parent->GetAxis(), parent->GetPosition()); else box.SetMax(parent->GetAxis(), parent->GetPosition()); return box; } int VspTree::ComputeBoxIntersections(const AxisAlignedBox3 &box, ViewCellContainer &viewCells) const { stack nodeStack; ViewCell::NewMail(); while (!nodeStack.empty()) { VspNode *node = nodeStack.top(); nodeStack.pop(); const AxisAlignedBox3 bbox = GetBoundingBox(node); if (bbox.Includes(box)) { // node geometry is contained in box CollectViewCells(node, true, viewCells, true); } else if (Overlap(bbox, box)) { if (node->IsLeaf()) { BspLeaf *leaf = dynamic_cast(node); if (!leaf->GetViewCell()->Mailed() && leaf->TreeValid()) { leaf->GetViewCell()->Mail(); viewCells.push_back(leaf->GetViewCell()); } } else { VspInterior *interior = dynamic_cast(node); VspNode *first = interior->GetFront(); VspNode *second = interior->GetBack(); nodeStack.push(first); nodeStack.push(second); } } // default: cull } return (int)viewCells.size(); } void VspTree::PreprocessRays(const VssRayContainer &sampleRays, RayInfoContainer &rays) { VssRayContainer::const_iterator rit, rit_end = sampleRays.end(); long startTime = GetTime(); cout << "storing rays ... "; Intersectable::NewMail(); //-- store rays and objects for (rit = sampleRays.begin(); rit != rit_end; ++ rit) { VssRay *ray = *rit; float minT, maxT; static Ray hray; hray.Init(*ray); // TODO: not very efficient to implictly cast between rays types if (GetBoundingBox().GetRaySegment(hray, minT, maxT)) { float len = ray->Length(); if (!len) len = Limits::Small; rays.push_back(RayInfo(ray, minT / len, maxT / len)); } } cout << "finished in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl; } void VspTree::GetViewCells(const VssRay &ray, ViewCellContainer &viewCells) { #if 0 // use view cells manager to compute view cells mViewCellsManager->ComputeSampleContribution(ray, false, true); viewCells = ray.mViewCells; ray.mViewCells.clear(); #else static Ray hray; hray.Init(ray); float tmin = 0, tmax = 1.0; if (!mBoundingBox.GetRaySegment(hray, tmin, tmax) || (tmin > tmax)) return; const Vector3 origin = hray.Extrap(tmin); const Vector3 termination = hray.Extrap(tmax); // if no precomputation of view cells CastLineSegment(origin, termination, viewCells); #endif } SubdivisionCandidate *VspTree::PrepareConstruction(const VssRayContainer &sampleRays, AxisAlignedBox3 *forcedViewSpace, RayInfoContainer &rays) { // store pointer to this tree VspSubdivisionCandidate::sVspTree = this; mVspStats.nodes = 1; // compute view space bounding box ComputeBoundingBox(sampleRays, forcedViewSpace); // initialise termination criteria mTermMinProbability *= mBoundingBox.GetVolume(); mGlobalCostMisses = 0; // get clipped rays PreprocessRays(sampleRays, rays); const int pvsSize = EvalPvsSize(rays); Debug << "pvs size: " << (int)pvsSize << endl; Debug << "rays size: " << (int)rays.size() << endl; //-- prepare view space partition // add first candidate for view space partition VspLeaf *leaf = new VspLeaf(); mRoot = leaf; const float prop = mBoundingBox.GetVolume(); // first vsp traversal data VspTraversalData vData(leaf, 0, &rays, pvsSize, prop, mBoundingBox); // create first view cell CreateViewCell(vData, false); #if WORK_WITH_VIEWCELL_PVS // add first view cell to all the objects view cell pvs ObjectPvsMap::const_iterator oit, oit_end = leaf->GetViewCell()->GetPvs().mEntries.end(); for (oit = leaf->GetViewCell()->GetPvs().mEntries.begin(); oit != oit_end; ++ oit) { Intersectable *obj = (*oit).first; obj->mViewCellPvs.AddSample(leaf->GetViewCell(), 1); } #endif //-- compute first split candidate VspSubdivisionCandidate *splitCandidate = new VspSubdivisionCandidate(vData); EvalSubdivisionCandidate(*splitCandidate); mTotalCost = (float)pvsSize; EvalSubdivisionStats(*splitCandidate); return splitCandidate; } void VspTree::CollectDirtyCandidates(VspSubdivisionCandidate *sc, vector &dirtyList) { VspTraversalData &tData = sc->mParentData; VspLeaf *node = tData.mNode; KdLeaf::NewMail(); RayInfoContainer::const_iterator rit, rit_end = tData.mRays->end(); // add all kd nodes seen by the rays for (rit = tData.mRays->begin(); rit != rit_end; ++ rit) { VssRay *ray = (*rit).mRay; KdLeaf *leaf = mHierarchyManager->mOspTree->GetLeaf(ray->mOrigin, ray->mOriginNode); if (!leaf->Mailed()) { leaf->Mail(); dirtyList.push_back(leaf->mSubdivisionCandidate); } leaf = mHierarchyManager->mOspTree->GetLeaf(ray->mTermination, ray->mTerminationNode); if (!leaf->Mailed()) { leaf->Mail(); dirtyList.push_back(leaf->mSubdivisionCandidate); } } } }