]> git.mxchange.org Git - simgear.git/blob - simgear/scene/model/model.cxx
Modified Files:
[simgear.git] / simgear / scene / model / model.cxx
1 // model.cxx - manage a 3D aircraft model.
2 // Written by David Megginson, started 2002.
3 //
4 // This file is in the Public Domain, and comes with no warranty.
5
6 #ifdef HAVE_CONFIG_H
7 #include <simgear_config.h>
8 #endif
9
10 #include <osg/observer_ptr>
11 #include <osg/ref_ptr>
12 #include <osg/Group>
13 #include <osg/NodeCallback>
14 #include <osg/Switch>
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>
24
25 #include <simgear/scene/util/SGSceneFeatures.hxx>
26 #include <simgear/scene/util/SGStateAttributeVisitor.hxx>
27 #include <simgear/scene/util/SGTextureStateAttributeVisitor.hxx>
28
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>
33
34 #include "animation.hxx"
35 #include "model.hxx"
36
37 SG_USING_STD(vector);
38 SG_USING_STD(set);
39
40 // Little helper class that holds an extra reference to a
41 // loaded 3d model.
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 {
50 public:
51   SGDatabaseReference(osg::Referenced* referenced) :
52     mReferenced(referenced)
53   { }
54   virtual void objectDeleted(void*)
55   {
56     mReferenced = 0;
57   }
58 private:
59   osg::ref_ptr<osg::Referenced> mReferenced;
60 };
61
62 // Visitor for 
63 class SGTextureUpdateVisitor : public SGTextureStateAttributeVisitor {
64 public:
65   SGTextureUpdateVisitor(const osgDB::FilePathList& pathList) :
66     mPathList(pathList)
67   { }
68   osg::Texture2D* textureReplace(int unit,
69                                  osg::StateSet::RefAttributePair& refAttr)
70   {
71     osg::Texture2D* texture;
72     texture = dynamic_cast<osg::Texture2D*>(refAttr.first.get());
73     if (!texture)
74       return 0;
75     
76     osg::ref_ptr<osg::Image> image = texture->getImage(0);
77     if (!image)
78       return 0;
79
80     // The currently loaded file name
81     std::string fullFilePath = image->getFileName();
82     // The short name
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)
88       return 0;
89
90     image = osgDB::readImageFile(fullLiveryFile);
91     if (!image)
92       return 0;
93
94     osg::CopyOp copyOp(osg::CopyOp::DEEP_COPY_ALL &
95                        ~osg::CopyOp::DEEP_COPY_IMAGES);
96     texture = static_cast<osg::Texture2D*>(copyOp(texture));
97     if (!texture)
98       return 0;
99     texture->setImage(image.get());
100     return texture;
101   }
102   virtual void apply(osg::StateSet* stateSet)
103   {
104     if (!stateSet)
105       return;
106
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);
115         if (texture) {
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);
120         }
121         ++i;
122       }
123     }
124   }
125
126 private:
127   osgDB::FilePathList mPathList;
128 };
129
130 class SGTexCompressionVisitor : public SGTextureStateAttributeVisitor {
131 public:
132   virtual void apply(int, osg::StateSet::RefAttributePair& refAttr)
133   {
134     osg::Texture2D* texture;
135     texture = dynamic_cast<osg::Texture2D*>(refAttr.first.get());
136     if (!texture)
137       return;
138     
139     osg::Image* image = texture->getImage(0);
140     if (!image)
141       return;
142
143     int s = image->s();
144     int t = image->t();
145
146     if (s <= t && 32 <= s) {
147       SGSceneFeatures::instance()->setTextureCompression(texture);
148     } else if (t < s && 32 <= t) {
149       SGSceneFeatures::instance()->setTextureCompression(texture);
150     }
151   }
152 };
153
154 class SGTexDataVarianceVisitor : public SGTextureStateAttributeVisitor {
155 public:
156   virtual void apply(int, osg::StateSet::RefAttributePair& refAttr)
157   {
158     osg::Texture* texture;
159     texture = dynamic_cast<osg::Texture*>(refAttr.first.get());
160     if (!texture)
161       return;
162     
163     texture->setDataVariance(osg::Object::STATIC);
164   }
165 };
166
167 class SGAcMaterialCrippleVisitor : public SGStateAttributeVisitor {
168 public:
169   virtual void apply(osg::StateSet::RefAttributePair& refAttr)
170   {
171     osg::Material* material;
172     material = dynamic_cast<osg::Material*>(refAttr.first.get());
173     if (!material)
174       return;
175     material->setColorMode(osg::Material::AMBIENT_AND_DIFFUSE);
176   }
177 };
178
179 class SGReadFileCallback :
180   public osgDB::Registry::ReadFileCallback {
181 public:
182   virtual osgDB::ReaderWriter::ReadResult
183   readImage(const std::string& fileName,
184             const osgDB::ReaderWriter::Options* opt)
185   {
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;
191     }
192
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() << "\"");
199     else
200       SG_LOG(SG_IO, SG_INFO, "Reading image \""
201              << res.getImage()->getFileName() << "\"");
202
203     return res;
204   }
205
206   virtual osgDB::ReaderWriter::ReadResult
207   readNode(const std::string& fileName,
208            const osgDB::ReaderWriter::Options* opt)
209   {
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;
215     }
216
217     osgDB::Registry* registry = osgDB::Registry::instance();
218     osgDB::ReaderWriter::ReadResult res;
219     res = registry->readNodeImplementation(absFileName, opt);
220     if (!res.validNode())
221       return res;
222
223     if (res.loadedFromCache()) {
224       SG_LOG(SG_IO, SG_INFO, "Returning cached model \""
225              << absFileName << "\"");
226     } else {
227       SG_LOG(SG_IO, SG_INFO, "Reading model \""
228              << absFileName << "\"");
229
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,
235                       0, 0, 1, 0,
236                       0, -1, 0, 0,
237                       0, 0, 0, 1);
238         
239         osg::ref_ptr<osg::Group> root = new osg::Group;
240         osg::MatrixTransform* transform = new osg::MatrixTransform;
241         root->addChild(transform);
242         
243         transform->setDataVariance(osg::Object::STATIC);
244         transform->setMatrix(m);
245         transform->addChild(res.getNode());
246         
247         res = osgDB::ReaderWriter::ReadResult(0);
248         
249         osgUtil::Optimizer optimizer;
250         unsigned opts = osgUtil::Optimizer::FLATTEN_STATIC_TRANSFORMS;
251         optimizer.optimize(root.get(), opts);
252
253         // strip away unneeded groups
254         if (root->getNumChildren() == 1 && root->getName().empty()) {
255           res = osgDB::ReaderWriter::ReadResult(root->getChild(0));
256         } else
257           res = osgDB::ReaderWriter::ReadResult(root.get());
258         
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);
269       }
270       
271       osgUtil::Optimizer optimizer;
272       unsigned opts = 0;
273       // Don't use this one. It will break animation names ...
274       // opts |= osgUtil::Optimizer::REMOVE_REDUNDANT_NODES;
275
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;
284       if (needTristrip)
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);
289
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());
295       
296       SGTexCompressionVisitor texComp;
297       res.getNode()->accept(texComp);
298     }
299
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);
317
318     // Update liveries
319     SGTextureUpdateVisitor liveryUpdate(osgDB::getDataFilePathList());
320     res.getNode()->accept(liveryUpdate);
321
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);
327
328     return res;
329   }
330 };
331
332 class SGReadCallbackInstaller {
333 public:
334   SGReadCallbackInstaller()
335   {
336     osg::Referenced::setThreadSafeReferenceCounting(true);
337
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);
344   }
345 };
346
347 static SGReadCallbackInstaller readCallbackInstaller;
348
349 osg::Texture2D*
350 SGLoadTexture2D(const std::string& path, bool wrapu, bool wrapv, int)
351 {
352   osg::Image* image = osgDB::readImageFile(path);
353   osg::ref_ptr<osg::Texture2D> texture = new osg::Texture2D;
354   texture->setImage(image);
355   if (wrapu)
356     texture->setWrap(osg::Texture::WRAP_S, osg::Texture::REPEAT);
357   else
358     texture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP);
359   if (wrapv)
360     texture->setWrap(osg::Texture::WRAP_T, osg::Texture::REPEAT);
361   else
362     texture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP);
363
364   if (image) {
365     int s = image->s();
366     int t = image->t();
367
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());
372     }
373   }
374
375   // Make sure the texture is shared if we already have the same texture
376   // somewhere ...
377   {
378     osg::ref_ptr<osg::Node> tmpNode = new osg::Node;
379     osg::StateSet* stateSet = tmpNode->getOrCreateStateSet();
380     stateSet->setTextureAttribute(0, texture.get());
381
382     // OSGFIXME: don't forget that mutex here
383     osgDB::Registry* registry = osgDB::Registry::instance();
384     registry->getOrCreateSharedStateManager()->share(tmpNode.get(), 0);
385
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);
391     if (texture2D)
392       texture = texture2D;
393   }
394
395   return texture.release();
396 }
397
398 class SGSwitchUpdateCallback : public osg::NodeCallback {
399 public:
400   SGSwitchUpdateCallback(SGCondition* condition) :
401     mCondition(condition) {}
402   virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
403   { 
404     assert(dynamic_cast<osg::Switch*>(node));
405     osg::Switch* s = static_cast<osg::Switch*>(node);
406
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.
412       traverse(node, nv);
413     } else
414       s->setAllChildrenOff();
415   }
416
417 private:
418   SGSharedPtr<SGCondition> mCondition;
419 };
420
421 \f
422 ////////////////////////////////////////////////////////////////////////
423 // Global functions.
424 ////////////////////////////////////////////////////////////////////////
425
426 osg::Node *
427 sgLoad3DModel( const string &fg_root, const string &path,
428                SGPropertyNode *prop_root,
429                double sim_time_sec, osg::Node *(*load_panel)(SGPropertyNode *),
430                SGModelData *data,
431                const SGPath& externalTexturePath )
432 {
433   osg::ref_ptr<osg::Node> model;
434   SGPropertyNode props;
435
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;
442   }
443
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"));
453       }
454     } else {
455       if (!model)
456         model = new osg::Switch;
457     }
458   }
459
460   osgDB::FilePathList pathList = osgDB::getDataFilePathList();
461   osgDB::Registry::instance()->initFilePathLists();
462
463   // Assume that textures are in
464   // the same location as the XML file.
465   if (!model) {
466     if (texturepath.extension() != "")
467           texturepath = texturepath.dir();
468
469     osgDB::Registry::instance()->getDataFilePathList().push_front(texturepath.str());
470
471     model = osgDB::readNodeFile(modelpath.str());
472     if (model == 0)
473       throw sg_io_exception("Failed to load 3D model", 
474                             sg_location(modelpath.str()));
475   }
476
477   osgDB::Registry::instance()->getDataFilePathList().push_front(externalTexturePath.str());
478
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,
485     osg::Vec3(0, 1, 0),
486     props.getFloatValue("/offsets/roll-deg", 0.0)*SG_DEGREES_TO_RADIANS,
487     osg::Vec3(1, 0, 0),
488     props.getFloatValue("/offsets/heading-deg", 0.0)*SG_DEGREES_TO_RADIANS,
489     osg::Vec3(0, 0, 1));
490
491   osg::Matrix tmat;
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);
496
497   // Load sub-models
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,
505       osg::Vec3(0, 1, 0),
506       node->getDoubleValue("offsets/roll-deg", 0.0)*SG_DEGREES_TO_RADIANS,
507       osg::Vec3(1, 0, 0),
508       node->getDoubleValue("offsets/heading-deg", 0.0)*SG_DEGREES_TO_RADIANS,
509       osg::Vec3(0, 0, 1));
510     
511     tmat.makeIdentity();
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);
516
517     osg::ref_ptr<osg::Node> kid;
518     const char* submodel = node->getStringValue("path");
519     try {
520       kid = sgLoad3DModel( fg_root, submodel, prop_root, sim_time_sec, load_panel );
521
522     } catch (const sg_throwable &t) {
523       SG_LOG(SG_INPUT, SG_ALERT, "Failed to load submodel: " << t.getFormattedMessage());
524       throw;
525     }
526     align->addChild(kid.get());
527
528     align->setName(node->getStringValue("name", ""));
529
530     SGPropertyNode *cond = node->getNode("condition", false);
531     if (cond) {
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");
537     } else {
538       alignmainmodel->addChild(align.get());
539     }
540   }
541
542   if ( load_panel ) {
543     // Load panels
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());
551     }
552   }
553
554   if (data) {
555     alignmainmodel->setUserData(data);
556     data->modelLoaded(path, &props, alignmainmodel.get());
557   }
558
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);
564
565   // restore old path list
566   osgDB::setDataFilePathList(pathList);
567
568   if (props.hasChild("debug-outfile")) {
569     std::string outputfile = props.getStringValue("debug-outfile",
570                                                   "debug-model.osg");
571     osgDB::writeNodeFile(*alignmainmodel, outputfile);
572   }
573
574   return alignmainmodel.release();
575 }
576
577 // end of model.cxx