root/OpenSceneGraph/trunk/src/osgPlugins/txp/TXPNode.cpp @ 11037

Revision 11037, 9.8 kB (checked in by robert, 5 years ago)

From Ryan Kawicki, added removal of TXPArchive from ReaderWriterTXP when the TXPNode destructs to fix memory consumption issue relating to leaving unused archives in memory.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1#include <osg/Notify>
2#include <osg/BoundingBox>
3#include <osg/PagedLOD>
4#include <osg/Timer>
5#include <osg/MatrixTransform>
6#include <osgUtil/CullVisitor>
7#include <osgDB/Registry>
8#include <osgDB/ReaderWriter>
9
10#include <iostream>
11#include <vector>
12#include <algorithm>
13#include <stdio.h>
14
15#include "TileMapper.h"
16#include "TXPNode.h"
17#include "TXPPagedLOD.h"
18#include "ReaderWriterTXP.h"
19
20
21using namespace txp;
22using namespace osg;
23
24
25
26class RetestCallback : public osg::NodeCallback
27{
28
29public:
30    RetestCallback()
31    {
32        timer = osg::Timer::instance(); // get static timer
33        prevTime = 0; // should this be instantiated with current time?
34    }
35
36    virtual void operator () ( osg::Node * node, osg::NodeVisitor * nv )
37    {
38        osg::Group *pLOD = (osg::Group *) node;
39        osg::Group *n = NULL;
40        if ((pLOD->getNumChildren() > 0) &&
41            (n = (osg::Group *) pLOD->getChild(0)) &&
42            (n->getNumChildren() == 0))
43        {
44            osg::Timer_t curTime = timer->tick();
45            if ((prevTime + 2.0/timer->getSecondsPerTick() ) < curTime)
46            {
47                prevTime = curTime;
48                pLOD->removeChildren( 0, pLOD->getNumChildren());
49            }
50        }
51
52        NodeCallback::traverse( node, nv );
53    }
54
55protected:
56    const osg::Timer* timer;
57    osg::Timer_t prevTime;
58};
59
60
61
62#define TXPNodeERROR(s) osg::notify(osg::NOTICE) << "txp::TXPNode::" << (s) << " error: "
63
64TXPNode::TXPNode():
65osg::Group(),
66_originX(0.0),
67_originY(0.0)
68{
69    setNumChildrenRequiringUpdateTraversal(1);
70    setCullingActive(false);
71}
72           
73TXPNode::TXPNode(const TXPNode& txpNode,const osg::CopyOp& copyop):
74osg::Group(txpNode,copyop),
75_originX(txpNode._originX),
76_originY(txpNode._originY)
77{
78    setNumChildrenRequiringUpdateTraversal(1);
79}
80
81TXPNode::~TXPNode()
82{
83   if (_archive.get())
84   {
85      if (osgDB::ReaderWriter * rw =
86          osgDB::Registry::instance()->getReaderWriterForExtension("txp"))
87      {
88         if (ReaderWriterTXP * rwTXP =
89             dynamic_cast< ReaderWriterTXP * >(rw))
90         {
91            const int id = _archive->getId();
92            if (!rwTXP->removeArchive(id))
93            {
94               TXPNodeERROR("Failed to remove archive ") << id << std::endl;
95            }
96         }
97      }
98   }
99}
100
101TXPArchive* TXPNode::getArchive()
102{
103    return _archive.get();
104}
105
106void TXPNode::traverse(osg::NodeVisitor& nv)
107{
108    switch(nv.getVisitorType())
109    {
110    case osg::NodeVisitor::CULL_VISITOR:
111    {
112
113        OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex);
114               
115        osgUtil::CullVisitor* cv = dynamic_cast<osgUtil::CullVisitor*>(&nv);
116        if (cv)
117        {
118//#define PRINT_TILEMAPP_TIMEINFO
119#ifdef PRINT_TILEMAPP_TIMEINFO
120            const osg::Timer& timer = *osg::Timer::instance();
121            osg::Timer_t start = timer.tick();
122            std::cout<<"Doing visible tile search"<<std::endl;
123#endif // PRINT_TILEMAPP_TIMEINFO
124       
125            osg::ref_ptr<TileMapper> tileMapper = new TileMapper;
126            tileMapper->setLODScale(cv->getLODScale());
127            tileMapper->pushReferenceViewPoint(cv->getReferenceViewPoint());
128            tileMapper->pushViewport(cv->getViewport());
129            tileMapper->pushProjectionMatrix((cv->getProjectionMatrix()));
130            tileMapper->pushModelViewMatrix((cv->getModelViewMatrix()), osg::Transform::RELATIVE_RF);
131
132            // traverse the scene graph to search for valid tiles
133            accept(*tileMapper);
134
135            tileMapper->popModelViewMatrix();
136            tileMapper->popProjectionMatrix();
137            tileMapper->popViewport();
138            tileMapper->popReferenceViewPoint();
139
140            //std::cout<<"   found " << tileMapper._tileMap.size() << std::endl;
141           
142            tileMapper->checkValidityOfAllVisibleTiles();
143           
144            cv->setUserData(tileMapper.get());
145
146#ifdef PRINT_TILEMAPP_TIMEINFO       
147            std::cout<<"Completed visible tile search in "<<timer.delta_m(start,timer.tick())<<std::endl;
148#endif // PRINT_TILEMAPP_TIMEINFO       
149
150        }       
151   
152        updateEye(nv);
153        break;
154    }
155    case osg::NodeVisitor::UPDATE_VISITOR:
156    {
157        OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex);
158
159        updateSceneGraph();
160        break;
161    }
162    default:
163        break;
164    }
165    Group::traverse(nv);
166}
167
168osg::BoundingSphere TXPNode::computeBound() const
169{
170#if 1
171
172    // Steve Lunsford 10/28/05 : - Had to avoid using the child group nodes for bounds calculation
173    // because apparently the loader doesn't load all the sub-tiles for this node, resulting in a Group::computeBounds
174    // call which returns a size smaller than the actual size represented by this node so consequently this node gets culled out.
175    // note, submission merged and rearranged by Robert Osfield as an #if #else just in case we need to revert.
176    return osg::BoundingSphere( _extents );
177#else
178    // original code which uses the extents of the children when one is available.
179    if (getNumChildren() == 0)
180    {
181        return osg::BoundingSphere( _extents );
182    }
183    return Group::computeBound();
184#endif
185}
186
187void TXPNode::setArchiveName(const std::string& archiveName)
188{
189    _archiveName = archiveName;
190}
191
192void TXPNode::setOptions(const std::string& options)
193{
194    _options = options;
195}
196
197const std::string& TXPNode::getOptions() const
198{
199    return _options;
200}
201
202const std::string& TXPNode::getArchiveName() const
203{
204    return _archiveName;
205}
206
207bool TXPNode::loadArchive(TXPArchive* archive)
208{
209    //if (_archive.get())
210    //{
211    //    TXPNodeERROR("loadArchive()") << "archive already open" << std::endl;
212    //    return false;
213    //}
214
215
216   //modified by Brad Anderegg on May-27-08
217   //if NULL is passed in we will create a new archive and open the database
218   //otherwise we will use the archive provided which should have already been loaded
219   //by ReaderWriterTXP::getArchive(). See line 57-77 of ReaderWriterTXP.cpp.
220   if(archive == NULL)
221   {
222       _archive = new TXPArchive;
223       if (_archive->openFile(_archiveName) == false)
224       {
225           TXPNodeERROR("loadArchive()") << "failed to load archive: \"" << _archiveName << "\"" << std::endl;
226           return false;
227       }
228   }
229   else
230   {
231      _archive = archive;
232   }
233
234    _archive->getOrigin(_originX,_originY);
235    _archive->getExtents(_extents);
236
237    int32 numLod;
238    _archive->GetHeader()->GetNumLods(numLod);
239
240    trpg2iPoint tileSize;
241    _archive->GetHeader()->GetLodSize(0,tileSize);
242
243    _pageManager = new TXPPageManager;
244
245    // We are going to use _pageManager to manage lod 0 only, all other lod
246    // are managed by this OSG plugin
247    _pageManager->Init(_archive.get(), 1);
248
249    return true;
250}
251
252void TXPNode::updateEye(osg::NodeVisitor& nv)
253{
254    if (!_pageManager)
255    {
256        osg::notify(osg::NOTICE)<<"TXPNode::updateEye() no pageManager created"<<std::endl;
257        return;
258    }
259
260    trpg2dPoint loc;
261    loc.x = nv.getEyePoint().x() - _originX;
262    loc.y = nv.getEyePoint().y() - _originY;
263
264    if (_pageManager->SetLocation(loc))
265    {
266        trpgManagedTile *tile=NULL;
267
268        while((tile = _pageManager->GetNextUnload()))
269        {
270            int x,y,lod;
271            tile->GetTileLoc(x,y,lod);
272            if (lod == 0)
273            {
274                osg::Node* node = (osg::Node*)(tile->GetLocalData());
275                _nodesToRemove.push_back(node);
276
277                //osg::notify(osg::NOTICE) << "Tile unload: " << x << " " << y << " " << lod << std::endl;
278            }
279            _pageManager->AckUnload();
280        }
281
282        while ((tile = _pageManager->GetNextLoad()))
283        {
284            int x,y,lod;
285            tile->GetTileLoc(x,y,lod);
286            if (lod==0)
287            {
288                osg::Node* node = addPagedLODTile(x,y);
289                tile->SetLocalData(node);
290                //osg::notify(osg::NOTICE) << "Tile load: " << x << " " << y << " " << lod << std::endl;
291            }
292            _pageManager->AckLoad();
293           
294        }
295    }
296}
297
298osg::Node* TXPNode::addPagedLODTile(int x, int y)
299{
300    // For TerraPage 2.1 and over this method must only be use with lod = 0.
301    // If you look at the code that calls it, it is effectively called only when
302    // lod = 0. So all is OK
303    int lod = 0;
304    char pagedLODfile[1024];
305    sprintf(pagedLODfile,"%s\\tile%d_%dx%d_%d.txp",_archive->getDir(),lod,x,y,_archive->getId());
306
307
308    TXPArchive::TileInfo info;
309    _archive->getTileInfo(x,y,lod,info);
310
311    osg::PagedLOD* pagedLOD = new osg::PagedLOD;
312    pagedLOD->setFileName(0,pagedLODfile);
313    pagedLOD->setPriorityOffset(0,_archive->getNumLODs());
314    pagedLOD->setPriorityScale(0,1.0f);
315    pagedLOD->setRange(0,0.0,info.maxRange);
316    pagedLOD->setCenter(info.center);
317    pagedLOD->setRadius(info.radius);
318    pagedLOD->setNumChildrenThatCannotBeExpired(1);
319    pagedLOD->setUpdateCallback(new RetestCallback);
320
321    const trpgHeader* header = _archive->GetHeader();
322    trpgHeader::trpgTileType tileType;
323    header->GetTileOriginType(tileType);
324    if(tileType == trpgHeader::TileLocal)
325    {
326        // add in MatrixTransform node with Matrixd offsets
327        // get offsets from tile.bbox
328        osg::Vec3d sw(info.bbox._min);
329        sw[2] = 0.0;
330        osg::Matrix offset;
331        offset.setTrans(sw);
332        osg::MatrixTransform *tform = new osg::MatrixTransform(offset);
333        pagedLOD->setCenter(info.center - sw);
334        tform->addChild(pagedLOD);
335        _nodesToAdd.push_back(tform);
336        return tform;
337    }
338    else
339    {
340    _nodesToAdd.push_back(pagedLOD);
341   
342    return pagedLOD;
343}
344}
345
346void TXPNode::updateSceneGraph()
347{
348    if (!_nodesToRemove.empty())
349    {
350        for (unsigned int i = 0; i < _nodesToRemove.size(); i++)
351        {
352            removeChild(_nodesToRemove[i]);
353        }
354        _nodesToRemove.clear();
355    }
356
357    if (!_nodesToAdd.empty())
358    {
359        for (unsigned int i = 0; i < _nodesToAdd.size(); i++)
360        {
361            addChild(_nodesToAdd[i]);
362        }
363        _nodesToAdd.clear();
364       
365    }   
366}
367
Note: See TracBrowser for help on using the browser.