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