]> git.mxchange.org Git - simgear.git/blob - simgear/scene/model/SGReaderWriterXML.cxx
Restore lights in the Rembrandt renderer
[simgear.git] / simgear / scene / model / SGReaderWriterXML.cxx
1 // Copyright (C) 2007 Tim Moore timoore@redhat.com
2 // Copyright (C) 2008 Till Busch buti@bux.at
3 //
4 // This program is free software; you can redistribute it and/or
5 // modify it under the terms of the GNU General Public License as
6 // published by the Free Software Foundation; either version 2 of the
7 // License, or (at your option) any later version.
8 //
9 // This program is distributed in the hope that it will be useful, but
10 // WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12 // General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with this program; if not, write to the Free Software
16 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17 //
18
19 #ifdef HAVE_CONFIG_H
20 #  include <simgear_config.h>
21 #endif
22
23 #include <algorithm>
24 //yuck
25 #include <cstring>
26 #include <cassert>
27
28 #include <boost/bind.hpp>
29
30 #include <osg/Geode>
31 #include <osg/MatrixTransform>
32 #include <osgDB/ReadFile>
33 #include <osgDB/WriteFile>
34 #include <osgDB/Registry>
35 #include <osg/Switch>
36 #include <osgDB/FileNameUtils>
37
38 #include <simgear/compiler.h>
39 #include <simgear/structure/exception.hxx>
40 #include <simgear/props/props.hxx>
41 #include <simgear/props/props_io.hxx>
42 #include <simgear/props/condition.hxx>
43 #include <simgear/scene/util/SGNodeMasks.hxx>
44 #include <simgear/scene/util/SGReaderWriterOptions.hxx>
45
46 #include "modellib.hxx"
47 #include "SGReaderWriterXML.hxx"
48
49 #include "animation.hxx"
50 #include "particles.hxx"
51 #include "model.hxx"
52 #include "SGText.hxx"
53 #include "SGMaterialAnimation.hxx"
54
55 using namespace std;
56 using namespace simgear;
57 using namespace osg;
58
59 static osg::Node *
60 sgLoad3DModel_internal(const SGPath& path,
61                        const osgDB::Options* options,
62                        SGPropertyNode *overlay = 0);
63
64
65 SGReaderWriterXML::SGReaderWriterXML()
66 {
67     supportsExtension("xml", "SimGear xml database format");
68 }
69
70 SGReaderWriterXML::~SGReaderWriterXML()
71 {
72 }
73
74 const char* SGReaderWriterXML::className() const
75 {
76     return "XML database reader";
77 }
78
79 osgDB::ReaderWriter::ReadResult
80 SGReaderWriterXML::readNode(const std::string& fileName,
81                             const osgDB::Options* options) const
82 {
83     osg::Node *result=0;
84     try {
85         SGPath p = SGModelLib::findDataFile(fileName);
86         if (!p.exists()) {
87           return ReadResult::FILE_NOT_FOUND;
88         }
89         
90         result=sgLoad3DModel_internal(p, options);
91     } catch (const sg_exception &t) {
92         SG_LOG(SG_INPUT, SG_ALERT, "Failed to load model: " << t.getFormattedMessage()
93           << "\n\tfrom:" << fileName);
94         result=new osg::Node;
95     }
96     if (result)
97         return result;
98     else
99         return ReadResult::FILE_NOT_HANDLED;
100 }
101
102 class SGSwitchUpdateCallback : public osg::NodeCallback
103 {
104 public:
105     SGSwitchUpdateCallback(SGCondition* condition) :
106             mCondition(condition) {}
107     virtual void operator()(osg::Node* node, osg::NodeVisitor* nv) {
108         assert(dynamic_cast<osg::Switch*>(node));
109         osg::Switch* s = static_cast<osg::Switch*>(node);
110
111         if (mCondition && mCondition->test()) {
112             s->setAllChildrenOn();
113             // note, callback is responsible for scenegraph traversal so
114             // should always include call traverse(node,nv) to ensure
115             // that the rest of cullbacks and the scene graph are traversed.
116             traverse(node, nv);
117         } else
118             s->setAllChildrenOff();
119     }
120
121 private:
122     SGSharedPtr<SGCondition> mCondition;
123 };
124
125
126 // Little helper class that holds an extra reference to a
127 // loaded 3d model.
128 // Since we clone all structural nodes from our 3d models,
129 // the database pager will only see one single reference to
130 // top node of the model and expire it relatively fast.
131 // We attach that extra reference to every model cloned from
132 // a base model in the pager. When that cloned model is deleted
133 // this extra reference is deleted too. So if there are no
134 // cloned models left the model will expire.
135 namespace {
136 class SGDatabaseReference : public osg::Observer
137 {
138 public:
139     SGDatabaseReference(osg::Referenced* referenced) :
140         mReferenced(referenced)
141     { }
142     virtual void objectDeleted(void*)
143     {
144         mReferenced = 0;
145     }
146 private:
147     osg::ref_ptr<osg::Referenced> mReferenced;
148 };
149
150 void makeEffectAnimations(PropertyList& animation_nodes,
151                           PropertyList& effect_nodes)
152 {
153     for (PropertyList::iterator itr = animation_nodes.begin();
154          itr != animation_nodes.end();
155          ++itr) {
156         SGPropertyNode_ptr effectProp;
157         SGPropertyNode* animProp = itr->ptr();
158         SGPropertyNode* typeProp = animProp->getChild("type");
159         if (!typeProp)
160             continue;
161         const char* typeString = typeProp->getStringValue();
162         if (!strcmp(typeString, "material")) {
163             effectProp
164                 = SGMaterialAnimation::makeEffectProperties(animProp);
165         } else if (!strcmp(typeString, "shader")) {
166             
167             SGPropertyNode* shaderProp = animProp->getChild("shader");
168             if (!shaderProp || strcmp(shaderProp->getStringValue(), "chrome"))
169                 continue;
170             *itr = 0;           // effect replaces animation
171             SGPropertyNode* textureProp = animProp->getChild("texture");
172             if (!textureProp)
173                 continue;
174             effectProp = new SGPropertyNode();
175             makeChild(effectProp.ptr(), "inherits-from")
176                 ->setValue("Effects/chrome");
177             SGPropertyNode* paramsProp = makeChild(effectProp.get(), "parameters");
178             makeChild(paramsProp, "chrome-texture")
179                 ->setValue(textureProp->getStringValue());
180         }
181         if (effectProp.valid()) {
182             PropertyList objectNameNodes = animProp->getChildren("object-name");
183             for (PropertyList::iterator objItr = objectNameNodes.begin(),
184                      end = objectNameNodes.end();
185                  objItr != end;
186                  ++objItr)
187                 effectProp->addChild("object-name")
188                     ->setStringValue((*objItr)->getStringValue());
189             effect_nodes.push_back(effectProp);
190
191         }
192     }
193     animation_nodes.erase(remove_if(animation_nodes.begin(),
194                                     animation_nodes.end(),
195                                     !boost::bind(&SGPropertyNode_ptr::valid,
196                                                  _1)),
197                           animation_nodes.end());
198 }
199 }
200
201 class SGSetNodeMaskVisitor : public osg::NodeVisitor {
202 public:
203     SGSetNodeMaskVisitor(osg::Node::NodeMask nms, osg::Node::NodeMask nmc) :
204         osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN), nodeMaskSet(nms), nodeMaskClear(nmc)
205     {}
206     virtual void apply(osg::Geode& node) {
207         node.setNodeMask((node.getNodeMask() | nodeMaskSet) & ~nodeMaskClear);
208         traverse(node);
209     }
210 private:
211     osg::Node::NodeMask nodeMaskSet;
212     osg::Node::NodeMask nodeMaskClear;
213 };
214
215 static osg::Node *
216 sgLoad3DModel_internal(const SGPath& path,
217                        const osgDB::Options* dbOptions,
218                        SGPropertyNode *overlay)
219 {
220     if (!path.exists()) {
221       SG_LOG(SG_INPUT, SG_ALERT, "Failed to load file: \"" << path.str() << "\"");
222       return NULL;
223     }
224
225     osg::ref_ptr<SGReaderWriterOptions> options;
226     options = SGReaderWriterOptions::copyOrCreate(dbOptions);
227     
228     SGPath modelpath(path);
229     SGPath texturepath(path);
230     SGPath modelDir(modelpath.dir());
231     
232     SGSharedPtr<SGPropertyNode> prop_root = options->getPropertyNode();
233     if (!prop_root.valid())
234         prop_root = new SGPropertyNode;
235     // The model data appear to be only used in the topmost model
236     osg::ref_ptr<SGModelData> data = options->getModelData();
237     options->setModelData(0);
238     
239     osg::ref_ptr<osg::Node> model;
240     osg::ref_ptr<osg::Group> group;
241     SGPropertyNode_ptr props = new SGPropertyNode;
242
243     // Check for an XML wrapper
244     if (modelpath.extension() == "xml") {
245        try {
246             readProperties(modelpath.str(), props);
247         } catch (const sg_exception &t) {
248             SG_LOG(SG_INPUT, SG_ALERT, "Failed to load xml: "
249                    << t.getFormattedMessage());
250             throw;
251         }
252         if (overlay)
253             copyProperties(overlay, props);
254
255         if (props->hasValue("/path")) {
256             string modelPathStr = props->getStringValue("/path");
257             modelpath = SGModelLib::findDataFile(modelPathStr, NULL, modelDir);
258             if (modelpath.isNull())
259                 throw sg_io_exception("Model file not found: '" + modelPathStr + "'",
260                         path.str());
261
262             if (props->hasValue("/texture-path")) {
263                 string texturePathStr = props->getStringValue("/texture-path");
264                 if (!texturePathStr.empty())
265                 {
266                     texturepath = SGModelLib::findDataFile(texturePathStr, NULL, modelDir);
267                     if (texturepath.isNull())
268                         throw sg_io_exception("Texture file not found: '" + texturePathStr + "'",
269                                 path.str());
270                 }
271             }
272         } else {
273             model = new osg::Node;
274         }
275
276         SGPropertyNode *mp = props->getNode("multiplay");
277         if (mp && prop_root && prop_root->getParent())
278             copyProperties(mp, prop_root);
279     } else {
280         // model without wrapper
281     }
282
283     // Assume that textures are in
284     // the same location as the XML file.
285     if (!model) {
286         if (!texturepath.extension().empty())
287             texturepath = texturepath.dir();
288
289         options->setDatabasePath(texturepath.str());
290         osgDB::ReaderWriter::ReadResult modelResult;
291         modelResult = osgDB::readNodeFile(modelpath.str(), options.get());
292         if (!modelResult.validNode())
293             throw sg_io_exception("Failed to load 3D model:" + modelResult.message(),
294                                   modelpath.str());
295         model = copyModel(modelResult.getNode());
296         // Add an extra reference to the model stored in the database.
297         // That is to avoid expiring the object from the cache even if
298         // it is still in use. Note that the object cache will think
299         // that a model is unused if the reference count is 1. If we
300         // clone all structural nodes here we need that extra
301         // reference to the original object
302         SGDatabaseReference* databaseReference;
303         databaseReference = new SGDatabaseReference(modelResult.getNode());
304         model->addObserver(databaseReference);
305
306         // Update liveries
307         TextureUpdateVisitor liveryUpdate(options->getDatabasePathList());
308         model->accept(liveryUpdate);
309
310         // Copy the userdata fields, still sharing the boundingvolumes,
311         // but introducing new data for velocities.
312         UserDataCopyVisitor userDataCopyVisitor;
313         model->accept(userDataCopyVisitor);
314     }
315     model->setName(modelpath.str());
316
317     bool needTransform=false;
318     // Set up the alignment node if needed
319     SGPropertyNode *offsets = props->getNode("offsets", false);
320     if (offsets) {
321         needTransform=true;
322         osg::MatrixTransform *alignmainmodel = new osg::MatrixTransform;
323         alignmainmodel->setDataVariance(osg::Object::STATIC);
324         osg::Matrix res_matrix;
325         res_matrix.makeRotate(
326             offsets->getFloatValue("pitch-deg", 0.0)*SG_DEGREES_TO_RADIANS,
327             osg::Vec3(0, 1, 0),
328             offsets->getFloatValue("roll-deg", 0.0)*SG_DEGREES_TO_RADIANS,
329             osg::Vec3(1, 0, 0),
330             offsets->getFloatValue("heading-deg", 0.0)*SG_DEGREES_TO_RADIANS,
331             osg::Vec3(0, 0, 1));
332
333         osg::Matrix tmat;
334         tmat.makeTranslate(offsets->getFloatValue("x-m", 0.0),
335                            offsets->getFloatValue("y-m", 0.0),
336                            offsets->getFloatValue("z-m", 0.0));
337         alignmainmodel->setMatrix(res_matrix*tmat);
338         group = alignmainmodel;
339     }
340     if (!group) {
341         group = new osg::Group;
342     }
343     group->addChild(model.get());
344
345     // Load sub-models
346     vector<SGPropertyNode_ptr> model_nodes = props->getChildren("model");
347     for (unsigned i = 0; i < model_nodes.size(); i++) {
348         SGPropertyNode_ptr sub_props = model_nodes[i];
349
350         SGPath submodelpath;
351         osg::ref_ptr<osg::Node> submodel;
352         
353         string subPathStr = sub_props->getStringValue("path");
354         SGPath submodelPath = SGModelLib::findDataFile(subPathStr, 
355           NULL, modelDir);
356
357         if (submodelPath.isNull()) {
358           SG_LOG(SG_INPUT, SG_ALERT, "Failed to load file: \"" << subPathStr << "\"");
359           continue;
360         }
361
362         try {
363             submodel = sgLoad3DModel_internal(submodelPath, options.get(),
364                                               sub_props->getNode("overlay"));
365         } catch (const sg_exception &t) {
366             SG_LOG(SG_INPUT, SG_ALERT, "Failed to load submodel: " << t.getFormattedMessage()
367               << "\n\tfrom:" << t.getOrigin());
368             continue;
369         }
370
371         osg::ref_ptr<osg::Node> submodel_final = submodel;
372         SGPropertyNode *offs = sub_props->getNode("offsets", false);
373         if (offs) {
374             osg::Matrix res_matrix;
375             osg::ref_ptr<osg::MatrixTransform> align = new osg::MatrixTransform;
376             align->setDataVariance(osg::Object::STATIC);
377             res_matrix.makeIdentity();
378             res_matrix.makeRotate(
379                 offs->getDoubleValue("pitch-deg", 0.0)*SG_DEGREES_TO_RADIANS,
380                 osg::Vec3(0, 1, 0),
381                 offs->getDoubleValue("roll-deg", 0.0)*SG_DEGREES_TO_RADIANS,
382                 osg::Vec3(1, 0, 0),
383                 offs->getDoubleValue("heading-deg", 0.0)*SG_DEGREES_TO_RADIANS,
384                 osg::Vec3(0, 0, 1));
385
386             osg::Matrix tmat;
387             tmat.makeIdentity();
388             tmat.makeTranslate(offs->getDoubleValue("x-m", 0),
389                                offs->getDoubleValue("y-m", 0),
390                                offs->getDoubleValue("z-m", 0));
391             align->setMatrix(res_matrix*tmat);
392             align->addChild(submodel.get());
393             submodel_final = align;
394         }
395         submodel_final->setName(sub_props->getStringValue("name", ""));
396
397         SGPropertyNode *cond = sub_props->getNode("condition", false);
398         if (cond) {
399             osg::ref_ptr<osg::Switch> sw = new osg::Switch;
400             sw->setUpdateCallback(new SGSwitchUpdateCallback(sgReadCondition(prop_root, cond)));
401             group->addChild(sw.get());
402             sw->addChild(submodel_final.get());
403             sw->setName("submodel condition switch");
404         } else {
405             group->addChild(submodel_final.get());
406         }
407     } // end of submodel loading
408
409     osg::Node *(*load_panel)(SGPropertyNode *) = options->getLoadPanel();
410     if ( load_panel ) {
411         // Load panels
412         vector<SGPropertyNode_ptr> panel_nodes = props->getChildren("panel");
413         for (unsigned i = 0; i < panel_nodes.size(); i++) {
414             SG_LOG(SG_INPUT, SG_DEBUG, "Loading a panel");
415             osg::ref_ptr<osg::Node> panel = load_panel(panel_nodes[i]);
416             if (panel_nodes[i]->hasValue("name"))
417                 panel->setName(panel_nodes[i]->getStringValue("name"));
418             group->addChild(panel.get());
419         }
420     }
421
422     if (dbOptions->getPluginStringData("SimGear::PARTICLESYSTEM") != "OFF") {
423         std::vector<SGPropertyNode_ptr> particle_nodes;
424         particle_nodes = props->getChildren("particlesystem");
425         for (unsigned i = 0; i < particle_nodes.size(); ++i) {
426             osg::ref_ptr<SGReaderWriterOptions> options2;
427             options2 = new SGReaderWriterOptions(*options);
428             if (i==0) {
429                 if (!texturepath.extension().empty())
430                     texturepath = texturepath.dir();
431                 
432                 options2->setDatabasePath(texturepath.str());
433             }
434             group->addChild(Particles::appendParticles(particle_nodes[i],
435                                                        prop_root,
436                                                        options2.get()));
437         }
438     }
439
440     std::vector<SGPropertyNode_ptr> text_nodes;
441     text_nodes = props->getChildren("text");
442     for (unsigned i = 0; i < text_nodes.size(); ++i) {
443         group->addChild(SGText::appendText(text_nodes[i],
444                         prop_root,
445                         options.get()));
446     }
447
448     PropertyList effect_nodes = props->getChildren("effect");
449     PropertyList animation_nodes = props->getChildren("animation");
450     // Some material animations (eventually all) are actually effects.
451     makeEffectAnimations(animation_nodes, effect_nodes);
452     {
453         ref_ptr<Node> modelWithEffects
454             = instantiateEffects(group.get(), effect_nodes, options.get());
455         group = static_cast<Group*>(modelWithEffects.get());
456     }
457
458     SGSetNodeMaskVisitor snmv(0, simgear::MODELLIGHT_BIT);
459     group->accept(snmv);
460     for (unsigned i = 0; i < animation_nodes.size(); ++i)
461         /// OSGFIXME: duh, why not only model?????
462         SGAnimation::animate(group.get(), animation_nodes[i], prop_root,
463                              options.get(), path.str(), i);
464
465     if (!needTransform && group->getNumChildren() < 2) {
466         model = group->getChild(0);
467         group->removeChild(model.get());
468         if (data.valid())
469             data->modelLoaded(modelpath.str(), props, model.get());
470         return model.release();
471     }
472     if (data.valid())
473         data->modelLoaded(modelpath.str(), props, group.get());
474     if (props->hasChild("debug-outfile")) {
475         std::string outputfile = props->getStringValue("debug-outfile",
476                                  "debug-model.osg");
477         osgDB::writeNodeFile(*group, outputfile);
478     }
479
480     return group.release();
481 }
482