proper scene graph
[laserbrain_demo] / src / sceneload.cc
1 #include <stdio.h>
2 #include <vector>
3 #include <map>
4 #include <gmath/gmath.h>
5 #include <assimp/cimport.h>
6 #include <assimp/postprocess.h>
7 #include <assimp/scene.h>
8 #include <assimp/mesh.h>
9 #include <assimp/material.h>
10 #include <assimp/anim.h>
11 #include <assimp/vector3.h>
12 #include <assimp/matrix4x4.h>
13 #include <assimp/quaternion.h>
14 #include "scene.h"
15 #include "objmesh.h"
16 #include "datamap.h"
17
18 static bool load_material(Scene *scn, Material *mat, const aiMaterial *aimat);
19 static SceneNode *load_node(Scene *scn, const aiScene *aiscn, unsigned int flags, const aiNode *ainode);
20 static Mesh *load_mesh(Scene *scn, const aiScene *aiscn, unsigned int flags, const aiMesh *aimesh);
21 static void print_nodes(SceneNode *node, int lvl = 0);
22 /*static const char *mprop_semantic(int x);
23 static int count_textures(const aiMaterial *aimat);*/
24 static int assimp_textype(aiTextureType type);
25
26 static Mat4 assimp_matrix(const aiMatrix4x4 &aim);
27
28 /*static Vec3 assimp_vector(const aiVector3D &v);
29 static Quat assimp_quat(const aiQuaternion &q);
30 static long assimp_time(const aiAnimation *anim, double aitime);
31 static void print_hierarchy(const aiNode *node);
32 */
33
34 static std::map<std::string, SceneNode*> node_by_name;
35 static std::map<aiMesh*, Mesh*> mesh_by_aimesh;
36
37 bool Scene::load(const char *fname, unsigned int flags)
38 {
39         unsigned int ppflags = aiProcess_CalcTangentSpace |
40                 aiProcess_GenNormals |
41                 aiProcess_JoinIdenticalVertices |
42                 aiProcess_Triangulate |
43                 aiProcess_SortByPType |
44                 aiProcess_GenUVCoords |
45                 aiProcess_TransformUVCoords;
46
47         if(flags & SCNLOAD_FLIPTEX) {
48                 ppflags |= aiProcess_FlipUVs;
49         }
50
51         const aiScene *aiscn = aiImportFile(fname, ppflags);
52         if(!aiscn) {
53                 fprintf(stderr, "failed to load scene file: %s\n", fname);
54                 return false;
55         }
56
57         // assimp adds its own root node, which might have transformations
58         Vec3 root_pos, root_scaling(1.0, 1.0, 1.0);
59         Quat root_rot;
60
61         if(aiscn->mRootNode) {
62                 Mat4 root_matrix = assimp_matrix(aiscn->mRootNode->mTransformation);
63                 root_pos = root_matrix.get_translation();
64                 root_rot = root_matrix.get_rotation();
65                 root_scaling = root_matrix.get_scaling();
66
67                 printf("assimp root node: %s\n", aiscn->mRootNode->mName.data);
68                 printf("  pos: %f %f %f\n", root_pos.x, root_pos.y, root_pos.z);
69                 printf("  rot: %f %+f %+f %+f\n", root_rot.w, root_rot.x, root_rot.y, root_rot.z);
70                 printf("  scaling: %f %f %f\n", root_scaling.x, root_scaling.y, root_scaling.z);
71         }
72
73         // load all meshes
74         for(unsigned int i=0; i<aiscn->mNumMeshes; i++) {
75                 aiMesh *aimesh = aiscn->mMeshes[i];
76                 Mesh *mesh;
77
78                 switch(aimesh->mPrimitiveTypes) {
79                 case aiPrimitiveType_TRIANGLE:
80                         if((mesh = load_mesh(this, aiscn, flags, aimesh))) {
81                                 mesh_by_aimesh[aimesh] = mesh;
82                                 meshes.push_back(mesh);
83                         }
84                         break;
85
86                 default:
87                         fprintf(stderr, "unsupported primitive type: %u\n", aimesh->mPrimitiveTypes);
88                         break;
89                 }
90         }
91
92         if(!nodes) {
93                 nodes = new SceneNode;
94                 nodes->set_name("root");
95                 nodes->set_position(root_pos);
96                 nodes->set_rotation(root_rot);
97                 nodes->set_scaling(root_scaling);
98         }
99
100         // load all the nodes recursively
101         for(unsigned int i=0; i<aiscn->mRootNode->mNumChildren; i++) {
102                 SceneNode *node = load_node(this, aiscn, flags, aiscn->mRootNode->mChildren[i]);
103                 if(node) {
104                         nodes->add_child(node);
105                 }
106         }
107
108         node_by_name.clear();
109         mesh_by_aimesh.clear();
110
111         aiReleaseImport(aiscn);
112         printf("loaded scene file: %s, %d meshes\n", fname, (int)meshes.size());
113         nodes->update(0);
114         print_nodes(nodes);
115         return true;
116 }
117
118 static bool load_material(Scene *scn, Material *mat, const aiMaterial *aimat)
119 {
120         aiString name;
121         aiColor4D aicol;
122         float shin, shin_str;
123
124         if(aiGetMaterialString(aimat, AI_MATKEY_NAME, &name) == 0) {
125                 mat->name = name.data;
126         } else {
127                 mat->name = "unknown";
128         }
129         //printf("load_material: %s\n", mat->name.c_str());
130
131         if(aiGetMaterialColor(aimat, AI_MATKEY_COLOR_DIFFUSE, &aicol) == 0) {
132                 mat->diffuse = Vec3(aicol[0], aicol[1], aicol[2]);
133         }
134         if(aiGetMaterialColor(aimat, AI_MATKEY_COLOR_SPECULAR, &aicol) == 0) {
135                 mat->specular = Vec3(aicol[0], aicol[1], aicol[2]);
136         }
137
138         unsigned int count = 1;
139         if(aiGetMaterialFloatArray(aimat, AI_MATKEY_SHININESS_STRENGTH, &shin_str, &count) != 0) {
140                 shin_str = 1.0;
141         }
142         if(aiGetMaterialFloatArray(aimat, AI_MATKEY_SHININESS, &shin, &count) == 0) {
143                 // XXX can't remember how I came up with this...
144                 mat->shininess = shin * shin_str * 0.0001 * 128.0;
145         }
146
147         // load textures
148
149         const int num_tex_types = aiTextureType_UNKNOWN + 1;
150         for(int i=0; i<num_tex_types; i++) {
151                 aiTextureType aitype = (aiTextureType)i;
152                 int count = aiGetMaterialTextureCount(aimat, aitype);
153
154                 for(int j=0; j<count; j++) {
155                         aiString aipath;
156                         if(aiGetMaterialTexture(aimat, aitype, j, &aipath) != 0) {
157                                 continue;
158                         }
159
160                         char *fname;
161                         int nsize = datamap_path_size(aipath.data);
162                         if(nsize) {
163                                 fname = new char[nsize];
164                                 datamap_lookup(aipath.data, fname, nsize);
165                         } else {
166                                 fname = new char[strlen(aipath.data) + 1];
167                                 char *dptr = fname;
168                                 char *sptr = aipath.data;
169                                 do {
170                                         *dptr++ = *sptr == '\\' ? '/' : *sptr;
171                                 } while(*sptr++);
172                         }
173
174                         Texture *tex = scn->texset->get(fname);
175                         if(!tex) {
176                                 fprintf(stderr, "failed to load texture: %s\n", fname);
177                                 delete [] fname;
178                                 continue;
179                         }
180                         delete [] fname;
181
182                         mat->textures.push_back(tex);
183
184                         int textype = assimp_textype(aitype);
185                         if(textype != MTL_TEX_UNKNOWN && !mat->stdtex[textype]) {
186                                 mat->stdtex[textype] = tex;
187                         }
188                 }
189         }
190
191         return true;
192 }
193
194 static SceneNode *load_node(Scene *scn, const aiScene *aiscn, unsigned int flags, const aiNode *ainode)
195 {
196         SceneNode *node = new SceneNode;
197         node->set_name(ainode->mName.data);
198
199         // transformation
200         Mat4 matrix = assimp_matrix(ainode->mTransformation);
201         Vec3 pos = matrix.get_translation();
202         Quat rot = matrix.get_rotation();
203         Vec3 scale = matrix.get_scaling();
204
205         node->set_position(pos);
206         node->set_rotation(rot);
207         node->set_scaling(scale);
208         node->dbg_xform = matrix;
209
210         // meshes
211         for(unsigned int i=0; i<ainode->mNumMeshes; i++) {
212                 aiMesh *aimesh = aiscn->mMeshes[ainode->mMeshes[i]];
213
214                 Mesh *mesh = mesh_by_aimesh[aimesh];
215                 if(mesh) {
216                         ObjMesh *obj = new ObjMesh;
217                         obj->mesh = mesh;
218                         // also grab the material of this mesh
219                         load_material(scn, &obj->mtl, aiscn->mMaterials[aimesh->mMaterialIndex]);
220
221                         node->add_object(obj);
222                         scn->objects.push_back(obj);
223                 }
224         }
225
226         /* recurse to all children */
227         for(unsigned int i=0; i<ainode->mNumChildren; i++) {
228                 SceneNode *child = load_node(scn, aiscn, flags, ainode->mChildren[i]);
229                 if(child) {
230                         node->add_child(child);
231                 }
232         }
233
234         node_by_name[node->get_name()] = node;
235         return node;
236 }
237
238 static Mesh *load_mesh(Scene *scn, const aiScene *aiscn, unsigned int flags, const aiMesh *aimesh)
239 {
240         Mesh *mesh = new Mesh;
241
242         int num_verts = aimesh->mNumVertices;
243         int num_faces = aimesh->mNumFaces;
244
245         mesh->set_attrib_data(MESH_ATTR_VERTEX, 3, num_verts, (float*)aimesh->mVertices);
246
247         if(aimesh->mNormals) {
248                 mesh->set_attrib_data(MESH_ATTR_NORMAL, 3, num_verts, (float*)aimesh->mNormals);
249         }
250         if(aimesh->mTangents) {
251                 mesh->set_attrib_data(MESH_ATTR_TANGENT, 3, num_verts, (float*)aimesh->mTangents);
252         }
253         if(aimesh->mTextureCoords[0]) {
254                 mesh->set_attrib_data(MESH_ATTR_TEXCOORD, 3, num_verts, (float*)aimesh->mTextureCoords[0]);
255         }
256         if(aimesh->mTextureCoords[1]) {
257                 mesh->set_attrib_data(MESH_ATTR_TEXCOORD2, 3, num_verts, (float*)aimesh->mTextureCoords[1]);
258         }
259
260         if(flags & SCNLOAD_FLIPYZ) {
261                 Vec3 *vptr = (Vec3*)mesh->get_attrib_data(MESH_ATTR_VERTEX);
262                 for(int i=0; i<num_verts; i++) {
263                         *vptr = vptr->xzy();
264                         ++vptr;
265                 }
266
267                 Vec3 *nptr = (Vec3*)mesh->get_attrib_data(MESH_ATTR_NORMAL);
268                 for(int i=0; i<num_verts; i++) {
269                         *nptr = nptr->xzy();
270                         ++nptr;
271                 }
272
273                 Vec3 *tptr = (Vec3*)mesh->get_attrib_data(MESH_ATTR_TANGENT);
274                 for(int i=0; i<num_verts; i++) {
275                         *tptr = tptr->xzy();
276                         ++tptr;
277                 }
278         }
279
280         unsigned int *iptr = mesh->set_index_data(num_faces * 3);
281         for(int i=0; i<num_faces; i++) {
282                 iptr[0] = aimesh->mFaces[i].mIndices[0];
283                 iptr[1] = aimesh->mFaces[i].mIndices[flags & SCNLOAD_FLIPYZ ? 2 : 1];
284                 iptr[2] = aimesh->mFaces[i].mIndices[flags & SCNLOAD_FLIPYZ ? 1 : 2];
285                 iptr += 3;
286         }
287
288         return mesh;
289 }
290
291 static void print_nodes(SceneNode *node, int lvl)
292 {
293         Vec3 pos = node->get_node_position();
294         Quat rot = node->get_node_rotation();
295         Vec3 scale = node->get_node_scaling();
296
297         const char *type = node->get_num_objects() > 0 ? "mesh node" : "null node";
298
299         for(int i=0; i<lvl; i++) {
300                 fputs("  ", stdout);
301         }
302         printf("%s[%s] p(%g %g %g) rq(%g %+gi %+gj %+gk) s(%g %g %g)\n", type, node->get_name(),
303                         pos.x, pos.y, pos.z, rot.w, rot.x, rot.y, rot.z, scale.x, scale.y, scale.z);
304
305         if(node->get_num_objects()) {
306                 Mat4 xform = node->get_matrix();
307                 xform.print(stdout);
308         }
309
310         int nchld = node->get_num_children();
311         for(int i=0; i<nchld; i++) {
312                 print_nodes(node->get_child(i), lvl + 1);
313         }
314 }
315
316 static int assimp_textype(aiTextureType type)
317 {
318         switch(type) {
319         case aiTextureType_DIFFUSE:
320                 return MTL_TEX_DIFFUSE;
321         case aiTextureType_SPECULAR:
322                 return MTL_TEX_SPECULAR;
323         case aiTextureType_NORMALS:
324                 return MTL_TEX_NORMALMAP;
325         case aiTextureType_LIGHTMAP:
326                 return MTL_TEX_LIGHTMAP;
327         case aiTextureType_REFLECTION:
328                 return MTL_TEX_ENVMAP;
329         default:
330                 break;
331         }
332         return MTL_TEX_UNKNOWN;
333 }
334
335 static Mat4 assimp_matrix(const aiMatrix4x4 &aim)
336 {
337         Mat4 m;
338         memcpy(m[0], &aim, 16 * sizeof(float));
339         return transpose(m);
340 }