added strip_path in metascene
[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 #ifdef 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 static bool proc_node(MetaScene *mscn, struct ts_node *node)
79 {
80         struct ts_node *c = node->child_list;
81         while(c) {
82                 if(!proc_node(mscn, c)) {
83                         return false;
84                 }
85                 c = c->next;
86         }
87
88         // do this last to allow other contents of the node to do their thing
89         if(strcmp(node->name, "scenefile") == 0) {
90                 return proc_scenefile(mscn, node);
91
92         } else if(strcmp(node->name, "remap") == 0) {
93                 const char *match = ts_get_attr_str(node, "match");
94                 const char *replace = ts_get_attr_str(node, "replace");
95                 if(match && replace) {
96                         mscn->datamap.map(match, replace);
97                 }
98         }
99
100         return true;
101 }
102
103
104
105 struct SceneData {
106         MetaScene *meta;
107         std::string walkmesh_regexp, spawn_regexp;
108         std::vector<MaterialEdit> mtledit;
109 };
110
111 static bool proc_scenefile(MetaScene *mscn, struct ts_node *node)
112 {
113         const char *fname = ts_get_attr_str(node, "file");
114         if(fname) {
115                 SceneData *sdat = new SceneData;
116                 sdat->meta = mscn;
117
118                 // datapath
119                 struct ts_attr *adpath = attr_inscope(node, "datapath");
120                 if(adpath && adpath->val.type == TS_STRING) {
121                         mscn->datamap.set_path(adpath->val.str);
122                 }
123
124                 // strip path
125                 struct ts_attr *aspath = attr_inscope(node, "strip_path");
126                 if(aspath && aspath->val.type == TS_NUMBER) {
127                         mscn->datamap.set_strip(aspath->val.inum);
128                 }
129
130                 // walkmesh
131                 struct ts_attr *awmesh = attr_inscope(node, "walkmesh");
132                 if(awmesh && awmesh->val.type == TS_STRING) {
133                         sdat->walkmesh_regexp = std::string(awmesh->val.str);
134                 }
135
136                 // spawn node
137                 struct ts_attr *awspawn = attr_inscope(node, "spawn");
138                 if(awspawn) {
139                         switch(awspawn->val.type) {
140                         case TS_VECTOR:
141                                 mscn->start_pos = Vec3(awspawn->val.vec[0], awspawn->val.vec[1],
142                                                 awspawn->val.vec[2]);
143                                 break;
144
145                         case TS_STRING:
146                         default:
147                                 sdat->spawn_regexp = std::string(awspawn->val.str);
148                         }
149                 }
150                 if((awspawn = attr_inscope(node, "spawn_rot")) && awspawn->val.type == TS_VECTOR) {
151                         Quat rot;
152                         rot.rotate(Vec3(1, 0, 0), deg_to_rad(awspawn->val.vec[0]));
153                         rot.rotate(Vec3(0, 1, 0), deg_to_rad(awspawn->val.vec[1]));
154                         rot.rotate(Vec3(0, 0, 1), deg_to_rad(awspawn->val.vec[2]));
155                         mscn->start_rot = rot;
156                 }
157
158                 int namesz = mscn->datamap.lookup(fname, 0, 0);
159                 char *namebuf = (char*)alloca(namesz + 1);
160                 if(mscn->datamap.lookup(fname, namebuf, namesz + 1)) {
161                         fname = namebuf;
162                 }
163
164                 // material edits
165                 struct ts_node *child = node->child_list;
166                 while(child) {
167                         MaterialEdit medit;
168                         if(proc_mtledit(mscn, &medit, child)) {
169                                 sdat->mtledit.push_back(medit);
170                         }
171                         child = child->next;
172                 }
173
174                 Scene *newscn = sceneman.get(fname);
175                 /* NOTE: setting all these after get() is not a race condition, because
176                  * scene_loaded() which uses this, will only run in our main loop during
177                  * SceneSet::update() on the main thread.
178                  */
179                 newscn->datamap = mscn->datamap;
180                 mscn->datamap.clear();
181
182                 newscn->metascn = mscn;
183                 mscn->scndata[newscn] = sdat;
184         }
185         return true;
186 }
187
188 bool MetaScene::scene_loaded(Scene *newscn)
189 {
190         SceneData *sdat = (SceneData*)scndata[newscn];
191         if(!sdat) {
192                 error_log("MetaScene::scene_loaded called, but corresponding SceneData not found\n");
193                 return false;
194         }
195
196         // extract the walk mesh if necessary
197         Scene *wscn;
198         if(!sdat->walkmesh_regexp.empty() && (wscn = newscn->extract_nodes(sdat->walkmesh_regexp.c_str()))) {
199                 // apply all transformations to the meshes
200                 wscn->apply_xform();
201
202                 int nmeshes = wscn->meshes.size();
203                 for(int i=0; i<nmeshes; i++) {
204                         Mesh *m = wscn->meshes[i];
205
206                         if(walk_mesh) {
207                                 walk_mesh->append(*m);
208                         } else {
209                                 walk_mesh = m;
210                                 wscn->remove_mesh(m);   // to save it from destruction
211                         }
212                 }
213
214                 delete wscn;
215         }
216
217         // extract the spawn node
218         if(!sdat->spawn_regexp.empty() && (wscn = newscn->extract_nodes(sdat->spawn_regexp.c_str()))) {
219
220                 int nmeshes = wscn->meshes.size();
221                 int nnodes = wscn->nodes ? wscn->nodes->get_num_children() : 0;
222
223                 if(nmeshes) {
224                         Vec3 pos;
225                         for(int i=0; i<nmeshes; i++) {
226                                 const Sphere &bsph = wscn->meshes[i]->get_bsphere();
227                                 pos += bsph.center;
228                         }
229                         pos /= (float)nmeshes;
230                         sdat->meta->start_pos = pos;
231
232                 } else if(nnodes) {
233                         // just use the first one
234                         SceneNode *first = wscn->nodes->get_child(0);
235                         sdat->meta->start_pos = first->get_position();
236                         sdat->meta->start_rot = first->get_rotation();
237                 }
238                 delete wscn;
239         }
240
241         int num_medits = sdat->mtledit.size();
242         for(int i=0; i<num_medits; i++) {
243                 // perform material edits
244                 apply_mtledit(newscn, sdat->mtledit[i]);
245         }
246
247         scenes.push_back(newscn);
248         return true;
249 }
250
251 static bool proc_mtledit(MetaScene *mscn, MaterialEdit *med, struct ts_node *node)
252 {
253         if(strcmp(node->name, "mtledit") != 0) {
254                 return false;
255         }
256
257         const char *restr = ".*";
258         struct ts_attr *amtl = ts_get_attr(node, "material");
259         if(amtl && amtl->val.type == TS_STRING) {
260                 restr = amtl->val.str;
261         }
262
263         med->name_re = std::regex(restr);
264
265         node = node->child_list;
266         while(node) {
267                 struct ts_node *cn = node;
268                 node = node->next;
269
270                 if(strcmp(cn->name, "texture") == 0) {
271                         // add/change/remove a texture
272                         struct ts_attr *atype = ts_get_attr(cn, "type");
273                         struct ts_attr *afile = ts_get_attr(cn, "file");
274
275                         int textype = MTL_TEX_DIFFUSE;
276                         if(atype) {
277                                 if(atype->val.type == TS_STRING) {
278                                         textype = mtl_parse_type(atype->val.str);
279                                 } else if(atype->val.type == TS_NUMBER) {
280                                         textype = atype->val.inum;
281                                         if(textype < 0 || textype >= NUM_MTL_TEXTURES) {
282                                                 error_log("invalid texture in mtledit: %d\n", textype);
283                                                 continue;
284                                         }
285                                 } else {
286                                         error_log("unexpected texture type in mtledit: %s\n", atype->val.str);
287                                         continue;
288                                 }
289                         }
290
291                         med->attr = textype;
292
293                         if(!afile || !afile->val.str || !*afile->val.str) {
294                                 // remove
295                                 med->tex = 0;
296                         } else {
297                                 med->tex = texman.get_texture(afile->val.str, TEX_2D, &mscn->datamap);
298                         }
299                 }
300                 // TODO add more edit modes
301         }
302
303         return true;
304 }
305
306 static void apply_mtledit(Scene *scn, const MaterialEdit &med)
307 {
308         // search all the objects to find matching material names
309         int nobj = scn->objects.size();
310         for(int i=0; i<nobj; i++) {
311                 Object *obj = scn->objects[i];
312                 if(std::regex_match(obj->mtl.name, med.name_re)) {
313                         apply_mtledit(&obj->mtl, med);
314                 }
315         }
316 }
317
318 static void apply_mtledit(Material *mtl, const MaterialEdit &med)
319 {
320         // TODO more edit modes...
321         if(med.tex) {
322                 mtl->add_texture(med.tex, med.attr);
323         } else {
324                 Texture *tex = mtl->stdtex[med.attr];
325                 if(tex) {
326                         mtl->remove_texture(tex);
327                 }
328         }
329 }
330
331 static struct ts_attr *attr_inscope(struct ts_node *node, const char *name)
332 {
333         struct ts_attr *attr = 0;
334
335         while(node && !(attr = ts_get_attr(node, name))) {
336                 node = node->parent;
337         }
338         return attr;
339 }
340
341 static void print_scene_graph(SceneNode *n, int level)
342 {
343         if(!n) return;
344
345         for(int i=0; i<level; i++) {
346                 info_log("  ");
347         }
348
349         int nobj = n->get_num_objects();
350         if(nobj) {
351                 info_log("%s - %d obj\n", n->get_name(), n->get_num_objects());
352         } else {
353                 info_log("%s\n", n->get_name());
354         }
355
356         for(int i=0; i<n->get_num_children(); i++) {
357                 print_scene_graph(n->get_child(i), level + 1);
358         }
359 }