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