1 // Copyright (C) 2007 Tim Moore timoore@redhat.com
2 // Copyright (C) 2008 Till Busch buti@bux.at
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.
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.
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.
20 # include <simgear_config.h>
23 #include <osg/MatrixTransform>
24 #include <osgDB/WriteFile>
25 #include <osgDB/Registry>
27 #include <osgDB/FileNameUtils>
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>
36 #include "modellib.hxx"
37 #include "SGPagedLOD.hxx"
38 #include "SGReaderWriterXML.hxx"
39 #include "SGReaderWriterXMLOptions.hxx"
41 #include "animation.hxx"
42 #include "particles.hxx"
46 using namespace simgear;
49 sgLoad3DModel_internal(const std::string& path,
50 const osgDB::ReaderWriter::Options* options,
51 SGPropertyNode *overlay = 0);
54 SGReaderWriterXML::SGReaderWriterXML()
56 supportsExtension("xml", "SimGear xml database format");
59 SGReaderWriterXML::~SGReaderWriterXML()
63 const char* SGReaderWriterXML::className() const
65 return "XML database reader";
68 osgDB::ReaderWriter::ReadResult
69 SGReaderWriterXML::readNode(const std::string& fileName,
70 const osgDB::ReaderWriter::Options* options) const
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());
82 return ReadResult::FILE_NOT_HANDLED;
85 class SGSwitchUpdateCallback : public osg::NodeCallback
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);
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.
101 s->setAllChildrenOff();
105 SGSharedPtr<SGCondition> mCondition;
109 // Little helper class that holds an extra reference to a
111 // Since we clone all structural nodes from our 3d models,
112 // the database pager will only see one single reference to
113 // top node of the model and expire it relatively fast.
114 // We attach that extra reference to every model cloned from
115 // a base model in the pager. When that cloned model is deleted
116 // this extra reference is deleted too. So if there are no
117 // cloned models left the model will expire.
119 class SGDatabaseReference : public osg::Observer
122 SGDatabaseReference(osg::Referenced* referenced) :
123 mReferenced(referenced)
125 virtual void objectDeleted(void*)
130 osg::ref_ptr<osg::Referenced> mReferenced;
135 sgLoad3DModel_internal(const string &path,
136 const osgDB::ReaderWriter::Options* options_,
137 SGPropertyNode *overlay)
139 const SGReaderWriterXMLOptions* xmlOptions;
140 xmlOptions = dynamic_cast<const SGReaderWriterXMLOptions*>(options_);
142 SGSharedPtr<SGPropertyNode> prop_root;
143 osg::Node *(*load_panel)(SGPropertyNode *)=0;
144 osg::ref_ptr<SGModelData> data;
147 prop_root = xmlOptions->getPropRoot();
148 load_panel = xmlOptions->getLoadPanel();
149 data = xmlOptions->getModelData();
152 prop_root = new SGPropertyNode;
155 osgDB::FilePathList filePathList;
156 filePathList = osgDB::Registry::instance()->getDataFilePathList();
157 filePathList.push_front(std::string());
159 SGPath modelpath = osgDB::findFileInPath(path, filePathList);
160 if (modelpath.str().empty()) {
161 SG_LOG(SG_INPUT, SG_ALERT, "Failed to load file: \"" << path << "\"");
164 SGPath texturepath = modelpath;
166 osg::ref_ptr<osg::Node> model;
167 osg::ref_ptr<osg::Group> group;
168 SGPropertyNode_ptr props = new SGPropertyNode;
170 // Check for an XML wrapper
171 if (modelpath.extension() == "xml") {
173 readProperties(modelpath.str(), props);
174 } catch (const sg_throwable &t) {
175 SG_LOG(SG_INPUT, SG_ALERT, "Failed to load xml: "
176 << t.getFormattedMessage());
180 copyProperties(overlay, props);
182 if (props->hasValue("/path")) {
183 modelpath = modelpath.dir();
184 modelpath.append(props->getStringValue("/path"));
185 if (props->hasValue("/texture-path")) {
186 texturepath = texturepath.dir();
187 texturepath.append(props->getStringValue("/texture-path"));
190 model = new osg::Node;
193 SGPropertyNode *mp = props->getNode("multiplay");
194 if (mp && prop_root && prop_root->getParent())
195 copyProperties(mp, prop_root);
198 osg::ref_ptr<SGReaderWriterXMLOptions> options
199 = new SGReaderWriterXMLOptions(*options_);
200 options->setPropRoot(prop_root);
201 options->setLoadPanel(load_panel);
203 // Assume that textures are in
204 // the same location as the XML file.
206 if (!texturepath.extension().empty())
207 texturepath = texturepath.dir();
209 options->setDatabasePath(texturepath.str());
211 = osgDB::readNodeFile(modelpath.str(), options.get());
214 throw sg_io_exception("Failed to load 3D model",
215 sg_location(modelpath.str()));
216 model = copyModel(origModel);
217 // Add an extra reference to the model stored in the database.
218 // That is to avoid expiring the object from the cache even if
219 // it is still in use. Note that the object cache will think
220 // that a model is unused if the reference count is 1. If we
221 // clone all structural nodes here we need that extra
222 // reference to the original object
223 SGDatabaseReference* databaseReference;
224 databaseReference = new SGDatabaseReference(origModel);
225 model->addObserver(databaseReference);
228 TextureUpdateVisitor liveryUpdate(options->getDatabasePathList());
229 model->accept(liveryUpdate);
231 // Copy the userdata fields, still sharing the boundingvolumes,
232 // but introducing new data for velocities.
233 UserDataCopyVisitor userDataCopyVisitor;
234 model->accept(userDataCopyVisitor);
236 model->setName(modelpath.str());
238 bool needTransform=false;
239 // Set up the alignment node if needed
240 SGPropertyNode *offsets = props->getNode("offsets", false);
243 osg::MatrixTransform *alignmainmodel = new osg::MatrixTransform;
244 alignmainmodel->setDataVariance(osg::Object::STATIC);
245 osg::Matrix res_matrix;
246 res_matrix.makeRotate(
247 offsets->getFloatValue("pitch-deg", 0.0)*SG_DEGREES_TO_RADIANS,
249 offsets->getFloatValue("roll-deg", 0.0)*SG_DEGREES_TO_RADIANS,
251 offsets->getFloatValue("heading-deg", 0.0)*SG_DEGREES_TO_RADIANS,
255 tmat.makeTranslate(offsets->getFloatValue("x-m", 0.0),
256 offsets->getFloatValue("y-m", 0.0),
257 offsets->getFloatValue("z-m", 0.0));
258 alignmainmodel->setMatrix(res_matrix*tmat);
259 group = alignmainmodel;
262 group = new osg::Group;
264 group->addChild(model.get());
267 vector<SGPropertyNode_ptr> model_nodes = props->getChildren("model");
268 for (unsigned i = 0; i < model_nodes.size(); i++) {
269 SGPropertyNode_ptr sub_props = model_nodes[i];
272 osg::ref_ptr<osg::Node> submodel;
273 string submodelFileName = sub_props->getStringValue("path");
274 if ( submodelFileName.size() > 2 && submodelFileName.substr( 0, 2 ) == "./" ) {
275 submodelpath = modelpath.dir();
276 submodelpath.append( submodelFileName.substr( 2 ) );
278 submodelpath = submodelFileName;
280 osg::ref_ptr<SGReaderWriterXMLOptions> options;
281 options = new SGReaderWriterXMLOptions(*options_);
282 options->setPropRoot(prop_root);
283 options->setLoadPanel(load_panel);
285 submodel = sgLoad3DModel_internal(submodelpath.str(), options.get(),
286 sub_props->getNode("overlay"));
287 } catch (const sg_throwable &t) {
288 SG_LOG(SG_INPUT, SG_ALERT, "Failed to load submodel: " << t.getFormattedMessage());
292 osg::ref_ptr<osg::Node> submodel_final=submodel.get();
293 SGPropertyNode *offs = sub_props->getNode("offsets", false);
295 osg::Matrix res_matrix;
296 osg::ref_ptr<osg::MatrixTransform> align = new osg::MatrixTransform;
297 align->setDataVariance(osg::Object::STATIC);
298 res_matrix.makeIdentity();
299 res_matrix.makeRotate(
300 offs->getDoubleValue("pitch-deg", 0.0)*SG_DEGREES_TO_RADIANS,
302 offs->getDoubleValue("roll-deg", 0.0)*SG_DEGREES_TO_RADIANS,
304 offs->getDoubleValue("heading-deg", 0.0)*SG_DEGREES_TO_RADIANS,
309 tmat.makeTranslate(offs->getDoubleValue("x-m", 0),
310 offs->getDoubleValue("y-m", 0),
311 offs->getDoubleValue("z-m", 0));
312 align->setMatrix(res_matrix*tmat);
313 align->addChild(submodel.get());
314 submodel_final=align.get();
316 submodel_final->setName(sub_props->getStringValue("name", ""));
318 SGPropertyNode *cond = sub_props->getNode("condition", false);
320 osg::ref_ptr<osg::Switch> sw = new osg::Switch;
321 sw->setUpdateCallback(new SGSwitchUpdateCallback(sgReadCondition(prop_root, cond)));
322 group->addChild(sw.get());
323 sw->addChild(submodel_final.get());
324 sw->setName("submodel condition switch");
326 group->addChild(submodel_final.get());
328 } // end of submodel loading
332 vector<SGPropertyNode_ptr> panel_nodes = props->getChildren("panel");
333 for (unsigned i = 0; i < panel_nodes.size(); i++) {
334 SG_LOG(SG_INPUT, SG_DEBUG, "Loading a panel");
335 osg::ref_ptr<osg::Node> panel = load_panel(panel_nodes[i]);
336 if (panel_nodes[i]->hasValue("name"))
337 panel->setName(panel_nodes[i]->getStringValue("name"));
338 group->addChild(panel.get());
342 std::vector<SGPropertyNode_ptr> particle_nodes;
343 particle_nodes = props->getChildren("particlesystem");
344 for (unsigned i = 0; i < particle_nodes.size(); ++i) {
346 if (!texturepath.extension().empty())
347 texturepath = texturepath.dir();
349 options->setDatabasePath(texturepath.str());
351 group->addChild(Particles::appendParticles(particle_nodes[i],
356 std::vector<SGPropertyNode_ptr> text_nodes;
357 text_nodes = props->getChildren("text");
358 for (unsigned i = 0; i < text_nodes.size(); ++i) {
359 group->addChild(SGText::appendText(text_nodes[i],
364 std::vector<SGPropertyNode_ptr> animation_nodes;
365 animation_nodes = props->getChildren("animation");
366 for (unsigned i = 0; i < animation_nodes.size(); ++i)
367 /// OSGFIXME: duh, why not only model?????
368 SGAnimation::animate(group.get(), animation_nodes[i], prop_root,
371 if (!needTransform && group->getNumChildren() < 2) {
372 model = group->getChild(0);
373 group->removeChild(model.get());
375 data->modelLoaded(modelpath.str(), props, model.get());
376 return model.release();
379 data->modelLoaded(modelpath.str(), props, group.get());
380 if (props->hasChild("debug-outfile")) {
381 std::string outputfile = props->getStringValue("debug-outfile",
383 osgDB::writeNodeFile(*group, outputfile);
386 return group.release();