d9f96fbaaf38b3d4bac9d3086e60066fca587f76
[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 "treestore.h"
17 #include "logger.h"
18 #include "app.h"
19 #include "dbg_gui.h"
20
21 #if defined(WIN32) || defined(__WIN32__)
22 #include <malloc.h>
23 #else
24 #include <alloca.h>
25 #endif
26
27 struct MaterialEdit {
28         std::regex name_re;
29         int attr;
30         Texture *tex;
31 };
32
33 static bool proc_node(MetaScene *mscn, struct ts_node *node);
34 static bool proc_scenefile(MetaScene *mscn, struct ts_node *node);
35 static bool proc_mtledit(MetaScene *mscn, MaterialEdit *med, struct ts_node *node);
36 static bool proc_music(MetaScene *mscn, struct ts_node *node);
37 static void apply_mtledit(Scene *scn, const MaterialEdit &med);
38 static void apply_mtledit(Material *mtl, const MaterialEdit &med);
39 static struct ts_attr *attr_inscope(struct ts_node *node, const char *name);
40
41 static void print_scene_graph(SceneNode *n, int level);
42
43
44 MetaScene::MetaScene()
45 {
46         walk_mesh = 0;
47         music = 0;
48 }
49
50 MetaScene::~MetaScene()
51 {
52         delete walk_mesh;
53         delete music;
54 }
55
56 bool MetaScene::load(const char *fname)
57 {
58         struct ts_node *root = ts_load(fname);
59         if(!root || strcmp(root->name, "scene") != 0) {
60                 ts_free_tree(root);
61                 error_log("failed to load scene metadata: %s\n", fname);
62                 return false;
63         }
64
65         bool res = proc_node(this, root);
66         ts_free_tree(root);
67
68         /*info_log("loaded scene: %s\n", fname);
69         info_log("scene graph:\n");
70         print_scene_graph(scn->nodes, 0);
71         */
72         return res;
73 }
74
75 void MetaScene::update(float dt)
76 {
77         bool expanded;
78         static char text[256];
79         if(debug_gui) {
80                 ImGui::Begin("MetaScene nodes", 0, 0);
81                 ImGui::Columns(2);
82
83                 static bool once;
84                 if(!once) {
85                         float x = ImGui::GetColumnOffset(1);
86                         ImGui::SetColumnOffset(1, x * 1.7);
87                         once = true;
88                 }
89         }
90
91         int nscn = scenes.size();
92         for(int i=0; i<nscn; i++) {
93
94                 if(debug_gui) {
95                         if(scenes[i]->name.empty()) {
96                                 sprintf(text, "scene %3d", i);
97                         } else {
98                                 sprintf(text, "scene %3d: %s", i, scenes[i]->name.c_str());
99                         }
100                         expanded = parent_expanded = ImGui::TreeNode(text);
101                         ImGui::NextColumn();
102                         ImGui::NextColumn();
103                 }
104
105                 scenes[i]->update(dt);
106
107                 if(debug_gui && expanded) {
108                         ImGui::TreePop();
109                 }
110         }
111
112         if(debug_gui) {
113                 ImGui::Columns(1);
114                 ImGui::End();
115         }
116 }
117
118 // XXX not used, renderer draws
119 void MetaScene::draw() const
120 {
121         int nscn = scenes.size();
122         for(int i=0; i<nscn; i++) {
123                 scenes[i]->draw();
124         }
125 }
126
127 SceneNode *MetaScene::find_node(const char *name) const
128 {
129         int num = scenes.size();
130         for(int i=0; i<num; i++) {
131                 SceneNode *n = scenes[i]->find_node(name);
132                 if(n) return n;
133         }
134         return 0;
135 }
136
137 SceneNode *MetaScene::match_node(const char *qstr) const
138 {
139         int num = scenes.size();
140         for(int i=0; i<num; i++) {
141                 SceneNode *n = scenes[i]->match_node(qstr);
142                 if(n) return n;
143         }
144         return 0;
145 }
146
147 std::list<SceneNode*> MetaScene::match_nodes(const char *qstr) const
148 {
149         std::list<SceneNode*> res;
150         int num = scenes.size();
151         for(int i=0; i<num; i++) {
152                 std::list<SceneNode*> tmp = scenes[i]->match_nodes(qstr);
153                 if(!tmp.empty()) {
154                         res.splice(res.end(), tmp);
155                 }
156         }
157         return std::move(res);
158 }
159
160 Scene *MetaScene::extract_nodes(const char *qstr)
161 {
162         Scene *scn = 0;
163         int nscn = scenes.size();
164         for(int i=0; i<nscn; i++) {
165                 Scene *tmp = scenes[i]->extract_nodes(qstr);
166                 if(tmp) {
167                         if(!scn) {
168                                 scn = tmp;
169                         } else {
170                                 scn->merge(tmp);
171                                 delete tmp;
172                         }
173                 }
174         }
175         return scn;
176 }
177
178 static bool proc_node(MetaScene *mscn, struct ts_node *node)
179 {
180         struct ts_node *c = node->child_list;
181         while(c) {
182                 if(!proc_node(mscn, c)) {
183                         return false;
184                 }
185                 c = c->next;
186         }
187
188         // do this last to allow other contents of the node to do their thing
189         if(strcmp(node->name, "scenefile") == 0) {
190                 return proc_scenefile(mscn, node);
191
192         } else if(strcmp(node->name, "remap") == 0) {
193                 const char *match = ts_get_attr_str(node, "match");
194                 const char *replace = ts_get_attr_str(node, "replace");
195                 if(match && replace) {
196                         mscn->datamap.map(match, replace);
197                 }
198
199         } else if(strcmp(node->name, "music") == 0) {
200                 return proc_music(mscn, node);
201         }
202
203         return true;
204 }
205
206
207
208 struct SceneData {
209         MetaScene *meta;
210         std::string walkmesh_regexp, spawn_regexp;
211         std::vector<MaterialEdit> mtledit;
212 };
213
214 /*! Processes a `scenefile` node. And kicks off scene loading (if necessary) by
215  * calling `SceneSet::get`.
216  */
217 static bool proc_scenefile(MetaScene *mscn, struct ts_node *node)
218 {
219         const char *fname = ts_get_attr_str(node, "file");
220         if(fname) {
221                 SceneData *sdat = new SceneData;
222                 sdat->meta = mscn;
223
224                 // datapath
225                 struct ts_attr *adpath = attr_inscope(node, "datapath");
226                 if(adpath && adpath->val.type == TS_STRING) {
227                         mscn->datamap.set_path(adpath->val.str);
228                 }
229
230                 // strip path
231                 struct ts_attr *aspath = attr_inscope(node, "strip_path");
232                 if(aspath && aspath->val.type == TS_NUMBER) {
233                         mscn->datamap.set_strip(aspath->val.inum);
234                 }
235
236                 // walkmesh
237                 struct ts_attr *awmesh = attr_inscope(node, "walkmesh");
238                 if(awmesh && awmesh->val.type == TS_STRING) {
239                         sdat->walkmesh_regexp = std::string(awmesh->val.str);
240                 }
241
242                 // spawn node
243                 struct ts_attr *awspawn = attr_inscope(node, "spawn");
244                 if(awspawn) {
245                         switch(awspawn->val.type) {
246                         case TS_VECTOR:
247                                 mscn->start_pos = Vec3(awspawn->val.vec[0], awspawn->val.vec[1],
248                                                 awspawn->val.vec[2]);
249                                 break;
250
251                         case TS_STRING:
252                         default:
253                                 sdat->spawn_regexp = std::string(awspawn->val.str);
254                         }
255                 }
256                 if((awspawn = attr_inscope(node, "spawn_rot")) && awspawn->val.type == TS_VECTOR) {
257                         Quat rot;
258                         rot.rotate(Vec3(1, 0, 0), deg_to_rad(awspawn->val.vec[0]));
259                         rot.rotate(Vec3(0, 1, 0), deg_to_rad(awspawn->val.vec[1]));
260                         rot.rotate(Vec3(0, 0, 1), deg_to_rad(awspawn->val.vec[2]));
261                         mscn->start_rot = rot;
262                 }
263
264                 int namesz = mscn->datamap.lookup(fname, 0, 0);
265                 char *namebuf = (char*)alloca(namesz + 1);
266                 if(mscn->datamap.lookup(fname, namebuf, namesz + 1)) {
267                         fname = namebuf;
268                 }
269
270                 // material edits are kept in a list to be applied when the scene has been loaded
271                 struct ts_node *child = node->child_list;
272                 while(child) {
273                         MaterialEdit medit;
274                         if(proc_mtledit(mscn, &medit, child)) {
275                                 sdat->mtledit.push_back(medit);
276                         }
277                         child = child->next;
278                 }
279
280                 Scene *newscn = sceneman.get(fname);
281                 /* NOTE: setting all these after get() is not a race condition, because
282                  * scene_loaded() which uses this, will only run in our main loop during
283                  * SceneSet::update() on the main thread.
284                  */
285                 newscn->datamap = mscn->datamap;
286                 mscn->datamap.clear();
287
288                 newscn->metascn = mscn;
289                 mscn->scndata[newscn] = sdat;
290         }
291         return true;
292 }
293
294 bool MetaScene::scene_loaded(Scene *newscn)
295 {
296         SceneData *sdat = (SceneData*)scndata[newscn];
297         if(!sdat) {
298                 error_log("MetaScene::scene_loaded called, but corresponding SceneData not found\n");
299                 return false;
300         }
301
302         // extract the walk mesh if necessary
303         Scene *wscn;
304         if(!sdat->walkmesh_regexp.empty() && (wscn = newscn->extract_nodes(sdat->walkmesh_regexp.c_str()))) {
305                 // apply all transformations to the meshes
306                 wscn->apply_xform();
307
308                 int nmeshes = wscn->meshes.size();
309                 for(int i=0; i<nmeshes; i++) {
310                         Mesh *m = wscn->meshes[i];
311
312                         if(walk_mesh) {
313                                 walk_mesh->append(*m);
314                         } else {
315                                 walk_mesh = m;
316                                 wscn->remove_mesh(m);   // to save it from destruction
317                         }
318                 }
319
320                 delete wscn;
321         }
322
323         // extract the spawn node
324         if(!sdat->spawn_regexp.empty() && (wscn = newscn->extract_nodes(sdat->spawn_regexp.c_str()))) {
325
326                 int nmeshes = wscn->meshes.size();
327                 int nnodes = wscn->nodes ? wscn->nodes->get_num_children() : 0;
328
329                 if(nmeshes) {
330                         Vec3 pos;
331                         for(int i=0; i<nmeshes; i++) {
332                                 const Sphere &bsph = wscn->meshes[i]->get_bsphere();
333                                 pos += bsph.center;
334                         }
335                         pos /= (float)nmeshes;
336                         sdat->meta->start_pos = pos;
337
338                 } else if(nnodes) {
339                         // just use the first one
340                         SceneNode *first = wscn->nodes->get_child(0);
341                         sdat->meta->start_pos = first->get_position();
342                         sdat->meta->start_rot = first->get_rotation();
343                 }
344                 delete wscn;
345         }
346
347         int num_medits = sdat->mtledit.size();
348         for(int i=0; i<num_medits; i++) {
349                 // perform material edits
350                 apply_mtledit(newscn, sdat->mtledit[i]);
351         }
352
353         scenes.push_back(newscn);
354         return true;
355 }
356
357 static bool proc_mtledit(MetaScene *mscn, MaterialEdit *med, struct ts_node *node)
358 {
359         if(strcmp(node->name, "mtledit") != 0) {
360                 return false;
361         }
362
363         const char *restr = ".*";
364         struct ts_attr *amtl = ts_get_attr(node, "material");
365         if(amtl && amtl->val.type == TS_STRING) {
366                 restr = amtl->val.str;
367         }
368
369         med->name_re = std::regex(restr);
370
371         node = node->child_list;
372         while(node) {
373                 struct ts_node *cn = node;
374                 node = node->next;
375
376                 if(strcmp(cn->name, "texture") == 0) {
377                         // add/change/remove a texture
378                         struct ts_attr *atype = ts_get_attr(cn, "type");
379                         struct ts_attr *afile = ts_get_attr(cn, "file");
380
381                         int textype = MTL_TEX_DIFFUSE;
382                         if(atype) {
383                                 if(atype->val.type == TS_STRING) {
384                                         textype = mtl_parse_type(atype->val.str);
385                                 } else if(atype->val.type == TS_NUMBER) {
386                                         textype = atype->val.inum;
387                                         if(textype < 0 || textype >= NUM_MTL_TEXTURES) {
388                                                 error_log("invalid texture in mtledit: %d\n", textype);
389                                                 continue;
390                                         }
391                                 } else {
392                                         error_log("unexpected texture type in mtledit: %s\n", atype->val.str);
393                                         continue;
394                                 }
395                         }
396
397                         med->attr = textype;
398
399                         if(!afile || !afile->val.str || !*afile->val.str) {
400                                 // remove
401                                 med->tex = 0;
402                         } else {
403                                 med->tex = texman.get_texture(afile->val.str, TEX_2D, &mscn->datamap);
404                         }
405                 }
406                 // TODO add more edit modes
407         }
408
409         return true;
410 }
411
412 static void apply_mtledit(Scene *scn, const MaterialEdit &med)
413 {
414         // search all the objects to find matching material names
415         int nobj = scn->objects.size();
416         for(int i=0; i<nobj; i++) {
417                 Object *obj = scn->objects[i];
418                 if(std::regex_match(obj->mtl.name, med.name_re)) {
419                         apply_mtledit(&obj->mtl, med);
420                 }
421         }
422 }
423
424 static bool proc_music(MetaScene *mscn, struct ts_node *node)
425 {
426         const char *fname = ts_get_attr_str(node, "file");
427         if(fname) {
428                 SceneData *sdat = new SceneData;
429                 sdat->meta = mscn;
430
431                 // datapath
432                 struct ts_attr *adpath = attr_inscope(node, "datapath");
433                 if(adpath && adpath->val.type == TS_STRING) {
434                         mscn->datamap.set_path(adpath->val.str);
435                 }
436
437                 int namesz = mscn->datamap.lookup(fname, 0, 0);
438                 char *namebuf = (char*)alloca(namesz + 1);
439                 if(mscn->datamap.lookup(fname, namebuf, namesz + 1)) {
440                         fname = namebuf;
441                 }
442
443                 OggVorbisStream *ovstream = new OggVorbisStream;
444                 if(!ovstream->open(fname)) {
445                         delete ovstream;
446                         return false;
447                 }
448
449                 delete mscn->music;
450                 mscn->music = ovstream;
451         }
452         return true;
453 }
454
455 static void apply_mtledit(Material *mtl, const MaterialEdit &med)
456 {
457         // TODO more edit modes...
458         if(med.tex) {
459                 mtl->add_texture(med.tex, med.attr);
460         } else {
461                 Texture *tex = mtl->stdtex[med.attr];
462                 if(tex) {
463                         mtl->remove_texture(tex);
464                 }
465         }
466 }
467
468 static struct ts_attr *attr_inscope(struct ts_node *node, const char *name)
469 {
470         struct ts_attr *attr = 0;
471
472         while(node && !(attr = ts_get_attr(node, name))) {
473                 node = node->parent;
474         }
475         return attr;
476 }
477
478 static void print_scene_graph(SceneNode *n, int level)
479 {
480         if(!n) return;
481
482         for(int i=0; i<level; i++) {
483                 info_log("  ");
484         }
485
486         int nobj = n->get_num_objects();
487         if(nobj) {
488                 info_log("%s - %d obj\n", n->get_name(), n->get_num_objects());
489         } else {
490                 info_log("%s\n", n->get_name());
491         }
492
493         for(int i=0; i<n->get_num_children(); i++) {
494                 print_scene_graph(n->get_child(i), level + 1);
495         }
496 }