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

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