rendering all objects belonging to each mirror
[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.55);
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 res;     // hopefully it'll be moved
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         FlatMirror *planes = 0;
207
208         int num_mirrors = 0;
209         while(mirrors) {
210                 FlatMirror *m = mirrors;
211                 mirrors = mirrors->next;
212                 delete m;
213         }
214         mirrors = 0;
215         objmirror.clear();
216
217         int numscn = scenes.size();
218         for(int i=0; i<numscn; i++) {
219                 Scene *scn = scenes[i];
220
221                 int numobj = scn->objects.size();
222                 for(int j=0; j<numobj; j++) {
223                         Object *obj = scn->objects[j];
224
225                         if(obj->mtl.flat_mirror && obj->get_type() == OBJ_MESH) {
226                                 const Mesh *mesh = ((ObjMesh*)obj)->mesh;
227                                 if(!mesh) continue;
228
229                                 FlatMirror *mir = new FlatMirror;
230                                 mir->reflect = obj->mtl.reflect;
231                                 mir->node = obj->node;
232
233                                 if(obj->mtl.flat_mirror == MTL_MIRROR_AUTO) {
234                                         // grab the first triangle and make a plane
235                                         Triangle face = Triangle(0, (const Vec3*)mesh->get_attrib_data(MESH_ATTR_VERTEX),
236                                                         mesh->get_index_data());
237                                         face.calc_normal();
238
239                                         mir->plane.pt = face.v[0];
240                                         mir->plane.normal = face.normal;
241                                 } else {
242                                         int plane_idx = obj->mtl.flat_mirror - MTL_MIRROR_AABB_PX;
243                                         mir->plane = obj->get_aabox().get_plane(plane_idx);
244                                 }
245
246                                 mir->wplane = mir->plane;
247                                 if(obj->node) {
248                                         const Mat4 &xform = obj->node->get_matrix();
249                                         mir->wplane.pt = xform * mir->wplane.pt;
250                                         mir->wplane.normal = normalize(xform.upper3x3() * mir->wplane.normal);
251                                 }
252
253                                 // check to see if we have found this mirror plane already
254                                 bool found = false;
255                                 FlatMirror *node = planes;
256                                 while(node) {
257                                         float d1 = dot(mir->wplane.normal, mir->wplane.pt);
258                                         float d2 = dot(node->wplane.normal, node->wplane.pt);
259
260                                         if(1.0f - dot(mir->wplane.normal, node->wplane.normal) < 1e-4f &&
261                                                         fabs(d1 - d2) < 1e-4) {
262                                                 found = true;
263                                                 break;
264                                         }
265                                         node = node->next;
266                                 }
267
268                                 debug_log("[%s@%s] mirror plane: local(%g %g %g %g), world(%g %g %g %g)%s\n",
269                                                 obj->get_name(), obj->node ? obj->node->get_name() : "<no-node>",
270                                                 mir->plane.normal.x, mir->plane.normal.y, mir->plane.normal.z,
271                                                 dot(mir->plane.normal, mir->plane.pt), mir->wplane.normal.x, mir->wplane.normal.y,
272                                                 mir->wplane.normal.z, dot(mir->wplane.normal, mir->wplane.pt), found ? " duplicate" : "");
273
274                                 if(!found) {
275                                         mir->next = mirrors;
276                                         mirrors = mir;
277
278                                         // also add a node to the mirror plane matching list
279                                         FlatMirror *m = new FlatMirror;
280                                         m->wplane = mir->wplane;
281                                         m->next = planes;
282                                         planes = node;
283
284                                         mir->objects.push_back(obj);
285                                         objmirror[obj] = mir;   // associate with object
286                                         ++num_mirrors;
287                                 } else {
288                                         node->objects.push_back(obj);
289                                         delete mir;
290                                 }
291                         }
292                 }
293         }
294
295         while(planes) {
296                 FlatMirror *tmp = planes;
297                 planes = planes->next;
298                 delete tmp;
299         }
300
301         return num_mirrors;
302 }
303
304 static bool proc_node(MetaScene *mscn, struct ts_node *node)
305 {
306         struct ts_node *c = node->child_list;
307         while(c) {
308                 if(!proc_node(mscn, c)) {
309                         return false;
310                 }
311                 c = c->next;
312         }
313
314         // do this last to allow other contents of the node to do their thing
315         if(strcmp(node->name, "scenefile") == 0) {
316                 return proc_scenefile(mscn, node);
317
318         } else if(strcmp(node->name, "remap") == 0) {
319                 const char *match = ts_get_attr_str(node, "match");
320                 const char *replace = ts_get_attr_str(node, "replace");
321                 if(match && replace) {
322                         mscn->datamap.map(match, replace);
323                 }
324
325         } else if(strcmp(node->name, "music") == 0) {
326                 return proc_music(mscn, node);
327         }
328
329         return true;
330 }
331
332
333
334 struct SceneData {
335         MetaScene *meta;
336         std::string walkmesh_regexp, spawn_regexp;
337         std::vector<MaterialEdit> mtledit;
338 };
339
340 /*! Processes a `scenefile` node. And kicks off scene loading (if necessary) by
341  * calling `SceneSet::get`.
342  */
343 static bool proc_scenefile(MetaScene *mscn, struct ts_node *node)
344 {
345         const char *fname = ts_get_attr_str(node, "file");
346         if(fname) {
347                 SceneData *sdat = new SceneData;
348                 sdat->meta = mscn;
349
350                 // datapath
351                 struct ts_attr *adpath = attr_inscope(node, "datapath");
352                 if(adpath && adpath->val.type == TS_STRING) {
353                         mscn->datamap.set_path(adpath->val.str);
354                 }
355
356                 // strip path
357                 struct ts_attr *aspath = attr_inscope(node, "strip_path");
358                 if(aspath && aspath->val.type == TS_NUMBER) {
359                         mscn->datamap.set_strip(aspath->val.inum);
360                 }
361
362                 // walkmesh
363                 struct ts_attr *awmesh = attr_inscope(node, "walkmesh");
364                 if(awmesh && awmesh->val.type == TS_STRING) {
365                         sdat->walkmesh_regexp = std::string(awmesh->val.str);
366                 }
367
368                 // spawn node
369                 struct ts_attr *awspawn = attr_inscope(node, "spawn");
370                 if(awspawn) {
371                         switch(awspawn->val.type) {
372                         case TS_VECTOR:
373                                 mscn->start_pos = Vec3(awspawn->val.vec[0], awspawn->val.vec[1],
374                                                 awspawn->val.vec[2]);
375                                 break;
376
377                         case TS_STRING:
378                         default:
379                                 sdat->spawn_regexp = std::string(awspawn->val.str);
380                         }
381                 }
382                 if((awspawn = attr_inscope(node, "spawn_rot")) && awspawn->val.type == TS_VECTOR) {
383                         Quat rot;
384                         rot.rotate(Vec3(1, 0, 0), deg_to_rad(awspawn->val.vec[0]));
385                         rot.rotate(Vec3(0, 1, 0), deg_to_rad(awspawn->val.vec[1]));
386                         rot.rotate(Vec3(0, 0, 1), deg_to_rad(awspawn->val.vec[2]));
387                         mscn->start_rot = rot;
388                 }
389
390                 int namesz = mscn->datamap.lookup(fname, 0, 0);
391                 char *namebuf = (char*)alloca(namesz + 1);
392                 if(mscn->datamap.lookup(fname, namebuf, namesz + 1)) {
393                         fname = namebuf;
394                 }
395
396                 // material edits are kept in a list to be applied when the scene has been loaded
397                 struct ts_node *child = node->child_list;
398                 while(child) {
399                         MaterialEdit medit;
400                         if(proc_mtledit(mscn, &medit, child)) {
401                                 sdat->mtledit.push_back(medit);
402                         }
403                         child = child->next;
404                 }
405
406                 Scene *newscn = sceneman.get(fname);
407                 /* NOTE: setting all these after get() is not a race condition, because
408                  * scene_loaded() which uses this, will only run in our main loop during
409                  * SceneSet::update() on the main thread.
410                  */
411                 newscn->datamap = mscn->datamap;
412                 mscn->datamap.clear();
413
414                 newscn->metascn = mscn;
415                 mscn->scndata[newscn] = sdat;
416         }
417         return true;
418 }
419
420 bool MetaScene::scene_loaded(Scene *newscn)
421 {
422         SceneData *sdat = (SceneData*)scndata[newscn];
423         if(!sdat) {
424                 error_log("MetaScene::scene_loaded called, but corresponding SceneData not found\n");
425                 return false;
426         }
427
428         // extract the walk mesh if necessary
429         Scene *wscn;
430         if(!sdat->walkmesh_regexp.empty() && (wscn = newscn->extract_nodes(sdat->walkmesh_regexp.c_str()))) {
431                 // apply all transformations to the meshes
432                 wscn->apply_xform();
433
434                 int nmeshes = wscn->meshes.size();
435                 for(int i=0; i<nmeshes; i++) {
436                         Mesh *m = wscn->meshes[i];
437
438                         if(walk_mesh) {
439                                 walk_mesh->append(*m);
440                         } else {
441                                 walk_mesh = m;
442                                 wscn->remove_mesh(m);   // to save it from destruction
443                         }
444                 }
445
446                 delete wscn;
447         }
448
449         // extract the spawn node
450         if(!sdat->spawn_regexp.empty() && (wscn = newscn->extract_nodes(sdat->spawn_regexp.c_str()))) {
451
452                 int nmeshes = wscn->meshes.size();
453                 int nnodes = wscn->nodes ? wscn->nodes->get_num_children() : 0;
454
455                 if(nmeshes) {
456                         Vec3 pos;
457                         for(int i=0; i<nmeshes; i++) {
458                                 const Sphere &bsph = wscn->meshes[i]->get_bsphere();
459                                 pos += bsph.center;
460                         }
461                         pos /= (float)nmeshes;
462                         sdat->meta->start_pos = pos;
463
464                 } else if(nnodes) {
465                         // just use the first one
466                         SceneNode *first = wscn->nodes->get_child(0);
467                         sdat->meta->start_pos = first->get_position();
468                         sdat->meta->start_rot = first->get_rotation();
469                 }
470                 delete wscn;
471         }
472
473         int num_medits = sdat->mtledit.size();
474         for(int i=0; i<num_medits; i++) {
475                 // perform material edits
476                 apply_mtledit(newscn, sdat->mtledit[i]);
477         }
478
479         scenes.push_back(newscn);
480         return true;
481 }
482
483 static bool proc_mtledit(MetaScene *mscn, MaterialEdit *med, struct ts_node *node)
484 {
485         if(strcmp(node->name, "mtledit") != 0) {
486                 return false;
487         }
488
489         const char *restr = ".*";
490         struct ts_attr *amtl = ts_get_attr(node, "material");
491         if(amtl && amtl->val.type == TS_STRING) {
492                 restr = amtl->val.str;
493         }
494         med->name_re = std::regex(restr);
495
496         node = node->child_list;
497         while(node) {
498                 struct ts_node *cn = node;
499                 node = node->next;
500
501                 if(strcmp(cn->name, "texture") == 0) {
502                         // add/change/remove a texture
503                         struct ts_attr *atype = ts_get_attr(cn, "type");
504                         struct ts_attr *afile = ts_get_attr(cn, "file");
505
506                         int textype = MTL_TEX_DIFFUSE;
507                         if(atype) {
508                                 if(atype->val.type == TS_STRING) {
509                                         textype = mtl_parse_type(atype->val.str);
510                                 } else if(atype->val.type == TS_NUMBER) {
511                                         textype = atype->val.inum;
512                                         if(textype < 0 || textype >= NUM_MTL_TEXTURES) {
513                                                 error_log("invalid texture in mtledit: %d\n", textype);
514                                                 continue;
515                                         }
516                                 } else {
517                                         error_log("unexpected texture type in mtledit: %s\n", atype->val.str);
518                                         continue;
519                                 }
520                         }
521
522                         med->tex.attr = textype;
523
524                         if(!afile || !afile->val.str || !*afile->val.str) {
525                                 // remove
526                                 med->tex.tex = 0;
527                         } else {
528                                 med->tex.tex = texman.get_texture(afile->val.str, TEX_2D, &mscn->datamap);
529                         }
530
531                         med->type = MTL_EDIT_TEXTURE;
532                         break;
533                 }
534
535                 if(strcmp(cn->name, "mirror") == 0) {
536                         // make this object a flat mirror (hopefully the object is flat otherwise this won't work)
537                         float refl = 1.0f;
538                         int plane = MTL_MIRROR_AUTO;
539
540                         struct ts_attr *aplane = ts_get_attr(cn, "plane");
541                         if(aplane) {
542                                 if(aplane->val.type == TS_NUMBER) {
543                                         plane = MTL_MIRROR_AABB_PX + aplane->val.inum;
544                                 } else {
545                                         char csign, caxis;
546                                         if(sscanf(aplane->val.str, "aabb%c%c", &csign, &caxis) != 2 || (csign != '+' && csign != '-')) {
547                                                 error_log("invalid reflect plane specifier: %s\n", aplane->val.str);
548                                                 continue;
549                                         }
550
551                                         switch(tolower(caxis)) {
552                                         case 'x':
553                                                 plane = csign == '+' ? MTL_MIRROR_AABB_PX : MTL_MIRROR_AABB_NX;
554                                                 break;
555                                         case 'y':
556                                                 plane = csign == '+' ? MTL_MIRROR_AABB_PY : MTL_MIRROR_AABB_NY;
557                                                 break;
558                                         case 'z':
559                                                 plane = csign == '+' ? MTL_MIRROR_AABB_PZ : MTL_MIRROR_AABB_NZ;
560                                                 break;
561                                         default:
562                                                 error_log("invalid reflect plane specifier: %s\n", aplane->val.str);
563                                                 continue;
564                                         }
565                                 }
566                         }
567
568                         struct ts_attr *arefl = ts_get_attr(cn, "reflect");
569                         if(arefl) {
570                                 if(arefl->val.type == TS_NUMBER) {
571                                         refl = arefl->val.fnum;
572                                 } else {
573                                         error_log("invalid reflect attribute in mirror mtledit: %s\n", arefl->val.str);
574                                         continue;
575                                 }
576                         }
577
578                         med->type = MTL_EDIT_MIRROR;
579                         med->mirror.reflectivity = refl;
580                         med->mirror.plane = plane;
581                         break;
582                 }
583         }
584
585         return true;
586 }
587
588 static void apply_mtledit(Scene *scn, const MaterialEdit &med)
589 {
590         // search all the objects to find matching material names
591         int nobj = scn->objects.size();
592         for(int i=0; i<nobj; i++) {
593                 Object *obj = scn->objects[i];
594                 if(std::regex_match(obj->mtl.name, med.name_re)) {
595                         apply_mtledit(&obj->mtl, med);
596                 }
597         }
598 }
599
600 static bool proc_music(MetaScene *mscn, struct ts_node *node)
601 {
602         const char *fname = ts_get_attr_str(node, "file");
603         if(fname) {
604                 SceneData *sdat = new SceneData;
605                 sdat->meta = mscn;
606
607                 // datapath
608                 struct ts_attr *adpath = attr_inscope(node, "datapath");
609                 if(adpath && adpath->val.type == TS_STRING) {
610                         mscn->datamap.set_path(adpath->val.str);
611                 }
612
613                 int namesz = mscn->datamap.lookup(fname, 0, 0);
614                 char *namebuf = (char*)alloca(namesz + 1);
615                 if(mscn->datamap.lookup(fname, namebuf, namesz + 1)) {
616                         fname = namebuf;
617                 }
618
619                 OggVorbisStream *ovstream = new OggVorbisStream;
620                 if(!ovstream->open(fname)) {
621                         delete ovstream;
622                         return false;
623                 }
624
625                 delete mscn->music;
626                 mscn->music = ovstream;
627         }
628         return true;
629 }
630
631 static void apply_mtledit(Material *mtl, const MaterialEdit &med)
632 {
633         // TODO more edit modes...
634         switch(med.type) {
635         case MTL_EDIT_TEXTURE:
636                 if(med.tex.tex) {
637                         mtl->add_texture(med.tex.tex, med.tex.attr);
638                 } else {
639                         Texture *tex = mtl->stdtex[med.tex.attr];
640                         if(tex) {
641                                 mtl->remove_texture(tex);
642                         }
643                 }
644                 break;
645
646         case MTL_EDIT_MIRROR:
647                 mtl->flat_mirror = med.mirror.plane;
648                 mtl->reflect = med.mirror.reflectivity;
649                 break;
650         }
651 }
652
653 static struct ts_attr *attr_inscope(struct ts_node *node, const char *name)
654 {
655         struct ts_attr *attr = 0;
656
657         while(node && !(attr = ts_get_attr(node, name))) {
658                 node = node->parent;
659         }
660         return attr;
661 }
662
663 static void print_scene_graph(SceneNode *n, int level)
664 {
665         if(!n) return;
666
667         for(int i=0; i<level; i++) {
668                 info_log("  ");
669         }
670
671         int nobj = n->get_num_objects();
672         if(nobj) {
673                 info_log("%s - %d obj\n", n->get_name(), n->get_num_objects());
674         } else {
675                 info_log("%s\n", n->get_name());
676         }
677
678         for(int i=0; i<n->get_num_children(); i++) {
679                 print_scene_graph(n->get_child(i), level + 1);
680         }
681 }