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