载入中...
搜索中...
未找到
SceneLoader.cpp
浏览该文件的文档.
4
8#include "common/ECS.h"
9#include "common/Resource.h"
12#include "data/ByteData.h"
13#include "filesystem/FileData.h"
15#include "graphics/Graphics.h"
16#include "graphics/Light.h"
17#include "graphics/Mesh.h"
19#include "graphics/Texture.h"
20#include "image/Image.h"
21#include "image/ImageData.h"
22#include "model3d/Model3D.h"
23#include "model3d/ModelData.h"
24#include "scene/NodeDesc.h"
25#include "scene/SceneHost.h"
27#include "thread/ThreadPool.h"
28
29#include <assimp/scene.h>
30#include <assimp/mesh.h>
31#include <assimp/material.h>
32#include <assimp/matrix4x4.h>
33#include <assimp/quaternion.h>
34#include <assimp/vector3.h>
35#include <assimp/texture.h>
36#include <assimp/light.h>
37#include <assimp/camera.h>
38#include <assimp/GltfMaterial.h>
39
40#include <glm/glm.hpp>
41#include <glm/gtx/matrix_decompose.hpp>
42#include <glm/gtc/matrix_transform.hpp>
43#include <glm/gtc/quaternion.hpp>
44
45#include <limits>
46
47#include <simplesquirrel/simplesquirrel.hpp>
48
49#include <algorithm>
50#include <cmath>
51#include <cstdlib>
52#include <functional>
53#include <memory>
54#include <unordered_set>
55
56namespace eve {
57namespace sceneloader {
58
59SceneLoader::DecodedScene::DecodedScene() = default;
60SceneLoader::DecodedScene::~DecodedScene() = default;
61SceneLoader::DecodedScene::DecodedScene(DecodedScene &&) noexcept = default;
62SceneLoader::DecodedScene &SceneLoader::DecodedScene::operator=(DecodedScene &&) noexcept = default;
63
65
67
70 // Decoded ModelData instances are owned by the unified resource cache
71 // (Model3D::newModelDataFromFile returns cache-shared resources), so no
72 // cleanup is needed here.
73 clearTextures();
74}
75
76namespace {
77
78constexpr float kEps = 1e-5f;
79
80template <class T>
81T *borrowResult(eve::Result<T *> result) {
82 if (!result.ok()) return nullptr;
83 return result.value();
84}
85
86std::string normPath(const std::string &p) {
87 std::string out;
88 out.reserve(p.size());
89 for (char c : p) {
90 if (c == '\\') out.push_back('/');
91 else out.push_back(c);
92 }
93 return out;
94}
95
96graphics::Graphics *currentGraphics() {
97 return ModuleManager::getInstance<graphics::Graphics>("Graphics");
98}
99
100model3d::ModelLoadOptions toModelOptions(const LoadOptions &o) {
101 model3d::ModelLoadOptions m;
102 m.triangulate = o.triangulate;
103 m.generateNormalsIfMissing = o.generateNormalsIfMissing;
104 m.joinIdenticalVertices = o.joinIdenticalVertices;
105 m.flipUVs = o.flipUVs;
106 m.improveCacheLocality = o.improveCacheLocality;
107 return m;
108}
109
110bool approx(float a, float b) { return std::fabs(a - b) < kEps; }
111
112// ---- transform helpers ----
113
114void decomposeNode(const aiMatrix4x4 &m, float &x, float &y, float &z, float &yaw, float &pitch,
115 float &roll, float &sx, float &sy, float &sz) {
116 aiVector3D pos, scale;
117 aiQuaternion rot;
118 m.Decompose(scale, rot, pos);
119 x = pos.x;
120 y = pos.y;
121 z = pos.z;
122 sx = scale.x;
123 sy = scale.y;
124 sz = scale.z;
125 glm::quat q(rot.w, rot.x, rot.y, rot.z);
126 // The inverse of the order localMatrix() recomposes; glm::eulerAngles()
127 // belongs to a different family and mangled every multi-axis import.
129}
130
131std::string uniqueId(const std::string &base, std::unordered_map<std::string, int> &counts) {
132 std::string b = base.empty() ? "node" : base;
133 int &n = counts[b];
134 std::string id = b;
135 if (n > 0) id = b + "_" + std::to_string(n);
136 ++n;
137 return id;
138}
139
140bool startsWithInsensitive(const std::string &value, const char *prefix) {
141 const size_t n = std::char_traits<char>::length(prefix);
142 if (value.size() < n) return false;
143 for (size_t i = 0; i < n; ++i)
144 if (std::tolower(static_cast<unsigned char>(value[i])) !=
145 std::tolower(static_cast<unsigned char>(prefix[i])))
146 return false;
147 return true;
148}
149
150int lodFromName(const std::string &name) {
151 const size_t p = name.rfind("_LOD");
152 if (p == std::string::npos || p + 4 >= name.size()) return -1;
153 char *end = nullptr;
154 const long value = std::strtol(name.c_str() + p + 4, &end, 10);
155 return end == name.c_str() + p + 4 || value < 0 ? -1 : static_cast<int>(value);
156}
157
158LoadOptions presetOptions(const std::string &name) {
159 LoadOptions o;
160 if (name == "quality" || name == "balanced" || name.empty()) return o;
161 if (name == "mobile") {
162 o.importLights = false;
163 o.importCameras = false;
164 o.importAnimations = false;
165 return o;
166 }
167 if (name == "raw") {
168 o.generateNormalsIfMissing = false;
169 o.joinIdenticalVertices = false;
170 o.flipUVs = false;
171 o.improveCacheLocality = false;
172 o.sharedMeshes = false;
173 o.mipmaps = false;
174 o.importLights = false;
175 o.importCameras = false;
176 o.importAnimations = false;
177 return o;
178 }
179 throw eve::Exception("SceneLoader: unknown import preset '%s'", name.c_str());
180}
181
182// ---- texture helpers (embedded / VFS, cached by path) ----
183
185struct SamplerSpec {
186 bool repeatU = true;
187 bool repeatV = true;
188 bool mips = true;
189 std::string filter = "linear"; // "linear" | "nearest"
190 std::string mipmap = "linear"; // "none" | "linear" | "nearest"
191};
192
193SamplerSpec samplerFor(const aiMaterial *mat, aiTextureType type, bool wantMips) {
194 SamplerSpec s;
195 if (!mat) {
196 s.mips = wantMips;
197 return s;
198 }
199 int modeU = aiTextureMapMode_Wrap;
200 int modeV = aiTextureMapMode_Wrap;
201 mat->Get(AI_MATKEY_MAPPINGMODE_U(type, 0), modeU);
202 mat->Get(AI_MATKEY_MAPPINGMODE_V(type, 0), modeV);
203 s.repeatU = (modeU != aiTextureMapMode_Clamp && modeU != aiTextureMapMode_Mirror);
204 s.repeatV = (modeV != aiTextureMapMode_Clamp && modeV != aiTextureMapMode_Mirror);
205
206 // glTF sampler filter values (AI_MATKEY_GLTF_MAPPINGFILTER_*).
207 int mag = 0, min = 0;
208 mat->Get(AI_MATKEY_GLTF_MAPPINGFILTER_MAG(type, 0), mag);
209 mat->Get(AI_MATKEY_GLTF_MAPPINGFILTER_MIN(type, 0), min);
210 s.filter = (mag == 9728) ? "nearest" : "linear"; // 0 / 9729(linear) -> linear
211 switch (min) {
212 case 9728: // NEAREST
213 case 9729: // LINEAR — no mipmaps requested by the source
214 s.mips = false;
215 s.mipmap = "none";
216 break;
217 case 9986: // NEAREST_MIPMAP_LINEAR
218 case 9987: // LINEAR_MIPMAP_LINEAR
219 s.mips = wantMips;
220 s.mipmap = "linear";
221 break;
222 case 9984: // NEAREST_MIPMAP_NEAREST
223 case 9985: // LINEAR_MIPMAP_NEAREST
224 s.mips = wantMips;
225 s.mipmap = "nearest";
226 break;
227 default: // unspecified -> honor the global toggle
228 s.mips = wantMips;
229 s.mipmap = wantMips ? "linear" : "none";
230 break;
231 }
232 return s;
233}
234
235graphics::Texture *resolveTexture(graphics::Graphics *gfx, const aiScene *scene,
236 const aiMaterial *mat, aiTextureType type,
237 SceneLoader::TextureCache &cache, bool wantMips,
238 const SceneLoader::CpuImageMap *predecoded = nullptr) {
239 if (!gfx || !scene || !mat) return nullptr;
240 aiString path;
241 if (mat->GetTexture(type, 0, &path) != AI_SUCCESS) return nullptr;
242 const char *p = path.C_Str();
243 if (!p || !p[0]) return nullptr;
244
245 const SamplerSpec s = samplerFor(mat, type, wantMips);
246 auto *const imageModule = eve::image::Image::create();
247
248 const std::string keySuffix =
249 std::string(s.repeatU ? "|1" : "|0") + (s.repeatV ? "1" : "0") + "|" + s.filter + "|" +
250 s.mipmap;
251
252 // Embedded texture ("*0", "*1", ...).
253 if (p[0] == '*') {
254 int idx = std::atoi(p + 1);
255 if (idx < 0 || static_cast<unsigned>(idx) >= scene->mNumTextures) return nullptr;
256 const aiTexture *tex = scene->mTextures[idx];
257 if (!tex || !tex->pcData) return nullptr;
258 const std::string key = "*" + std::to_string(idx) + keySuffix;
259 auto it = cache.find(key);
260 if (it != cache.end()) return it->second;
261
262 graphics::Texture *t = nullptr;
263 if (tex->mHeight == 0) {
264 eve::data::ByteData bytes(tex->pcData, static_cast<size_t>(tex->mWidth));
265 try {
266 eve::image::ImageData *img = imageModule->newImageData(&bytes);
267 t = gfx->newTextureWithSampler(img, s.repeatU, s.repeatV, s.mips, 8.f, s.filter,
268 s.mipmap);
269 delete img;
270 } catch (...) {
271 return nullptr;
272 }
273 } else {
274 const unsigned w = tex->mWidth;
275 const unsigned h = tex->mHeight;
276 std::vector<uint8_t> rgba(size_t(w) * size_t(h) * 4);
277 const aiTexel *src = tex->pcData;
278 for (unsigned i = 0; i < w * h; ++i) {
279 rgba[i * 4 + 0] = src[i].r;
280 rgba[i * 4 + 1] = src[i].g;
281 rgba[i * 4 + 2] = src[i].b;
282 rgba[i * 4 + 3] = src[i].a;
283 }
284 eve::image::ImageData img(int(w), int(h), "RGBA8", rgba.data(), false);
285 t = gfx->newTextureWithSampler(&img, s.repeatU, s.repeatV, s.mips, 8.f, s.filter,
286 s.mipmap);
287 }
288 if (t) cache[key] = t;
289 return t;
290 }
291
292 // External file through the VFS.
293 const std::string key = normPath(p) + keySuffix;
294 auto it = cache.find(key);
295 if (it != cache.end()) return it->second;
296
297 // Off-thread pre-decoded CPU image (async path): upload directly, no disk IO.
298 if (predecoded) {
299 auto pit = predecoded->find(key);
300 if (pit != predecoded->end()) {
301 const SceneLoader::CpuImage &ci = pit->second;
302 eve::image::ImageData img(ci.w, ci.h, "RGBA8",
303 const_cast<uint8_t *>(ci.rgba.data()), false);
304 graphics::Texture *t = gfx->newTextureWithSampler(&img, s.repeatU, s.repeatV, s.mips,
305 8.f, s.filter, s.mipmap);
306 if (t) cache[key] = t;
307 return t;
308 }
309 }
310
311 try {
312 auto *fs = eve::filesystem::Filesystem::create();
313 std::unique_ptr<eve::filesystem::FileData> fd(fs->read(p));
314 if (fd && fd->getSize() > 0) {
315 eve::image::ImageData *img = imageModule->newImageData(fd.get());
316 graphics::Texture *t = gfx->newTextureWithSampler(img, s.repeatU, s.repeatV, s.mips,
317 8.f, s.filter, s.mipmap);
318 delete img;
319 if (t) cache[key] = t;
320 return t;
321 }
322 } catch (...) {
323 }
324 return nullptr;
325}
326
327// Pre-decode external (non-embedded) texture files off the calling thread so the
328// async loader can skip disk IO + image decode on the render thread.
329void collectCpuImages(const aiScene *scene, const MeshSlotMap &slots, bool wantMips,
331 if (!scene) return;
332 auto *const imageModule = eve::image::Image::create();
333 const aiTextureType kTypes[4] = {aiTextureType_BASE_COLOR, aiTextureType_DIFFUSE,
334 aiTextureType_NORMALS, aiTextureType_HEIGHT};
335 for (const auto &kv : slots) {
336 for (const MeshSlot &slot : kv.second) {
337 if (!slot.scene || slot.materialIndex >= scene->mNumMaterials) continue;
338 const aiMaterial *mat = scene->mMaterials[slot.materialIndex];
339 if (!mat) continue;
340 for (aiTextureType type : kTypes) {
341 aiString p;
342 if (mat->GetTexture(type, 0, &p) != AI_SUCCESS) continue;
343 const char *c = p.C_Str();
344 if (!c || !c[0] || c[0] == '*') continue; // embedded handled on main thread
345 const SamplerSpec s = samplerFor(mat, type, wantMips);
346 const std::string key = normPath(c) + std::string(s.repeatU ? "|1" : "|0") +
347 (s.repeatV ? "1" : "0") + "|" + s.filter + "|" + s.mipmap;
348 if (out.count(key)) continue;
349 try {
350 auto *fs = eve::filesystem::Filesystem::create();
351 std::unique_ptr<eve::filesystem::FileData> fd(fs->read(c));
352 if (!fd || fd->getSize() == 0) continue;
353 eve::image::ImageData *img = imageModule->newImageData(fd.get());
354 if (!img) continue;
355 if (img->getFormat() == "RGBA8") {
356 SceneLoader::CpuImage ci;
357 ci.w = img->getWidth();
358 ci.h = img->getHeight();
359 const size_t n = size_t(ci.w) * size_t(ci.h) * 4;
360 ci.rgba.assign(reinterpret_cast<const uint8_t *>(img->getData()),
361 reinterpret_cast<const uint8_t *>(img->getData()) + n);
362 out[key] = std::move(ci);
363 }
364 delete img;
365 } catch (...) {
366 }
367 }
368 }
369 }
370}
371
372// ---- renderable creation ----
373
374graphics::Renderable3D *makeRenderable(graphics::Graphics *gfx, const MeshSlot &slot,
375 SceneLoader::TextureCache &textures, bool mipmaps) {
376 if (!gfx || !slot.mesh) return nullptr;
377 graphics::Mesh *mesh = gfx->newMeshFromAssimp(*slot.mesh); // local-space (hierarchy transform)
378 if (!mesh) return nullptr;
379 auto *r = graphics::Renderable3D::create();
380 r->meshRenderer()->visible = true;
381 r->setMesh(mesh);
382
383 const aiScene *scene = slot.scene;
384 const aiMaterial *mat = nullptr;
385 if (scene && scene->mMaterials && slot.materialIndex < scene->mNumMaterials)
386 mat = scene->mMaterials[slot.materialIndex];
387
388 aiColor3D base(1.f, 1.f, 1.f);
389 if (mat) {
390 if (mat->Get(AI_MATKEY_BASE_COLOR, base) != AI_SUCCESS)
391 mat->Get(AI_MATKEY_COLOR_DIFFUSE, base);
392 float metallic = 0.f;
393 float roughness = 0.45f;
394 mat->Get(AI_MATKEY_METALLIC_FACTOR, metallic);
395 mat->Get(AI_MATKEY_ROUGHNESS_FACTOR, roughness);
396 r->setMetallic(metallic);
397 r->setRoughness(roughness);
398 }
399
400 graphics::Texture *albedo =
401 resolveTexture(gfx, scene, mat, aiTextureType_BASE_COLOR, textures, mipmaps);
402 if (!albedo) albedo = resolveTexture(gfx, scene, mat, aiTextureType_DIFFUSE, textures, mipmaps);
403 graphics::Texture *normal =
404 resolveTexture(gfx, scene, mat, aiTextureType_NORMALS, textures, mipmaps);
405 graphics::Texture *height =
406 resolveTexture(gfx, scene, mat, aiTextureType_HEIGHT, textures, mipmaps);
407
408 r->setTint(base.r, base.g, base.b, 1.f);
409 if (albedo) r->setTexture(albedo);
410 if (normal) r->setNormalTexture(normal);
411 if (height) r->setHeightTexture(height);
412 return r;
413}
414
415void destroyRenderable(graphics::Renderable3D *r) {
416 if (r) ecs::DestroyEntity(r);
417}
418
419// ---- mesh AABB bounds (picking / culling) ----
420
421glm::mat4 nodeLocalMatrix(const scene::SceneNode &n) {
422 glm::mat4 m(1.f);
423 m = glm::translate(m, glm::vec3(n.x, n.y, n.z));
424 if (n.space == "2d") {
425 m = glm::rotate(m, n.roll, glm::vec3(0.f, 0.f, 1.f));
426 } else {
427 m = glm::rotate(m, n.yaw, glm::vec3(0.f, 1.f, 0.f));
428 m = glm::rotate(m, n.pitch, glm::vec3(1.f, 0.f, 0.f));
429 m = glm::rotate(m, n.roll, glm::vec3(0.f, 0.f, 1.f));
430 }
431 m = glm::scale(m, glm::vec3(n.sx, n.sy, n.sz));
432 return m;
433}
434
435void fillMeshBoundsFromSlot(scene::SceneNode &n, const MeshSlot &slot) {
436 const aiMesh *mesh = slot.mesh;
437 if (!mesh || !mesh->mVertices || mesh->mNumVertices == 0) return;
438 float mn[3] = {std::numeric_limits<float>::max(),
439 std::numeric_limits<float>::max(),
440 std::numeric_limits<float>::max()};
441 float mx[3] = {std::numeric_limits<float>::lowest(),
442 std::numeric_limits<float>::lowest(),
443 std::numeric_limits<float>::lowest()};
444 for (unsigned i = 0; i < mesh->mNumVertices; ++i) {
445 const aiVector3D &v = mesh->mVertices[i];
446 for (int c = 0; c < 3; ++c) {
447 const float f = v[c];
448 mn[c] = std::min(mn[c], f);
449 mx[c] = std::max(mx[c], f);
450 }
451 }
452 n.bminX = mn[0];
453 n.bminY = mn[1];
454 n.bminZ = mn[2];
455 n.bmaxX = mx[0];
456 n.bmaxY = mx[1];
457 n.bmaxZ = mx[2];
458 n.hasBounds = true;
459}
460
462void unionChildBounds(scene::SceneHost::Tree &tree, int nodeIndex) {
463 scene::SceneNode &n = tree.nodes[size_t(nodeIndex)];
464 for (int c = n.firstChild; c >= 0; c = tree.nodes[size_t(c)].nextSibling) {
465 unionChildBounds(tree, c);
466 }
467
468 bool any = false;
469 float mn[3] = {std::numeric_limits<float>::max(),
470 std::numeric_limits<float>::max(),
471 std::numeric_limits<float>::max()};
472 float mx[3] = {std::numeric_limits<float>::lowest(),
473 std::numeric_limits<float>::lowest(),
474 std::numeric_limits<float>::lowest()};
475 for (int c = n.firstChild; c >= 0; c = tree.nodes[size_t(c)].nextSibling) {
476 scene::SceneNode &ch = tree.nodes[size_t(c)];
477 if (!ch.hasBounds) continue;
478 any = true;
479 const glm::mat4 lm = nodeLocalMatrix(ch);
480 for (int i = 0; i < 8; ++i) {
481 const glm::vec3 p((i & 1) ? ch.bmaxX : ch.bminX,
482 (i & 2) ? ch.bmaxY : ch.bminY,
483 (i & 4) ? ch.bmaxZ : ch.bminZ);
484 const glm::vec4 w = lm * glm::vec4(p, 1.f);
485 for (int k = 0; k < 3; ++k) {
486 mn[k] = std::min(mn[k], w[k]);
487 mx[k] = std::max(mx[k], w[k]);
488 }
489 }
490 }
491 if (!any) return;
492 if (!n.hasBounds) {
493 n.bminX = mn[0];
494 n.bminY = mn[1];
495 n.bminZ = mn[2];
496 n.bmaxX = mx[0];
497 n.bmaxY = mx[1];
498 n.bmaxZ = mx[2];
499 n.hasBounds = true;
500 } else {
501 n.bminX = std::min(n.bminX, mn[0]);
502 n.bminY = std::min(n.bminY, mn[1]);
503 n.bminZ = std::min(n.bminZ, mn[2]);
504 n.bmaxX = std::max(n.bmaxX, mx[0]);
505 n.bmaxY = std::max(n.bmaxY, mx[1]);
506 n.bmaxZ = std::max(n.bmaxZ, mx[2]);
507 }
508}
509
510// ---- NodeDesc build ----
511
512void buildNodeRecursive(const aiScene *scene, const aiNode *node, scene::NodeDesc &out,
513 MeshSlotMap *slots, std::unordered_map<std::string, int> &counts) {
514 const std::string rawName = (node && node->mName.length) ? node->mName.C_Str() : "<root>";
515 const std::string id = uniqueId(rawName, counts);
516
517 out.id = id;
518 out.key = id;
519 out.name = rawName;
520 out.space = "3d";
521 out.visible = true;
522 if (startsWithInsensitive(rawName, "SOCKET_")) out.tags.push_back("model-socket");
523 if (startsWithInsensitive(rawName, "UCX_") || startsWithInsensitive(rawName, "UBX_") ||
524 startsWithInsensitive(rawName, "USP_") || startsWithInsensitive(rawName, "UCP_")) {
525 out.tags.push_back("collision");
526 out.visible = false;
527 }
528 const int lod = lodFromName(rawName);
529 if (lod >= 0) {
530 out.tags.push_back("lod");
531 out.tags.push_back("lod:" + std::to_string(lod));
532 out.visible = lod == 0;
533 }
534 decomposeNode(node->mTransformation, out.x, out.y, out.z, out.yaw, out.pitch, out.roll,
535 out.sx, out.sy, out.sz);
536
537 for (unsigned i = 0; node && i < node->mNumMeshes; ++i) {
538 const unsigned mi = node->mMeshes[i];
539 if (mi >= scene->mNumMeshes) continue;
540 const aiMesh *mesh = scene->mMeshes[mi];
541 if (!mesh || mesh->mNumFaces == 0) continue;
542
543 const std::string cid = id + "_mesh" + std::to_string(i);
544 scene::NodeDesc child;
545 child.id = cid;
546 child.key = cid;
547 child.name = std::string("mesh") + std::to_string(i);
548 child.space = "3d";
549 child.visible = out.visible;
550 child.tags = out.tags;
551 out.children.push_back(std::move(child));
552
553 if (slots) {
554 MeshSlot s;
555 s.scene = scene;
556 s.mesh = mesh;
557 s.materialIndex = mesh->mMaterialIndex;
558 (*slots)[cid].push_back(std::move(s));
559 }
560 }
561
562 for (unsigned c = 0; node && c < node->mNumChildren; ++c) {
563 scene::NodeDesc child;
564 buildNodeRecursive(scene, node->mChildren[c], child, slots, counts);
565 out.children.push_back(std::move(child));
566 }
567}
568
569bool propsChanged(const scene::SceneNode &n, const scene::NodeDesc &d) {
570 if (n.visible != d.visible) return true;
571 return !(approx(n.x, d.x) && approx(n.y, d.y) && approx(n.z, d.z) && approx(n.yaw, d.yaw) &&
572 approx(n.pitch, d.pitch) && approx(n.roll, d.roll) && approx(n.sx, d.sx) &&
573 approx(n.sy, d.sy) && approx(n.sz, d.sz));
574}
575
576// Walk the new tree in DFS order, emitting Add / Move / Modify entries.
577void walkNew(const scene::NodeDesc &d, const std::string &parentId,
578 const std::unordered_map<std::string, const scene::SceneNode *> &oldNodes,
579 const std::unordered_map<std::string, std::string> &oldParent, SceneDiff &out) {
580 auto it = oldNodes.find(d.id);
581 if (it == oldNodes.end()) {
582 out.entries.push_back({SceneDiffEntry::Action::Add, d.id, parentId});
583 ++out.added;
584 } else {
585 auto pit = oldParent.find(d.id);
586 const std::string op = (pit != oldParent.end()) ? pit->second : "";
587 if (op != parentId) {
588 out.entries.push_back({SceneDiffEntry::Action::Move, d.id, parentId});
589 ++out.moved;
590 } else if (propsChanged(*it->second, d)) {
591 out.entries.push_back({SceneDiffEntry::Action::Modify, d.id, ""});
592 ++out.modified;
593 }
594 }
595 for (const auto &child : d.children) walkNew(child, d.id, oldNodes, oldParent, out);
596}
597
598// ---- lights / cameras / animation import ----
599
600void importLights(const aiScene *scene, std::vector<graphics::Light3D *> &out) {
601 if (!scene) return;
602 for (unsigned i = 0; i < scene->mNumLights; ++i) {
603 const aiLight *l = scene->mLights[i];
604 if (!l) continue;
605 std::string type = "point";
606 switch (l->mType) {
607 case aiLightSource_DIRECTIONAL:
608 type = "dir";
609 break;
610 case aiLightSource_POINT:
611 case aiLightSource_SPOT:
612 case aiLightSource_AREA:
613 default:
614 type = "point";
615 break;
616 }
617 graphics::Light3D *light = graphics::Light3D::createLight(type);
618 if (type == "dir") {
619 light->setDirection(l->mDirection.x, l->mDirection.y, l->mDirection.z);
620 } else {
621 light->setPosition(l->mPosition.x, l->mPosition.y, l->mPosition.z);
622 float radius = 8.f;
623 if (l->mAttenuationQuadratic > 1e-6f)
624 radius = 1.f / std::sqrt(l->mAttenuationQuadratic);
625 light->setRadius(radius);
626 }
627 light->setColor(l->mColorDiffuse.r, l->mColorDiffuse.g, l->mColorDiffuse.b, 1.f);
628 out.push_back(light);
629 }
630}
631
632void importCameras(const aiScene *scene, std::vector<graphics::Camera3D *> &out) {
633 if (!scene) return;
634 for (unsigned i = 0; i < scene->mNumCameras; ++i) {
635 const aiCamera *c = scene->mCameras[i];
636 if (!c) continue;
637 graphics::Camera3D *cam = graphics::Camera3D::createCamera();
638 cam->setActive(false);
639 cam->setEye(c->mPosition.x, c->mPosition.y, c->mPosition.z);
640 cam->setTarget(c->mLookAt.x, c->mLookAt.y, c->mLookAt.z);
641 cam->setUp(c->mUp.x, c->mUp.y, c->mUp.z);
642 cam->setFov(glm::degrees(c->mHorizontalFOV));
643 out.push_back(cam);
644 }
645}
646
647void importAnimations(const aiScene *scene, const LoadOptions &options,
648 animation::AnimSkeleton **skeletonOut,
649 std::vector<animation::AnimClip *> &clips) {
650 if (!scene || !options.importAnimations || scene->mNumAnimations == 0) return;
651 animation::AnimSkeleton *skeleton = animation::AnimImporter::loadSkeleton(scene);
652 if (!skeleton) return;
653 *skeletonOut = skeleton;
654 for (unsigned i = 0; i < scene->mNumAnimations; ++i) {
655 animation::AnimClip *clip = animation::AnimImporter::loadClip(scene, skeleton, int(i));
656 if (clip) clips.push_back(clip);
657 }
658}
659
660} // namespace
661
662// ---- public: pure helpers ----
663
666 if (!scene || !scene->mRootNode) return root;
667 std::unordered_map<std::string, int> counts;
668 buildNodeRecursive(scene, scene->mRootNode, root, slotsOut, counts);
669 return root;
670}
671
674 std::unordered_map<std::string, const scene::SceneNode *> oldNodes;
675 std::unordered_map<std::string, std::string> oldParent;
676 if (host) {
677 auto t = host->tree();
678 for (size_t i = 0; i < t->nodes.size(); ++i) {
679 const scene::SceneNode &n = t->nodes[i];
680 oldNodes[n.id] = &n;
681 oldParent[n.id] = (n.parent >= 0) ? t->nodes[size_t(n.parent)].id : "";
682 }
683 }
684
685 // Collect the set of ids present in the new tree.
686 std::unordered_set<std::string> newIds;
687 std::function<void(const scene::NodeDesc &)> collect = [&](const scene::NodeDesc &d) {
688 newIds.insert(d.id);
689 for (const auto &c : d.children) collect(c);
690 };
691 collect(newRoot);
692
693 // Removed: present in old, absent in new.
694 for (const auto &kv : oldNodes) {
695 if (!newIds.count(kv.first)) {
696 out.entries.push_back({SceneDiffEntry::Action::Remove, kv.first, ""});
697 ++out.removed;
698 }
699 }
700
701 // Add / Move / Modify: walk the new tree (DFS so parents precede children).
702 walkNew(newRoot, "", oldNodes, oldParent, out);
703 return out;
704}
705
707 const SceneDiff &diff, graphics::Graphics *gfx,
708 const MeshSlotMap *slots) {
709 if (!host || diff.empty()) return false;
710
711 // Snapshot the mounted tree by id so kept GameObjects can keep their linked
712 // Renderable3D (no re-upload / no object rebuild) across the update.
713 std::unordered_map<std::string, const scene::SceneNode *> oldNodes;
714 {
715 auto t = host->tree();
716 for (const auto &n : t->nodes) oldNodes[n.id] = &n;
717 }
718
719 // Collect the ids present in the new tree.
720 std::unordered_set<std::string> newIds;
721 std::function<void(const scene::NodeDesc &)> collect = [&](const scene::NodeDesc &d) {
722 newIds.insert(d.id);
723 for (const auto &c : d.children) collect(c);
724 };
725 collect(newRoot);
726
727 // Destroy Renderable3D of removed GameObjects.
728 for (const auto &kv : oldNodes) {
729 if (!newIds.count(kv.first)) {
730 if (const auto *l = host->findLink(kv.second, scene::findLinkKind("renderable3d"))) {
731 destroyRenderable(static_cast<graphics::Renderable3D *>(l->target));
732 }
733 }
734 }
735
736 // Rebuild the arena from the new tree (DFS). Kept nodes copy their link from
737 // the old node (identity preserved); added mesh nodes get a fresh Renderable3D.
738 std::vector<scene::SceneNode> nodes;
739 nodes.reserve(newIds.size());
740 std::function<int(const scene::NodeDesc &, int)> build = [&](const scene::NodeDesc &d,
741 int parentIndex) -> int {
742 const int idx = int(nodes.size());
744 n.id = d.id;
745 n.key = d.key.empty() ? d.id : d.key;
746 n.name = d.name.empty() ? d.id : d.name;
747 n.space = d.space.empty() ? "3d" : d.space;
748 n.visible = d.visible;
749 n.x = d.x;
750 n.y = d.y;
751 n.z = d.z;
752 n.yaw = d.yaw;
753 n.pitch = d.pitch;
754 n.roll = d.roll;
755 n.sx = d.sx;
756 n.sy = d.sy;
757 n.sz = d.sz;
758 n.localDirty = true;
759 n.world = glm::mat4(1.f);
760 n.firstChild = -1;
761 n.nextSibling = -1;
762 n.parent = parentIndex;
763
764 auto oldIt = oldNodes.find(d.id);
765 if (oldIt != oldNodes.end()) {
766 n.links = oldIt->second->links;
767 n.objectId = oldIt->second->objectId;
768 n.bminX = oldIt->second->bminX;
769 n.bminY = oldIt->second->bminY;
770 n.bminZ = oldIt->second->bminZ;
771 n.bmaxX = oldIt->second->bmaxX;
772 n.bmaxY = oldIt->second->bmaxY;
773 n.bmaxZ = oldIt->second->bmaxZ;
774 n.hasBounds = oldIt->second->hasBounds;
775 }
776
777 nodes.push_back(std::move(n));
778
779 int prevChild = -1;
780 int firstChild = -1;
781 for (const auto &c : d.children) {
782 const int ci = build(c, idx);
783 if (firstChild < 0) firstChild = ci;
784 if (prevChild >= 0) nodes[size_t(prevChild)].nextSibling = ci;
785 prevChild = ci;
786 }
787 nodes[size_t(idx)].firstChild = firstChild;
788 return idx;
789 };
790 const int root = build(newRoot, -1);
791
792 // Fresh Renderable3D for newly added mesh GameObjects (only changed ones).
793 if (gfx && slots) {
794 TextureCache unused;
795 for (auto &n : nodes) {
796 if (!n.links.empty()) continue;
797 if (std::find(n.tags.begin(), n.tags.end(), "collision") != n.tags.end()) continue;
798 auto sit = slots->find(n.id);
799 if (sit == slots->end() || sit->second.empty()) continue;
800 graphics::Renderable3D *r = nullptr;
801 try {
802 r = makeRenderable(gfx, sit->second[0], unused, true);
803 } catch (...) {
804 r = nullptr;
805 }
806 if (r) {
807 n.links.push_back(scene::SceneLink{scene::findLinkKind("renderable3d"), r, 0});
808 }
809 }
810 }
811
812 host->tree()->nodes = std::move(nodes);
813 host->tree()->root = root;
814 host->invalidateIndex();
815 host->markTransformDirty();
817 return true;
818}
819
821 if (!host) return;
822 auto t = host->tree();
823 for (auto &n : t->nodes) {
824 auto it = slots.find(n.id);
825 if (it == slots.end() || it->second.empty()) continue;
826 fillMeshBoundsFromSlot(n, it->second[0]);
827 }
828 if (t->root >= 0) unionChildBounds(*t, t->root);
829}
830
831// ---- public: file / lifecycle ----
832// ---- private: linking + async decode ----
833
834void SceneLoader::linkMeshNodes(scene::SceneHost *host, const MeshSlotMap &slots,
836 TextureCache &textures, MeshCache &shared,
837 const CpuImageMap *predecoded) {
838 if (!gfx) return;
839 for (const auto &kv : slots) {
840 scene::SceneNode *n = borrowResult(host->findById(kv.first));
841 if (!n || kv.second.empty()) continue;
842 if (std::find(n->tags.begin(), n->tags.end(), "collision") != n->tags.end()) continue;
843 if (host->findLink(n, scene::findLinkKind("renderable3d"))) continue;
844 const MeshSlot &slot = kv.second[0];
845 graphics::Mesh *mesh = nullptr;
846 auto it = shared.find(slot.mesh);
847 if (options.sharedMeshes && it != shared.end()) {
848 mesh = it->second;
849 } else {
850 try {
851 mesh = gfx->newMeshFromAssimp(*slot.mesh);
852 } catch (...) {
853 mesh = nullptr;
854 }
855 if (mesh && options.sharedMeshes) shared[slot.mesh] = mesh;
856 }
857 if (!mesh) continue;
858 auto *r = graphics::Renderable3D::create();
859 r->meshRenderer()->visible = true;
860 r->setMesh(mesh);
861
862 const aiScene *scene = slot.scene;
863 const aiMaterial *mat = nullptr;
864 if (scene && scene->mMaterials && slot.materialIndex < scene->mNumMaterials)
865 mat = scene->mMaterials[slot.materialIndex];
866 aiColor3D base(1.f, 1.f, 1.f);
867 if (mat) {
868 if (mat->Get(AI_MATKEY_BASE_COLOR, base) != AI_SUCCESS)
869 mat->Get(AI_MATKEY_COLOR_DIFFUSE, base);
870 float metallic = 0.f;
871 float roughness = 0.45f;
872 mat->Get(AI_MATKEY_METALLIC_FACTOR, metallic);
873 mat->Get(AI_MATKEY_ROUGHNESS_FACTOR, roughness);
874 r->setMetallic(metallic);
875 r->setRoughness(roughness);
876 }
877 graphics::Texture *albedo = resolveTexture(gfx, scene, mat, aiTextureType_BASE_COLOR,
878 textures, options.mipmaps, predecoded);
879 if (!albedo)
880 albedo = resolveTexture(gfx, scene, mat, aiTextureType_DIFFUSE, textures,
881 options.mipmaps, predecoded);
882 graphics::Texture *normal = resolveTexture(gfx, scene, mat, aiTextureType_NORMALS,
883 textures, options.mipmaps, predecoded);
884 graphics::Texture *height = resolveTexture(gfx, scene, mat, aiTextureType_HEIGHT,
885 textures, options.mipmaps, predecoded);
886 r->setTint(base.r, base.g, base.b, 1.f);
887 if (albedo) r->setTexture(albedo);
888 if (normal) r->setNormalTexture(normal);
889 if (height) r->setHeightTexture(height);
890 n->links.push_back(scene::SceneLink{scene::findLinkKind("renderable3d"), r, 0});
891 }
892}
893
894bool SceneLoader::decode(const std::string &path, const LoadOptions &options, DecodedScene *out) {
895 const std::string key = normPath(path);
896 // The unified resource cache may hold a decode from an earlier load; a
897 // reload/diff must see the file as it is now, so refresh the cached entry
898 // before asking for it (no-op when nothing is cached yet).
899 eve::ResourceManager::getInstance().reload(path).ignore("scene reload");
900
901 auto *mod3d = ModuleManager::getInstance<model3d::Model3D>("Model3D");
902 if (!mod3d) mod3d = model3d::Model3D::create();
903 model3d::ModelData *md = nullptr;
904 try {
905 md = mod3d->newModelDataFromFile(path, toModelOptions(options));
906 } catch (const std::exception &e) {
907 std::lock_guard<std::mutex> lock(pendingMu_);
908 lastErrors_[key] = e.what();
909 return false;
910 } catch (...) {
911 std::lock_guard<std::mutex> lock(pendingMu_);
912 lastErrors_[key] = "unknown model decode error";
913 return false;
914 }
915 if (!md) {
916 std::lock_guard<std::mutex> lock(pendingMu_);
917 lastErrors_[key] = "model decoder returned no scene";
918 return false;
919 }
920
921 std::vector<std::string> importWarnings;
922 for (int i = 0; i < md->getMeshCount(); ++i) {
923 if (!md->hasNormals(i))
924 importWarnings.push_back("mesh " + std::to_string(i) + " has no normals");
925 if (!md->hasTexCoords(i))
926 importWarnings.push_back("mesh " + std::to_string(i) + " has no UV0");
927 }
928 {
929 std::lock_guard<std::mutex> lock(pendingMu_);
930 lastErrors_.erase(key);
931 warnings_[key] = std::move(importWarnings);
932 }
933
934 out->path = normPath(path);
935 out->md = md;
936 out->options = options;
937 out->root = std::make_unique<scene::NodeDesc>(buildNodeDesc(md->getScene(), &out->slots));
938 collectCpuImages(md->getScene(), out->slots, options.mipmaps, out->cpuImages);
939 return true;
940}
941
942scene::SceneHost *SceneLoader::mount(DecodedScene &d) {
943 scene::SceneHost *host = borrowResult(scene::SceneHost::createHost(d.path));
944 if (!host) return nullptr;
945 host->setTree(std::move(*d.root));
946
947 graphics::Graphics *gfx = currentGraphics();
948 if (!d.slots.empty()) fillSceneBounds(host, d.slots);
949
950 if (gfx) {
951 MeshCache shared;
952 linkMeshNodes(host, d.slots, gfx, d.options, textures_, shared, &d.cpuImages);
953 if (d.options.importLights) importLights(d.md->getScene(), d.lights);
954 if (d.options.importCameras) importCameras(d.md->getScene(), d.cameras);
955 importAnimations(d.md->getScene(), d.options, &d.skeleton, d.clips);
956 }
957 fillSceneBounds(host, d.slots);
959 scenes_[d.path] = Loaded{d.path, host, gfx, d.options, std::move(d.lights),
960 std::move(d.cameras), d.skeleton, std::move(d.clips)};
961 return host;
962}
963
964void SceneLoader::clearTextures() {
965 for (auto &kv : textures_) delete kv.second;
966 textures_.clear();
967}
968
969// ---- public: file / lifecycle ----
970
971scene::SceneHost *SceneLoader::load(const std::string &path, bool linkRenderables,
972 const LoadOptions &options) {
973 const std::string key = normPath(path);
974 DecodedScene d;
975 auto warm = prewarmed_.find(key);
976 if (warm != prewarmed_.end()) {
977 d = std::move(warm->second);
978 prewarmed_.erase(warm);
979 } else if (!decode(path, options, &d)) {
980 return nullptr;
981 }
982 if (!linkRenderables) {
984 if (!host) return nullptr;
985 host->setTree(std::move(*d.root));
987 scenes_[d.path] = Loaded{d.path, host, nullptr, options, {}, {}, nullptr, {}};
988 return host;
989 }
990 scene::SceneHost *host = mount(d);
991 return host;
992}
993
995 return load(path, true, options);
996}
997
998scene::SceneHost *SceneLoader::loadPreset(const std::string &path, const std::string &preset) {
999 return load(path, presetOptions(preset));
1000}
1001
1003 const std::string key = normPath(path);
1004 auto it = scenes_.find(key);
1005 if (it == scenes_.end()) {
1006 if (!load(path, options)) {
1007 const std::string message = decodeErrorFor(path);
1009 eve::DiagnosticCode::Failed, message.empty() ? "scene reload failed to load the scene" : message, key,
1010 {}, "sceneloader.reload"));
1011 }
1012 if (out) *out = SceneDiff{};
1014 }
1015 Loaded &ld = it->second;
1016
1017 DecodedScene d;
1018 if (!decode(path, options, &d)) {
1019 const std::string message = decodeErrorFor(path);
1021 eve::DiagnosticCode::Failed, message.empty() ? "scene reload failed to decode the scene" : message, key, {},
1022 "sceneloader.reload"));
1023 }
1024
1025 SceneDiff diff = diffTree(ld.host, *d.root);
1026 if (out) *out = diff;
1027 if (!diff.empty()) {
1028 applyTreeDiff(ld.host, *d.root, diff, nullptr, nullptr);
1029 MeshCache shared;
1030 linkMeshNodes(ld.host, d.slots, ld.gfx, options, textures_, shared, &d.cpuImages);
1032 }
1035}
1036
1037SceneDiff SceneLoader::diff(const std::string &path) {
1038 const std::string key = normPath(path);
1039 eve::ResourceManager::getInstance().reload(path).ignore("scene diff reload"); // fresh decode for diffing
1040 auto *mod3d = ModuleManager::getInstance<model3d::Model3D>("Model3D");
1041 if (!mod3d) mod3d = model3d::Model3D::create();
1042 model3d::ModelData *md = nullptr;
1043 try {
1044 md = mod3d->newModelDataFromFile(path);
1045 } catch (...) {
1046 return SceneDiff{};
1047 }
1048 if (!md) return SceneDiff{};
1050 scene::NodeDesc newRoot = buildNodeDesc(md->getScene(), &slots);
1051 SceneDiff d;
1052 auto it = scenes_.find(key);
1053 if (it != scenes_.end() && it->second.host) {
1054 d = diffTree(it->second.host, newRoot);
1055 } else {
1056 // Nothing mounted: every node in the new tree is an add.
1057 std::function<void(const scene::NodeDesc &, const std::string &)> walk =
1058 [&](const scene::NodeDesc &n, const std::string &parent) {
1059 d.entries.push_back({SceneDiffEntry::Action::Add, n.id, parent});
1060 ++d.added;
1061 for (const auto &c : n.children) walk(c, n.id);
1062 };
1063 walk(newRoot, "");
1064 }
1065 return d;
1066}
1067
1069 const LoadOptions &options) {
1070 DecodedScene decoded;
1071 if (!decode(path, options, &decoded)) {
1072 const std::string message = decodeErrorFor(path);
1075 message.empty() ? "scene inspection failed to decode the source" : message,
1076 normPath(path), {}, "sceneloader.inspect"));
1077 }
1079 const auto mounted = scenes_.find(normPath(path));
1080 if (mounted != scenes_.end() && mounted->second.host)
1081 result.diff = diffTree(mounted->second.host, *decoded.root);
1082 else {
1083 std::function<void(const scene::NodeDesc&, const std::string&)> add =
1084 [&](const scene::NodeDesc& node, const std::string& parent) {
1085 result.diff.entries.push_back({SceneDiffEntry::Action::Add, node.id, parent});
1086 ++result.diff.added;
1087 for (const auto& child : node.children) add(child, node.id);
1088 };
1089 add(*decoded.root, "");
1090 }
1091 std::function<void(const scene::NodeDesc&)> collect = [&](const scene::NodeDesc& node) {
1092 ++result.nodeCount;
1093 if (decoded.slots.find(node.id) != decoded.slots.end()) ++result.meshNodeCount;
1094 if (std::find(node.tags.begin(), node.tags.end(), "model-socket") != node.tags.end())
1095 result.sockets.push_back(node.name);
1096 if (std::find(node.tags.begin(), node.tags.end(), "collision") != node.tags.end())
1097 result.collisions.push_back(node.name);
1098 for (const auto& child : node.children) collect(child);
1099 };
1100 collect(*decoded.root);
1101 const int count = warningCount(path);
1102 for (int i = 0; i < count; ++i) result.warnings.push_back(warning(path, i));
1104}
1105
1107 auto it = scenes_.find(normPath(path));
1108 return (it != scenes_.end()) ? it->second.host : nullptr;
1109}
1110
1111int SceneLoader::nodeCount(const std::string &path) {
1113 return h ? h->getNodeCount() : 0;
1114}
1115
1116bool SceneLoader::loaded(const std::string &path) { return scenes_.count(normPath(path)) > 0; }
1117
1118void SceneLoader::unload(const std::string &path) {
1119 auto it = scenes_.find(normPath(path));
1120 if (it == scenes_.end()) return;
1121 if (it->second.host) {
1122 auto t = it->second.host->tree();
1123 for (auto &n : t->nodes) {
1124 if (const auto *l = it->second.host->findLink(&n, scene::findLinkKind("renderable3d"))) {
1125 destroyRenderable(static_cast<graphics::Renderable3D *>(l->target));
1126 }
1127 n.links.clear();
1128 }
1129 ecs::DestroyEntity(it->second.host);
1130 }
1131 for (graphics::Light3D *l : it->second.lights) ecs::DestroyEntity(l);
1132 for (graphics::Camera3D *c : it->second.cameras) ecs::DestroyEntity(c);
1133 delete it->second.skeleton;
1134 for (animation::AnimClip *clip : it->second.clips) delete clip;
1135 scenes_.erase(it);
1136}
1137
1138// ---- async loading ----
1139
1140bool SceneLoader::loadAsync(const std::string &path, const LoadOptions &options,
1141 std::function<void(scene::SceneHost *)> done) {
1142 const std::string key = normPath(path);
1143 {
1144 std::lock_guard<std::mutex> lock(pendingMu_);
1145 if (inFlight_.count(key)) return false;
1146 inFlight_.insert(key);
1147 }
1148 if (!pool_) pool_ = std::make_shared<thread::ThreadPool>(2);
1149
1150 auto self = this;
1151 pool_->submit([self, key, options, done = std::move(done)]() mutable {
1152 DecodedScene d;
1153 if (self->decode(key, options, &d)) {
1154 std::lock_guard<std::mutex> lock(self->pendingMu_);
1155 d.done = std::move(done);
1156 self->pending_.push_back(std::move(d));
1157 }
1158 std::lock_guard<std::mutex> lock(self->pendingMu_);
1159 self->inFlight_.erase(key);
1160 });
1161 return true;
1162}
1163
1164bool SceneLoader::loadAsyncPreset(const std::string &path, const std::string &preset) {
1165 return loadAsync(path, presetOptions(preset));
1166}
1167
1169 std::vector<DecodedScene> ready;
1170 {
1171 std::lock_guard<std::mutex> lock(pendingMu_);
1172 ready.swap(pending_);
1173 }
1174 for (auto &d : ready) {
1175 if (!d.md) continue;
1176 if (d.prewarmOnly) {
1177 prewarmed_[d.path] = std::move(d);
1178 continue;
1179 }
1180 scene::SceneHost *h = mount(d);
1181 if (d.done) d.done(h);
1182 }
1183 return static_cast<int>(ready.size());
1184}
1185
1186bool SceneLoader::prewarmAsync(const std::string &path, const LoadOptions &options) {
1187 const std::string key = normPath(path);
1188 {
1189 std::lock_guard<std::mutex> lock(pendingMu_);
1190 if (prewarmed_.count(key) || inFlight_.count(key)) return false;
1191 inFlight_.insert(key);
1192 }
1193 if (!pool_) pool_ = std::make_shared<thread::ThreadPool>(2);
1194
1195 auto self = this;
1196 pool_->submit([self, key, options]() {
1197 DecodedScene d;
1198 if (self->decode(key, options, &d)) {
1199 d.prewarmOnly = true;
1200 std::lock_guard<std::mutex> lock(self->pendingMu_);
1201 self->pending_.push_back(std::move(d));
1202 }
1203 std::lock_guard<std::mutex> lock(self->pendingMu_);
1204 self->inFlight_.erase(key);
1205 });
1206 return true;
1207}
1208
1209bool SceneLoader::prewarmed(const std::string &path) const {
1210 return prewarmed_.count(normPath(path)) > 0;
1211}
1212
1213void SceneLoader::clearPrewarm(const std::string &path) {
1214 auto it = prewarmed_.find(normPath(path));
1215 if (it == prewarmed_.end()) return;
1216 prewarmed_.erase(it);
1217}
1218
1220 std::lock_guard<std::mutex> lock(pendingMu_);
1221 return static_cast<int>(pending_.size() + inFlight_.size());
1222}
1223
1224std::string SceneLoader::decodeErrorFor(const std::string &path) const {
1225 std::lock_guard<std::mutex> lock(pendingMu_);
1226 auto it = lastErrors_.find(normPath(path));
1227 return it == lastErrors_.end() ? std::string{} : it->second;
1228}
1229
1230int SceneLoader::warningCount(const std::string &path) const {
1231 std::lock_guard<std::mutex> lock(pendingMu_);
1232 auto it = warnings_.find(normPath(path));
1233 return it == warnings_.end() ? 0 : static_cast<int>(it->second.size());
1234}
1235
1236std::string SceneLoader::warning(const std::string &path, int index) const {
1237 std::lock_guard<std::mutex> lock(pendingMu_);
1238 auto it = warnings_.find(normPath(path));
1239 if (it == warnings_.end() || index < 0 || static_cast<size_t>(index) >= it->second.size())
1240 return {};
1241 return it->second[static_cast<size_t>(index)];
1242}
1243
1244bool SceneLoader::setLod(const std::string &path, int level) {
1246 if (!h || level < 0) return false;
1247 bool found = false;
1248 auto tree = h->tree();
1249 for (scene::SceneNode &node : tree->nodes) {
1250 int nodeLod = -1;
1251 for (const std::string &tag : node.tags)
1252 if (tag.rfind("lod:", 0) == 0) nodeLod = std::atoi(tag.c_str() + 4);
1253 if (nodeLod >= 0) {
1254 node.visible = nodeLod == level;
1255 found = found || node.visible;
1256 }
1257 }
1258 return found;
1259}
1260
1261int SceneLoader::socketCount(const std::string &path) const {
1262 auto it = scenes_.find(normPath(path));
1263 if (it == scenes_.end() || !it->second.host) return 0;
1264 return static_cast<int>(it->second.host->findAllByTag("model-socket").size());
1265}
1266
1267std::string SceneLoader::socketName(const std::string &path, int index) const {
1268 auto it = scenes_.find(normPath(path));
1269 if (it == scenes_.end() || !it->second.host || index < 0) return {};
1270 auto sockets = it->second.host->findAllByTag("model-socket");
1271 return static_cast<size_t>(index) < sockets.size() ? sockets[static_cast<size_t>(index)]->name
1272 : std::string{};
1273}
1274
1275int SceneLoader::collisionCount(const std::string &path) const {
1276 auto it = scenes_.find(normPath(path));
1277 if (it == scenes_.end() || !it->second.host) return 0;
1278 return static_cast<int>(it->second.host->findAllByTag("collision").size());
1279}
1280
1281std::string SceneLoader::collisionName(const std::string &path, int index) const {
1282 auto it = scenes_.find(normPath(path));
1283 if (it == scenes_.end() || !it->second.host || index < 0) return {};
1284 auto nodes = it->second.host->findAllByTag("collision");
1285 return static_cast<size_t>(index) < nodes.size() ? nodes[static_cast<size_t>(index)]->name
1286 : std::string{};
1287}
1288
1289// ---- imported scene extras ----
1290
1291int SceneLoader::lightCount(const std::string &path) {
1292 auto it = scenes_.find(normPath(path));
1293 return (it != scenes_.end()) ? static_cast<int>(it->second.lights.size()) : 0;
1294}
1295
1297 auto it = scenes_.find(normPath(path));
1298 if (it == scenes_.end() || index < 0 ||
1299 static_cast<size_t>(index) >= it->second.lights.size())
1300 return nullptr;
1301 return it->second.lights[size_t(index)];
1302}
1303
1304int SceneLoader::cameraCount(const std::string &path) {
1305 auto it = scenes_.find(normPath(path));
1306 return (it != scenes_.end()) ? static_cast<int>(it->second.cameras.size()) : 0;
1307}
1308
1310 auto it = scenes_.find(normPath(path));
1311 if (it == scenes_.end() || index < 0 ||
1312 static_cast<size_t>(index) >= it->second.cameras.size())
1313 return nullptr;
1314 return it->second.cameras[size_t(index)];
1315}
1316
1317int SceneLoader::animationCount(const std::string &path) {
1318 auto it = scenes_.find(normPath(path));
1319 return (it != scenes_.end()) ? static_cast<int>(it->second.clips.size()) : 0;
1320}
1321
1323 auto it = scenes_.find(normPath(path));
1324 return (it != scenes_.end()) ? it->second.skeleton : nullptr;
1325}
1326
1328 auto it = scenes_.find(normPath(path));
1329 if (it == scenes_.end() || index < 0 ||
1330 static_cast<size_t>(index) >= it->second.clips.size())
1331 return nullptr;
1332 return it->second.clips[size_t(index)];
1333}
1334
1335void SceneLoader::expose(ssq::Table &table) {
1336 auto cls = table.addClass(name, SceneLoader::create, false);
1337 expose(cls);
1338}
1339
1340void SceneLoader::expose(ssq::Class &cls) {
1341 cls.addFunc("getName", &SceneLoader::getName);
1342 cls.addFunc("load",
1343 std::function<scene::SceneHost *(SceneLoader *, const std::string &)>(
1344 [](SceneLoader *sl, const std::string &path) -> scene::SceneHost * {
1345 return sl ? sl->load(path) : nullptr;
1346 }));
1347 cls.addFunc("loadPreset", &SceneLoader::loadPreset);
1348 cls.addFunc("host", &SceneLoader::host);
1349 const HSQUIRRELVM vm = cls.getHandle();
1350 cls.addFunc("reload", [vm](SceneLoader *value, const std::string &path) {
1351 if (!value)
1353 vm,
1355 "scene loader must not be null", "scene")),
1356 [](bool changed) { return eve::Value::boolean(changed); });
1357 return eve::script::projectResult(vm, value->reload(path),
1358 [](bool changed) { return eve::Value::boolean(changed); });
1359 });
1360 cls.addFunc("nodeCount", &SceneLoader::nodeCount);
1361 cls.addFunc("loaded", &SceneLoader::loaded);
1362 cls.addFunc("unload", &SceneLoader::unload);
1363 cls.addFunc("pollAsync", &SceneLoader::pollAsync);
1364 cls.addFunc("loadAsync", &SceneLoader::loadAsyncDefault);
1365 cls.addFunc("loadAsyncPreset", &SceneLoader::loadAsyncPreset);
1366 cls.addFunc("pendingAsyncCount", &SceneLoader::pendingAsyncCount);
1367 cls.addFunc("prewarmed", &SceneLoader::prewarmed);
1368 cls.addFunc("clearPrewarm", &SceneLoader::clearPrewarm);
1369 cls.addFunc("prewarm", &SceneLoader::prewarm);
1370 cls.addFunc("warningCount", &SceneLoader::warningCount);
1371 cls.addFunc("warning", &SceneLoader::warning);
1372 cls.addFunc("setLod", &SceneLoader::setLod);
1373 cls.addFunc("socketCount", &SceneLoader::socketCount);
1374 cls.addFunc("socketName", &SceneLoader::socketName);
1375 cls.addFunc("collisionCount", &SceneLoader::collisionCount);
1376 cls.addFunc("collisionName", &SceneLoader::collisionName);
1377 cls.addFunc("lightCount", &SceneLoader::lightCount);
1378 cls.addFunc("cameraCount", &SceneLoader::cameraCount);
1379 cls.addFunc("animationCount", &SceneLoader::animationCount);
1380 cls.addFunc("light", &SceneLoader::light);
1381 cls.addFunc("camera", &SceneLoader::camera);
1382 cls.addFunc("skeleton", &SceneLoader::skeleton);
1383 cls.addFunc("clip", &SceneLoader::clip);
1384}
1385
1386} // namespace sceneloader
1387} // namespace eve
double z
double y
double m[16]
double x
float w
Definition AnimClip.cpp:738
int root
Definition AnimSmr.cpp:119
const std::string & s
float yaw
Definition BushMesh.cpp:37
struct SQVM * HSQUIRRELVM
bool changed
graphics::Texture * albedo
glm::vec4 p[6]
HSQUIRRELVM vm
Definition ECS.cpp:38
HSQOBJECT cls
Definition ECS.cpp:39
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
std::uint64_t parentId
std::string message
glm::vec4 clip
glm::vec3 n
Definition Grass.cpp:63
std::array< double, 10 > q
double r
float v
std::int32_t second
std::int32_t c
int h
std::uint32_t height
const ColourScope * parent
std::array< float, 3 > scale
std::map< std::string, Node > nodes
std::string id
Poco::JSON::Object::Ptr result
bool done
std::uint64_t bytes
MeleePoint3 b
Definition MeleeHit.cpp:41
double radius
Definition MeleeHit.cpp:42
MeleePoint3 a
Definition MeleeHit.cpp:40
float roughness
Texture * normal
float metallic
int level
const std::string * tag
#define Module_IMPL(ModuleName, newExpr)
Definition Module.h:27
OceanMeshSettings mesh
int idx
float f
std::string path
Definition PlayHost.cpp:111
std::weak_ptr< PrimitiveScene > scene
Object::Ptr value
float d
float t
std::string build
std::string slot
int lod
const RoadNode * node
bool found
bool repeatV
std::string filter
std::string mipmap
bool repeatU
bool mips
ScriptStructure out
size_t end
Light3D::Data * light
Definition Shadow.cpp:147
LocalPageCacheEntry slots[ShadowConfig::kLocalSlots]
Definition Shadow.cpp:159
const SquirrelValueOptions & options
int count
The single Squirrel projection for common Result, Status and Value.
Share string attribute map operations through the Windows Foundation DLL.
int children
Definition TreeMesh.cpp:432
UIHostHandle host
uint32_t index
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
EVENGINE_API_FOUNDATION public API.
Definition Exception.h:13
virtual std::string getName() const =0
Returns the name.
eve::Result< bool > reload(const std::string &normPath) override
Reloads .
Definition Resource.cpp:390
static ResourceManager & getInstance()
Returns the instance.
Definition Resource.cpp:15
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
static Value boolean(bool value)
Compatibility factory for a boolean value.
Definition Value.h:119
Keyframed skeletal animation clip (local TRS tracks per bone). Script type: AnimClip.
Definition AnimClip.h:145
static AnimClip * loadClip(const aiScene *scene, const AnimSkeleton *skeleton, int animIndex=0)
Load clip by index; maps node-name channels onto skeleton bones.
static AnimSkeleton * loadSkeleton(const aiScene *scene)
Build skeleton from the scene node hierarchy (depth-first).
3D bone hierarchy + bind-pose local TRS for skeletal animation. Independent of ik::Skeleton3D (FABRIK...
In-memory byte buffer implementing eve::Data (ref-counted).
Definition ByteData.h:13
EVENGINE_API_BACKENDS public API.
static Camera3D * createCamera(ecs::Table &table= *ecs::current())
Create an active camera in the current ECS table.
virtual Mesh * newMeshFromAssimp(const ::aiMesh &mesh)=0
Creates a mesh from assimp. @ownership Caller deletes unless documented otherwise.
Declarative 3D light. Collected by RenderSystem3D (max 8 per frame). type: "point" | "dir" | "spot" (...
Definition Light.h:190
static Light3D * createLight(const std::string &type="point")
Definition Light.cpp:91
GPU mesh handle (+ optional CPU morph targets).
Definition Mesh.h:26
EVENGINE_API_BACKENDS public API.
Represents raw pixel data.
Definition ImageData.h:38
void * getData() const
std::string getFormat() const
CPU-side decoded 3D model (Assimp scene owned via medialoader::ModelScene). Does not upload to GPU — ...
Definition ModelData.h:39
const aiScene * getScene() const
Returns the scene.
Definition ModelData.cpp:67
ECS mount point for one scene graph (full scene or nested subtree root). Isomorphic to eve::ui::UIHos...
Definition SceneHost.h:89
static eve::Result< SceneHost * > createHost(const std::string &name="")
Creates an ECS-owned scene host with an explicit Result contract.
static void updateHost(SceneHost *host)
Updates host.
Loads a 3D scene (glTF / OBJ / FBX / GLB ... via Assimp/medialoader) into the ECS scene tree.
bool loadAsync(const std::string &path, const LoadOptions &options={}, std::function< void(scene::SceneHost *)> done=nullptr)
Decode path on a worker thread, then apply it on the main thread the next time pollAsync() is called ...
int pendingAsyncCount() const
Number of async loads still waiting to be mounted.
static bool applyTreeDiff(scene::SceneHost *host, const scene::NodeDesc &newRoot, const SceneDiff &diff, graphics::Graphics *gfx, const MeshSlotMap *slots)
Apply a diff to the host arena in place. Creates/destroys Renderable3D for added/removed mesh objects...
int collisionCount(const std::string &path) const
Number of imported UCX_/UBX_/USP_/UCP_ collision nodes.
std::unordered_map< const aiMesh *, graphics::Mesh * > MeshCache
eve::Result< SceneInspection > inspect(const std::string &path, const LoadOptions &options={})
Decode with explicit options and return copied metadata without mounting or GPU upload.
graphics::Light3D * light(const std::string &path, int index)
Light.
void clearPrewarm(const std::string &path)
Drop a decoded prewarm result and release its CPU scene.
int lightCount(const std::string &path)
Number of imported Light3D entities for path; 0 if none / disabled.
eve::Result< bool > reload(const std::string &path, SceneDiff *out=nullptr, const LoadOptions &options={})
Hot-reload path. Re-decodes, diffs, and applies only what changed.
bool prewarm(const std::string &path)
Script-friendly CPU prewarm using the default import preset.
int animationCount(const std::string &path)
Number of imported animation clips for path; 0 if none / disabled.
bool prewarmAsync(const std::string &path, const LoadOptions &options={})
Decode and retain a scene without creating ECS/GPU objects.
scene::SceneHost * load(const std::string &path, bool linkRenderables=true, const LoadOptions &options={})
Full load: build the GameObject tree from path, mount it, return host.
std::string collisionName(const std::string &path, int index) const
Name of an imported collision node, or an empty string.
std::unordered_map< std::string, CpuImage > CpuImageMap
SceneDiff diff(const std::string &path)
Dry-run diff for path against the currently mounted tree (no mutation).
scene::SceneHost * host(const std::string &path)
The mounted host for path, or nullptr if not loaded.
std::string socketName(const std::string &path, int index) const
Name of an imported SOCKET_ node, or an empty string.
animation::AnimSkeleton * skeleton(const std::string &path)
Imported skeleton for path (nullptr when the scene has no animations).
bool loaded(const std::string &path)
True if path is currently loaded.
int socketCount(const std::string &path) const
Number of imported SOCKET_ nodes.
animation::AnimClip * clip(const std::string &path, int index)
Clip.
static scene::NodeDesc buildNodeDesc(const aiScene *scene, MeshSlotMap *slotsOut=nullptr)
Flatten an Assimp scene into a scene::NodeDesc tree (id = object id).
bool setLod(const std::string &path, int level)
Select imported name-convention LOD (_LOD0, _LOD1, ...).
bool loadAsyncDefault(const std::string &path)
Script-friendly async load using the default import preset.
static void fillSceneBounds(scene::SceneHost *host, const MeshSlotMap &slots)
Fill node bounds from Assimp mesh AABBs (mesh GameObjects get the exact local-space AABB; ancestors g...
static SceneDiff diffTree(scene::SceneHost *host, const scene::NodeDesc &newRoot)
Diff a mounted host tree against a freshly built NodeDesc tree.
std::string warning(const std::string &path, int index) const
Non-fatal import warning at index, or an empty string.
~SceneLoader() override
Scene loader.
bool loadAsyncPreset(const std::string &path, const std::string &preset)
Loads async preset.
void unload(const std::string &path)
Drop the loaded scene for path, destroying linked Renderable3D objects.
bool prewarmed(const std::string &path) const
True when a decoded scene is ready for load() to consume.
int warningCount(const std::string &path) const
Number of non-fatal import warnings retained for path.
int nodeCount(const std::string &path)
Number of GameObjects (SceneNodes) currently mounted for path; 0 if none.
graphics::Camera3D * camera(const std::string &path, int index)
Camera.
SceneLoader()
Construct the loader and publish its optional action-block provider.
int pollAsync()
Mount every decoded-but-not-applied scene. Must be called on the main / render thread....
scene::SceneHost * loadPreset(const std::string &path, const std::string &preset)
Load with a built-in preset: quality, balanced, mobile, or raw.
std::unordered_map< std::string, graphics::Texture * > TextureCache
Caches shared across the loader: textures by source key, GPU meshes per aiMesh.
int cameraCount(const std::string &path)
Number of imported Camera3D entities for path; 0 if none / disabled.
ShapeState * child(const JPH::Body &body, const JPH::SubShapeID &id)
Resolves a native child record for a synchronous callback or query. @ownership Borrowed from the worl...
int findLinkKind(const char *kind)
Finds link kind.
void shutdownPrefabActionCapabilities()
Release all provider-owned prefab instances during SceneLoader shutdown.
void registerPrefabActionCapabilities()
Register the SceneLoader-backed prefab action provider.
std::unordered_map< std::string, std::vector< MeshSlot > > MeshSlotMap
ssq::Table projectResult(HSQUIRRELVM vm, Result< void > &&result)
Consume and project a void native Result using the common schema.
Build metadata (engine git commit, build time, third-party version).
Definition Build.cpp:16
void eulerYxzFromQuat(const glm::qua< T, glm::defaultp > &q, T &yaw, T &pitch, T &roll)
Quaternion overload of eulerYxzFromMatrix(); float and double both work.
Declarative scene-node description (build once / on dirty → flatten into SceneHost::Tree)....
Definition NodeDesc.h:19
Retained scene node (arena). Conceptual GameObject; isomorphic to eve::ui::UINode.
Definition SceneHost.h:46
Options controlling how a 3D scene file is decoded and mounted.
A GPU mesh reference for one Assimp mesh referenced by an aiNode. The loader uploads one Renderable3D...
Definition SceneLoader.h:99
SceneDiff public API.
Definition SceneLoader.h:71
bool empty() const
Empty.
Definition SceneLoader.h:79
CPU-only import inspection result used by editor preflight.
Definition SceneLoader.h:83
glm::uvec4 counts