forked from jefftrull/ColladaOgreImporter
-
Notifications
You must be signed in to change notification settings - Fork 3
/
OgreSceneWriter.cpp
352 lines (301 loc) · 15.9 KB
/
OgreSceneWriter.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
// Implementation of Collada to Ogre translation
// Author: Jeff Trull <[email protected]>
/*
Copyright (c) 2010 Aditazz, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <boost/filesystem.hpp>
#include <boost/lexical_cast.hpp>
#include <COLLADABUURI.h>
#include <COLLADAFWCamera.h>
#include <COLLADAFWMesh.h>
#include <COLLADAFWNode.h>
#include <COLLADAFWEffectCommon.h>
#include <OgreLogManager.h>
#include <OgreManualObject.h>
#include <OgreMatrix4.h>
#include <OgreEntity.h>
#include <OgreSubEntity.h>
#include <OgreMesh.h>
#include <OgreSceneNode.h>
#include <OgreCamera.h>
#include "OgreSceneWriter.h"
OgreCollada::SceneWriter::SceneWriter(Ogre::SceneManager* mgr,
Ogre::SceneNode* topnode,
const Ogre::String& dir) : Writer(dir, 0, false, false),
m_topNode(topnode), m_sceneMgr(mgr) {}
OgreCollada::SceneWriter::~SceneWriter() {}
bool OgreCollada::SceneWriter::writeCamera(const COLLADAFW::Camera* camera) {
m_cameras.insert(std::make_pair(camera->getUniqueId(), *camera));
return true;
}
bool OgreCollada::SceneWriter::writeGeometry(const COLLADAFW::Geometry* g) {
if (m_calculateGeometryStats) {
// remember this for later use
m_geometryNames.insert(std::make_pair(g->getUniqueId(), g->getOriginalId()));
m_geometryInstanceCounts.insert(std::make_pair(g->getUniqueId(), 0));
m_geometryLineCounts.insert(std::make_pair(g->getUniqueId(), 0));
m_geometryTriangleCounts.insert(std::make_pair(g->getUniqueId(), 0));
}
if (g->getType() != COLLADAFW::Geometry::GEO_TYPE_MESH) {
Ogre::String geotype;
if (g->getType() == COLLADAFW::Geometry::GEO_TYPE_SPLINE) {
geotype = "spline";
} else if (g->getType() == COLLADAFW::Geometry::GEO_TYPE_CONVEX_MESH) {
geotype = "convex mesh";
} else {
geotype = "unknown";
}
LOG_DEBUG("COLLADA WARNING: writeGeometry called on type " + geotype + ", which is not supported. Skipping)");
return false;
}
// create a mesh object out of this Geometry
// After a lot of experimenting it seems like the "ManualObject" flow is the way to go.
// I had initially avoided it because it didn't allow vertex sharing among submeshes.
// However, I've discovered that such sharing may be impossible anyway, because Collada
// has this mixed-index thing where a pair of indices (e.g., vertex/texture index) can reference
// an arbitrary vertex position/normal out of one set of (Collada) vertices and a texture coordinate
// out of another. Ogre wants a single index and a single vertex buffer, so you have to make a mapping
// from the Collada pair (triple, quad...) to the Ogre index, and create a single vertex buffer for it
// to reference with all the possible combinations expanded, which means NO SHARING. So let's use the
// simpler interface for clarity. (we still have to flatten the index tuples)
Ogre::ManualObject* manobj = new Ogre::ManualObject(g->getOriginalId() + "_mobj");
const COLLADAFW::Mesh* cmesh = dynamic_cast<const COLLADAFW::Mesh*>(g);
// do some estimating of ultimate sizes, for performance
manobj->estimateVertexCount(cmesh->getPositions().getValuesCount());
int index_count = 0;
for (int prim = 0, count = cmesh->getMeshPrimitives().getCount(); prim < count; ++prim) {
index_count += cmesh->getMeshPrimitives()[prim]->getPositionIndices().getCount();
}
manobj->estimateIndexCount(index_count); // probably more than this, actually...
if (!addGeometry(g, manobj)) {
LOG_DEBUG("Could not find valid submesh to create, so not creating the parent mesh");
return true; // make this harmless - for now
}
// convert manual object to mesh
Ogre::MeshPtr mesh = manobj->convertToMesh(g->getOriginalId());
// record materials information for later reference
for (int i = 0, count = cmesh->getMeshPrimitives().getCount(); i < count; ++i) {
const COLLADAFW::MeshPrimitive& prim = *(cmesh->getMeshPrimitives()[i]);
m_meshmatids[mesh].push_back(prim.getMaterialId());
}
if (!mesh->isManuallyLoaded()) {
LOG_DEBUG("mesh " + mesh->getName() + " is not marked manual, for some reason. It is likely we failed to load it");
}
// store this mesh somewhere we can refer to it later (e.g. from a library instance)
m_meshMap.insert(std::make_pair(g->getUniqueId(), mesh));
return true;
}
void OgreCollada::SceneWriter::finish() {
// this is the only function we're guaranteed will be called after all the others...
// so do everything from here
createMaterials();
// GraphViz debug output
if (m_dotfn) {
std::ofstream os(m_dotfn);
if (os.is_open()) {
dump_as_dot(os);
} else {
LOG_DEBUG("Could not open dot output file " + Ogre::String(m_dotfn));
}
}
// Create an intervening "shim" scene node to handle the fact that the Collada "up" axis and that of Ogre are likely different
// This would also be a good place to introduce other transformations for the import, i.e. translation to desired location
Ogre::SceneNode* transformShimNode = m_topNode->createChildSceneNode();
transformShimNode->setOrientation(m_ColladaRotation);
transformShimNode->setScale(m_ColladaScale);
// next: (recursively) process root node associated with "visual scene" element of input
for (size_t i = 0; i < m_vsRootNodes.size(); ++i) {
createSceneDFS(m_vsRootNodes[i],
transformShimNode->createChildSceneNode(m_vsRootNodes[i]->getName()),
m_vsRootNodes[i]->getName() + ":");
}
if (m_calculateGeometryStats) {
// output geometry stats
std::vector<COLLADAFW::UniqueId> geometries;
// BOZO should use some type of function object magic here instead
for (std::map<COLLADAFW::UniqueId, int>::const_iterator icit = m_geometryInstanceCounts.begin();
icit != m_geometryInstanceCounts.end(); ++icit) {
geometries.push_back(icit->first);
}
std::sort(geometries.begin(), geometries.end(),
TriangleCountComparator(m_geometryInstanceCounts, m_geometryTriangleCounts));
LOG_DEBUG("loaded geometry data as follows:");
for (std::vector<COLLADAFW::UniqueId>::const_iterator git = geometries.begin();
git != geometries.end(); ++git) {
LOG_DEBUG(m_geometryNames[*git] +
"\t" + Ogre::StringConverter::toString(m_geometryTriangleCounts[*git]) +
"\t" + Ogre::StringConverter::toString(m_geometryLineCounts[*git]) +
"\t" + Ogre::StringConverter::toString(m_geometryInstanceCounts[*git]));
}
}
}
bool OgreCollada::SceneWriter::createSceneDFS(const COLLADAFW::Node* cn, Ogre::SceneNode* sn, const Ogre::String& prefix) {
// General algorithm (assumes Ogre scene node is already created):
// set transformation
// for each instance node, build copy of its subtree recursively, with uniquified name
// for each attached geometry, create an entity using our name prefix
// recursively handle child each node
// handle this node's transformation matrix
const COLLADAFW::TransformationPointerArray& tarr = cn->getTransformations();
if (tarr.getCount()) {
Ogre::Matrix4 xform = Ogre::Matrix4::IDENTITY; // begin with an identity transformation
for (size_t i = 0; i < tarr.getCount(); ++i) {
xform = xform * computeTransformation(tarr[i]);
}
// have to split this up into components b/c Ogre::SceneNode has no direct way to set 4x4 transform
Ogre::Vector3 position, scale;
Ogre::Quaternion orientation;
xform.decomposition(position, scale, orientation);
if (orientation.isNaN()) {
LOG_DEBUG("COLLADA WARNING: the orientation appears to be gibberish!");
} else {
sn->setOrientation(orientation);
}
sn->setPosition(position);
sn->setScale(scale);
}
// collect the different types of child nodes
const COLLADAFW::InstanceNodePointerArray& inodes = cn->getInstanceNodes();
const COLLADAFW::InstanceGeometryPointerArray& ginodes = cn->getInstanceGeometries();
const COLLADAFW::NodePointerArray& cnodes = cn->getChildNodes();
const COLLADAFW::InstanceCameraPointerArray& camnodes = cn->getInstanceCameras();
// optimization: often (in Sketchup output, anyway) a library instance is the only child of a regular scene node
// which supplies its transformation matrix. in this case we can simply make build the instance in the current node,
// rather than an added child node. This makes the hierarchy clearer and cleaner for users to navigate
// see if we can instantiate just one library node
if ((ginodes.getCount() == 0) && (cnodes.getCount() == 0) && (inodes.getCount() == 1)) {
LibNodesIterator lit = m_libNodes.find(inodes[0]->getInstanciatedObjectId());
if ((lit != m_libNodes.end()) && (lit->second->getTransformations().getCount() == 0)) {
// get the name of the referred-to library node
LibNodesIterator lit = m_libNodes.find(inodes[0]->getInstanciatedObjectId());
if (lit == m_libNodes.end()) {
LOG_DEBUG("COLLADA WARNING: could not find library node with unique ID " + Ogre::StringConverter::toString(inodes[0]->getInstanciatedObjectId()));
return false;
}
Ogre::String iname = sn->getName() + ":" + lit->second->getOriginalId();
return processLibraryInstance(inodes[0], sn, iname + ":");
}
}
// connect up library instances
for (int i = 0, count = inodes.getCount(); i < count; ++i) {
Ogre::String iname = prefix + "LibraryInstance_" + boost::lexical_cast<Ogre::String>(inodes[i]->getInstanciatedObjectId());
Ogre::SceneNode* lsn = sn->createChildSceneNode(iname);
processLibraryInstance(inodes[i], lsn, iname + ":");
}
// implement geometry instances
for (int i = 0, count = ginodes.getCount(); i < count; ++i) {
COLLADAFW::InstanceGeometry* gi = ginodes[i];
std::map<COLLADAFW::UniqueId, Ogre::MeshPtr>::const_iterator mit = m_meshMap.find(gi->getInstanciatedObjectId());
if (mit != m_meshMap.end()) {
// so load it
Ogre::MeshPtr m = mit->second;
Ogre::String ename = prefix + m->getName();
Ogre::Entity* e = m_sceneMgr->createEntity(ename, m->getName());
MeshMaterialIdMapIterator mmapit = m_meshmatids.find(m);
if (mmapit == m_meshmatids.end()) {
LOG_DEBUG("Cannot find mesh material ids for mesh " + m->getName());
continue;
}
// attach materials
const COLLADAFW::MaterialBindingArray& mba = gi->getMaterialBindings();
for (int i = 0, count = mba.getCount(); i < count; ++i) {
const COLLADAFW::MaterialBinding mb = mba[i];
// and each material binding has an array of texture bindings (!)
const COLLADAFW::TextureCoordinateBindingArray& tba = mb.getTextureCoordinateBindingArray();
for (int j = 0, tcount = tba.getCount(); j < tcount; ++j) {
const COLLADAFW::TextureCoordinateBinding& tcb = tba[j];
// BOZO seems like we should be doing something here!
(void)tcb;
}
// look up this material and make sure we can find it
MaterialMapIterator matit = m_materials.find(mb.getReferencedMaterial());
if (matit == m_materials.end()) {
LOG_DEBUG("material " + Ogre::StringConverter::toString(mb.getReferencedMaterial()) + " is not found in the stored materials");
} else {
// check that this material has been defined - TBD
const Ogre::String& matname = matit->second.first;
// go through the subentities and see which ones have this material ID
bool found_mat_match = false;
for (int j = 0, mcount = mmapit->second.size(); j < mcount; ++j) {
if (mmapit->second[j] == mb.getMaterialId()) {
e->getSubEntity(j)->setMaterialName(matname);
found_mat_match = true;
}
}
if (!found_mat_match) {
LOG_DEBUG("instance geometry " + gi->getName() + " has no subentities matching material ID " + boost::lexical_cast<Ogre::String>(mb.getMaterialId()) + " for material name " + matname);
}
}
}
sn->attachObject(e);
if (m_calculateGeometryStats) {
// stats
if (m_geometryInstanceCounts.find(gi->getInstanciatedObjectId()) != m_geometryInstanceCounts.end()) {
m_geometryInstanceCounts[gi->getInstanciatedObjectId()]++;
} else {
LOG_DEBUG("cannot find instanciated object of unique id " + boost::lexical_cast<Ogre::String>(gi->getInstanciatedObjectId()) + " for counting");
}
}
} else {
LOG_DEBUG("Geometry instance with object id " + boost::lexical_cast<std::string>(gi->getInstanciatedObjectId()) + " is NOT a mesh we know about");
}
}
// instantiate/attach cameras
for (int i = 0, count = camnodes.getCount(); i < count; ++i) {
// verify we have recorded this one previously
auto const & camit = m_cameras.find(camnodes[i]->getInstanciatedObjectId());
if (camit == m_cameras.end()) {
std::cerr << "COLLADA ERROR: could not find referenced camera with id=" << camnodes[i]->getInstanciatedObjectId() << std::endl;
continue;
}
Ogre::Camera* camera = m_sceneMgr->createCamera(camit->second.getName());
camera->setFOVy((Ogre::Degree)camit->second.getYFov());
camera->setNearClipDistance(camit->second.getNearClippingPlane());
camera->setFarClipDistance(camit->second.getFarClippingPlane());
sn->attachObject(camera);
m_instantiatedCameras.push_back(camera);
}
// for each regular child node:
// create the node, call recursively
for (int i = 0, count = cnodes.getCount(); i < count; ++i) {
Ogre::String cname = prefix + cnodes[i]->getOriginalId();
if (!createSceneDFS(cnodes[i], sn->createChildSceneNode(cname), cname + ":"))
return false;
}
return true;
}
// instantiate library node at the given Ogre SceneNode, assuming transformation is set for you
bool OgreCollada::SceneWriter::processLibraryInstance(const COLLADAFW::InstanceNode* inode,
Ogre::SceneNode* lsn, const Ogre::String& prefix) {
// an instantiation of an entire subtree
// follow the hierarchy (the regular node and its subtree) associated with this instance node by looking it up in the library nodes
LibNodesIterator lit = m_libNodes.find(inode->getInstanciatedObjectId());
if (lit == m_libNodes.end()) {
LOG_DEBUG("COLLADA WARNING: could not find library node with unique ID " + Ogre::StringConverter::toString(inode->getInstanciatedObjectId()));
return false;
}
// subtree copying. Need to prefix downstream names with something to uniquify
// using parent node ID for this
// BOZO if we have more than one instantiation of the same library node in the same regular node, we get name duplication = badness
// JET actually I think when this happens we always have a node that "owns" this instantiation
// i.e., there is a <node> which has only the transformation matrix and the relevant
// <instance_node>. Each <node> has a unique name within its parent node. (Need to verify
// this is true)
if (!lit->second->getName().empty()) {
// store the type (name of the library node) as a property
Ogre::UserObjectBindings& lsprops = lsn->getUserObjectBindings();
lsprops.setUserAny("LibNodeType", Ogre::Any(lit->second->getName()));
}
if (!createSceneDFS(lit->second, lsn, prefix))
return false;
return true;
}
Ogre::Camera* OgreCollada::SceneWriter::getCamera() {
if (!m_instantiatedCameras.empty()) {
return m_instantiatedCameras[0];
}
return nullptr;
}