1 // model.cxx - manage a 3D aircraft model.
2 // Written by David Megginson, started 2002.
4 // This file is in the Public Domain, and comes with no warranty.
7 #include <simgear_config.h>
10 #include <osg/observer_ptr>
11 #include <osg/ref_ptr>
13 #include <osg/NodeCallback>
15 #include <osg/MatrixTransform>
16 #include <osgDB/Archive>
17 #include <osgDB/FileNameUtils>
18 #include <osgDB/FileUtils>
19 #include <osgDB/ReadFile>
20 #include <osgDB/WriteFile>
21 #include <osgDB/Registry>
22 #include <osgDB/SharedStateManager>
23 #include <osgUtil/Optimizer>
25 #include <simgear/scene/util/SGSceneFeatures.hxx>
26 #include <simgear/scene/util/SGStateAttributeVisitor.hxx>
27 #include <simgear/scene/util/SGTextureStateAttributeVisitor.hxx>
29 #include <simgear/structure/exception.hxx>
30 #include <simgear/props/props.hxx>
31 #include <simgear/props/props_io.hxx>
32 #include <simgear/props/condition.hxx>
34 #include "animation.hxx"
40 // Little helper class that holds an extra reference to a
42 // Since we clone all structural nodes from our 3d models,
43 // the database pager will only see one single reference to
44 // top node of the model and expire it relatively fast.
45 // We attach that extra reference to every model cloned from
46 // a base model in the pager. When that cloned model is deleted
47 // this extra reference is deleted too. So if there are no
48 // cloned models left the model will expire.
49 class SGDatabaseReference : public osg::Observer {
51 SGDatabaseReference(osg::Referenced* referenced) :
52 mReferenced(referenced)
54 virtual void objectDeleted(void*)
59 osg::ref_ptr<osg::Referenced> mReferenced;
63 class SGTextureUpdateVisitor : public SGTextureStateAttributeVisitor {
65 SGTextureUpdateVisitor(const osgDB::FilePathList& pathList) :
68 osg::Texture2D* textureReplace(int unit,
69 osg::StateSet::RefAttributePair& refAttr)
71 osg::Texture2D* texture;
72 texture = dynamic_cast<osg::Texture2D*>(refAttr.first.get());
76 osg::ref_ptr<osg::Image> image = texture->getImage(0);
80 // The currently loaded file name
81 std::string fullFilePath = image->getFileName();
83 std::string fileName = osgDB::getSimpleFileName(fullFilePath);
84 // The name that should be found with the current database path
85 std::string fullLiveryFile = osgDB::findFileInPath(fileName, mPathList);
86 // If they are identical then there is nothing to do
87 if (fullLiveryFile == fullFilePath)
90 image = osgDB::readImageFile(fullLiveryFile);
94 osg::CopyOp copyOp(osg::CopyOp::DEEP_COPY_ALL &
95 ~osg::CopyOp::DEEP_COPY_IMAGES);
96 texture = static_cast<osg::Texture2D*>(copyOp(texture));
99 texture->setImage(image.get());
102 virtual void apply(osg::StateSet* stateSet)
107 // get a copy that we can safely modify the statesets values.
108 osg::StateSet::TextureAttributeList attrList;
109 attrList = stateSet->getTextureAttributeList();
110 for (unsigned unit = 0; unit < attrList.size(); ++unit) {
111 osg::StateSet::AttributeList::iterator i;
112 i = attrList[unit].begin();
113 while (i != attrList[unit].end()) {
114 osg::Texture2D* texture = textureReplace(unit, i->second);
116 stateSet->removeTextureAttribute(unit, i->second.first.get());
117 stateSet->setTextureAttribute(unit, texture, i->second.second);
118 stateSet->setTextureMode(unit, GL_TEXTURE_2D,
119 osg::StateAttribute::ON);
127 osgDB::FilePathList mPathList;
130 class SGTexCompressionVisitor : public SGTextureStateAttributeVisitor {
132 virtual void apply(int, osg::StateSet::RefAttributePair& refAttr)
134 osg::Texture2D* texture;
135 texture = dynamic_cast<osg::Texture2D*>(refAttr.first.get());
139 osg::Image* image = texture->getImage(0);
146 if (s <= t && 32 <= s) {
147 SGSceneFeatures::instance()->setTextureCompression(texture);
148 } else if (t < s && 32 <= t) {
149 SGSceneFeatures::instance()->setTextureCompression(texture);
154 class SGTexDataVarianceVisitor : public SGTextureStateAttributeVisitor {
156 virtual void apply(int, osg::StateSet::RefAttributePair& refAttr)
158 osg::Texture* texture;
159 texture = dynamic_cast<osg::Texture*>(refAttr.first.get());
163 texture->setDataVariance(osg::Object::STATIC);
167 class SGAcMaterialCrippleVisitor : public SGStateAttributeVisitor {
169 virtual void apply(osg::StateSet::RefAttributePair& refAttr)
171 osg::Material* material;
172 material = dynamic_cast<osg::Material*>(refAttr.first.get());
175 material->setColorMode(osg::Material::AMBIENT_AND_DIFFUSE);
179 class SGReadFileCallback :
180 public osgDB::Registry::ReadFileCallback {
182 virtual osgDB::ReaderWriter::ReadResult
183 readImage(const std::string& fileName,
184 const osgDB::ReaderWriter::Options* opt)
186 std::string absFileName = osgDB::findDataFile(fileName);
187 if (!osgDB::fileExists(absFileName)) {
188 SG_LOG(SG_IO, SG_ALERT, "Cannot find image file \""
189 << fileName << "\"");
190 return osgDB::ReaderWriter::ReadResult::FILE_NOT_FOUND;
193 osgDB::Registry* registry = osgDB::Registry::instance();
194 osgDB::ReaderWriter::ReadResult res;
195 res = registry->readImageImplementation(absFileName, opt);
196 if (res.loadedFromCache())
197 SG_LOG(SG_IO, SG_INFO, "Returning cached image \""
198 << res.getImage()->getFileName() << "\"");
200 SG_LOG(SG_IO, SG_INFO, "Reading image \""
201 << res.getImage()->getFileName() << "\"");
206 virtual osgDB::ReaderWriter::ReadResult
207 readNode(const std::string& fileName,
208 const osgDB::ReaderWriter::Options* opt)
210 std::string absFileName = osgDB::findDataFile(fileName);
211 if (!osgDB::fileExists(absFileName)) {
212 SG_LOG(SG_IO, SG_ALERT, "Cannot find model file \""
213 << fileName << "\"");
214 return osgDB::ReaderWriter::ReadResult::FILE_NOT_FOUND;
217 osgDB::Registry* registry = osgDB::Registry::instance();
218 osgDB::ReaderWriter::ReadResult res;
219 res = registry->readNodeImplementation(absFileName, opt);
220 if (!res.validNode())
223 if (res.loadedFromCache()) {
224 SG_LOG(SG_IO, SG_INFO, "Returning cached model \""
225 << absFileName << "\"");
227 SG_LOG(SG_IO, SG_INFO, "Reading model \""
228 << absFileName << "\"");
230 bool needTristrip = true;
231 if (osgDB::getLowerCaseFileExtension(absFileName) == "ac") {
232 // we get optimal geometry from the loader.
233 needTristrip = false;
234 osg::Matrix m(1, 0, 0, 0,
239 osg::ref_ptr<osg::Group> root = new osg::Group;
240 osg::MatrixTransform* transform = new osg::MatrixTransform;
241 root->addChild(transform);
243 transform->setDataVariance(osg::Object::STATIC);
244 transform->setMatrix(m);
245 transform->addChild(res.getNode());
247 res = osgDB::ReaderWriter::ReadResult(0);
249 osgUtil::Optimizer optimizer;
250 unsigned opts = osgUtil::Optimizer::FLATTEN_STATIC_TRANSFORMS;
251 optimizer.optimize(root.get(), opts);
253 // strip away unneeded groups
254 if (root->getNumChildren() == 1 && root->getName().empty()) {
255 res = osgDB::ReaderWriter::ReadResult(root->getChild(0));
257 res = osgDB::ReaderWriter::ReadResult(root.get());
259 // Ok, this step is questionable.
260 // It is there to have the same visual appearance of ac objects for the
261 // first cut. Osg's ac3d loader will correctly set materials from the
262 // ac file. But the old plib loader used GL_AMBIENT_AND_DIFFUSE for the
263 // materials that in effect igored the ambient part specified in the
264 // file. We emulate that for the first cut here by changing all
265 // ac models here. But in the long term we should use the
266 // unchanged model and fix the input files instead ...
267 SGAcMaterialCrippleVisitor matCriple;
268 res.getNode()->accept(matCriple);
271 osgUtil::Optimizer optimizer;
273 // Don't use this one. It will break animation names ...
274 // opts |= osgUtil::Optimizer::REMOVE_REDUNDANT_NODES;
276 // opts |= osgUtil::Optimizer::REMOVE_LOADED_PROXY_NODES;
277 // opts |= osgUtil::Optimizer::COMBINE_ADJACENT_LODS;
278 // opts |= osgUtil::Optimizer::SHARE_DUPLICATE_STATE;
279 opts |= osgUtil::Optimizer::MERGE_GEOMETRY;
280 // opts |= osgUtil::Optimizer::CHECK_GEOMETRY;
281 // opts |= osgUtil::Optimizer::SPATIALIZE_GROUPS;
282 // opts |= osgUtil::Optimizer::COPY_SHARED_NODES;
283 opts |= osgUtil::Optimizer::FLATTEN_STATIC_TRANSFORMS;
285 opts |= osgUtil::Optimizer::TRISTRIP_GEOMETRY;
286 // opts |= osgUtil::Optimizer::TESSELATE_GEOMETRY;
287 // opts |= osgUtil::Optimizer::OPTIMIZE_TEXTURE_SETTINGS;
288 optimizer.optimize(res.getNode(), opts);
290 // Make sure the data variance of sharable objects is set to STATIC ...
291 SGTexDataVarianceVisitor dataVarianceVisitor;
292 res.getNode()->accept(dataVarianceVisitor);
293 // ... so that textures are now globally shared
294 registry->getSharedStateManager()->share(res.getNode());
296 SGTexCompressionVisitor texComp;
297 res.getNode()->accept(texComp);
300 // Add an extra reference to the model stored in the database.
301 // That it to avoid expiring the object from the cache even if it is still
302 // in use. Note that the object cache will think that a model is unused
303 // if the reference count is 1. If we clone all structural nodes here
304 // we need that extra reference to the original object
305 SGDatabaseReference* databaseReference;
306 databaseReference = new SGDatabaseReference(res.getNode());
307 osg::CopyOp::CopyFlags flags = osg::CopyOp::DEEP_COPY_ALL;
308 flags &= ~osg::CopyOp::DEEP_COPY_TEXTURES;
309 flags &= ~osg::CopyOp::DEEP_COPY_IMAGES;
310 flags &= ~osg::CopyOp::DEEP_COPY_ARRAYS;
311 flags &= ~osg::CopyOp::DEEP_COPY_PRIMITIVES;
312 // This will safe display lists ...
313 flags &= ~osg::CopyOp::DEEP_COPY_DRAWABLES;
314 flags &= ~osg::CopyOp::DEEP_COPY_SHAPES;
315 res = osgDB::ReaderWriter::ReadResult(osg::CopyOp(flags)(res.getNode()));
316 res.getNode()->addObserver(databaseReference);
319 SGTextureUpdateVisitor liveryUpdate(osgDB::getDataFilePathList());
320 res.getNode()->accept(liveryUpdate);
322 // Make sure the data variance of sharable objects is set to STATIC ...
323 SGTexDataVarianceVisitor dataVarianceVisitor;
324 res.getNode()->accept(dataVarianceVisitor);
325 // ... so that textures are now globally shared
326 registry->getOrCreateSharedStateManager()->share(res.getNode(), 0);
332 class SGReadCallbackInstaller {
334 SGReadCallbackInstaller()
336 osg::Referenced::setThreadSafeReferenceCounting(true);
338 osgDB::Registry* registry = osgDB::Registry::instance();
339 osgDB::ReaderWriter::Options* options = new osgDB::ReaderWriter::Options;
340 options->setObjectCacheHint(osgDB::ReaderWriter::Options::CACHE_ALL);
341 registry->setOptions(options);
342 registry->getOrCreateSharedStateManager()->setShareMode(osgDB::SharedStateManager::SHARE_TEXTURES);
343 registry->setReadFileCallback(new SGReadFileCallback);
347 static SGReadCallbackInstaller readCallbackInstaller;
350 SGLoadTexture2D(const std::string& path, bool wrapu, bool wrapv, int)
352 osg::Image* image = osgDB::readImageFile(path);
353 osg::ref_ptr<osg::Texture2D> texture = new osg::Texture2D;
354 texture->setImage(image);
356 texture->setWrap(osg::Texture::WRAP_S, osg::Texture::REPEAT);
358 texture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP);
360 texture->setWrap(osg::Texture::WRAP_T, osg::Texture::REPEAT);
362 texture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP);
368 if (s <= t && 32 <= s) {
369 SGSceneFeatures::instance()->setTextureCompression(texture.get());
370 } else if (t < s && 32 <= t) {
371 SGSceneFeatures::instance()->setTextureCompression(texture.get());
375 // Make sure the texture is shared if we already have the same texture
378 osg::ref_ptr<osg::Node> tmpNode = new osg::Node;
379 osg::StateSet* stateSet = tmpNode->getOrCreateStateSet();
380 stateSet->setTextureAttribute(0, texture.get());
382 // OSGFIXME: don't forget that mutex here
383 osgDB::Registry* registry = osgDB::Registry::instance();
384 registry->getOrCreateSharedStateManager()->share(tmpNode.get(), 0);
386 // should be the same, but be paranoid ...
387 stateSet = tmpNode->getStateSet();
388 osg::StateAttribute* stateAttr;
389 stateAttr = stateSet->getTextureAttribute(0, osg::StateAttribute::TEXTURE);
390 osg::Texture2D* texture2D = dynamic_cast<osg::Texture2D*>(stateAttr);
395 return texture.release();
398 class SGSwitchUpdateCallback : public osg::NodeCallback {
400 SGSwitchUpdateCallback(SGCondition* condition) :
401 mCondition(condition) {}
402 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
404 assert(dynamic_cast<osg::Switch*>(node));
405 osg::Switch* s = static_cast<osg::Switch*>(node);
407 if (mCondition && mCondition->test()) {
408 s->setAllChildrenOn();
409 // note, callback is responsible for scenegraph traversal so
410 // should always include call traverse(node,nv) to ensure
411 // that the rest of cullbacks and the scene graph are traversed.
414 s->setAllChildrenOff();
418 SGSharedPtr<SGCondition> mCondition;
422 ////////////////////////////////////////////////////////////////////////
424 ////////////////////////////////////////////////////////////////////////
427 sgLoad3DModel( const string &fg_root, const string &path,
428 SGPropertyNode *prop_root,
429 double sim_time_sec, osg::Node *(*load_panel)(SGPropertyNode *),
431 const SGPath& externalTexturePath )
433 osg::ref_ptr<osg::Node> model;
434 SGPropertyNode props;
436 // Load the 3D aircraft object itself
437 SGPath modelpath = path, texturepath = path;
438 if ( !ulIsAbsolutePathName( path.c_str() ) ) {
439 SGPath tmp = fg_root;
440 tmp.append(modelpath.str());
441 modelpath = texturepath = tmp;
444 // Check for an XML wrapper
445 if (modelpath.str().substr(modelpath.str().size() - 4, 4) == ".xml") {
446 readProperties(modelpath.str(), &props);
447 if (props.hasValue("/path")) {
448 modelpath = modelpath.dir();
449 modelpath.append(props.getStringValue("/path"));
450 if (props.hasValue("/texture-path")) {
451 texturepath = texturepath.dir();
452 texturepath.append(props.getStringValue("/texture-path"));
456 model = new osg::Switch;
460 osgDB::FilePathList pathList = osgDB::getDataFilePathList();
461 osgDB::Registry::instance()->initFilePathLists();
463 // Assume that textures are in
464 // the same location as the XML file.
466 if (texturepath.extension() != "")
467 texturepath = texturepath.dir();
469 osgDB::Registry::instance()->getDataFilePathList().push_front(texturepath.str());
471 model = osgDB::readNodeFile(modelpath.str());
473 throw sg_io_exception("Failed to load 3D model",
474 sg_location(modelpath.str()));
477 osgDB::Registry::instance()->getDataFilePathList().push_front(externalTexturePath.str());
479 // Set up the alignment node
480 osg::ref_ptr<osg::MatrixTransform> alignmainmodel = new osg::MatrixTransform;
481 alignmainmodel->addChild(model.get());
482 osg::Matrix res_matrix;
483 res_matrix.makeRotate(
484 props.getFloatValue("/offsets/pitch-deg", 0.0)*SG_DEGREES_TO_RADIANS,
486 props.getFloatValue("/offsets/roll-deg", 0.0)*SG_DEGREES_TO_RADIANS,
488 props.getFloatValue("/offsets/heading-deg", 0.0)*SG_DEGREES_TO_RADIANS,
492 tmat.makeTranslate(props.getFloatValue("/offsets/x-m", 0.0),
493 props.getFloatValue("/offsets/y-m", 0.0),
494 props.getFloatValue("/offsets/z-m", 0.0));
495 alignmainmodel->setMatrix(res_matrix*tmat);
498 vector<SGPropertyNode_ptr> model_nodes = props.getChildren("model");
499 for (unsigned i = 0; i < model_nodes.size(); i++) {
500 SGPropertyNode_ptr node = model_nodes[i];
501 osg::ref_ptr<osg::MatrixTransform> align = new osg::MatrixTransform;
502 res_matrix.makeIdentity();
503 res_matrix.makeRotate(
504 node->getDoubleValue("offsets/pitch-deg", 0.0)*SG_DEGREES_TO_RADIANS,
506 node->getDoubleValue("offsets/roll-deg", 0.0)*SG_DEGREES_TO_RADIANS,
508 node->getDoubleValue("offsets/heading-deg", 0.0)*SG_DEGREES_TO_RADIANS,
512 tmat.makeTranslate(node->getDoubleValue("offsets/x-m", 0),
513 node->getDoubleValue("offsets/y-m", 0),
514 node->getDoubleValue("offsets/z-m", 0));
515 align->setMatrix(res_matrix*tmat);
517 osg::ref_ptr<osg::Node> kid;
518 const char* submodel = node->getStringValue("path");
520 kid = sgLoad3DModel( fg_root, submodel, prop_root, sim_time_sec, load_panel );
522 } catch (const sg_throwable &t) {
523 SG_LOG(SG_INPUT, SG_ALERT, "Failed to load submodel: " << t.getFormattedMessage());
526 align->addChild(kid.get());
528 align->setName(node->getStringValue("name", ""));
530 SGPropertyNode *cond = node->getNode("condition", false);
532 osg::ref_ptr<osg::Switch> sw = new osg::Switch;
533 sw->setUpdateCallback(new SGSwitchUpdateCallback(sgReadCondition(prop_root, cond)));
534 alignmainmodel->addChild(sw.get());
535 sw->addChild(align.get());
536 sw->setName("submodel condition switch");
538 alignmainmodel->addChild(align.get());
544 vector<SGPropertyNode_ptr> panel_nodes = props.getChildren("panel");
545 for (unsigned i = 0; i < panel_nodes.size(); i++) {
546 SG_LOG(SG_INPUT, SG_DEBUG, "Loading a panel");
547 osg::ref_ptr<osg::Node> panel = load_panel(panel_nodes[i]);
548 if (panel_nodes[i]->hasValue("name"))
549 panel->setName((char *)panel_nodes[i]->getStringValue("name"));
550 alignmainmodel->addChild(panel.get());
555 alignmainmodel->setUserData(data);
556 data->modelLoaded(path, &props, alignmainmodel.get());
559 std::vector<SGPropertyNode_ptr> animation_nodes;
560 animation_nodes = props.getChildren("animation");
561 for (unsigned i = 0; i < animation_nodes.size(); ++i)
562 /// OSGFIXME: duh, why not only model?????
563 SGAnimation::animate(alignmainmodel.get(), animation_nodes[i], prop_root);
565 // restore old path list
566 osgDB::setDataFilePathList(pathList);
568 if (props.hasChild("debug-outfile")) {
569 std::string outputfile = props.getStringValue("debug-outfile",
571 osgDB::writeNodeFile(*alignmainmodel, outputfile);
574 return alignmainmodel.release();