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