source: GTP/trunk/Lib/Vis/OnlineCullingCHC/OGRE/src/OgreOcclusionCullingSceneManager.cpp @ 1296

Revision 1296, 36.8 KB checked in by szydlowski, 18 years ago (diff)

Implemented PVS support in kdtree scene manager - not complete, defunct
modified BoundingBoxConverter? to work with KdTreeSceneManager?

Line 
1#include "OgreOcclusionCullingSceneManager.h"
2#include "OgreVisibilityOptionsManager.h"
3#include <OgreMath.h>
4#include <OgreIteratorWrappers.h>
5#include <OgreRenderSystem.h>
6#include <OgreCamera.h>
7#include <OgreLogManager.h>
8#include <OgreStringConverter.h>
9#include <OgreEntity.h>
10#include <OgreSubEntity.h>
11#include <OgreMaterialManager.h>
12#include <OgreIteratorWrappers.h>
13#include <OgreHeightmapTerrainPageSource.h>
14#include "VspBspTree.h"
15#include "Containers.h"
16#include "ViewCellsManager.h"
17#include <OgreConfigFile.h>
18#include "OgreTypeConverter.h"
19#include "OgreMeshInstance.h"
20#include "common.h"
21#include "OgreBoundingBoxConverter.h"
22
23
24namespace Ogre {
25
26//-----------------------------------------------------------------------
27OcclusionCullingSceneManager::OcclusionCullingSceneManager(const String& name,
28                                                        GtpVisibility::VisibilityManager *visManager):
29TerrainSceneManager(name),
30mVisibilityManager(visManager),
31mShowVisualization(false),
32mRenderNodesForViz(false),
33mRenderNodesContentForViz(false),
34mVisualizeCulledNodes(false),
35mLeavePassesInQueue(0),
36mDelayRenderTransparents(true),
37mUseDepthPass(false),
38mIsDepthPassPhase(false),
39mUseItemBuffer(false),
40mIsItemBufferPhase(false),
41mCurrentEntityId(1),
42mEnableDepthWrite(true),
43mSkipTransparents(false),
44mRenderTransparentsForItemBuffer(true),
45mExecuteVertexProgramForAllPasses(false),
46mIsHierarchicalCulling(false),
47mViewCellsLoaded(false),
48mUseViewCells(false),
49mUseVisibilityFilter(false),
50mCurrentViewCell(NULL),
51mElementaryViewCell(NULL),
52mDeleteQueueAfterRendering(true),
53mNormalExecution(false)
54{
55        Ogre::LogManager::getSingleton().logMessage("creating occlusion culling scene manager");
56
57        mHierarchyInterface = new OctreeHierarchyInterface(this, mDestRenderSystem);
58       
59        if (0)
60        {
61                mDisplayNodes = true;
62                mShowBoundingBoxes = true;
63                mShowBoxes = true;
64        }
65
66        // TODO: set maxdepth to reasonable value
67        mMaxDepth = 50;
68}
69//-----------------------------------------------------------------------
70void OcclusionCullingSceneManager::InitDepthPass()
71{
72        MaterialPtr depthMat = MaterialManager::getSingleton().getByName("Visibility/DepthPass");
73
74        if (depthMat.isNull())
75    {
76                depthMat = MaterialManager::getSingleton().create(
77                "Visibility/DepthPass",
78                ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
79
80        mDepthPass = depthMat->getTechnique(0)->getPass(0);
81                mDepthPass->setColourWriteEnabled(false);
82                mDepthPass->setDepthWriteEnabled(true);
83                mDepthPass->setLightingEnabled(false);
84        }
85        else
86        {
87                mDepthPass = depthMat->getTechnique(0)->getPass(0);
88        }
89}
90//-----------------------------------------------------------------------
91OcclusionCullingSceneManager::~OcclusionCullingSceneManager()
92{
93        OGRE_DELETE(mHierarchyInterface);
94        CLEAR_CONTAINER(mObjects);
95        OGRE_DELETE(mCurrentViewCell);
96}
97//-----------------------------------------------------------------------
98void OcclusionCullingSceneManager::InitItemBufferPass()
99{
100        MaterialPtr itemBufferMat = MaterialManager::getSingleton().
101                getByName("Visibility/ItemBufferPass");
102
103        if (itemBufferMat.isNull())
104    {
105                // Init
106                itemBufferMat = MaterialManager::getSingleton().create("Visibility/ItemBufferPass",
107                ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
108
109                mItemBufferPass = itemBufferMat->getTechnique(0)->getPass(0);
110                mItemBufferPass->setColourWriteEnabled(true);
111                mItemBufferPass->setDepthWriteEnabled(true);
112                mItemBufferPass->setLightingEnabled(true);
113                //mItemBufferPass->setLightingEnabled(false);
114        }
115        else
116        {
117                mItemBufferPass = itemBufferMat->getTechnique(0)->getPass(0);
118        }
119        //mItemBufferPass->setAmbient(1, 1, 0);
120}
121//-------------------------------------------------------------------------
122#if 1
123void OcclusionCullingSceneManager::setWorldGeometry( DataStreamPtr& stream, const String& typeName )
124{
125    // Clear out any existing world resources (if not default)
126    if (ResourceGroupManager::getSingleton().getWorldResourceGroupName() !=
127        ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME)
128    {
129        ResourceGroupManager::getSingleton().clearResourceGroup(
130            ResourceGroupManager::getSingleton().getWorldResourceGroupName());
131    }
132        destroyLevelIndexes();
133    mTerrainPages.clear();
134    // Load the configuration
135    loadConfig(stream);
136        initLevelIndexes();
137
138    // Resize the octree, allow for 1 page for now
139    float max_x = mOptions.scale.x * mOptions.pageSize;
140    float max_y = mOptions.scale.y;
141    float max_z = mOptions.scale.z * mOptions.pageSize;
142
143        float maxAxis = std::max(max_x, max_y);
144        maxAxis = std::max(maxAxis, max_z);
145        resize( AxisAlignedBox( 0, 0, 0, maxAxis, maxAxis, maxAxis ) );
146   
147    setupTerrainMaterial();
148
149    setupTerrainPages();
150
151 }
152#endif
153//-----------------------------------------------------------------------
154void OcclusionCullingSceneManager::PrepareVisualization(Camera *cam)
155{
156        // add player camera for visualization purpose
157        try
158        {
159                Camera *c;
160                if ((c = getCamera("PlayerCam")) != NULL)
161                {
162                        getRenderQueue()->addRenderable(c);
163                }   
164    }
165    catch (...)
166    {
167        // ignore
168    }
169        // add bounding boxes of rendered objects
170        if (0)
171        for (BoxList::iterator it = mBoxes.begin(); it != mBoxes.end(); ++it)
172        {
173                getRenderQueue()->addRenderable(*it);
174        }
175       
176        if (mRenderNodesForViz || mRenderNodesContentForViz)
177        {
178                // HACK: change node material so it is better suited for visualization
179                MaterialPtr nodeMat = MaterialManager::getSingleton().getByName("Core/NodeMaterial");
180                nodeMat->setAmbient(1, 1, 0);
181                nodeMat->setLightingEnabled(true);
182                nodeMat->getTechnique(0)->getPass(0)->removeAllTextureUnitStates();
183
184                for (NodeList::iterator it = mVisible.begin(); it != mVisible.end(); ++it)
185                {
186                        if (mRenderNodesForViz)
187                        {
188                                // render the leaf nodes
189                                if ((*it)->numAttachedObjects() &&
190                                        !(*it)->numChildren() &&
191                                        ((*it)->getAttachedObject(0)->getMovableType() == "Entity") &&
192                                        (*it)->getAttachedObject(0)->isVisible())
193                                {
194                                        getRenderQueue()->addRenderable((*it));
195                                }
196
197                                // addbounding boxes instead of node itself
198                                //(*it)->_addBoundingBoxToQueue(getRenderQueue());
199                        }
200                        // add renderables itself
201                        if (mRenderNodesContentForViz)
202                        {
203                                (*it)->_addToRenderQueue(cam, getRenderQueue(), false);
204                        }
205                }
206        }       
207}
208//-----------------------------------------------------------------------
209const Pass *OcclusionCullingSceneManager::_setPass(const Pass* pass, bool evenIfSuppressed)
210{
211        if (mNormalExecution)
212        {
213                return SceneManager::_setPass(pass);
214        }
215
216        // TODO: setting vertex program is not efficient
217        //Pass *usedPass = ((mIsDepthPassPhase && !pass->hasVertexProgram()) ? mDepthPass : pass);
218       
219        // set depth fill pass if we currently do not make an aabb occlusion query
220        const bool useDepthPass =
221                (mIsDepthPassPhase && !mHierarchyInterface->IsBoundingBoxQuery());
222
223        const IlluminationRenderStage savedStage = mIlluminationStage;
224       
225        // set illumination stage to NONE so no shadow material is used
226        // for depth pass or for occlusion query
227        if (mIsDepthPassPhase || mHierarchyInterface->IsBoundingBoxQuery())
228        {
229                mIlluminationStage = IRS_NONE;
230        }
231       
232        // --- set vertex program of current pass in order to set correct depth
233        if (mExecuteVertexProgramForAllPasses &&
234                mIsDepthPassPhase &&
235                pass->hasVertexProgram())
236        {
237                // add vertex program of current pass to depth pass
238                mDepthPass->setVertexProgram(pass->getVertexProgramName());
239
240                if (mDepthPass->hasVertexProgram())
241                {
242                        const GpuProgramPtr& prg = mDepthPass->getVertexProgram();
243                        // Load this program if not done already
244                        if (!prg->isLoaded())
245                                prg->load();
246                        // Copy params
247                        mDepthPass->setVertexProgramParameters(pass->getVertexProgramParameters());
248                }
249        }
250        else if (mDepthPass->hasVertexProgram()) // reset vertex program
251        {
252                mDepthPass->setVertexProgram("");
253        }
254       
255        const Pass *usedPass = useDepthPass ? mDepthPass : pass;
256
257        // save old depth write: needed for item buffer
258        const bool IsDepthWrite = usedPass->getDepthWriteEnabled();
259
260        // global option which enables / disables depth writes
261        if (!mEnableDepthWrite)
262        {
263                //usedPass->setDepthWriteEnabled(false);
264        }
265        //else if (mIsItemBufferPass) {usedPass = mItemBufferPass;}
266       
267
268        //-- set actual pass here
269
270        const Pass *result = SceneManager::_setPass(usedPass);
271
272
273        // reset depth write
274        if (!mEnableDepthWrite)
275        {
276                //usedPass->setDepthWriteEnabled(IsDepthWrite);
277        }
278
279        // reset illumination stage
280        mIlluminationStage = savedStage;
281
282        return result;
283}
284//-----------------------------------------------------------------------
285void OcclusionCullingSceneManager::_findVisibleObjects(Camera* cam,
286                                                                                                                bool onlyShadowCasters)
287{
288        if (mNormalExecution)
289        {
290                OctreeSceneManager::_findVisibleObjects(cam, onlyShadowCasters);
291                return;
292        }
293
294
295        //-- show visible scene nodes and octree bounding boxes from last frame
296        if (mShowVisualization)
297    {
298                PrepareVisualization(cam);
299        }
300        else
301        {       
302                // for hierarchical culling, we interleave identification
303                // and rendering of objects in _renderVisibibleObjects
304
305                // for the shadow pass we use only standard rendering
306                // because of low occlusion
307                if (mShadowTechnique == SHADOWTYPE_TEXTURE_MODULATIVE &&
308                        mIlluminationStage == IRS_RENDER_TO_TEXTURE)
309                {
310                        OctreeSceneManager::_findVisibleObjects(cam, onlyShadowCasters);
311                }
312
313                // only shadow casters will be rendered in shadow texture pass
314                if (0) mHierarchyInterface->SetOnlyShadowCasters(onlyShadowCasters);
315
316
317                //-- apply view cell pvs
318                updatePvs(cam);
319        }
320       
321       
322        // lists only used for visualization
323        mVisible.clear();
324        mBoxes.clear();
325}
326//-----------------------------------------------------------------------
327void OcclusionCullingSceneManager::_renderVisibleObjects()
328{
329        if (mNormalExecution)
330        {
331                OctreeSceneManager::_renderVisibleObjects();
332                return;
333        }
334
335        InitDepthPass();          // create material for depth pass
336        InitItemBufferPass(); // create material for item buffer pass
337
338        // save ambient light to reset later
339        ColourValue savedAmbient = mAmbientLight;
340
341        //-- apply standard rendering for some modes (e.g., visualization, shadow pass)
342
343        if (mShowVisualization ||
344           (mShadowTechnique == SHADOWTYPE_TEXTURE_MODULATIVE &&
345            mIlluminationStage == IRS_RENDER_TO_TEXTURE))
346        {       
347                IlluminationRenderStage savedStage = mIlluminationStage;
348       
349                if (mShowVisualization)
350                {
351                        // disable illumination stage to prevent rendering shadows
352                        mIlluminationStage = IRS_NONE;
353                }
354
355                // standard rendering for shadow maps because of performance
356                TerrainSceneManager::_renderVisibleObjects();
357
358                mIlluminationStage = savedStage;
359        }
360        else //-- the hierarchical culling algorithm
361        {
362                // note matt: this is also called in TerrainSceneManager: really necessary?
363                mDestRenderSystem -> setLightingEnabled(false);
364
365                // don't render backgrounds for item buffer
366                if (mUseItemBuffer)
367                {
368                        clearSpecialCaseRenderQueues();
369                        getRenderQueue()->clear();
370                }
371
372                //-- hierarchical culling
373                // the objects of different layers (e.g., background, scene,
374                // overlay) must be identified and rendered one after another
375
376                //-- render all early skies
377                clearSpecialCaseRenderQueues();
378                addSpecialCaseRenderQueue(RENDER_QUEUE_BACKGROUND);
379                addSpecialCaseRenderQueue(RENDER_QUEUE_SKIES_EARLY);
380                setSpecialCaseRenderQueueMode(SceneManager::SCRQM_INCLUDE);
381
382                TerrainSceneManager::_renderVisibleObjects();
383
384#ifdef GTP_VISIBILITY_MODIFIED_OGRE
385                // delete previously rendered content
386                _deleteRenderedQueueGroups();
387#endif
388
389                //-- prepare queue for visible objects (i.e., all but overlay and skies late)
390                clearSpecialCaseRenderQueues();
391                addSpecialCaseRenderQueue(RENDER_QUEUE_SKIES_LATE);
392                addSpecialCaseRenderQueue(RENDER_QUEUE_OVERLAY);
393       
394                // exclude this queues from hierarchical rendering
395                setSpecialCaseRenderQueueMode(SceneManager::SCRQM_EXCLUDE);
396
397
398                // set all necessary parameters for
399                // hierarchical visibility culling and rendering
400                InitVisibilityCulling(mCameraInProgress);
401
402
403                /**
404                * the hierarchical culling algorithm
405                * for depth pass: we just find objects and update depth buffer
406                * for "delayed" rendering: we render some passes afterwards
407                * e.g., transparents, because they need front-to-back sorting
408                **/
409               
410                mVisibilityManager->ApplyVisibilityCulling();
411
412                // delete remaining renderables from queue:
413                // all which are not in mLeavePassesInQueue)
414#ifdef GTP_VISIBILITY_MODIFIED_OGRE
415                _deleteRenderedQueueGroups(mLeavePassesInQueue);
416#endif
417
418                //-- reset parameters needed for special rendering
419               
420                mIsDepthPassPhase = false;
421                mIsItemBufferPhase = false;
422                mSkipTransparents = false;
423                mIsHierarchicalCulling = false;
424               
425                mLeavePassesInQueue = 0;
426               
427                // add visible nodes found by the visibility culling algorithm
428                if (mUseDepthPass)
429                {
430                        NodeList::const_iterator it, it_end = mVisible.end();
431
432                        //getRenderQueue()->clear();
433                        for (it = mVisible.begin(); it != it_end; ++ it)
434                        {
435                                (*it)->_addToRenderQueue(mCameraInProgress, getRenderQueue(), false);
436                        }
437                }
438                //-- now we can render all remaining queue objects
439                //-- used for depth pass, transparents, overlay
440                clearSpecialCaseRenderQueues();
441
442                TerrainSceneManager::_renderVisibleObjects();
443        } // end hierarchical culling
444               
445        // HACK: set the new render level index, important to avoid cracks
446        // in terrain caused by LOD
447        TerrainRenderable::NextRenderLevelIndex();
448       
449        // reset ambient light
450        setAmbientLight(savedAmbient);
451
452        if (!mDeleteQueueAfterRendering)
453                getRenderQueue()->clear(); // finally clear render queue
454        else
455                OGRE_DELETE(mRenderQueue); // HACK: should rather only be cleared ...
456
457        if (0) WriteLog(); // write out stats
458}
459
460//-----------------------------------------------------------------------
461void OcclusionCullingSceneManager::_updateSceneGraph(Camera* cam)
462{
463        if (mNormalExecution)
464        {
465                OctreeSceneManager::_updateSceneGraph(cam);
466                return;
467        }
468
469        mVisibilityManager->GetCullingManager()->SetHierarchyInterface(mHierarchyInterface);
470        mHierarchyInterface->SetRenderSystem(mDestRenderSystem);
471
472        TerrainSceneManager::_updateSceneGraph(cam);
473}
474//-----------------------------------------------------------------------
475bool OcclusionCullingSceneManager::setOption(const String & key, const void * val)
476{
477        if (key == "UseDepthPass")
478        {
479                mUseDepthPass = (*static_cast<const bool *>(val));
480                return true;
481        }
482        if (key == "PrepareVisualization")
483        {
484                mShowVisualization = (*static_cast<const bool *>(val));
485                return true;
486        }
487        if (key == "RenderNodesForViz")
488        {
489                mRenderNodesForViz = (*static_cast<const bool *>(val));
490                return true;
491        }
492        if (key == "RenderNodesContentForViz")
493        {
494                mRenderNodesContentForViz = (*static_cast<const bool *>(val));
495                return true;
496        }
497        if (key == "SkyBoxEnabled")
498        {
499                mSkyBoxEnabled = (*static_cast<const bool *>(val));
500                return true;
501        }
502        if (key == "SkyPlaneEnabled")
503        {
504                mSkyPlaneEnabled = (*static_cast<const bool *>(val));
505                return true;
506        }
507        if (key == "SkyDomeEnabled")
508        {
509                mSkyDomeEnabled = (*static_cast<const bool *>(val));
510                return true;
511        }
512        if (key == "VisualizeCulledNodes")
513        {
514                mVisualizeCulledNodes = (*static_cast<const bool *>(val));
515                return true;
516        }
517        if (key == "DelayRenderTransparents")
518        {
519                mDelayRenderTransparents = (*static_cast<const bool *>(val));
520                return true;
521        }
522        if (key == "DepthWrite")
523        {
524                mEnableDepthWrite = (*static_cast<const bool *>(val));
525                return true;
526        }
527        if (key == "UseItemBuffer")
528        {
529                mUseItemBuffer = (*static_cast<const bool *>(val));
530                return true;
531        }
532        if (key == "ExecuteVertexProgramForAllPasses")
533        {
534                mExecuteVertexProgramForAllPasses  = (*static_cast<const bool *>(val));
535                return true;
536        }
537        if (key == "RenderTransparentsForItemBuffer")
538        {
539                mRenderTransparentsForItemBuffer  = (*static_cast<const bool *>(val));
540                return true;
541        }
542        else if (key == "DeleteRenderQueue")
543        {
544                mDeleteQueueAfterRendering = (*static_cast<const bool *>(val));
545                return true;
546        }
547        if (key == "NodeVizScale")
548        {
549                OctreeNode::setVizScale(*static_cast<const float *>(val));
550                return true;
551        }
552        if (key == "LoadViewCells")
553        {
554                if (!mViewCellsLoaded)
555                {
556                        String filename(static_cast<const char *>(val));
557                        mViewCellsLoaded = LoadViewCells(filename);     
558                }
559
560                return mViewCellsLoaded;
561        }
562        if (key == "UseViewCells")
563        {
564                if (mViewCellsLoaded)
565                {
566                        mUseViewCells = *static_cast<const bool *>(val);
567
568                        // reset view cell
569                        OGRE_DELETE(mCurrentViewCell);
570
571                        if (mUseViewCells)
572                                mCurrentViewCell = mViewCellsManager->GenerateViewCell();
573
574                        mElementaryViewCell = NULL;
575
576                        // if using view cells, all objects are set to false initially
577                        SetObjectsVisible(!mUseViewCells);
578                }
579
580                return true;
581        }
582        if (key == "NormalExecution")
583        {
584                mNormalExecution = *static_cast<const bool *>(val);
585                return true;
586        }
587        if (key == "UseVisibilityFilter")
588        {
589                mUseVisibilityFilter = *static_cast<const bool *>(val);
590                // set null =>recomputation of the pvs
591        mElementaryViewCell = NULL;
592                return true;
593        }
594
595        return VisibilityOptionsManager(mVisibilityManager, mHierarchyInterface).
596                setOption(key, val) || TerrainSceneManager::setOption(key, val);
597}
598//-----------------------------------------------------------------------
599bool OcclusionCullingSceneManager::getOption(const String & key, void *val)
600{
601        if (key == "NumHierarchyNodes")
602        {
603                * static_cast<unsigned int *>(val) = (unsigned int)mNumOctants;
604                return true;
605        }
606        if (key == "VisibilityManager")
607        {
608                * static_cast<GtpVisibility::VisibilityManager **>(val) =
609                        (GtpVisibility::VisibilityManager *)mVisibilityManager;
610                return true;
611        }
612        if (key == "HierarchInterface")
613        {
614                * static_cast<GtpVisibility::HierarchyInterface **>(val) =
615                        (GtpVisibility::HierarchyInterface *)mHierarchyInterface;
616                return true;
617        }
618
619        return VisibilityOptionsManager(mVisibilityManager, mHierarchyInterface).
620                getOption(key, val) && TerrainSceneManager::getOption(key, val);
621}
622//-----------------------------------------------------------------------
623bool OcclusionCullingSceneManager::getOptionValues(const String & key,
624                                                                                                        StringVector &refValueList)
625{
626        return TerrainSceneManager::getOptionValues( key, refValueList);
627}
628//-----------------------------------------------------------------------
629bool OcclusionCullingSceneManager::getOptionKeys(StringVector & refKeys)
630{
631        return VisibilityOptionsManager(mVisibilityManager, mHierarchyInterface).
632                getOptionKeys(refKeys) || TerrainSceneManager::getOptionKeys(refKeys);
633}
634//-----------------------------------------------------------------------
635void OcclusionCullingSceneManager::setVisibilityManager(GtpVisibility::
636                                                                                                                 VisibilityManager *visManager)
637{
638        mVisibilityManager = visManager;
639}
640//-----------------------------------------------------------------------
641GtpVisibility::VisibilityManager *OcclusionCullingSceneManager::getVisibilityManager( void )
642{
643        return mVisibilityManager;
644}
645//-----------------------------------------------------------------------
646void OcclusionCullingSceneManager::WriteLog()
647{
648        std::stringstream d;
649
650        d << "Depth pass: " << StringConverter::toString(mUseDepthPass) << ", "
651          << "Delay transparents: " << StringConverter::toString(mDelayRenderTransparents) << ", "
652          << "Use optimization: " << StringConverter::toString(mHierarchyInterface->GetTestGeometryForVisibleLeaves()) << ", "
653          << "Algorithm type: " << mVisibilityManager->GetCullingManagerType() << ", "
654          << "Hierarchy nodes: " << mNumOctants << ", "
655          << "Traversed nodes: " << mHierarchyInterface->GetNumTraversedNodes() << ", "
656          << "Rendered nodes: " << mHierarchyInterface->GetNumRenderedNodes() << ", "
657          << "Query culled nodes: " << mVisibilityManager->GetCullingManager()->GetNumQueryCulledNodes() << ", "
658          << "Frustum culled nodes: " << mVisibilityManager->GetCullingManager()->GetNumFrustumCulledNodes() << ", "
659      << "Queries issued: " << mVisibilityManager->GetCullingManager()->GetNumQueriesIssued() << ", "
660          << "Found objects: " << (int)mVisible.size() << "\n";
661
662        LogManager::getSingleton().logMessage(d.str());
663}
664//-----------------------------------------------------------------------
665void OcclusionCullingSceneManager::renderBasicQueueGroupObjects(RenderQueueGroup* pGroup,
666                                                                                                                                QueuedRenderableCollection::OrganisationMode om)
667{
668    // Basic render loop
669    // Iterate through priorities
670    RenderQueueGroup::PriorityMapIterator groupIt = pGroup->getIterator();
671
672    while (groupIt.hasMoreElements())
673    {
674        RenderPriorityGroup* pPriorityGrp = groupIt.getNext();
675
676        // Sort the queue first
677        pPriorityGrp->sort(mCameraInProgress);
678
679        // Do solids
680        renderObjects(pPriorityGrp->getSolidsBasic(), om, true);
681
682                // for correct rendering, transparents must be rendered after hierarchical culling
683                // => do nothing
684
685        // Do transparents (always descending)
686                if (mNormalExecution || !mSkipTransparents)
687                {
688                        renderObjects(pPriorityGrp->getTransparents(),
689                        QueuedRenderableCollection::OM_SORT_DESCENDING, true);
690                }
691
692
693    }// for each priority
694}
695
696//-----------------------------------------------------------------------
697bool OcclusionCullingSceneManager::validatePassForRendering(Pass* pass)
698{
699        if (mNormalExecution)
700        {
701                return SceneManager::validatePassForRendering(pass);
702        }
703
704        // skip all but first pass if we are doing the depth pass
705        if ((mIsDepthPassPhase || mIsItemBufferPhase) && (pass->getIndex() > 0))
706        {
707                return false;
708        }
709        // all but first pass
710        /*else if ((!mIsDepthPassPhase || mIsItemBufferPhase) && (pass->getIndex() != 0))
711        {
712                return false;
713        }*/
714
715        return SceneManager::validatePassForRendering(pass);
716}
717//-----------------------------------------------------------------------
718void OcclusionCullingSceneManager::_renderQueueGroupObjects(RenderQueueGroup* pGroup,
719                                                                                                                        QueuedRenderableCollection::OrganisationMode om)
720{
721        if (mNormalExecution || !mIsItemBufferPhase)
722        {
723                TerrainSceneManager::_renderQueueGroupObjects(pGroup, om);
724                return;
725        }
726#ifdef  ITEM_BUFFER
727        //-- item buffer
728        //-- item buffer: render objects using false colors
729
730    // Iterate through priorities
731    RenderQueueGroup::PriorityMapIterator groupIt = pGroup->getIterator();
732
733        while (groupIt.hasMoreElements())
734    {
735                RenderItemBuffer(groupIt.getNext());
736        }
737#endif // ITEM_BUFFER
738}
739#ifdef ITEM_BUFFER
740//-----------------------------------------------------------------------
741void OcclusionCullingSceneManager::RenderItemBuffer(RenderPriorityGroup* pGroup)
742{
743        // Do solids
744        QueuedRenderableCollection solidObjs = pGroup->getSolidsBasic();//msz
745
746        // ----- SOLIDS LOOP -----
747        RenderPriorityGroup::SolidRenderablePassMap::const_iterator ipass, ipassend;
748        ipassend = solidObjs.end();
749
750        for (ipass = solidObjs.begin(); ipass != ipassend; ++ipass)
751        {
752                // Fast bypass if this group is now empty
753                if (ipass->second->empty())
754                        continue;
755
756                // Render only first pass of renderable as false color
757                if (ipass->first->getIndex() > 0)
758                        continue;
759
760                RenderPriorityGroup::RenderableList* rendList = ipass->second;
761               
762                RenderPriorityGroup::RenderableList::const_iterator irend, irendend;
763                irendend = rendList->end();
764                       
765                for (irend = rendList->begin(); irend != irendend; ++irend)
766                {
767                        if (0)
768                        {
769                        std::stringstream d; d << "itembuffer, pass name: " <<
770                                ipass->first->getParent()->getParent()->getName();
771                               
772                        LogManager::getSingleton().logMessage(d.str());
773                        }
774                       
775                        RenderSingleObjectForItemBuffer(*irend, ipass->first);
776                }
777        }
778
779        //-- TRANSPARENT LOOP: must be handled differently from solids
780
781        // transparents are treated either as solids or completely discarded
782        if (mRenderTransparentsForItemBuffer)
783        {
784                QueuedRenderableCollection transpObjs = pGroup->getTransparents(); //msz
785                RenderPriorityGroup::TransparentRenderablePassList::const_iterator
786                        itrans, itransend;
787
788                itransend = transpObjs.end();
789                for (itrans = transpObjs.begin(); itrans != itransend; ++itrans)
790                {
791                        // like for solids, render only first pass
792                        if (itrans->pass->getIndex() == 0)
793                        {       
794                                RenderSingleObjectForItemBuffer(itrans->renderable, itrans->pass);
795                        }
796                }
797        }
798}
799//-----------------------------------------------------------------------
800void OcclusionCullingSceneManager::RenderSingleObjectForItemBuffer(Renderable *rend, Pass *pass)
801{
802        static LightList nullLightList;
803       
804        int col[4];
805       
806        // -- create color code out of object id
807        col[0] = (rend->getId() >> 16) & 255;
808        col[1] = (rend->getId() >> 8) & 255;
809        col[2] = rend->getId() & 255;
810//      col[3] = 255;
811
812        //mDestRenderSystem->setColour(col[0], col[1], col[2], col[3]);
813   
814        mItemBufferPass->setAmbient(ColourValue(col[0] / 255.0f,
815                                                                                    col[1] / 255.0f,
816                                                                                        col[2] / 255.0f, 1));
817
818        // set vertex program of current pass
819        if (mExecuteVertexProgramForAllPasses && pass->hasVertexProgram())
820        {
821                mItemBufferPass->setVertexProgram(pass->getVertexProgramName());
822
823                if (mItemBufferPass->hasVertexProgram())
824                {
825                        const GpuProgramPtr& prg = mItemBufferPass->getVertexProgram();
826                        // Load this program if not done already
827                        if (!prg->isLoaded())
828                                prg->load();
829                        // Copy params
830                        mItemBufferPass->setVertexProgramParameters(pass->getVertexProgramParameters());
831                }
832        }
833        else if (mItemBufferPass->hasVertexProgram())
834        {
835                mItemBufferPass->setVertexProgram("");
836        }
837
838        const Pass *usedPass = _setPass(mItemBufferPass);
839
840
841        // render a single object, this will set up auto params if required
842        renderSingleObject(rend, usedPass, false, &nullLightList);
843}
844#endif // ITEM_BUFFER
845//-----------------------------------------------------------------------
846GtpVisibility::VisibilityManager *OcclusionCullingSceneManager::GetVisibilityManager()
847{
848        return mVisibilityManager;
849}
850//-----------------------------------------------------------------------
851void OcclusionCullingSceneManager::InitVisibilityCulling(Camera *cam)
852{
853        // reset culling manager stats
854        mVisibilityManager->GetCullingManager()->InitFrame(mVisualizeCulledNodes);
855
856        // set depth pass flag before rendering
857        mIsDepthPassPhase = mUseDepthPass;
858
859        mIsHierarchicalCulling = true; // during hierarchical culling
860
861        // item buffer needs full ambient lighting to use item colors as unique id
862        if (mUseItemBuffer)
863        {
864                mIsItemBufferPhase = true;
865                setAmbientLight(ColourValue(1,1,1,1));
866        }
867
868
869        // set passes which are stored in render queue
870        // for rendering AFTER hierarchical culling, i.e., passes which need
871        // a special rendering order
872       
873        mLeavePassesInQueue = 0;
874
875        // if we have the depth pass or use an item buffer, no passes are left in the queue
876        if (1 && !mUseDepthPass && !mUseItemBuffer)
877        {
878                if (mShadowTechnique == SHADOWTYPE_STENCIL_ADDITIVE)
879                {
880                        // TODO: remove this pass because it should be processed during hierarchical culling
881                        //mLeavePassesInQueue |= RenderPriorityGroup::SOLID_PASSES_NOSHADOW;
882
883                        mLeavePassesInQueue |= RenderPriorityGroup::SOLID_PASSES_DECAL;
884                        mLeavePassesInQueue |= RenderPriorityGroup::SOLID_PASSES_DIFFUSE_SPECULAR;
885                        mLeavePassesInQueue |= RenderPriorityGroup::TRANSPARENT_PASSES;
886
887                        // just render ambient passes
888                        /*** msz: no more IRS_AMBIENT, see OgreSceneManager.h ***/
889                        // mIlluminationStage = IRS_AMBIENT;
890                        //getRenderQueue()->setSplitPassesByLightingType(true);
891                }
892       
893                if (mShadowTechnique == SHADOWTYPE_STENCIL_MODULATIVE)
894                {
895                        mLeavePassesInQueue |= RenderPriorityGroup::SOLID_PASSES_NOSHADOW;
896                        mLeavePassesInQueue |= RenderPriorityGroup::TRANSPARENT_PASSES;
897                }
898       
899                // transparents should be rendered after hierarchical culling to
900                // provide front-to-back ordering
901                if (mDelayRenderTransparents)
902                {
903                        mLeavePassesInQueue |= RenderPriorityGroup::TRANSPARENT_PASSES;
904                }
905        }
906
907        // skip rendering transparents during the hierarchical culling
908        // (because they will be rendered afterwards)
909        mSkipTransparents =
910                (mIsDepthPassPhase || (mLeavePassesInQueue & RenderPriorityGroup::TRANSPARENT_PASSES));
911
912        // -- initialise interface for rendering traversal of the hierarchy
913        mHierarchyInterface->SetHierarchyRoot(mOctree);
914       
915        // possible two cameras (one for culling, one for rendering)
916        mHierarchyInterface->InitTraversal(mCameraInProgress,
917                                                                           mCullCamera ? getCamera("CullCamera") : NULL,
918                                                                           mLeavePassesInQueue);
919               
920}
921//-----------------------------------------------------------------------
922OctreeHierarchyInterface *OcclusionCullingSceneManager::GetHierarchyInterface()
923{
924        return mHierarchyInterface;
925}
926//-----------------------------------------------------------------------
927void OcclusionCullingSceneManager::endFrame()
928{
929        TerrainRenderable::ResetRenderLevelIndex();
930}
931//-----------------------------------------------------------------------
932Entity* OcclusionCullingSceneManager::createEntity(const String& entityName,
933                                                                                                        const String& meshName)
934{
935        Entity *ent = SceneManager::createEntity(entityName, meshName);
936
937        for (int i = 0; i < (int)ent->getNumSubEntities(); ++i)
938        {
939                ent->getSubEntity(i)->setId(mCurrentEntityId);
940        }
941
942        // increase counter of entity id values
943        ++ mCurrentEntityId;
944
945        return ent;
946}
947//-----------------------------------------------------------------------
948void OcclusionCullingSceneManager::renderAdditiveStencilShadowedQueueGroupObjects(
949        RenderQueueGroup* pGroup, QueuedRenderableCollection::OrganisationMode om)
950{
951        // only render solid passes during hierarchical culling
952        if (mIsHierarchicalCulling)
953        {
954                RenderQueueGroup::PriorityMapIterator groupIt = pGroup->getIterator();
955            LightList lightList;
956
957                while (groupIt.hasMoreElements())
958                {
959                        RenderPriorityGroup* pPriorityGrp = groupIt.getNext();
960
961                        // Sort the queue first
962                        pPriorityGrp->sort(mCameraInProgress);
963
964                        // Clear light list
965                        lightList.clear();
966
967                        // Render all the ambient passes first, no light iteration, no lights
968                        /*** msz: no more IRS_AMBIENT, see OgreSceneManager.h ***/
969                        // mIlluminationStage = IRS_AMBIENT;
970
971                        OctreeSceneManager::renderObjects(pPriorityGrp->getSolidsBasic(), om, false, &lightList);
972                        // Also render any objects which have receive shadows disabled
973                        OctreeSceneManager::renderObjects(pPriorityGrp->getSolidsNoShadowReceive(), om, true);
974#if 0           
975                        std::stringstream d;
976                        d << " solid size: " << (int)pPriorityGrp->_getSolidPasses().size()
977                                << " solid no shadow size: " << (int)pPriorityGrp->_getSolidPassesNoShadow().size()
978                                << "difspec size: " << (int)pPriorityGrp->_getSolidPassesDiffuseSpecular().size()
979                                << " decal size: " << (int)pPriorityGrp->_getSolidPassesDecal().size();
980                        LogManager::getSingleton().logMessage(d.str());
981#endif
982                }
983        }
984        else // render the rest of the passes
985        {
986                OctreeSceneManager::renderAdditiveStencilShadowedQueueGroupObjects(pGroup, om);
987        }
988}
989//-----------------------------------------------------------------------
990void OcclusionCullingSceneManager::renderModulativeStencilShadowedQueueGroupObjects(
991        RenderQueueGroup* pGroup, QueuedRenderableCollection::OrganisationMode om)
992{
993   if (mIsHierarchicalCulling)
994   {
995           // Iterate through priorities
996           RenderQueueGroup::PriorityMapIterator groupIt = pGroup->getIterator();
997
998           while (groupIt.hasMoreElements())
999           {
1000                   RenderPriorityGroup* pPriorityGrp = groupIt.getNext();
1001
1002                   // Sort the queue first
1003                   pPriorityGrp->sort(mCameraInProgress);
1004
1005                   // Do (shadowable) solids
1006                   OctreeSceneManager::renderObjects(pPriorityGrp->getSolidsBasic(), om, true);
1007           }
1008   }
1009   else
1010   {
1011           OctreeSceneManager::renderModulativeStencilShadowedQueueGroupObjects(pGroup, om);
1012   }
1013}
1014//-------------------------------------------------------------------------
1015void OcclusionCullingSceneManager::SetObjectsVisible(const bool visible)
1016{
1017        GtpVisibilityPreprocessor::ObjectContainer::iterator it, it_end = mObjects.end();
1018
1019        for (it = mObjects.begin(); it != it_end; ++ it)
1020        {
1021                OgreMeshInstance *omi = static_cast<OgreMeshInstance *>(*it);
1022                Entity *ent = omi->GetMesh();
1023               
1024                ent->setVisible(visible);
1025        }
1026}
1027//-----------------------------------------------------------------------
1028bool OcclusionCullingSceneManager::LoadViewCells(const String &filename)
1029{
1030        // objects are set to invisible initially
1031        SetObjectsVisible(false);
1032       
1033        const string bboxesFilename = mVisibilityManager->GetVisibilityEnvironment()->getViewCellsFileName();
1034
1035        // converter between view cell ids and Ogre entites
1036        GtpVisibilityPreprocessor::IndexedBoundingBoxContainer iboxes;
1037        OgreBoundingBoxConverter bconverter(this);
1038
1039        // load the view cells assigning the found objects to the pvss
1040        mViewCellsManager =
1041                GtpVisibilityPreprocessor::ViewCellsManager::LoadViewCells(filename, &mObjects, false, &bconverter);
1042
1043        return (mViewCellsManager != NULL);
1044}
1045//-------------------------------------------------------------------------
1046void OcclusionCullingSceneManager::applyViewCellPvs(GtpVisibilityPreprocessor::ViewCell *vc,
1047                                                                                                        const bool load)
1048{       // NOTE: should not happen, rather apply view cell representing unbounded space then
1049        if (!vc)
1050        {       
1051                // set everything visible for savety
1052                SetObjectsVisible(true);
1053
1054                return;
1055        }
1056               
1057        GtpVisibilityPreprocessor::ObjectPvsMap::const_iterator oit,
1058                        oit_end = vc->GetPvs().mEntries.end();
1059
1060        //-- PVS of view cell
1061        for (oit = vc->GetPvs().mEntries.begin(); oit != oit_end; ++ oit)
1062        {
1063                if (!(*oit).first) continue;
1064
1065                OgreMeshInstance *omi = dynamic_cast<OgreMeshInstance *>((*oit).first);
1066                omi->GetMesh()->setVisible(load);
1067                //GtpVisibilityPreprocessor::Debug << "assigned id " << omi->GetId() << endl;
1068        }
1069}
1070//-------------------------------------------------------------------------
1071void OcclusionCullingSceneManager::updatePvs(Camera *cam)
1072{
1073        if (!(mViewCellsLoaded && mUseViewCells))
1074                return;
1075
1076        const GtpVisibilityPreprocessor::Vector3 viewPoint =
1077                OgreTypeConverter::ConvertFromOgre(cam->getDerivedPosition());
1078
1079        GtpVisibilityPreprocessor::ViewCell *newElementary =
1080                mViewCellsManager->GetViewCell(viewPoint);
1081
1082        // elementary view cell did not change => apply same pvs
1083        if (mElementaryViewCell == newElementary)
1084                return;
1085
1086        mElementaryViewCell = newElementary;
1087        //LogManager::getSingleton().logMessage("unloading");
1088        //-- unload old pvs
1089        applyViewCellPvs(mCurrentViewCell, false);
1090
1091
1092        //-- the new view cell
1093               
1094        GtpVisibilityPreprocessor::ViewCell *viewCell;
1095
1096               
1097        if (mUseVisibilityFilter)
1098        {
1099                //-- compute new filtered cell
1100                GtpVisibilityPreprocessor::PrVs prvs;
1101                mViewCellsManager->GetPrVS(viewPoint, prvs, 5);
1102                viewCell = prvs.mViewCell;
1103        }
1104        else
1105        {
1106                viewCell = newElementary;
1107        }
1108        //LogManager::getSingleton().logMessage("loading");
1109        //-- load new pvs
1110        applyViewCellPvs(viewCell, true);
1111
1112        // store pvs
1113        mCurrentViewCell->SetPvs(viewCell->GetPvs());
1114
1115        // delete merge tree of filtered view cell
1116        if (mUseVisibilityFilter)
1117                mViewCellsManager->DeleteLocalMergeTree(viewCell);
1118}
1119#if 0
1120//-------------------------------------------------------------------------
1121void OcclusionCullingSceneManager::TestVisible(SceneNode *node)
1122{
1123        // first test for scene node, then for octant (part of the hierarchy)
1124        if (!node->mVisibleChildren)
1125                node->setVisible(false);
1126
1127        node->getOctant()->mVisibleChildren --;
1128}
1129//-------------------------------------------------------------------------
1130void OcclusionCullingSceneManager::TestVisible(Octree *octant)
1131{
1132        // first test for scene node, then for octant (part of the hierarchy)
1133        if (!octant->mVisibleChildren)
1134                octant->setVisible(false);
1135}
1136
1137//-------------------------------------------------------------------------
1138void OcclusionCullingSceneManager::UpdateVisibility(Entity *ent)
1139{
1140        if (!ent->isVisible())
1141        {
1142                bool visible = TestVisible(ent->getParentNode());
1143               
1144                if (!visible)
1145                        visible = TestVisible(octant->getParentNode());
1146
1147                if (!visible)
1148                        mHierarchyInterface->pullupVisibility();
1149        }
1150}
1151#endif
1152//-----------------------------------------------------------------------
1153const String OcclusionCullingSceneManagerFactory::FACTORY_TYPE_NAME = "OcclusionCullingSceneManager";
1154//-----------------------------------------------------------------------
1155void OcclusionCullingSceneManagerFactory::initMetaData(void) const
1156{
1157        mMetaData.typeName = FACTORY_TYPE_NAME;
1158        mMetaData.description = "Scene manager organising the scene on the basis of an octree with advanced occlusion culling (TM).";
1159        mMetaData.sceneTypeMask = 0xFFFF; // support all types
1160        mMetaData.worldGeometrySupported = false;
1161}
1162//-----------------------------------------------------------------------
1163SceneManager *OcclusionCullingSceneManagerFactory::createInstance(
1164                const String& instanceName)
1165{
1166        OcclusionCullingSceneManager* tsm = new OcclusionCullingSceneManager(instanceName, visManager);
1167       
1168        // Create & register default sources (one per manager)
1169        HeightmapTerrainPageSource* ps = new HeightmapTerrainPageSource();
1170        mTerrainPageSources.push_back(ps);
1171        tsm->registerPageSource("Heightmap", ps);
1172
1173        return tsm;
1174}
1175//-----------------------------------------------------------------------
1176void OcclusionCullingSceneManagerFactory::destroyInstance(SceneManager* instance)
1177{
1178        delete instance;
1179}
1180
1181} // namespace Ogre
Note: See TracBrowser for help on using the repository browser.