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