]> git.mxchange.org Git - simgear.git/blob - simgear/scene/model/SGReaderWriterXML.cxx
Invent a property root if not given in the options struct.
[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 <osg/MatrixTransform>
24 #include <osgDB/WriteFile>
25 #include <osgDB/Registry>
26 #include <osg/Switch>
27 #include <osgDB/FileNameUtils>
28
29 #include <simgear/compiler.h>
30 #include <simgear/structure/exception.hxx>
31 #include <simgear/props/props.hxx>
32 #include <simgear/props/props_io.hxx>
33 #include <simgear/props/condition.hxx>
34 #include <simgear/scene/util/SGNodeMasks.hxx>
35
36 #include "modellib.hxx"
37 #include "SGPagedLOD.hxx"
38 #include "SGReaderWriterXML.hxx"
39 #include "SGReaderWriterXMLOptions.hxx"
40
41 #include "animation.hxx"
42 #include "particles.hxx"
43 #include "model.hxx"
44
45 #include "SGReaderWriterXMLOptions.hxx"
46 #include "SGReaderWriterXML.hxx"
47
48 using namespace simgear;
49
50 static osg::Node *
51 sgLoad3DModel_internal(const string &path,
52                        SGPropertyNode *prop_root,
53                        SGModelData *data = 0,
54                        osg::Node *(*load_panel)(SGPropertyNode *) = 0,
55                        SGPropertyNode *overlay = 0);
56
57
58 SGReaderWriterXML::SGReaderWriterXML()
59 {
60     supportsExtension("xml", "SimGear xml database format");
61 }
62
63 SGReaderWriterXML::~SGReaderWriterXML()
64 {
65 }
66
67 const char* SGReaderWriterXML::className() const
68 {
69     return "XML database reader";
70 }
71
72 osgDB::ReaderWriter::ReadResult
73 SGReaderWriterXML::readNode(const std::string& fileName,
74                             const osgDB::ReaderWriter::Options* options) const
75 {
76     // SG_LOG(SG_GENERAL, SG_ALERT, "SGReaderWriterXML::readNode(" << fileName << ")");
77
78     const SGReaderWriterXMLOptions* xmlOptions
79     = dynamic_cast<const SGReaderWriterXMLOptions*>(options);
80
81     string fg_root;
82     SGSharedPtr<SGPropertyNode> prop_root;
83     osg::Node *(*load_panel)(SGPropertyNode *)=0;
84     SGModelData *model_data=0;
85     SGPath externalTexturePath;
86
87     if (xmlOptions) {
88         prop_root = xmlOptions->getPropRoot();
89         load_panel = xmlOptions->getLoadPanel();
90         model_data = xmlOptions->getModelData();
91     }
92     if (!prop_root) {
93         prop_root = new SGPropertyNode;
94     }
95
96     fg_root=osgDB::Registry::instance()->getDataFilePathList().front();
97
98     osg::Node *result=0;
99
100     try {
101         result=sgLoad3DModel_internal(fileName, prop_root, model_data, load_panel);
102     } catch (const sg_throwable &t) {
103         SG_LOG(SG_INPUT, SG_ALERT, "Failed to load model: " << t.getFormattedMessage());
104         result=new osg::Node;
105     }
106     if (result)
107         return result;
108     else
109         return ReadResult::FILE_NOT_HANDLED;
110 }
111
112 class SGSwitchUpdateCallback : public osg::NodeCallback
113 {
114 public:
115     SGSwitchUpdateCallback(SGCondition* condition) :
116             mCondition(condition) {}
117     virtual void operator()(osg::Node* node, osg::NodeVisitor* nv) {
118         assert(dynamic_cast<osg::Switch*>(node));
119         osg::Switch* s = static_cast<osg::Switch*>(node);
120
121         if (mCondition && mCondition->test()) {
122             s->setAllChildrenOn();
123             // note, callback is responsible for scenegraph traversal so
124             // should always include call traverse(node,nv) to ensure
125             // that the rest of cullbacks and the scene graph are traversed.
126             traverse(node, nv);
127         } else
128             s->setAllChildrenOff();
129     }
130
131 private:
132     SGSharedPtr<SGCondition> mCondition;
133 };
134
135 static osg::Node *
136 sgLoad3DModel_internal(const string &path,
137                        SGPropertyNode *prop_root,
138                        SGModelData *data,
139                        osg::Node *(*load_panel)(SGPropertyNode *),
140                        SGPropertyNode *overlay)
141 {
142     if ( !prop_root ) {
143         SG_LOG(SG_GENERAL, SG_ALERT, "prop_root NULL: " << path);
144     }
145
146     string fg_root=osgDB::Registry::instance()->getDataFilePathList().front();
147     osg::ref_ptr<osg::Node> model;
148     osg::ref_ptr<osg::Group> group;
149     SGPropertyNode_ptr props = new SGPropertyNode;
150
151     // Load the 3D object itself
152     SGPath modelpath = path, texturepath = path;
153     if ( !ulIsAbsolutePathName( path.c_str() ) ) {
154         SGPath tmp = fg_root;
155         tmp.append(modelpath.str());
156         modelpath = texturepath = tmp;
157     }
158
159     // Check for an XML wrapper
160     if (modelpath.str().substr(modelpath.str().size() - 4, 4) == ".xml") {
161         try {
162             readProperties(modelpath.str(), props);
163         } catch (const sg_throwable &t) {
164             SG_LOG(SG_INPUT, SG_ALERT, "Failed to load xml: " << t.getFormattedMessage());
165             throw;
166         }
167         if (overlay)
168             copyProperties(overlay, props);
169
170         if (props->hasValue("/path")) {
171             modelpath = modelpath.dir();
172             modelpath.append(props->getStringValue("/path"));
173             if (props->hasValue("/texture-path")) {
174                 texturepath = texturepath.dir();
175                 texturepath.append(props->getStringValue("/texture-path"));
176             }
177         } else {
178             model = new osg::Node;
179         }
180
181         SGPropertyNode *mp = props->getNode("multiplay");
182         if (mp && prop_root && prop_root->getParent())
183             copyProperties(mp, prop_root);
184     }
185
186     osg::ref_ptr<SGReaderWriterXMLOptions> options
187     = new SGReaderWriterXMLOptions(*osgDB::Registry::instance()->getOptions());
188
189     // Assume that textures are in
190     // the same location as the XML file.
191     if (!model) {
192         if (texturepath.extension() != "")
193             texturepath = texturepath.dir();
194
195         options->setDatabasePath(texturepath.str());
196         model = osgDB::readNodeFile(modelpath.str(), options.get());
197         if (model == 0)
198             throw sg_io_exception("Failed to load 3D model",
199                                   sg_location(modelpath.str()));
200     }
201     model->setName(modelpath.str());
202
203     bool needTransform=false;
204     // Set up the alignment node if needed
205     SGPropertyNode *offsets = props->getNode("offsets", false);
206     if (offsets) {
207         needTransform=true;
208         osg::MatrixTransform *alignmainmodel = new osg::MatrixTransform;
209         osg::Matrix res_matrix;
210         res_matrix.makeRotate(
211             offsets->getFloatValue("pitch-deg", 0.0)*SG_DEGREES_TO_RADIANS,
212             osg::Vec3(0, 1, 0),
213             offsets->getFloatValue("roll-deg", 0.0)*SG_DEGREES_TO_RADIANS,
214             osg::Vec3(1, 0, 0),
215             offsets->getFloatValue("heading-deg", 0.0)*SG_DEGREES_TO_RADIANS,
216             osg::Vec3(0, 0, 1));
217
218         osg::Matrix tmat;
219         tmat.makeTranslate(offsets->getFloatValue("x-m", 0.0),
220                            offsets->getFloatValue("y-m", 0.0),
221                            offsets->getFloatValue("z-m", 0.0));
222         alignmainmodel->setMatrix(res_matrix*tmat);
223         group = alignmainmodel;
224     }
225     if (!group) {
226         group = new osg::Group;
227     }
228     group->addChild(model.get());
229
230     // Load sub-models
231     vector<SGPropertyNode_ptr> model_nodes = props->getChildren("model");
232     for (unsigned i = 0; i < model_nodes.size(); i++) {
233         SGPropertyNode_ptr sub_props = model_nodes[i];
234
235         SGPath submodelpath;
236         osg::ref_ptr<osg::Node> submodel;
237         string submodelFileName = sub_props->getStringValue("path");
238         if ( submodelFileName.size() > 2 && submodelFileName.substr( 0, 2 ) == "./" ) {
239             submodelpath = modelpath.dir();
240             submodelpath.append( submodelFileName.substr( 2 ) );
241         } else {
242             submodelpath = submodelFileName;
243         }
244         try {
245             submodel = sgLoad3DModel_internal(submodelpath.str(), prop_root, 0, load_panel,
246                                               sub_props->getNode("overlay"));
247         } catch (const sg_throwable &t) {
248             SG_LOG(SG_INPUT, SG_ALERT, "Failed to load submodel: " << t.getFormattedMessage());
249             throw;
250         }
251
252         osg::ref_ptr<osg::Node> submodel_final=submodel.get();
253         SGPropertyNode *offs = sub_props->getNode("offsets", false);
254         if (offs) {
255             osg::Matrix res_matrix;
256             osg::ref_ptr<osg::MatrixTransform> align = new osg::MatrixTransform;
257             res_matrix.makeIdentity();
258             res_matrix.makeRotate(
259                 offs->getDoubleValue("pitch-deg", 0.0)*SG_DEGREES_TO_RADIANS,
260                 osg::Vec3(0, 1, 0),
261                 offs->getDoubleValue("roll-deg", 0.0)*SG_DEGREES_TO_RADIANS,
262                 osg::Vec3(1, 0, 0),
263                 offs->getDoubleValue("heading-deg", 0.0)*SG_DEGREES_TO_RADIANS,
264                 osg::Vec3(0, 0, 1));
265
266             osg::Matrix tmat;
267             tmat.makeIdentity();
268             tmat.makeTranslate(offs->getDoubleValue("x-m", 0),
269                                offs->getDoubleValue("y-m", 0),
270                                offs->getDoubleValue("z-m", 0));
271             align->setMatrix(res_matrix*tmat);
272             align->addChild(submodel.get());
273             submodel_final=align.get();
274         }
275         submodel_final->setName(sub_props->getStringValue("name", ""));
276
277         SGPropertyNode *cond = sub_props->getNode("condition", false);
278         if (cond) {
279             osg::ref_ptr<osg::Switch> sw = new osg::Switch;
280             sw->setUpdateCallback(new SGSwitchUpdateCallback(sgReadCondition(prop_root, cond)));
281             group->addChild(sw.get());
282             sw->addChild(submodel_final.get());
283             sw->setName("submodel condition switch");
284         } else {
285             group->addChild(submodel_final.get());
286         }
287     } // end of submodel loading
288
289     if ( load_panel ) {
290         // Load panels
291         vector<SGPropertyNode_ptr> panel_nodes = props->getChildren("panel");
292         for (unsigned i = 0; i < panel_nodes.size(); i++) {
293             SG_LOG(SG_INPUT, SG_DEBUG, "Loading a panel");
294             osg::ref_ptr<osg::Node> panel = load_panel(panel_nodes[i]);
295             if (panel_nodes[i]->hasValue("name"))
296                 panel->setName((char *)panel_nodes[i]->getStringValue("name"));
297             group->addChild(panel.get());
298         }
299     }
300
301     std::vector<SGPropertyNode_ptr> particle_nodes;
302     particle_nodes = props->getChildren("particlesystem");
303     for (unsigned i = 0; i < particle_nodes.size(); ++i) {
304         if (i==0) {
305             if (texturepath.extension() != "")
306                 texturepath = texturepath.dir();
307
308             options->setDatabasePath(texturepath.str());
309         }
310         group->addChild(Particles::appendParticles(particle_nodes[i],
311                         prop_root,
312                         options.get()));
313     }
314
315     if (data) {
316         data->setProps(props);
317         options->setModelData(data);
318     }
319
320     std::vector<SGPropertyNode_ptr> animation_nodes;
321     animation_nodes = props->getChildren("animation");
322     for (unsigned i = 0; i < animation_nodes.size(); ++i)
323         /// OSGFIXME: duh, why not only model?????
324         SGAnimation::animate(group.get(), animation_nodes[i], prop_root,
325                              options.get());
326
327     if (props->hasChild("debug-outfile")) {
328         std::string outputfile = props->getStringValue("debug-outfile",
329                                  "debug-model.osg");
330         osgDB::writeNodeFile(*group, outputfile);
331     }
332     if (!needTransform && group->getNumChildren() < 2) {
333         model = group->getChild(0);
334         group->removeChild(model.get());
335         model->setUserData(group->getUserData());
336         return model.release();
337     }
338
339     return group.release();
340 }
341