]> git.mxchange.org Git - simgear.git/blob - simgear/scene/tgdb/ReaderWriterSPT.cxx
spt: Expose the paging levels to osg options.
[simgear.git] / simgear / scene / tgdb / ReaderWriterSPT.cxx
1 // ReaderWriterSPT.cxx -- Provide a paged database for flightgear scenery.
2 //
3 // Copyright (C) 2010 - 2013  Mathias Froehlich
4 //
5 // This program is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU General Public License as
7 // published by the Free Software Foundation; either version 2 of the
8 // License, or (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful, but
11 // WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 // General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with this program; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18 //
19
20 #ifdef HAVE_CONFIG_H
21 #  include <simgear_config.h>
22 #endif
23
24 #include "ReaderWriterSPT.hxx"
25
26 #include <cassert>
27
28 #include <osg/CullFace>
29 #include <osg/PagedLOD>
30 #include <osg/MatrixTransform>
31 #include <osg/Texture2D>
32
33 #include <osgDB/FileNameUtils>
34 #include <osgDB/FileUtils>
35 #include <osgDB/ReadFile>
36
37 #include <simgear/scene/util/OsgMath.hxx>
38
39 #include "BucketBox.hxx"
40
41 namespace simgear {
42
43 // Cull away tiles that we watch from downside
44 struct ReaderWriterSPT::CullCallback : public osg::NodeCallback {
45     virtual ~CullCallback()
46     { }
47     virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
48     {
49         const osg::BoundingSphere& nodeBound = node->getBound();
50         // If the bounding sphere of the node is empty, there is nothing to do
51         if (!nodeBound.valid())
52             return;
53
54         // Culling away tiles that we look at from the downside.
55         // This is done by computing the maximum distance we can
56         // see something from the current eyepoint. If the sphere
57         // that is defined by this radius does no intersects the
58         // nodes sphere, then this tile is culled away.
59         // Computing this radius happens by two rectangular triangles:
60         // Let r be the view point. rmin is the minimum radius we find
61         // a ground surface we need to look above. rmax is the
62         // maximum object radius we expect any object.
63         //
64         //    d1   d2
65         //  x----x----x
66         //  r\  rmin /rmax
67         //    \  |  /
68         //     \ | /
69         //      \|/
70         //
71         // The distance from the eyepoint to the point
72         // where the line of sight is perpandicular to
73         // the radius vector with minimal height is
74         // d1 = sqrt(r^2 - rmin^2).
75         // The distance from the point where the line of sight
76         // is perpandicular to the radius vector with minimal height
77         // to the highest possible object on earth with radius rmax is 
78         // d2 = sqrt(rmax^2 - rmin^2).
79         // So the maximum distance we can see something on the earth
80         // from a viewpoint r is
81         // d = d1 + d2
82
83         // This is the equatorial earth radius minus 450m,
84         // little lower than Dead Sea.
85         float rmin = 6378137 - 450;
86         float rmin2 = rmin*rmin;
87         // This is the equatorial earth radius plus 9000m,
88         // little higher than Mount Everest.
89         float rmax = 6378137 + 9000;
90         float rmax2 = rmax*rmax;
91
92         // Check if we are looking from below any ground
93         osg::Vec3 viewPoint = nv->getViewPoint();
94         // blow the viewpoint up to a spherical earth with equatorial radius:
95         osg::Vec3 sphericViewPoint = viewPoint;
96         sphericViewPoint[2] *= 1.0033641;
97         float r2 = sphericViewPoint.length2();
98         if (r2 <= rmin2)
99             return;
100
101         // Due to this line of sight computation, the visible tiles
102         // are limited to be within a sphere with radius d1 + d2.
103         float d1 = sqrtf(r2 - rmin2);
104         float d2 = sqrtf(rmax2 - rmin2);
105         // Note that we again base the sphere around elliptic view point,
106         // but use the radius from the spherical computation.
107         if (!nodeBound.intersects(osg::BoundingSphere(viewPoint, d1 + d2)))
108             return;
109
110         traverse(node, nv);
111     }
112 };
113
114 struct ReaderWriterSPT::LocalOptions {
115     LocalOptions(const osgDB::Options* options) :
116         _options(options)
117     {
118         std::string pageLevelsString;
119         if (_options)
120             pageLevelsString = _options->getPluginStringData("SimGear::SPT_PAGE_LEVELS");
121
122         // Get the default if nothing given from outside
123         if (pageLevelsString.empty()) {
124             // We want an other level of indirection for paging
125             // Here we get about 12x12 deg tiles
126             _pageLevels.push_back(3);
127             // We want an other level of indirection for paging
128             // Here we get about 2x2 deg tiles
129             _pageLevels.push_back(5);
130             // We want an other level of indirection for paging
131             // Here we get about 0.5x0.5 deg tiles
132             _pageLevels.push_back(7);
133         } else {
134             // If configured from outside
135             std::stringstream ss(pageLevelsString);
136             while (ss.good()) {
137                 unsigned level = ~0u;
138                 ss >> level;
139                 _pageLevels.push_back(level);
140             }
141         }
142     }
143
144     bool isPageLevel(unsigned level) const
145     {
146         return std::find(_pageLevels.begin(), _pageLevels.end(), level) != _pageLevels.end();
147     }
148
149     std::string getLodPathForBucketBox(const BucketBox& bucketBox) const
150     {
151         std::stringstream ss;
152         ss << "LOD/";
153         for (std::vector<unsigned>::const_iterator i = _pageLevels.begin(); i != _pageLevels.end(); ++i) {
154             if (bucketBox.getStartLevel() <= *i)
155                 break;
156             ss << bucketBox.getParentBox(*i) << "/";
157         }
158         ss << bucketBox;
159         return ss.str();
160     }
161
162     const osgDB::Options* _options;
163     std::vector<unsigned> _pageLevels;
164 };
165
166 ReaderWriterSPT::ReaderWriterSPT()
167 {
168     supportsExtension("spt", "SimGear paged terrain meta database.");
169 }
170
171 ReaderWriterSPT::~ReaderWriterSPT()
172 {
173 }
174
175 const char*
176 ReaderWriterSPT::className() const
177 {
178     return "simgear::ReaderWriterSPT";
179 }
180
181 osgDB::ReaderWriter::ReadResult
182 ReaderWriterSPT::readObject(const std::string& fileName, const osgDB::Options* options) const
183 {
184     // We get called with different extensions. To make sure search continues,
185     // we need to return FILE_NOT_HANDLED in this case.
186     if (osgDB::getLowerCaseFileExtension(fileName) != "spt")
187         return ReadResult(ReadResult::FILE_NOT_HANDLED);
188     if (fileName != "state.spt")
189         return ReadResult(ReadResult::FILE_NOT_FOUND);
190
191     osg::StateSet* stateSet = new osg::StateSet;
192     stateSet->setAttributeAndModes(new osg::CullFace);
193
194     std::string imageFileName = options->getPluginStringData("SimGear::FG_WORLD_TEXTURE");
195     if (imageFileName.empty()) {
196         imageFileName = options->getPluginStringData("SimGear::FG_ROOT");
197         imageFileName = osgDB::concatPaths(imageFileName, "Textures");
198         imageFileName = osgDB::concatPaths(imageFileName, "Globe");
199         imageFileName = osgDB::concatPaths(imageFileName, "world.topo.bathy.200407.3x4096x2048.png");
200     }
201     if (osg::Image* image = osgDB::readImageFile(imageFileName, options)) {
202         osg::Texture2D* texture = new osg::Texture2D;
203         texture->setImage(image);
204         texture->setWrap(osg::Texture2D::WRAP_S, osg::Texture2D::REPEAT);
205         texture->setWrap(osg::Texture2D::WRAP_T, osg::Texture2D::CLAMP);
206         stateSet->setTextureAttributeAndModes(0, texture);
207     }
208
209     return stateSet;
210 }
211
212 osgDB::ReaderWriter::ReadResult
213 ReaderWriterSPT::readNode(const std::string& fileName, const osgDB::Options* options) const
214 {
215     LocalOptions localOptions(options);
216
217     // The file name without path and without the spt extension
218     std::string strippedFileName = osgDB::getStrippedName(fileName);
219     if (strippedFileName == "earth")
220         return ReadResult(createTree(BucketBox(-180, -90, 360, 180), localOptions, true));
221
222     std::stringstream ss(strippedFileName);
223     BucketBox bucketBox;
224     ss >> bucketBox;
225     if (ss.fail())
226         return ReadResult::FILE_NOT_FOUND;
227
228     BucketBox bucketBoxList[2];
229     unsigned bucketBoxListSize = bucketBox.periodicSplit(bucketBoxList);
230     if (bucketBoxListSize == 0)
231         return ReadResult::FILE_NOT_FOUND;
232
233     if (bucketBoxListSize == 1)
234         return ReadResult(createTree(bucketBoxList[0], localOptions, true));
235
236     assert(bucketBoxListSize == 2);
237     osg::ref_ptr<osg::Group> group = new osg::Group;
238     group->addChild(createTree(bucketBoxList[0], localOptions, true));
239     group->addChild(createTree(bucketBoxList[1], localOptions, true));
240     return ReadResult(group);
241 }
242
243 osg::ref_ptr<osg::Node>
244 ReaderWriterSPT::createTree(const BucketBox& bucketBox, const LocalOptions& options, bool topLevel) const
245 {
246     if (bucketBox.getIsBucketSize()) {
247         std::string fileName;
248         fileName = bucketBox.getBucket().gen_index_str() + std::string(".stg");
249         return osgDB::readRefNodeFile(fileName, options._options);
250     } else if (!topLevel && options.isPageLevel(bucketBox.getStartLevel())) {
251         return createPagedLOD(bucketBox, options);
252     } else {
253         BucketBox bucketBoxList[100];
254         unsigned numTiles = bucketBox.getSubDivision(bucketBoxList, 100);
255         if (numTiles == 0)
256             return 0;
257
258         if (numTiles == 1)
259             return createTree(bucketBoxList[0], options, false);
260
261         osg::ref_ptr<osg::Group> group = new osg::Group;
262         for (unsigned i = 0; i < numTiles; ++i) {
263             osg::ref_ptr<osg::Node> node = createTree(bucketBoxList[i], options, false);
264             if (!node.valid())
265                 continue;
266             group->addChild(node.get());
267         }
268         if (!group->getNumChildren())
269             return 0;
270
271         return group;
272     }
273 }
274
275 osg::ref_ptr<osg::Node>
276 ReaderWriterSPT::createPagedLOD(const BucketBox& bucketBox, const LocalOptions& options) const
277 {
278     osg::PagedLOD* pagedLOD = new osg::PagedLOD;
279
280     pagedLOD->setCenterMode(osg::PagedLOD::USER_DEFINED_CENTER);
281     SGSpheref sphere = bucketBox.getBoundingSphere();
282     pagedLOD->setCenter(toOsg(sphere.getCenter()));
283     pagedLOD->setRadius(sphere.getRadius());
284
285     pagedLOD->setCullCallback(new CullCallback);
286
287     osg::ref_ptr<osgDB::Options> localOptions;
288     localOptions = static_cast<osgDB::Options*>(options._options->clone(osg::CopyOp()));
289     // FIXME:
290     // The particle systems have nodes with culling disabled.
291     // PagedLOD nodes with childnodes like this will never expire.
292     // So, for now switch them off.
293     localOptions->setPluginStringData("SimGear::PARTICLESYSTEM", "OFF");
294     pagedLOD->setDatabaseOptions(localOptions.get());
295
296     // The break point for the low level of detail to the high level of detail
297     float range = 2*sphere.getRadius();
298
299     // Look for a low level of detail tile
300     std::string lodPath = options.getLodPathForBucketBox(bucketBox);
301     const char* extensions[] = { ".btg.gz", ".flt" };
302     for (unsigned i = 0; i < sizeof(extensions)/sizeof(extensions[0]); ++i) {
303         std::string fileName = osgDB::findDataFile(lodPath + extensions[i], options._options);
304         if (fileName.empty())
305             continue;
306         osg::ref_ptr<osg::Node> node = osgDB::readRefNodeFile(fileName, options._options);
307         if (!node.valid())
308             continue;
309         pagedLOD->addChild(node.get(), range, std::numeric_limits<float>::max());
310         break;
311     }
312     // Add the static sea level textured shell if there is nothing found
313     if (pagedLOD->getNumChildren() == 0) {
314         osg::ref_ptr<osg::Node> node = createSeaLevelTile(bucketBox, options._options);
315         if (node.valid())
316             pagedLOD->addChild(node.get(), range, std::numeric_limits<float>::max());
317     }
318
319     // Add the paged file name that creates the subtrees on demand
320     std::stringstream ss;
321     ss << bucketBox << ".spt";
322     pagedLOD->setFileName(pagedLOD->getNumChildren(), ss.str());
323     pagedLOD->setRange(pagedLOD->getNumChildren(), 0.0, range);
324
325     return pagedLOD;
326 }
327
328 osg::ref_ptr<osg::Node>
329 ReaderWriterSPT::createSeaLevelTile(const BucketBox& bucketBox, const LocalOptions& options) const
330 {
331     if (options._options->getPluginStringData("SimGear::FG_EARTH") != "ON")
332         return 0;
333
334     SGSpheref sphere = bucketBox.getBoundingSphere();
335     osg::Matrixd transform;
336     transform.makeTranslate(toOsg(-sphere.getCenter()));
337
338     osg::Vec3Array* vertices = new osg::Vec3Array;
339     osg::Vec3Array* normals = new osg::Vec3Array;
340     osg::Vec2Array* texCoords = new osg::Vec2Array;
341         
342     unsigned widthLevel = bucketBox.getWidthLevel();
343     unsigned heightLevel = bucketBox.getHeightLevel();
344
345     unsigned incx = bucketBox.getWidthIncrement(widthLevel + 2);
346     incx = std::min(incx, bucketBox.getSize(0));
347     for (unsigned i = 0; incx != 0;) {
348         unsigned incy = bucketBox.getHeightIncrement(heightLevel + 2);
349         incy = std::min(incy, bucketBox.getSize(1));
350         for (unsigned j = 0; incy != 0;) {
351             SGVec3f v[6], n[6];
352             SGVec2f t[6];
353             unsigned num = bucketBox.getTileTriangles(i, j, incx, incy, v, n, t);
354             for (unsigned k = 0; k < num; ++k) {
355                 vertices->push_back(transform.preMult(toOsg(v[k])));
356                 normals->push_back(toOsg(n[k]));
357                 texCoords->push_back(toOsg(t[k]));
358             }
359             j += incy;
360             incy = std::min(incy, bucketBox.getSize(1) - j);
361         }
362         i += incx;
363         incx = std::min(incx, bucketBox.getSize(0) - i);
364     }
365         
366     osg::Vec4Array* colors = new osg::Vec4Array;
367     colors->push_back(osg::Vec4(1, 1, 1, 1));
368         
369     osg::Geometry* geometry = new osg::Geometry;
370     geometry->setDataVariance(osg::Object::STATIC);
371     geometry->setUseVertexBufferObjects(true);
372     geometry->setVertexArray(vertices);
373     geometry->setNormalArray(normals);
374     geometry->setNormalBinding(osg::Geometry::BIND_PER_VERTEX);
375     geometry->setColorArray(colors);
376     geometry->setColorBinding(osg::Geometry::BIND_OVERALL);
377     geometry->setTexCoordArray(0, texCoords);
378         
379     osg::DrawArrays* drawArrays = new osg::DrawArrays(osg::DrawArrays::TRIANGLES, 0, vertices->size());
380     drawArrays->setDataVariance(osg::Object::STATIC);
381     geometry->addPrimitiveSet(drawArrays);
382         
383     osg::Geode* geode = new osg::Geode;
384     geode->setDataVariance(osg::Object::STATIC);
385     geode->addDrawable(geometry);
386     osg::ref_ptr<osg::StateSet> stateSet = getLowLODStateSet(options);
387     geode->setStateSet(stateSet.get());
388
389     transform.makeTranslate(toOsg(sphere.getCenter()));
390     osg::MatrixTransform* matrixTransform = new osg::MatrixTransform(transform);
391     matrixTransform->setDataVariance(osg::Object::STATIC);
392     matrixTransform->addChild(geode);
393
394     return matrixTransform;
395 }
396
397 osg::ref_ptr<osg::StateSet>
398 ReaderWriterSPT::getLowLODStateSet(const LocalOptions& options) const
399 {
400     osg::ref_ptr<osgDB::Options> localOptions;
401     localOptions = static_cast<osgDB::Options*>(options._options->clone(osg::CopyOp()));
402     localOptions->setObjectCacheHint(osgDB::Options::CACHE_ALL);
403
404     osg::ref_ptr<osg::Object> object = osgDB::readRefObjectFile("state.spt", localOptions.get());
405     if (!dynamic_cast<osg::StateSet*>(object.get()))
406         return 0;
407
408     return static_cast<osg::StateSet*>(object.get());
409 }
410
411 } // namespace simgear
412