1 // ReaderWriterSPT.cxx -- Provide a paged database for flightgear scenery.
3 // Copyright (C) 2010 - 2013 Mathias Froehlich
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.
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.
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.
21 # include <simgear_config.h>
24 #include "ReaderWriterSPT.hxx"
28 #include <osg/CullFace>
29 #include <osg/PagedLOD>
30 #include <osg/MatrixTransform>
31 #include <osg/Texture2D>
33 #include <osgDB/FileNameUtils>
34 #include <osgDB/FileUtils>
35 #include <osgDB/ReadFile>
37 #include <simgear/scene/util/OsgMath.hxx>
39 #include "BucketBox.hxx"
43 // Cull away tiles that we watch from downside
44 struct ReaderWriterSPT::CullCallback : public osg::NodeCallback {
45 virtual ~CullCallback()
47 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
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())
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.
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
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;
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();
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)))
114 struct ReaderWriterSPT::LocalOptions {
115 LocalOptions(const osgDB::Options* options) :
118 std::string pageLevelsString;
120 pageLevelsString = _options->getPluginStringData("SimGear::SPT_PAGE_LEVELS");
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);
134 // If configured from outside
135 std::stringstream ss(pageLevelsString);
137 unsigned level = ~0u;
139 _pageLevels.push_back(level);
144 bool isPageLevel(unsigned level) const
146 return std::find(_pageLevels.begin(), _pageLevels.end(), level) != _pageLevels.end();
149 std::string getLodPathForBucketBox(const BucketBox& bucketBox) const
151 std::stringstream ss;
153 for (std::vector<unsigned>::const_iterator i = _pageLevels.begin(); i != _pageLevels.end(); ++i) {
154 if (bucketBox.getStartLevel() <= *i)
156 ss << bucketBox.getParentBox(*i) << "/";
162 const osgDB::Options* _options;
163 std::vector<unsigned> _pageLevels;
166 ReaderWriterSPT::ReaderWriterSPT()
168 supportsExtension("spt", "SimGear paged terrain meta database.");
171 ReaderWriterSPT::~ReaderWriterSPT()
176 ReaderWriterSPT::className() const
178 return "simgear::ReaderWriterSPT";
181 osgDB::ReaderWriter::ReadResult
182 ReaderWriterSPT::readObject(const std::string& fileName, const osgDB::Options* options) const
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);
191 osg::StateSet* stateSet = new osg::StateSet;
192 stateSet->setAttributeAndModes(new osg::CullFace);
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");
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);
212 osgDB::ReaderWriter::ReadResult
213 ReaderWriterSPT::readNode(const std::string& fileName, const osgDB::Options* options) const
215 LocalOptions localOptions(options);
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));
222 std::stringstream ss(strippedFileName);
226 return ReadResult::FILE_NOT_FOUND;
228 BucketBox bucketBoxList[2];
229 unsigned bucketBoxListSize = bucketBox.periodicSplit(bucketBoxList);
230 if (bucketBoxListSize == 0)
231 return ReadResult::FILE_NOT_FOUND;
233 if (bucketBoxListSize == 1)
234 return ReadResult(createTree(bucketBoxList[0], localOptions, true));
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);
243 osg::ref_ptr<osg::Node>
244 ReaderWriterSPT::createTree(const BucketBox& bucketBox, const LocalOptions& options, bool topLevel) const
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);
253 BucketBox bucketBoxList[100];
254 unsigned numTiles = bucketBox.getSubDivision(bucketBoxList, 100);
259 return createTree(bucketBoxList[0], options, false);
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);
266 group->addChild(node.get());
268 if (!group->getNumChildren())
275 osg::ref_ptr<osg::Node>
276 ReaderWriterSPT::createPagedLOD(const BucketBox& bucketBox, const LocalOptions& options) const
278 osg::PagedLOD* pagedLOD = new osg::PagedLOD;
280 pagedLOD->setCenterMode(osg::PagedLOD::USER_DEFINED_CENTER);
281 SGSpheref sphere = bucketBox.getBoundingSphere();
282 pagedLOD->setCenter(toOsg(sphere.getCenter()));
283 pagedLOD->setRadius(sphere.getRadius());
285 pagedLOD->setCullCallback(new CullCallback);
287 osg::ref_ptr<osgDB::Options> localOptions;
288 localOptions = static_cast<osgDB::Options*>(options._options->clone(osg::CopyOp()));
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());
296 // The break point for the low level of detail to the high level of detail
297 float range = 2*sphere.getRadius();
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())
306 osg::ref_ptr<osg::Node> node = osgDB::readRefNodeFile(fileName, options._options);
309 pagedLOD->addChild(node.get(), range, std::numeric_limits<float>::max());
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);
316 pagedLOD->addChild(node.get(), range, std::numeric_limits<float>::max());
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);
328 osg::ref_ptr<osg::Node>
329 ReaderWriterSPT::createSeaLevelTile(const BucketBox& bucketBox, const LocalOptions& options) const
331 if (options._options->getPluginStringData("SimGear::FG_EARTH") != "ON")
334 SGSpheref sphere = bucketBox.getBoundingSphere();
335 osg::Matrixd transform;
336 transform.makeTranslate(toOsg(-sphere.getCenter()));
338 osg::Vec3Array* vertices = new osg::Vec3Array;
339 osg::Vec3Array* normals = new osg::Vec3Array;
340 osg::Vec2Array* texCoords = new osg::Vec2Array;
342 unsigned widthLevel = bucketBox.getWidthLevel();
343 unsigned heightLevel = bucketBox.getHeightLevel();
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;) {
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]));
360 incy = std::min(incy, bucketBox.getSize(1) - j);
363 incx = std::min(incx, bucketBox.getSize(0) - i);
366 osg::Vec4Array* colors = new osg::Vec4Array;
367 colors->push_back(osg::Vec4(1, 1, 1, 1));
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);
379 osg::DrawArrays* drawArrays = new osg::DrawArrays(osg::DrawArrays::TRIANGLES, 0, vertices->size());
380 drawArrays->setDataVariance(osg::Object::STATIC);
381 geometry->addPrimitiveSet(drawArrays);
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());
389 transform.makeTranslate(toOsg(sphere.getCenter()));
390 osg::MatrixTransform* matrixTransform = new osg::MatrixTransform(transform);
391 matrixTransform->setDataVariance(osg::Object::STATIC);
392 matrixTransform->addChild(geode);
394 return matrixTransform;
397 osg::ref_ptr<osg::StateSet>
398 ReaderWriterSPT::getLowLODStateSet(const LocalOptions& options) const
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);
404 osg::ref_ptr<osg::Object> object = osgDB::readRefObjectFile("state.spt", localOptions.get());
405 if (!dynamic_cast<osg::StateSet*>(object.get()))
408 return static_cast<osg::StateSet*>(object.get());
411 } // namespace simgear