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