1 // ModelRegistry.hxx -- interface to the OSG model registry
3 // Copyright (C) 2005-2007 Mathias Froehlich
4 // Copyright (C) 2007 Tim Moore <timoore@redhat.com>
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License as
8 // published by the Free Software Foundation; either version 2 of the
9 // License, or (at your option) any later version.
11 // This program is distributed in the hope that it will be useful, but
12 // WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software
18 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 # include <simgear_config.h>
24 #include "ModelRegistry.hxx"
30 #include <OpenThreads/ScopedLock>
32 #include <osg/ref_ptr>
34 #include <osg/NodeCallback>
36 #include <osg/Material>
37 #include <osg/MatrixTransform>
38 #include <osgDB/Archive>
39 #include <osgDB/FileNameUtils>
40 #include <osgDB/FileUtils>
41 #include <osgDB/ReadFile>
42 #include <osgDB/WriteFile>
43 #include <osgDB/Registry>
44 #include <osgDB/SharedStateManager>
45 #include <osgUtil/Optimizer>
47 #include <simgear/scene/util/SGSceneFeatures.hxx>
48 #include <simgear/scene/util/SGStateAttributeVisitor.hxx>
49 #include <simgear/scene/util/SGTextureStateAttributeVisitor.hxx>
50 #include <simgear/scene/util/SGReaderWriterOptions.hxx>
51 #include <simgear/scene/util/NodeAndDrawableVisitor.hxx>
53 #include <simgear/structure/exception.hxx>
54 #include <simgear/props/props.hxx>
55 #include <simgear/props/props_io.hxx>
56 #include <simgear/props/condition.hxx>
58 #include "BoundingVolumeBuildVisitor.hxx"
63 using namespace osgUtil;
64 using namespace osgDB;
65 using namespace simgear;
68 // Set the name of a Texture to the simple name of its image
69 // file. This can be used to do livery substitution after the image
70 // has been deallocated.
71 class TextureNameVisitor : public NodeAndDrawableVisitor {
73 TextureNameVisitor(NodeVisitor::TraversalMode tm = NodeVisitor::TRAVERSE_ALL_CHILDREN) :
74 NodeAndDrawableVisitor(tm)
78 virtual void apply(Node& node)
80 nameTextures(node.getStateSet());
84 virtual void apply(Drawable& drawable)
86 nameTextures(drawable.getStateSet());
89 void nameTextures(StateSet* stateSet)
93 int numUnits = stateSet->getTextureAttributeList().size();
94 for (int i = 0; i < numUnits; ++i) {
96 = stateSet->getTextureAttribute(i, StateAttribute::TEXTURE);
97 Texture2D* texture = dynamic_cast<Texture2D*>(attr);
98 if (!texture || !texture->getName().empty())
100 const Image *image = texture->getImage();
103 texture->setName(image->getFileName());
109 class SGTexCompressionVisitor : public SGTextureStateAttributeVisitor {
111 virtual void apply(int, StateSet::RefAttributePair& refAttr)
114 texture = dynamic_cast<Texture2D*>(refAttr.first.get());
118 // Do not touch dynamically generated textures.
119 if (texture->getReadPBuffer())
121 if (texture->getDataVariance() == osg::Object::DYNAMIC)
124 // If no image attached, we assume this one is dynamically generated
125 Image* image = texture->getImage(0);
132 if (s <= t && 32 <= s) {
133 SGSceneFeatures::instance()->setTextureCompression(texture);
134 } else if (t < s && 32 <= t) {
135 SGSceneFeatures::instance()->setTextureCompression(texture);
140 class SGTexDataVarianceVisitor : public SGTextureStateAttributeVisitor {
142 virtual void apply(int, StateSet::RefAttributePair& refAttr)
145 texture = dynamic_cast<Texture*>(refAttr.first.get());
149 // Cannot be static if this is a render to texture thing
150 if (texture->getReadPBuffer())
152 if (texture->getDataVariance() == osg::Object::DYNAMIC)
154 // If no image attached, we assume this one is dynamically generated
155 Image* image = texture->getImage(0);
159 texture->setDataVariance(Object::STATIC);
162 virtual void apply(StateSet* stateSet)
166 stateSet->setDataVariance(Object::STATIC);
167 SGTextureStateAttributeVisitor::apply(stateSet);
173 Node* DefaultProcessPolicy::process(Node* node, const string& filename,
176 TextureNameVisitor nameVisitor;
177 node->accept(nameVisitor);
181 ReaderWriter::ReadResult
182 ModelRegistry::readImage(const string& fileName,
185 CallbackMap::iterator iter
186 = imageCallbackMap.find(getFileExtension(fileName));
188 if (iter != imageCallbackMap.end() && iter->second.valid())
189 return iter->second->readImage(fileName, opt);
190 string absFileName = SGModelLib::findDataFile(fileName, opt);
191 if (!fileExists(absFileName)) {
192 SG_LOG(SG_IO, SG_ALERT, "Cannot find image file \""
193 << fileName << "\"");
194 return ReaderWriter::ReadResult::FILE_NOT_FOUND;
197 Registry* registry = Registry::instance();
198 ReaderWriter::ReadResult res;
199 res = registry->readImageImplementation(absFileName, opt);
200 if (!res.success()) {
201 SG_LOG(SG_IO, SG_WARN, "Image loading failed:" << res.message());
205 if (res.loadedFromCache())
206 SG_LOG(SG_IO, SG_BULK, "Returning cached image \""
207 << res.getImage()->getFileName() << "\"");
209 SG_LOG(SG_IO, SG_BULK, "Reading image \""
210 << res.getImage()->getFileName() << "\"");
212 // Check for precompressed textures that depend on an extension
213 switch (res.getImage()->getPixelFormat()) {
215 // GL_EXT_texture_compression_s3tc
216 // patented, no way to decompress these
217 #ifndef GL_EXT_texture_compression_s3tc
218 #define GL_COMPRESSED_RGB_S3TC_DXT1_EXT 0x83F0
219 #define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1
220 #define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2
221 #define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3
223 case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
224 case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
225 case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT:
226 case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT:
228 // GL_EXT_texture_sRGB
229 // patented, no way to decompress these
230 #ifndef GL_EXT_texture_sRGB
231 #define GL_COMPRESSED_SRGB_S3TC_DXT1_EXT 0x8C4C
232 #define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT 0x8C4D
233 #define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT 0x8C4E
234 #define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT 0x8C4F
236 case GL_COMPRESSED_SRGB_S3TC_DXT1_EXT:
237 case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:
238 case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT:
239 case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:
241 // GL_TDFX_texture_compression_FXT1
242 // can decompress these in software but
243 // no code present in simgear.
244 #ifndef GL_3DFX_texture_compression_FXT1
245 #define GL_COMPRESSED_RGB_FXT1_3DFX 0x86B0
246 #define GL_COMPRESSED_RGBA_FXT1_3DFX 0x86B1
248 case GL_COMPRESSED_RGB_FXT1_3DFX:
249 case GL_COMPRESSED_RGBA_FXT1_3DFX:
251 // GL_EXT_texture_compression_rgtc
252 // can decompress these in software but
253 // no code present in simgear.
254 #ifndef GL_EXT_texture_compression_rgtc
255 #define GL_COMPRESSED_RED_RGTC1_EXT 0x8DBB
256 #define GL_COMPRESSED_SIGNED_RED_RGTC1_EXT 0x8DBC
257 #define GL_COMPRESSED_RED_GREEN_RGTC2_EXT 0x8DBD
258 #define GL_COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT 0x8DBE
260 case GL_COMPRESSED_RED_RGTC1_EXT:
261 case GL_COMPRESSED_SIGNED_RED_RGTC1_EXT:
262 case GL_COMPRESSED_RED_GREEN_RGTC2_EXT:
263 case GL_COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT:
265 SG_LOG(SG_IO, SG_ALERT, "Image \"" << fileName << "\"\n"
266 "uses compressed textures which cannot be supported on "
268 "Please decompress this texture for improved portability.");
280 osg::Node* DefaultCachePolicy::find(const string& fileName,
283 Registry* registry = Registry::instance();
285 = dynamic_cast<Node*>(registry->getFromObjectCache(fileName));
287 SG_LOG(SG_IO, SG_BULK, "Got cached model \""
288 << fileName << "\"");
290 SG_LOG(SG_IO, SG_BULK, "Reading model \""
291 << fileName << "\"");
295 void DefaultCachePolicy::addToCache(const string& fileName,
298 Registry::instance()->addEntryToObjectCache(fileName, node);
301 // Optimizations we don't use:
302 // Don't use this one. It will break animation names ...
303 // opts |= osgUtil::Optimizer::REMOVE_REDUNDANT_NODES;
305 // opts |= osgUtil::Optimizer::REMOVE_LOADED_PROXY_NODES;
306 // opts |= osgUtil::Optimizer::COMBINE_ADJACENT_LODS;
307 // opts |= osgUtil::Optimizer::CHECK_GEOMETRY;
308 // opts |= osgUtil::Optimizer::SPATIALIZE_GROUPS;
309 // opts |= osgUtil::Optimizer::COPY_SHARED_NODES;
310 // opts |= osgUtil::Optimizer::TESSELATE_GEOMETRY;
311 // opts |= osgUtil::Optimizer::OPTIMIZE_TEXTURE_SETTINGS;
313 OptimizeModelPolicy::OptimizeModelPolicy(const string& extension) :
314 _osgOptions(Optimizer::SHARE_DUPLICATE_STATE
315 | Optimizer::MERGE_GEOMETRY
316 | Optimizer::FLATTEN_STATIC_TRANSFORMS
317 | Optimizer::TRISTRIP_GEOMETRY)
321 osg::Node* OptimizeModelPolicy::optimize(osg::Node* node,
322 const string& fileName,
323 const osgDB::Options* opt)
325 osgUtil::Optimizer optimizer;
326 optimizer.optimize(node, _osgOptions);
328 // Make sure the data variance of sharable objects is set to
329 // STATIC so that textures will be globally shared.
330 SGTexDataVarianceVisitor dataVarianceVisitor;
331 node->accept(dataVarianceVisitor);
333 SGTexCompressionVisitor texComp;
334 node->accept(texComp);
338 string OSGSubstitutePolicy::substitute(const string& name,
341 string fileSansExtension = getNameLessExtension(name);
342 string osgFileName = fileSansExtension + ".osg";
343 string absFileName = SGModelLib::findDataFile(osgFileName, opt);
349 BuildLeafBVHPolicy::buildBVH(const std::string& fileName, osg::Node* node)
351 SG_LOG(SG_IO, SG_BULK, "Building leaf attached boundingvolume tree for \""
352 << fileName << "\".");
353 BoundingVolumeBuildVisitor bvBuilder(true);
354 node->accept(bvBuilder);
358 BuildGroupBVHPolicy::buildBVH(const std::string& fileName, osg::Node* node)
360 SG_LOG(SG_IO, SG_BULK, "Building group attached boundingvolume tree for \""
361 << fileName << "\".");
362 BoundingVolumeBuildVisitor bvBuilder(false);
363 node->accept(bvBuilder);
367 NoBuildBVHPolicy::buildBVH(const std::string& fileName, osg::Node*)
369 SG_LOG(SG_IO, SG_BULK, "Omitting boundingvolume tree for \""
370 << fileName << "\".");
373 ModelRegistry::ModelRegistry() :
374 _defaultCallback(new DefaultCallback(""))
379 ModelRegistry::addImageCallbackForExtension(const string& extension,
380 Registry::ReadFileCallback* callback)
382 imageCallbackMap.insert(CallbackMap::value_type(extension, callback));
386 ModelRegistry::addNodeCallbackForExtension(const string& extension,
387 Registry::ReadFileCallback* callback)
389 nodeCallbackMap.insert(CallbackMap::value_type(extension, callback));
392 ReaderWriter::ReadResult
393 ModelRegistry::readNode(const string& fileName,
396 ReaderWriter::ReadResult res;
397 CallbackMap::iterator iter
398 = nodeCallbackMap.find(getFileExtension(fileName));
399 ReaderWriter::ReadResult result;
400 if (iter != nodeCallbackMap.end() && iter->second.valid())
401 result = iter->second->readNode(fileName, opt);
403 result = _defaultCallback->readNode(fileName, opt);
408 class SGReadCallbackInstaller {
410 SGReadCallbackInstaller()
412 // XXX I understand why we want this, but this seems like a weird
413 // place to set this option.
414 Referenced::setThreadSafeReferenceCounting(true);
416 Registry* registry = Registry::instance();
417 Options* options = new Options;
418 int cacheOptions = Options::CACHE_ALL;
420 setObjectCacheHint((Options::CacheHintOptions)cacheOptions);
421 registry->setOptions(options);
422 registry->getOrCreateSharedStateManager()->
423 setShareMode(SharedStateManager::SHARE_STATESETS);
424 registry->setReadFileCallback(ModelRegistry::instance());
428 static SGReadCallbackInstaller readCallbackInstaller;
430 // we get optimal geometry from the loader (Hah!).
431 struct ACOptimizePolicy : public OptimizeModelPolicy {
432 ACOptimizePolicy(const string& extension) :
433 OptimizeModelPolicy(extension)
435 _osgOptions &= ~Optimizer::TRISTRIP_GEOMETRY;
437 Node* optimize(Node* node, const string& fileName,
440 ref_ptr<Node> optimized
441 = OptimizeModelPolicy::optimize(node, fileName, opt);
442 Group* group = dynamic_cast<Group*>(optimized.get());
443 MatrixTransform* transform
444 = dynamic_cast<MatrixTransform*>(optimized.get());
445 if (((transform && transform->getMatrix().isIdentity()) || group)
446 && group->getName().empty()
447 && group->getNumChildren() == 1) {
448 optimized = static_cast<Node*>(group->getChild(0));
449 group = dynamic_cast<Group*>(optimized.get());
450 if (group && group->getName().empty()
451 && group->getNumChildren() == 1)
452 optimized = static_cast<Node*>(group->getChild(0));
454 const SGReaderWriterOptions* sgopt
455 = dynamic_cast<const SGReaderWriterOptions*>(opt);
456 if (sgopt && sgopt->getInstantiateEffects())
457 optimized = instantiateEffects(optimized.get(), sgopt);
458 return optimized.release();
462 struct ACProcessPolicy {
463 ACProcessPolicy(const string& extension) {}
464 Node* process(Node* node, const string& filename,
471 // XXX Does there need to be a Group node here to trick the
472 // optimizer into optimizing the static transform?
473 osg::Group* root = new Group;
474 MatrixTransform* transform = new MatrixTransform;
475 root->addChild(transform);
477 transform->setDataVariance(Object::STATIC);
478 transform->setMatrix(m);
479 transform->addChild(node);
485 typedef ModelRegistryCallback<ACProcessPolicy, DefaultCachePolicy,
487 OSGSubstitutePolicy, BuildLeafBVHPolicy>
492 ModelRegistryCallbackProxy<ACCallback> g_acRegister("ac");