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