using aabb planes as mirror planes
[laserbrain_demo] / src / metascene.cc
1 /*! \file
2  * \brief Metascene implementation
3  *
4  * Loading starts at `MetaScene::load`, which calls `ts_load` (libtreestore)
5  * to load the metascene description tree into memory. Then `proc_node` is
6  * called at the root to recursively process the tree. `scenefile` nodes are
7  * handed over to `proc_scenefile`, which will trigger scene loading for any
8  * nodes with a `file` attribute. Scene loading is handled by requesting the
9  * filename from the scene resource manager, which is of type [SceneSet](\ref SceneSet).
10  */
11 #include <assert.h>
12 #include <string>
13 #include <regex>
14 #include "metascene.h"
15 #include "scene.h"
16 #include "objmesh.h"
17 #include "treestore.h"
18 #include "logger.h"
19 #include "app.h"
20 #include "dbg_gui.h"
21
22 #if defined(WIN32) || defined(__WIN32__)
23 #include <malloc.h>
24 #else
25 #include <alloca.h>
26 #endif
27
28 enum MaterialEditType {
29         MTL_EDIT_TEXTURE,
30         MTL_EDIT_MIRROR
31 };
32
33 struct MaterialEditTexture {
34         int attr;
35         Texture *tex;
36 };
37
38 struct MaterialEditMirror {
39         float reflectivity;
40         int plane;
41 };
42
43 struct MaterialEdit {
44         std::regex name_re;
45         MaterialEditType type;
46
47         MaterialEditTexture tex;
48         MaterialEditMirror mirror;
49 };
50
51 static bool proc_node(MetaScene *mscn, struct ts_node *node);
52 static bool proc_scenefile(MetaScene *mscn, struct ts_node *node);
53 static bool proc_mtledit(MetaScene *mscn, MaterialEdit *med, struct ts_node *node);
54 static bool proc_music(MetaScene *mscn, struct ts_node *node);
55 static void apply_mtledit(Scene *scn, const MaterialEdit &med);
56 static void apply_mtledit(Material *mtl, const MaterialEdit &med);
57 static struct ts_attr *attr_inscope(struct ts_node *node, const char *name);
58
59 static void print_scene_graph(SceneNode *n, int level);
60
61
62 MetaScene::MetaScene()
63 {
64         walk_mesh = 0;
65         music = 0;
66         mirrors = 0;
67 }
68
69 MetaScene::~MetaScene()
70 {
71         delete walk_mesh;
72         delete music;
73
74         while(mirrors) {
75                 FlatMirror *m = mirrors;
76                 mirrors = mirrors->next;
77                 delete m;
78         }
79 }
80
81 bool MetaScene::load(const char *fname)
82 {
83         struct ts_node *root = ts_load(fname);
84         if(!root || strcmp(root->name, "scene") != 0) {
85                 ts_free_tree(root);
86                 error_log("failed to load scene metadata: %s\n", fname);
87                 return false;
88         }
89
90         bool res = proc_node(this, root);
91         ts_free_tree(root);
92
93         /*info_log("loaded scene: %s\n", fname);
94         info_log("scene graph:\n");
95         print_scene_graph(scn->nodes, 0);
96         */
97         return res;
98 }
99
100 void MetaScene::update(float dt)
101 {
102         bool expanded;
103         static char text[256];
104         if(debug_gui) {
105                 ImGui::Begin("MetaScene nodes", 0, 0);
106                 ImGui::Columns(2);
107
108                 static bool once;
109                 if(!once) {
110                         float x = ImGui::GetColumnOffset(1);
111                         ImGui::SetColumnOffset(1, x * 1.7);
112                         once = true;
113                 }
114         }
115
116         int nscn = scenes.size();
117         for(int i=0; i<nscn; i++) {
118
119                 if(debug_gui) {
120                         if(scenes[i]->name.empty()) {
121                                 sprintf(text, "scene %3d", i);
122                         } else {
123                                 sprintf(text, "scene %3d: %s", i, scenes[i]->name.c_str());
124                         }
125                         expanded = parent_expanded = ImGui::TreeNode(text);
126                         ImGui::NextColumn();
127                         ImGui::NextColumn();
128                 }
129
130                 scenes[i]->update(dt);
131
132                 if(debug_gui && expanded) {
133                         ImGui::TreePop();
134                 }
135         }
136
137         if(debug_gui) {
138                 ImGui::Columns(1);
139                 ImGui::End();
140         }
141 }
142
143 // XXX not used, renderer draws
144 void MetaScene::draw() const
145 {
146         error_log("Don't call MetaScene::draw, use the Renderer\n");
147         int nscn = scenes.size();
148         for(int i=0; i<nscn; i++) {
149                 scenes[i]->draw();
150         }
151 }
152
153 SceneNode *MetaScene::find_node(const char *name) const
154 {
155         int num = scenes.size();
156         for(int i=0; i<num; i++) {
157                 SceneNode *n = scenes[i]->find_node(name);
158                 if(n) return n;
159         }
160         return 0;
161 }
162
163 SceneNode *MetaScene::match_node(const char *qstr) const
164 {
165         int num = scenes.size();
166         for(int i=0; i<num; i++) {
167                 SceneNode *n = scenes[i]->match_node(qstr);
168                 if(n) return n;
169         }
170         return 0;
171 }
172
173 std::list<SceneNode*> MetaScene::match_nodes(const char *qstr) const
174 {
175         std::list<SceneNode*> res;
176         int num = scenes.size();
177         for(int i=0; i<num; i++) {
178                 std::list<SceneNode*> tmp = scenes[i]->match_nodes(qstr);
179                 if(!tmp.empty()) {
180                         res.splice(res.end(), tmp);
181                 }
182         }
183         return std::move(res);
184 }
185
186 Scene *MetaScene::extract_nodes(const char *qstr)
187 {
188         Scene *scn = 0;
189         int nscn = scenes.size();
190         for(int i=0; i<nscn; i++) {
191                 Scene *tmp = scenes[i]->extract_nodes(qstr);
192                 if(tmp) {
193                         if(!scn) {
194                                 scn = tmp;
195                         } else {
196                                 scn->merge(tmp);
197                                 delete tmp;
198                         }
199                 }
200         }
201         return scn;
202 }
203
204 int MetaScene::calc_mirror_planes()
205 {
206         int num_mirrors = 0;
207         while(mirrors) {
208                 FlatMirror *m = mirrors;
209                 mirrors = mirrors->next;
210                 delete m;
211         }
212         mirrors = 0;
213         objmirror.clear();
214
215         int numscn = scenes.size();
216         for(int i=0; i<numscn; i++) {
217                 Scene *scn = scenes[i];
218
219                 int numobj = scn->objects.size();
220                 for(int j=0; j<numobj; j++) {
221                         Object *obj = scn->objects[j];
222
223                         if(obj->mtl.flat_mirror && obj->get_type() == OBJ_MESH) {
224                                 const Mesh *mesh = ((ObjMesh*)obj)->mesh;
225                                 if(!mesh) continue;
226
227                                 FlatMirror *mir = new FlatMirror;
228                                 mir->reflect = obj->mtl.reflect;
229
230                                 if(obj->mtl.flat_mirror == MTL_MIRROR_AUTO) {
231                                         // grab the first triangle and make a plane
232                                         Triangle face = Triangle(0, (const Vec3*)mesh->get_attrib_data(MESH_ATTR_VERTEX),
233                                                         mesh->get_index_data());
234                                         face.calc_normal();
235
236                                         mir->plane.pt = face.v[0];
237                                         mir->plane.normal = face.normal;
238                                 } else {
239                                         int plane_idx = obj->mtl.flat_mirror - MTL_MIRROR_AABB_PX;
240                                         if(obj->node) {
241                                                 mir->plane = obj->node->get_bounds().get_plane(plane_idx);
242                                         } else {
243                                                 mir->plane = obj->get_aabox().get_plane(plane_idx);
244                                         }
245                                         debug_log("mirror plane: p(%f %f %f) n(%f %f %f)\n", mir->plane.pt.x, mir->plane.pt.y,
246                                                         mir->plane.pt.z, mir->plane.normal.x, mir->plane.normal.y, mir->plane.normal.z);
247                                 }
248
249                                 // check to see if we have found this mirror plane already
250                                 bool found = false;
251                                 FlatMirror *node = mirrors;
252                                 while(node) {
253                                         if(1.0f - dot(mir->plane.normal, node->plane.normal) < 1e-4f &&
254                                                         fabs(dot(mir->plane.normal, normalize(mir->plane.pt - node->plane.pt))) < 1e-4) {
255                                                 found = true;
256                                                 break;
257                                         }
258                                         node = node->next;
259                                 }
260
261                                 if(!found) {
262                                         mir->next = mirrors;
263                                         mirrors = mir;
264
265                                         objmirror[obj] = mir;   // associate with object
266                                         ++num_mirrors;
267                                 } else {
268                                         delete mir;
269                                 }
270                         }
271                 }
272         }
273
274         return num_mirrors;
275 }
276
277 static bool proc_node(MetaScene *mscn, struct ts_node *node)
278 {
279         struct ts_node *c = node->child_list;
280         while(c) {
281                 if(!proc_node(mscn, c)) {
282                         return false;
283                 }
284                 c = c->next;
285         }
286
287         // do this last to allow other contents of the node to do their thing
288         if(strcmp(node->name, "scenefile") == 0) {
289                 return proc_scenefile(mscn, node);
290
291         } else if(strcmp(node->name, "remap") == 0) {
292                 const char *match = ts_get_attr_str(node, "match");
293                 const char *replace = ts_get_attr_str(node, "replace");
294                 if(match && replace) {
295                         mscn->datamap.map(match, replace);
296                 }
297
298         } else if(strcmp(node->name, "music") == 0) {
299                 return proc_music(mscn, node);
300         }
301
302         return true;
303 }
304
305
306
307 struct SceneData {
308         MetaScene *meta;
309         std::string walkmesh_regexp, spawn_regexp;
310         std::vector<MaterialEdit> mtledit;
311 };
312
313 /*! Processes a `scenefile` node. And kicks off scene loading (if necessary) by
314  * calling `SceneSet::get`.
315  */
316 static bool proc_scenefile(MetaScene *mscn, struct ts_node *node)
317 {
318         const char *fname = ts_get_attr_str(node, "file");
319         if(fname) {
320                 SceneData *sdat = new SceneData;
321                 sdat->meta = mscn;
322
323                 // datapath
324                 struct ts_attr *adpath = attr_inscope(node, "datapath");
325                 if(adpath && adpath->val.type == TS_STRING) {
326                         mscn->datamap.set_path(adpath->val.str);
327                 }
328
329                 // strip path
330                 struct ts_attr *aspath = attr_inscope(node, "strip_path");
331                 if(aspath && aspath->val.type == TS_NUMBER) {
332                         mscn->datamap.set_strip(aspath->val.inum);
333                 }
334
335                 // walkmesh
336                 struct ts_attr *awmesh = attr_inscope(node, "walkmesh");
337                 if(awmesh && awmesh->val.type == TS_STRING) {
338                         sdat->walkmesh_regexp = std::string(awmesh->val.str);
339                 }
340
341                 // spawn node
342                 struct ts_attr *awspawn = attr_inscope(node, "spawn");
343                 if(awspawn) {
344                         switch(awspawn->val.type) {
345                         case TS_VECTOR:
346                                 mscn->start_pos = Vec3(awspawn->val.vec[0], awspawn->val.vec[1],
347                                                 awspawn->val.vec[2]);
348                                 break;
349
350                         case TS_STRING:
351                         default:
352                                 sdat->spawn_regexp = std::string(awspawn->val.str);
353                         }
354                 }
355                 if((awspawn = attr_inscope(node, "spawn_rot")) && awspawn->val.type == TS_VECTOR) {
356                         Quat rot;
357                         rot.rotate(Vec3(1, 0, 0), deg_to_rad(awspawn->val.vec[0]));
358                         rot.rotate(Vec3(0, 1, 0), deg_to_rad(awspawn->val.vec[1]));
359                         rot.rotate(Vec3(0, 0, 1), deg_to_rad(awspawn->val.vec[2]));
360                         mscn->start_rot = rot;
361                 }
362
363                 int namesz = mscn->datamap.lookup(fname, 0, 0);
364                 char *namebuf = (char*)alloca(namesz + 1);
365                 if(mscn->datamap.lookup(fname, namebuf, namesz + 1)) {
366                         fname = namebuf;
367                 }
368
369                 // material edits are kept in a list to be applied when the scene has been loaded
370                 struct ts_node *child = node->child_list;
371                 while(child) {
372                         MaterialEdit medit;
373                         if(proc_mtledit(mscn, &medit, child)) {
374                                 sdat->mtledit.push_back(medit);
375                         }
376                         child = child->next;
377                 }
378
379                 Scene *newscn = sceneman.get(fname);
380                 /* NOTE: setting all these after get() is not a race condition, because
381                  * scene_loaded() which uses this, will only run in our main loop during
382                  * SceneSet::update() on the main thread.
383                  */
384                 newscn->datamap = mscn->datamap;
385                 mscn->datamap.clear();
386
387                 newscn->metascn = mscn;
388                 mscn->scndata[newscn] = sdat;
389         }
390         return true;
391 }
392
393 bool MetaScene::scene_loaded(Scene *newscn)
394 {
395         SceneData *sdat = (SceneData*)scndata[newscn];
396         if(!sdat) {
397                 error_log("MetaScene::scene_loaded called, but corresponding SceneData not found\n");
398                 return false;
399         }
400
401         // extract the walk mesh if necessary
402         Scene *wscn;
403         if(!sdat->walkmesh_regexp.empty() && (wscn = newscn->extract_nodes(sdat->walkmesh_regexp.c_str()))) {
404                 // apply all transformations to the meshes
405                 wscn->apply_xform();
406
407                 int nmeshes = wscn->meshes.size();
408                 for(int i=0; i<nmeshes; i++) {
409                         Mesh *m = wscn->meshes[i];
410
411                         if(walk_mesh) {
412                                 walk_mesh->append(*m);
413                         } else {
414                                 walk_mesh = m;
415                                 wscn->remove_mesh(m);   // to save it from destruction
416                         }
417                 }
418
419                 delete wscn;
420         }
421
422         // extract the spawn node
423         if(!sdat->spawn_regexp.empty() && (wscn = newscn->extract_nodes(sdat->spawn_regexp.c_str()))) {
424
425                 int nmeshes = wscn->meshes.size();
426                 int nnodes = wscn->nodes ? wscn->nodes->get_num_children() : 0;
427
428                 if(nmeshes) {
429                         Vec3 pos;
430                         for(int i=0; i<nmeshes; i++) {
431                                 const Sphere &bsph = wscn->meshes[i]->get_bsphere();
432                                 pos += bsph.center;
433                         }
434                         pos /= (float)nmeshes;
435                         sdat->meta->start_pos = pos;
436
437                 } else if(nnodes) {
438                         // just use the first one
439                         SceneNode *first = wscn->nodes->get_child(0);
440                         sdat->meta->start_pos = first->get_position();
441                         sdat->meta->start_rot = first->get_rotation();
442                 }
443                 delete wscn;
444         }
445
446         int num_medits = sdat->mtledit.size();
447         for(int i=0; i<num_medits; i++) {
448                 // perform material edits
449                 apply_mtledit(newscn, sdat->mtledit[i]);
450         }
451
452         scenes.push_back(newscn);
453         return true;
454 }
455
456 static bool proc_mtledit(MetaScene *mscn, MaterialEdit *med, struct ts_node *node)
457 {
458         if(strcmp(node->name, "mtledit") != 0) {
459                 return false;
460         }
461
462         const char *restr = ".*";
463         struct ts_attr *amtl = ts_get_attr(node, "material");
464         if(amtl && amtl->val.type == TS_STRING) {
465                 restr = amtl->val.str;
466         }
467         med->name_re = std::regex(restr);
468
469         node = node->child_list;
470         while(node) {
471                 struct ts_node *cn = node;
472                 node = node->next;
473
474                 if(strcmp(cn->name, "texture") == 0) {
475                         // add/change/remove a texture
476                         struct ts_attr *atype = ts_get_attr(cn, "type");
477                         struct ts_attr *afile = ts_get_attr(cn, "file");
478
479                         int textype = MTL_TEX_DIFFUSE;
480                         if(atype) {
481                                 if(atype->val.type == TS_STRING) {
482                                         textype = mtl_parse_type(atype->val.str);
483                                 } else if(atype->val.type == TS_NUMBER) {
484                                         textype = atype->val.inum;
485                                         if(textype < 0 || textype >= NUM_MTL_TEXTURES) {
486                                                 error_log("invalid texture in mtledit: %d\n", textype);
487                                                 continue;
488                                         }
489                                 } else {
490                                         error_log("unexpected texture type in mtledit: %s\n", atype->val.str);
491                                         continue;
492                                 }
493                         }
494
495                         med->tex.attr = textype;
496
497                         if(!afile || !afile->val.str || !*afile->val.str) {
498                                 // remove
499                                 med->tex.tex = 0;
500                         } else {
501                                 med->tex.tex = texman.get_texture(afile->val.str, TEX_2D, &mscn->datamap);
502                         }
503
504                         med->type = MTL_EDIT_TEXTURE;
505                         break;
506                 }
507
508                 if(strcmp(cn->name, "mirror") == 0) {
509                         // make this object a flat mirror (hopefully the object is flat otherwise this won't work)
510                         float refl = 1.0f;
511                         int plane = MTL_MIRROR_AUTO;
512
513                         struct ts_attr *aplane = ts_get_attr(cn, "plane");
514                         if(aplane) {
515                                 if(aplane->val.type == TS_NUMBER) {
516                                         plane = MTL_MIRROR_AABB_PX + aplane->val.inum;
517                                 } else {
518                                         char csign, caxis;
519                                         if(sscanf(aplane->val.str, "aabb%c%c", &csign, &caxis) != 2 || (csign != '+' && csign != '-')) {
520                                                 error_log("invalid reflect plane specifier: %s\n", aplane->val.str);
521                                                 continue;
522                                         }
523
524                                         switch(tolower(caxis)) {
525                                         case 'x':
526                                                 plane = caxis == '+' ? MTL_MIRROR_AABB_PX : MTL_MIRROR_AABB_NX;
527                                                 break;
528                                         case 'y':
529                                                 plane = caxis == '+' ? MTL_MIRROR_AABB_PY : MTL_MIRROR_AABB_NY;
530                                                 break;
531                                         case 'z':
532                                                 plane = caxis == '+' ? MTL_MIRROR_AABB_PZ : MTL_MIRROR_AABB_NZ;
533                                                 break;
534                                         default:
535                                                 error_log("invalid reflect plane specifier: %s\n", aplane->val.str);
536                                                 continue;
537                                         }
538                                 }
539                         }
540
541                         struct ts_attr *arefl = ts_get_attr(cn, "reflect");
542                         if(arefl) {
543                                 if(arefl->val.type == TS_NUMBER) {
544                                         refl = arefl->val.fnum;
545                                 } else {
546                                         error_log("invalid reflect attribute in mirror mtledit: %s\n", arefl->val.str);
547                                         continue;
548                                 }
549                         }
550
551                         med->type = MTL_EDIT_MIRROR;
552                         med->mirror.reflectivity = refl;
553                         med->mirror.plane = plane;
554                         break;
555                 }
556         }
557
558         return true;
559 }
560
561 static void apply_mtledit(Scene *scn, const MaterialEdit &med)
562 {
563         // search all the objects to find matching material names
564         int nobj = scn->objects.size();
565         for(int i=0; i<nobj; i++) {
566                 Object *obj = scn->objects[i];
567                 if(std::regex_match(obj->mtl.name, med.name_re)) {
568                         apply_mtledit(&obj->mtl, med);
569                 }
570         }
571 }
572
573 static bool proc_music(MetaScene *mscn, struct ts_node *node)
574 {
575         const char *fname = ts_get_attr_str(node, "file");
576         if(fname) {
577                 SceneData *sdat = new SceneData;
578                 sdat->meta = mscn;
579
580                 // datapath
581                 struct ts_attr *adpath = attr_inscope(node, "datapath");
582                 if(adpath && adpath->val.type == TS_STRING) {
583                         mscn->datamap.set_path(adpath->val.str);
584                 }
585
586                 int namesz = mscn->datamap.lookup(fname, 0, 0);
587                 char *namebuf = (char*)alloca(namesz + 1);
588                 if(mscn->datamap.lookup(fname, namebuf, namesz + 1)) {
589                         fname = namebuf;
590                 }
591
592                 OggVorbisStream *ovstream = new OggVorbisStream;
593                 if(!ovstream->open(fname)) {
594                         delete ovstream;
595                         return false;
596                 }
597
598                 delete mscn->music;
599                 mscn->music = ovstream;
600         }
601         return true;
602 }
603
604 static void apply_mtledit(Material *mtl, const MaterialEdit &med)
605 {
606         // TODO more edit modes...
607         switch(med.type) {
608         case MTL_EDIT_TEXTURE:
609                 if(med.tex.tex) {
610                         mtl->add_texture(med.tex.tex, med.tex.attr);
611                 } else {
612                         Texture *tex = mtl->stdtex[med.tex.attr];
613                         if(tex) {
614                                 mtl->remove_texture(tex);
615                         }
616                 }
617                 break;
618
619         case MTL_EDIT_MIRROR:
620                 mtl->flat_mirror = med.mirror.plane;
621                 mtl->reflect = med.mirror.reflectivity;
622                 break;
623         }
624 }
625
626 static struct ts_attr *attr_inscope(struct ts_node *node, const char *name)
627 {
628         struct ts_attr *attr = 0;
629
630         while(node && !(attr = ts_get_attr(node, name))) {
631                 node = node->parent;
632         }
633         return attr;
634 }
635
636 static void print_scene_graph(SceneNode *n, int level)
637 {
638         if(!n) return;
639
640         for(int i=0; i<level; i++) {
641                 info_log("  ");
642         }
643
644         int nobj = n->get_num_objects();
645         if(nobj) {
646                 info_log("%s - %d obj\n", n->get_name(), n->get_num_objects());
647         } else {
648                 info_log("%s\n", n->get_name());
649         }
650
651         for(int i=0; i<n->get_num_children(); i++) {
652                 print_scene_graph(n->get_child(i), level + 1);
653         }
654 }