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.
19 #include "ModelRegistry.hxx"
25 #include <OpenThreads/ScopedLock>
27 #include <osg/observer_ptr>
28 #include <osg/ref_ptr>
30 #include <osg/NodeCallback>
32 #include <osg/Material>
33 #include <osg/MatrixTransform>
34 #include <osgDB/Archive>
35 #include <osgDB/FileNameUtils>
36 #include <osgDB/FileUtils>
37 #include <osgDB/ReadFile>
38 #include <osgDB/WriteFile>
39 #include <osgDB/Registry>
40 #include <osgDB/SharedStateManager>
41 #include <osgUtil/Optimizer>
43 #include <simgear/scene/util/SGSceneFeatures.hxx>
44 #include <simgear/scene/util/SGStateAttributeVisitor.hxx>
45 #include <simgear/scene/util/SGTextureStateAttributeVisitor.hxx>
46 #include <simgear/scene/util/NodeAndDrawableVisitor.hxx>
48 #include <simgear/structure/exception.hxx>
49 #include <simgear/props/props.hxx>
50 #include <simgear/props/props_io.hxx>
51 #include <simgear/props/condition.hxx>
55 using namespace osgUtil;
56 using namespace osgDB;
57 using namespace simgear;
59 // Little helper class that holds an extra reference to a
61 // Since we clone all structural nodes from our 3d models,
62 // the database pager will only see one single reference to
63 // top node of the model and expire it relatively fast.
64 // We attach that extra reference to every model cloned from
65 // a base model in the pager. When that cloned model is deleted
66 // this extra reference is deleted too. So if there are no
67 // cloned models left the model will expire.
69 class SGDatabaseReference : public Observer {
71 SGDatabaseReference(Referenced* referenced) :
72 mReferenced(referenced)
74 virtual void objectDeleted(void*)
79 ref_ptr<Referenced> mReferenced;
82 // Set the name of a Texture to the simple name of its image
83 // file. This can be used to do livery substitution after the image
84 // has been deallocated.
85 class TextureNameVisitor : public NodeAndDrawableVisitor {
87 TextureNameVisitor(NodeVisitor::TraversalMode tm = NodeVisitor::TRAVERSE_ALL_CHILDREN) :
88 NodeAndDrawableVisitor(tm)
92 virtual void apply(Node& node)
94 nameTextures(node.getStateSet());
98 virtual void apply(Drawable& drawable)
100 nameTextures(drawable.getStateSet());
103 void nameTextures(StateSet* stateSet)
107 int numUnits = stateSet->getTextureAttributeList().size();
108 for (int i = 0; i < numUnits; ++i) {
110 = stateSet->getTextureAttribute(i, StateAttribute::TEXTURE);
111 Texture2D* texture = dynamic_cast<Texture2D*>(attr);
112 if (!texture || !texture->getName().empty())
114 const Image *image = texture->getImage();
117 texture->setName(image->getFileName());
122 // Change the StateSets of a model to hold different textures based on
125 class TextureUpdateVisitor : public NodeAndDrawableVisitor {
127 TextureUpdateVisitor(const FilePathList& pathList) :
128 NodeAndDrawableVisitor(NodeVisitor::TRAVERSE_ALL_CHILDREN),
133 virtual void apply(Node& node)
135 StateSet* stateSet = cloneStateSet(node.getStateSet());
137 node.setStateSet(stateSet);
141 virtual void apply(Drawable& drawable)
143 StateSet* stateSet = cloneStateSet(drawable.getStateSet());
145 drawable.setStateSet(stateSet);
147 // Copied from Mathias' earlier SGTextureUpdateVisitor
149 Texture2D* textureReplace(int unit, const StateAttribute* attr)
151 const Texture2D* texture = dynamic_cast<const Texture2D*>(attr);
156 const Image* image = texture->getImage();
157 const string* fullFilePath = 0;
159 // The currently loaded file name
160 fullFilePath = &image->getFileName();
163 fullFilePath = &texture->getName();
166 string fileName = getSimpleFileName(*fullFilePath);
167 if (fileName.empty())
169 // The name that should be found with the current database path
170 string fullLiveryFile = findFileInPath(fileName, _pathList);
171 // If it is empty or they are identical then there is nothing to do
172 if (fullLiveryFile.empty() || fullLiveryFile == *fullFilePath)
174 Image* newImage = readImageFile(fullLiveryFile);
177 CopyOp copyOp(CopyOp::DEEP_COPY_ALL & ~CopyOp::DEEP_COPY_IMAGES);
178 Texture2D* newTexture = static_cast<Texture2D*>(copyOp(texture));
182 newTexture->setImage(newImage);
187 StateSet* cloneStateSet(const StateSet* stateSet)
189 typedef pair<int, Texture2D*> Tex2D;
190 vector<Tex2D> newTextures;
191 StateSet* result = 0;
195 int numUnits = stateSet->getTextureAttributeList().size();
197 for (int i = 0; i < numUnits; ++i) {
198 const StateAttribute* attr
199 = stateSet->getTextureAttribute(i, StateAttribute::TEXTURE);
200 Texture2D* newTexture = textureReplace(i, attr);
202 newTextures.push_back(Tex2D(i, newTexture));
204 if (!newTextures.empty()) {
205 result = static_cast<StateSet*>(stateSet->clone(CopyOp()));
206 for (vector<Tex2D>::iterator i = newTextures.begin();
207 i != newTextures.end();
209 result->setTextureAttribute(i->first, i->second);
216 FilePathList _pathList;
220 class SGTexCompressionVisitor : public SGTextureStateAttributeVisitor {
222 virtual void apply(int, StateSet::RefAttributePair& refAttr)
225 texture = dynamic_cast<Texture2D*>(refAttr.first.get());
230 texture->setDataVariance(osg::Object::STATIC);
232 Image* image = texture->getImage(0);
239 if (s <= t && 32 <= s) {
240 SGSceneFeatures::instance()->setTextureCompression(texture);
241 } else if (t < s && 32 <= t) {
242 SGSceneFeatures::instance()->setTextureCompression(texture);
247 class SGTexDataVarianceVisitor : public SGTextureStateAttributeVisitor {
249 virtual void apply(int, StateSet::RefAttributePair& refAttr)
252 texture = dynamic_cast<Texture*>(refAttr.first.get());
256 texture->setDataVariance(Object::STATIC);
259 virtual void apply(StateSet* stateSet)
263 SGTextureStateAttributeVisitor::apply(stateSet);
264 stateSet->setDataVariance(Object::STATIC);
268 class SGAcMaterialCrippleVisitor : public SGStateAttributeVisitor {
270 virtual void apply(StateSet::RefAttributePair& refAttr)
273 material = dynamic_cast<Material*>(refAttr.first.get());
276 material->setColorMode(Material::AMBIENT_AND_DIFFUSE);
280 // Work around an OSG bug - the file loaders don't use the file path
281 // in options while the file is being loaded.
283 struct OptionsPusher {
284 FilePathList localPathList;
286 OptionsPusher(const ReaderWriter::Options* options):
291 Registry* registry = Registry::instance();
292 localPathList = registry->getDataFilePathList();
293 const FilePathList& regPathList = registry->getDataFilePathList();
294 const FilePathList& optionsPathList = options->getDatabasePathList();
295 for (FilePathList::const_iterator iter = optionsPathList.begin();
296 iter != optionsPathList.end();
298 if (find(regPathList.begin(), regPathList.end(), *iter)
299 == regPathList.end())
300 localPathList.push_back(*iter);
302 // Save the current Registry path list and install the augmented one.
303 localPathList.swap(registry->getDataFilePathList());
308 // Restore the old path list
310 localPathList.swap(Registry::instance()->getDataFilePathList());
315 Node* DefaultProcessPolicy::process(Node* node, const string& filename,
316 const ReaderWriter::Options* opt)
318 TextureNameVisitor nameVisitor;
319 node->accept(nameVisitor);
323 ReaderWriter::ReadResult
324 ModelRegistry::readImage(const string& fileName,
325 const ReaderWriter::Options* opt)
327 OpenThreads::ScopedLock<OpenThreads::ReentrantMutex> lock(readerMutex);
328 CallbackMap::iterator iter
329 = imageCallbackMap.find(getFileExtension(fileName));
330 // XXX Workaround for OSG plugin bug
332 OptionsPusher pusher(opt);
333 if (iter != imageCallbackMap.end() && iter->second.valid())
334 return iter->second->readImage(fileName, opt);
335 string absFileName = findDataFile(fileName);
336 if (!fileExists(absFileName)) {
337 SG_LOG(SG_IO, SG_ALERT, "Cannot find image file \""
338 << fileName << "\"");
339 return ReaderWriter::ReadResult::FILE_NOT_FOUND;
342 Registry* registry = Registry::instance();
343 ReaderWriter::ReadResult res;
344 res = registry->readImageImplementation(absFileName, opt);
345 if (res.loadedFromCache())
346 SG_LOG(SG_IO, SG_INFO, "Returning cached image \""
347 << res.getImage()->getFileName() << "\"");
349 SG_LOG(SG_IO, SG_INFO, "Reading image \""
350 << res.getImage()->getFileName() << "\"");
357 osg::Node* DefaultCachePolicy::find(const string& fileName,
358 const ReaderWriter::Options* opt)
360 Registry* registry = Registry::instance();
362 = dynamic_cast<Node*>(registry->getFromObjectCache(fileName));
364 SG_LOG(SG_IO, SG_INFO, "Got cached model \""
365 << fileName << "\"");
367 SG_LOG(SG_IO, SG_INFO, "Reading model \""
368 << fileName << "\"");
372 void DefaultCachePolicy::addToCache(const string& fileName,
375 Registry::instance()->addEntryToObjectCache(fileName, node);
378 // Optimizations we don't use:
379 // Don't use this one. It will break animation names ...
380 // opts |= osgUtil::Optimizer::REMOVE_REDUNDANT_NODES;
382 // opts |= osgUtil::Optimizer::REMOVE_LOADED_PROXY_NODES;
383 // opts |= osgUtil::Optimizer::COMBINE_ADJACENT_LODS;
384 // opts |= osgUtil::Optimizer::CHECK_GEOMETRY;
385 // opts |= osgUtil::Optimizer::SPATIALIZE_GROUPS;
386 // opts |= osgUtil::Optimizer::COPY_SHARED_NODES;
387 // opts |= osgUtil::Optimizer::TESSELATE_GEOMETRY;
388 // opts |= osgUtil::Optimizer::OPTIMIZE_TEXTURE_SETTINGS;
390 OptimizeModelPolicy::OptimizeModelPolicy(const string& extension) :
391 _osgOptions(Optimizer::SHARE_DUPLICATE_STATE
392 | Optimizer::MERGE_GEOMETRY
393 | Optimizer::FLATTEN_STATIC_TRANSFORMS
394 | Optimizer::TRISTRIP_GEOMETRY)
398 osg::Node* OptimizeModelPolicy::optimize(osg::Node* node,
399 const string& fileName,
400 const osgDB::ReaderWriter::Options* opt)
402 osgUtil::Optimizer optimizer;
403 optimizer.optimize(node, _osgOptions);
405 // Make sure the data variance of sharable objects is set to
406 // STATIC so that textures will be globally shared.
407 SGTexDataVarianceVisitor dataVarianceVisitor;
408 node->accept(dataVarianceVisitor);
410 SGTexCompressionVisitor texComp;
411 node->accept(texComp);
415 osg::Node* DefaultCopyPolicy::copy(osg::Node* model, const string& fileName,
416 const osgDB::ReaderWriter::Options* opt)
418 // Add an extra reference to the model stored in the database.
419 // That it to avoid expiring the object from the cache even if it is still
420 // in use. Note that the object cache will think that a model is unused
421 // if the reference count is 1. If we clone all structural nodes here
422 // we need that extra reference to the original object
423 SGDatabaseReference* databaseReference;
424 databaseReference = new SGDatabaseReference(model);
425 CopyOp::CopyFlags flags = CopyOp::DEEP_COPY_ALL;
426 flags &= ~CopyOp::DEEP_COPY_TEXTURES;
427 flags &= ~CopyOp::DEEP_COPY_IMAGES;
428 flags &= ~CopyOp::DEEP_COPY_STATESETS;
429 flags &= ~CopyOp::DEEP_COPY_STATEATTRIBUTES;
430 flags &= ~CopyOp::DEEP_COPY_ARRAYS;
431 flags &= ~CopyOp::DEEP_COPY_PRIMITIVES;
432 // This will safe display lists ...
433 flags &= ~CopyOp::DEEP_COPY_DRAWABLES;
434 flags &= ~CopyOp::DEEP_COPY_SHAPES;
435 osg::Node* res = CopyOp(flags)(model);
436 res->addObserver(databaseReference);
439 TextureUpdateVisitor liveryUpdate(opt->getDatabasePathList());
440 res->accept(liveryUpdate);
445 string OSGSubstitutePolicy::substitute(const string& name,
446 const ReaderWriter::Options* opt)
448 string fileSansExtension = getNameLessExtension(name);
449 string osgFileName = fileSansExtension + ".osg";
450 string absFileName = findDataFile(osgFileName, opt);
454 ModelRegistry::ModelRegistry() :
455 _defaultCallback(new DefaultCallback(""))
460 ModelRegistry::addImageCallbackForExtension(const string& extension,
461 Registry::ReadFileCallback* callback)
463 imageCallbackMap.insert(CallbackMap::value_type(extension, callback));
467 ModelRegistry::addNodeCallbackForExtension(const string& extension,
468 Registry::ReadFileCallback* callback)
470 nodeCallbackMap.insert(CallbackMap::value_type(extension, callback));
473 ref_ptr<ModelRegistry> ModelRegistry::instance;
475 ModelRegistry* ModelRegistry::getInstance()
478 if (!instance.valid())
479 instance = new ModelRegistry;
480 return instance.get();
483 ReaderWriter::ReadResult
484 ModelRegistry::readNode(const string& fileName,
485 const ReaderWriter::Options* opt)
487 OpenThreads::ScopedLock<OpenThreads::ReentrantMutex> lock(readerMutex);
488 // XXX Workaround for OSG plugin bug.
489 OptionsPusher pusher(opt);
490 Registry* registry = Registry::instance();
491 ReaderWriter::ReadResult res;
493 CallbackMap::iterator iter
494 = nodeCallbackMap.find(getFileExtension(fileName));
495 if (iter != nodeCallbackMap.end() && iter->second.valid())
496 return iter->second->readNode(fileName, opt);
497 return _defaultCallback->readNode(fileName, opt);
500 class SGReadCallbackInstaller {
502 SGReadCallbackInstaller()
504 // XXX I understand why we want this, but this seems like a weird
505 // place to set this option.
506 Referenced::setThreadSafeReferenceCounting(true);
508 Registry* registry = Registry::instance();
509 ReaderWriter::Options* options = new ReaderWriter::Options;
510 int cacheOptions = ReaderWriter::Options::CACHE_ALL;
512 setObjectCacheHint((ReaderWriter::Options::CacheHintOptions)cacheOptions);
513 registry->setOptions(options);
514 registry->getOrCreateSharedStateManager()->
515 setShareMode(SharedStateManager::SHARE_STATESETS);
516 registry->setReadFileCallback(ModelRegistry::getInstance());
520 static SGReadCallbackInstaller readCallbackInstaller;
522 // we get optimal geometry from the loader.
523 struct ACOptimizePolicy : public OptimizeModelPolicy {
524 ACOptimizePolicy(const string& extension) :
525 OptimizeModelPolicy(extension)
527 _osgOptions &= ~Optimizer::TRISTRIP_GEOMETRY;
529 Node* optimize(Node* node, const string& fileName,
530 const ReaderWriter::Options* opt)
532 ref_ptr<Node> optimized
533 = OptimizeModelPolicy::optimize(node, fileName, opt);
534 MatrixTransform* transform
535 = dynamic_cast<MatrixTransform*>(optimized.get());
536 if (transform && transform->getMatrix().isIdentity()
537 && transform->getName().empty()
538 && transform->getNumChildren() == 1) {
539 optimized = static_cast<Node*>(transform->getChild(0));
540 Group* group = dynamic_cast<Group*>(optimized.get());
541 if (group && group->getName().empty()
542 && group->getNumChildren() == 1)
543 optimized = static_cast<Node*>(group->getChild(0));
545 return optimized.release();
549 struct ACProcessPolicy {
550 ACProcessPolicy(const string& extension) {}
551 Node* process(Node* node, const string& filename,
552 const ReaderWriter::Options* opt)
558 // XXX Does there need to be a Group node here to trick the
559 // optimizer into optimizing the static transform?
560 osg::Group* root = new Group;
561 MatrixTransform* transform = new MatrixTransform;
562 root->addChild(transform);
564 transform->setDataVariance(Object::STATIC);
565 transform->setMatrix(m);
566 transform->addChild(node);
567 // Ok, this step is questionable.
568 // It is there to have the same visual appearance of ac objects for the
569 // first cut. Osg's ac3d loader will correctly set materials from the
570 // ac file. But the old plib loader used GL_AMBIENT_AND_DIFFUSE for the
571 // materials that in effect igored the ambient part specified in the
572 // file. We emulate that for the first cut here by changing all
573 // ac models here. But in the long term we should use the
574 // unchanged model and fix the input files instead ...
575 SGAcMaterialCrippleVisitor matCriple;
576 root->accept(matCriple);
581 typedef ModelRegistryCallback<ACProcessPolicy, DefaultCachePolicy,
582 ACOptimizePolicy, DefaultCopyPolicy,
583 OSGSubstitutePolicy> ACCallback;
587 ModelRegistryCallbackProxy<ACCallback> g_acRegister("ac");