2 * \brief Metascene implementation
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).
14 #include "metascene.h"
17 #include "treestore.h"
22 #if defined(WIN32) || defined(__WIN32__)
28 enum MaterialEditType {
33 struct MaterialEditTexture {
38 struct MaterialEditMirror {
45 MaterialEditType type;
47 MaterialEditTexture tex;
48 MaterialEditMirror mirror;
51 static bool proc_node(MetaScene *mscn, struct ts_node *node);
52 static bool proc_scenefile(MetaScene *mscn, struct ts_node *node);
53 static bool proc_mtledit(MetaScene *mscn, MaterialEdit *med, struct ts_node *node);
54 static bool proc_music(MetaScene *mscn, struct ts_node *node);
55 static void apply_mtledit(Scene *scn, const MaterialEdit &med);
56 static void apply_mtledit(Material *mtl, const MaterialEdit &med);
57 static struct ts_attr *attr_inscope(struct ts_node *node, const char *name);
59 static void print_scene_graph(SceneNode *n, int level);
62 MetaScene::MetaScene()
69 MetaScene::~MetaScene()
75 FlatMirror *m = mirrors;
76 mirrors = mirrors->next;
81 bool MetaScene::load(const char *fname)
83 struct ts_node *root = ts_load(fname);
84 if(!root || strcmp(root->name, "scene") != 0) {
86 error_log("failed to load scene metadata: %s\n", fname);
90 bool res = proc_node(this, root);
93 /*info_log("loaded scene: %s\n", fname);
94 info_log("scene graph:\n");
95 print_scene_graph(scn->nodes, 0);
100 void MetaScene::update(float dt)
103 static char text[256];
105 ImGui::Begin("MetaScene nodes", 0, 0);
110 float x = ImGui::GetColumnOffset(1);
111 ImGui::SetColumnOffset(1, x * 1.55);
116 int nscn = scenes.size();
117 for(int i=0; i<nscn; i++) {
120 if(scenes[i]->name.empty()) {
121 sprintf(text, "scene %3d", i);
123 sprintf(text, "scene %3d: %s", i, scenes[i]->name.c_str());
125 expanded = parent_expanded = ImGui::TreeNode(text);
130 scenes[i]->update(dt);
132 if(debug_gui && expanded) {
143 // XXX not used, renderer draws
144 void MetaScene::draw() const
146 error_log("Don't call MetaScene::draw, use the Renderer\n");
147 int nscn = scenes.size();
148 for(int i=0; i<nscn; i++) {
153 SceneNode *MetaScene::find_node(const char *name) const
155 int num = scenes.size();
156 for(int i=0; i<num; i++) {
157 SceneNode *n = scenes[i]->find_node(name);
163 SceneNode *MetaScene::match_node(const char *qstr) const
165 int num = scenes.size();
166 for(int i=0; i<num; i++) {
167 SceneNode *n = scenes[i]->match_node(qstr);
173 std::list<SceneNode*> MetaScene::match_nodes(const char *qstr) const
175 std::list<SceneNode*> res;
176 int num = scenes.size();
177 for(int i=0; i<num; i++) {
178 std::list<SceneNode*> tmp = scenes[i]->match_nodes(qstr);
180 res.splice(res.end(), tmp);
183 return res; // hopefully it'll be moved
186 Scene *MetaScene::extract_nodes(const char *qstr)
189 int nscn = scenes.size();
190 for(int i=0; i<nscn; i++) {
191 Scene *tmp = scenes[i]->extract_nodes(qstr);
204 int MetaScene::calc_mirror_planes()
206 FlatMirror *planes = 0;
210 FlatMirror *m = mirrors;
211 mirrors = mirrors->next;
217 int numscn = scenes.size();
218 for(int i=0; i<numscn; i++) {
219 Scene *scn = scenes[i];
221 int numobj = scn->objects.size();
222 for(int j=0; j<numobj; j++) {
223 Object *obj = scn->objects[j];
225 if(obj->mtl.flat_mirror && obj->get_type() == OBJ_MESH) {
226 const Mesh *mesh = ((ObjMesh*)obj)->mesh;
229 FlatMirror *mir = new FlatMirror;
230 mir->reflect = obj->mtl.reflect;
231 mir->node = obj->node;
233 if(obj->mtl.flat_mirror == MTL_MIRROR_AUTO) {
234 // grab the first triangle and make a plane
235 Triangle face = Triangle(0, (const Vec3*)mesh->get_attrib_data(MESH_ATTR_VERTEX),
236 mesh->get_index_data());
239 mir->plane.pt = face.v[0];
240 mir->plane.normal = face.normal;
242 int plane_idx = obj->mtl.flat_mirror - MTL_MIRROR_AABB_PX;
243 mir->plane = obj->get_aabox().get_plane(plane_idx);
246 mir->wplane = mir->plane;
248 const Mat4 &xform = obj->node->get_matrix();
249 mir->wplane.pt = xform * mir->wplane.pt;
250 mir->wplane.normal = normalize(xform.upper3x3() * mir->wplane.normal);
253 // check to see if we have found this mirror plane already
255 FlatMirror *node = planes;
257 float d1 = dot(mir->wplane.normal, mir->wplane.pt);
258 float d2 = dot(node->wplane.normal, node->wplane.pt);
260 if(1.0f - dot(mir->wplane.normal, node->wplane.normal) < 1e-4f &&
261 fabs(d1 - d2) < 1e-4) {
268 debug_log("[%s@%s] mirror plane: local(%g %g %g %g), world(%g %g %g %g)%s\n",
269 obj->get_name(), obj->node ? obj->node->get_name() : "<no-node>",
270 mir->plane.normal.x, mir->plane.normal.y, mir->plane.normal.z,
271 dot(mir->plane.normal, mir->plane.pt), mir->wplane.normal.x, mir->wplane.normal.y,
272 mir->wplane.normal.z, dot(mir->wplane.normal, mir->wplane.pt), found ? " duplicate" : "");
278 // also add a node to the mirror plane matching list
279 FlatMirror *m = new FlatMirror;
280 m->wplane = mir->wplane;
284 mir->objects.push_back(obj);
285 objmirror[obj] = mir; // associate with object
288 node->objects.push_back(obj);
296 FlatMirror *tmp = planes;
297 planes = planes->next;
304 static bool proc_node(MetaScene *mscn, struct ts_node *node)
306 struct ts_node *c = node->child_list;
308 if(!proc_node(mscn, c)) {
314 // do this last to allow other contents of the node to do their thing
315 if(strcmp(node->name, "scenefile") == 0) {
316 return proc_scenefile(mscn, node);
318 } else if(strcmp(node->name, "remap") == 0) {
319 const char *match = ts_get_attr_str(node, "match");
320 const char *replace = ts_get_attr_str(node, "replace");
321 if(match && replace) {
322 mscn->datamap.map(match, replace);
325 } else if(strcmp(node->name, "music") == 0) {
326 return proc_music(mscn, node);
336 std::string walkmesh_regexp, spawn_regexp;
337 std::vector<MaterialEdit> mtledit;
340 /*! Processes a `scenefile` node. And kicks off scene loading (if necessary) by
341 * calling `SceneSet::get`.
343 static bool proc_scenefile(MetaScene *mscn, struct ts_node *node)
345 const char *fname = ts_get_attr_str(node, "file");
347 SceneData *sdat = new SceneData;
351 struct ts_attr *adpath = attr_inscope(node, "datapath");
352 if(adpath && adpath->val.type == TS_STRING) {
353 mscn->datamap.set_path(adpath->val.str);
357 struct ts_attr *aspath = attr_inscope(node, "strip_path");
358 if(aspath && aspath->val.type == TS_NUMBER) {
359 mscn->datamap.set_strip(aspath->val.inum);
363 struct ts_attr *awmesh = attr_inscope(node, "walkmesh");
364 if(awmesh && awmesh->val.type == TS_STRING) {
365 sdat->walkmesh_regexp = std::string(awmesh->val.str);
369 struct ts_attr *awspawn = attr_inscope(node, "spawn");
371 switch(awspawn->val.type) {
373 mscn->start_pos = Vec3(awspawn->val.vec[0], awspawn->val.vec[1],
374 awspawn->val.vec[2]);
379 sdat->spawn_regexp = std::string(awspawn->val.str);
382 if((awspawn = attr_inscope(node, "spawn_rot")) && awspawn->val.type == TS_VECTOR) {
384 rot.rotate(Vec3(1, 0, 0), deg_to_rad(awspawn->val.vec[0]));
385 rot.rotate(Vec3(0, 1, 0), deg_to_rad(awspawn->val.vec[1]));
386 rot.rotate(Vec3(0, 0, 1), deg_to_rad(awspawn->val.vec[2]));
387 mscn->start_rot = rot;
390 int namesz = mscn->datamap.lookup(fname, 0, 0);
391 char *namebuf = (char*)alloca(namesz + 1);
392 if(mscn->datamap.lookup(fname, namebuf, namesz + 1)) {
396 // material edits are kept in a list to be applied when the scene has been loaded
397 struct ts_node *child = node->child_list;
400 if(proc_mtledit(mscn, &medit, child)) {
401 sdat->mtledit.push_back(medit);
406 Scene *newscn = sceneman.get(fname);
407 /* NOTE: setting all these after get() is not a race condition, because
408 * scene_loaded() which uses this, will only run in our main loop during
409 * SceneSet::update() on the main thread.
411 newscn->datamap = mscn->datamap;
412 mscn->datamap.clear();
414 newscn->metascn = mscn;
415 mscn->scndata[newscn] = sdat;
420 bool MetaScene::scene_loaded(Scene *newscn)
422 SceneData *sdat = (SceneData*)scndata[newscn];
424 error_log("MetaScene::scene_loaded called, but corresponding SceneData not found\n");
428 // extract the walk mesh if necessary
430 if(!sdat->walkmesh_regexp.empty() && (wscn = newscn->extract_nodes(sdat->walkmesh_regexp.c_str()))) {
431 // apply all transformations to the meshes
434 int nmeshes = wscn->meshes.size();
435 for(int i=0; i<nmeshes; i++) {
436 Mesh *m = wscn->meshes[i];
439 walk_mesh->append(*m);
442 wscn->remove_mesh(m); // to save it from destruction
449 // extract the spawn node
450 if(!sdat->spawn_regexp.empty() && (wscn = newscn->extract_nodes(sdat->spawn_regexp.c_str()))) {
452 int nmeshes = wscn->meshes.size();
453 int nnodes = wscn->nodes ? wscn->nodes->get_num_children() : 0;
457 for(int i=0; i<nmeshes; i++) {
458 const Sphere &bsph = wscn->meshes[i]->get_bsphere();
461 pos /= (float)nmeshes;
462 sdat->meta->start_pos = pos;
465 // just use the first one
466 SceneNode *first = wscn->nodes->get_child(0);
467 sdat->meta->start_pos = first->get_position();
468 sdat->meta->start_rot = first->get_rotation();
473 int num_medits = sdat->mtledit.size();
474 for(int i=0; i<num_medits; i++) {
475 // perform material edits
476 apply_mtledit(newscn, sdat->mtledit[i]);
479 scenes.push_back(newscn);
483 static bool proc_mtledit(MetaScene *mscn, MaterialEdit *med, struct ts_node *node)
485 if(strcmp(node->name, "mtledit") != 0) {
489 const char *restr = ".*";
490 struct ts_attr *amtl = ts_get_attr(node, "material");
491 if(amtl && amtl->val.type == TS_STRING) {
492 restr = amtl->val.str;
494 med->name_re = std::regex(restr);
496 node = node->child_list;
498 struct ts_node *cn = node;
501 if(strcmp(cn->name, "texture") == 0) {
502 // add/change/remove a texture
503 struct ts_attr *atype = ts_get_attr(cn, "type");
504 struct ts_attr *afile = ts_get_attr(cn, "file");
506 int textype = MTL_TEX_DIFFUSE;
508 if(atype->val.type == TS_STRING) {
509 textype = mtl_parse_type(atype->val.str);
510 } else if(atype->val.type == TS_NUMBER) {
511 textype = atype->val.inum;
512 if(textype < 0 || textype >= NUM_MTL_TEXTURES) {
513 error_log("invalid texture in mtledit: %d\n", textype);
517 error_log("unexpected texture type in mtledit: %s\n", atype->val.str);
522 med->tex.attr = textype;
524 if(!afile || !afile->val.str || !*afile->val.str) {
528 med->tex.tex = texman.get_texture(afile->val.str, TEX_2D, &mscn->datamap);
531 med->type = MTL_EDIT_TEXTURE;
535 if(strcmp(cn->name, "mirror") == 0) {
536 // make this object a flat mirror (hopefully the object is flat otherwise this won't work)
538 int plane = MTL_MIRROR_AUTO;
540 struct ts_attr *aplane = ts_get_attr(cn, "plane");
542 if(aplane->val.type == TS_NUMBER) {
543 plane = MTL_MIRROR_AABB_PX + aplane->val.inum;
546 if(sscanf(aplane->val.str, "aabb%c%c", &csign, &caxis) != 2 || (csign != '+' && csign != '-')) {
547 error_log("invalid reflect plane specifier: %s\n", aplane->val.str);
551 switch(tolower(caxis)) {
553 plane = csign == '+' ? MTL_MIRROR_AABB_PX : MTL_MIRROR_AABB_NX;
556 plane = csign == '+' ? MTL_MIRROR_AABB_PY : MTL_MIRROR_AABB_NY;
559 plane = csign == '+' ? MTL_MIRROR_AABB_PZ : MTL_MIRROR_AABB_NZ;
562 error_log("invalid reflect plane specifier: %s\n", aplane->val.str);
568 struct ts_attr *arefl = ts_get_attr(cn, "reflect");
570 if(arefl->val.type == TS_NUMBER) {
571 refl = arefl->val.fnum;
573 error_log("invalid reflect attribute in mirror mtledit: %s\n", arefl->val.str);
578 med->type = MTL_EDIT_MIRROR;
579 med->mirror.reflectivity = refl;
580 med->mirror.plane = plane;
588 static void apply_mtledit(Scene *scn, const MaterialEdit &med)
590 // search all the objects to find matching material names
591 int nobj = scn->objects.size();
592 for(int i=0; i<nobj; i++) {
593 Object *obj = scn->objects[i];
594 if(std::regex_match(obj->mtl.name, med.name_re)) {
595 apply_mtledit(&obj->mtl, med);
600 static bool proc_music(MetaScene *mscn, struct ts_node *node)
602 const char *fname = ts_get_attr_str(node, "file");
604 SceneData *sdat = new SceneData;
608 struct ts_attr *adpath = attr_inscope(node, "datapath");
609 if(adpath && adpath->val.type == TS_STRING) {
610 mscn->datamap.set_path(adpath->val.str);
613 int namesz = mscn->datamap.lookup(fname, 0, 0);
614 char *namebuf = (char*)alloca(namesz + 1);
615 if(mscn->datamap.lookup(fname, namebuf, namesz + 1)) {
619 OggVorbisStream *ovstream = new OggVorbisStream;
620 if(!ovstream->open(fname)) {
626 mscn->music = ovstream;
631 static void apply_mtledit(Material *mtl, const MaterialEdit &med)
633 // TODO more edit modes...
635 case MTL_EDIT_TEXTURE:
637 mtl->add_texture(med.tex.tex, med.tex.attr);
639 Texture *tex = mtl->stdtex[med.tex.attr];
641 mtl->remove_texture(tex);
646 case MTL_EDIT_MIRROR:
647 mtl->flat_mirror = med.mirror.plane;
648 mtl->reflect = med.mirror.reflectivity;
653 static struct ts_attr *attr_inscope(struct ts_node *node, const char *name)
655 struct ts_attr *attr = 0;
657 while(node && !(attr = ts_get_attr(node, name))) {
663 static void print_scene_graph(SceneNode *n, int level)
667 for(int i=0; i<level; i++) {
671 int nobj = n->get_num_objects();
673 info_log("%s - %d obj\n", n->get_name(), n->get_num_objects());
675 info_log("%s\n", n->get_name());
678 for(int i=0; i<n->get_num_children(); i++) {
679 print_scene_graph(n->get_child(i), level + 1);