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>
41#include <glm/gtx/matrix_decompose.hpp>
42#include <glm/gtc/matrix_transform.hpp>
43#include <glm/gtc/quaternion.hpp>
47#include <simplesquirrel/simplesquirrel.hpp>
54#include <unordered_set>
57namespace sceneloader {
59SceneLoader::DecodedScene::DecodedScene() =
default;
60SceneLoader::DecodedScene::~DecodedScene() =
default;
61SceneLoader::DecodedScene::DecodedScene(DecodedScene &&) noexcept = default;
62SceneLoader::DecodedScene &SceneLoader::DecodedScene::operator=(DecodedScene &&) noexcept = default;
78constexpr float kEps = 1e-5f;
82 if (!
result.ok())
return nullptr;
86std::string normPath(
const std::string &
p) {
88 out.reserve(
p.size());
90 if (
c ==
'\\')
out.push_back(
'/');
91 else out.push_back(
c);
96graphics::Graphics *currentGraphics() {
97 return ModuleManager::getInstance<graphics::Graphics>(
"Graphics");
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;
110bool approx(
float a,
float b) {
return std::fabs(
a -
b) < kEps; }
114void decomposeNode(
const aiMatrix4x4 &
m,
float &
x,
float &
y,
float &
z,
float &
yaw,
float &
pitch,
115 float &
roll,
float &
sx,
float &
sy,
float &
sz) {
125 glm::quat
q(rot.w, rot.x, rot.y, rot.z);
131std::string uniqueId(
const std::string &base, std::unordered_map<std::string, int> &
counts) {
132 std::string
b = base.empty() ?
"node" : base;
135 if (
n > 0)
id =
b +
"_" + std::to_string(
n);
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])))
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;
154 const long value = std::strtol(
name.c_str() +
p + 4, &
end, 10);
158LoadOptions presetOptions(
const std::string &
name) {
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;
168 o.generateNormalsIfMissing =
false;
169 o.joinIdenticalVertices =
false;
171 o.improveCacheLocality =
false;
172 o.sharedMeshes =
false;
174 o.importLights =
false;
175 o.importCameras =
false;
176 o.importAnimations =
false;
193SamplerSpec samplerFor(
const aiMaterial *mat, aiTextureType
type,
bool wantMips) {
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);
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";
225 s.mipmap =
"nearest";
229 s.mipmap = wantMips ?
"linear" :
"none";
235graphics::Texture *resolveTexture(graphics::Graphics *gfx,
const aiScene *scene,
236 const aiMaterial *mat, aiTextureType
type,
239 if (!gfx || !scene || !mat)
return nullptr;
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;
245 const SamplerSpec
s = samplerFor(mat,
type, wantMips);
246 auto *
const imageModule = eve::image::Image::create();
248 const std::string keySuffix =
249 std::string(
s.repeatU ?
"|1" :
"|0") + (
s.
repeatV ?
"1" :
"0") +
"|" +
s.
filter +
"|" +
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;
262 graphics::Texture *
t =
nullptr;
263 if (tex->mHeight == 0) {
267 t = gfx->newTextureWithSampler(img,
s.repeatU,
s.repeatV,
s.mips, 8.f,
s.filter,
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;
285 t = gfx->newTextureWithSampler(&img,
s.repeatU,
s.repeatV,
s.mips, 8.f,
s.filter,
288 if (
t) cache[
key] =
t;
293 const std::string
key = normPath(
p) + keySuffix;
294 auto it = cache.find(
key);
295 if (it != cache.end())
return it->second;
299 auto pit = predecoded->find(
key);
300 if (pit != predecoded->end()) {
301 const SceneLoader::CpuImage &ci = pit->second;
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;
312 auto *fs = eve::filesystem::Filesystem::create();
313 std::unique_ptr<eve::filesystem::FileData> fd(fs->read(
p));
314 if (fd && fd->getSize() > 0) {
316 graphics::Texture *
t = gfx->newTextureWithSampler(img,
s.repeatU,
s.repeatV,
s.mips,
317 8.f,
s.filter,
s.mipmap);
319 if (
t) cache[
key] =
t;
329void collectCpuImages(
const aiScene *scene,
const MeshSlotMap &
slots,
bool wantMips,
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) {
337 if (!
slot.scene ||
slot.materialIndex >=
scene->mNumMaterials)
continue;
338 const aiMaterial *mat =
scene->mMaterials[
slot.materialIndex];
340 for (aiTextureType
type : kTypes) {
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;
345 const SamplerSpec
s = samplerFor(mat,
type, wantMips);
346 const std::string
key = normPath(
c) + std::string(
s.repeatU ?
"|1" :
"|0") +
348 if (
out.count(
key))
continue;
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;
356 SceneLoader::CpuImage ci;
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);
374graphics::Renderable3D *makeRenderable(graphics::Graphics *gfx,
const MeshSlot &
slot,
376 if (!gfx || !
slot.mesh)
return nullptr;
377 graphics::Mesh *
mesh = gfx->newMeshFromAssimp(*
slot.mesh);
378 if (!
mesh)
return nullptr;
379 auto *
r = graphics::Renderable3D::create();
380 r->meshRenderer()->visible =
true;
384 const aiMaterial *mat =
nullptr;
385 if (scene &&
scene->mMaterials &&
slot.materialIndex <
scene->mNumMaterials)
386 mat =
scene->mMaterials[
slot.materialIndex];
388 aiColor3D base(1.f, 1.f, 1.f);
390 if (mat->Get(AI_MATKEY_BASE_COLOR, base) != AI_SUCCESS)
391 mat->Get(AI_MATKEY_COLOR_DIFFUSE, base);
394 mat->Get(AI_MATKEY_METALLIC_FACTOR,
metallic);
395 mat->Get(AI_MATKEY_ROUGHNESS_FACTOR,
roughness);
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);
408 r->setTint(base.r, base.g, base.b, 1.f);
415void destroyRenderable(graphics::Renderable3D *
r) {
416 if (
r) ecs::DestroyEntity(
r);
421glm::mat4 nodeLocalMatrix(
const scene::SceneNode &
n) {
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));
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));
431 m = glm::scale(
m, glm::vec3(
n.sx,
n.sy,
n.sz));
435void fillMeshBoundsFromSlot(scene::SceneNode &
n,
const MeshSlot &
slot) {
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);
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);
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;
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]);
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]);
512void buildNodeRecursive(
const aiScene *scene,
const aiNode *
node, scene::NodeDesc &
out,
514 const std::string rawName = (
node &&
node->mName.length) ?
node->mName.C_Str() :
"<root>";
515 const std::string
id = uniqueId(rawName,
counts);
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");
528 const int lod = lodFromName(rawName);
530 out.tags.push_back(
"lod");
531 out.tags.push_back(
"lod:" + std::to_string(
lod));
537 for (
unsigned i = 0;
node && i <
node->mNumMeshes; ++i) {
538 const unsigned mi =
node->mMeshes[i];
539 if (mi >=
scene->mNumMeshes)
continue;
541 if (!
mesh ||
mesh->mNumFaces == 0)
continue;
543 const std::string cid =
id +
"_mesh" + std::to_string(i);
544 scene::NodeDesc
child;
547 child.name = std::string(
"mesh") + std::to_string(i);
551 out.children.push_back(std::move(child));
557 s.materialIndex =
mesh->mMaterialIndex;
558 (*slots)[cid].push_back(std::move(
s));
562 for (
unsigned c = 0;
node &&
c <
node->mNumChildren; ++
c) {
563 scene::NodeDesc
child;
565 out.children.push_back(std::move(child));
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));
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()) {
585 auto pit = oldParent.find(
d.id);
586 const std::string op = (pit != oldParent.end()) ? pit->second :
"";
590 }
else if (propsChanged(*it->second,
d)) {
600void importLights(
const aiScene *scene, std::vector<graphics::Light3D *> &
out) {
602 for (
unsigned i = 0; i <
scene->mNumLights; ++i) {
603 const aiLight *l =
scene->mLights[i];
605 std::string
type =
"point";
607 case aiLightSource_DIRECTIONAL:
610 case aiLightSource_POINT:
611 case aiLightSource_SPOT:
612 case aiLightSource_AREA:
619 light->setDirection(l->mDirection.x, l->mDirection.y, l->mDirection.z);
621 light->setPosition(l->mPosition.x, l->mPosition.y, l->mPosition.z);
623 if (l->mAttenuationQuadratic > 1e-6f)
624 radius = 1.f / std::sqrt(l->mAttenuationQuadratic);
627 light->setColor(l->mColorDiffuse.r, l->mColorDiffuse.g, l->mColorDiffuse.b, 1.f);
632void importCameras(
const aiScene *scene, std::vector<graphics::Camera3D *> &
out) {
634 for (
unsigned i = 0; i <
scene->mNumCameras; ++i) {
635 const aiCamera *
c =
scene->mCameras[i];
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));
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;
652 if (!skeleton)
return;
653 *skeletonOut = skeleton;
654 for (
unsigned i = 0; i <
scene->mNumAnimations; ++i) {
667 std::unordered_map<std::string, int>
counts;
674 std::unordered_map<std::string, const scene::SceneNode *> oldNodes;
675 std::unordered_map<std::string, std::string> oldParent;
677 auto t =
host->tree();
678 for (
size_t i = 0; i <
t->nodes.size(); ++i) {
681 oldParent[
n.id] = (
n.parent >= 0) ?
t->nodes[
size_t(
n.parent)].
id :
"";
686 std::unordered_set<std::string> newIds;
689 for (
const auto &
c :
d.children) collect(
c);
694 for (
const auto &kv : oldNodes) {
695 if (!newIds.count(kv.first)) {
702 walkNew(newRoot,
"", oldNodes, oldParent,
out);
713 std::unordered_map<std::string, const scene::SceneNode *> oldNodes;
715 auto t =
host->tree();
716 for (
const auto &
n :
t->nodes) oldNodes[
n.id] = &
n;
720 std::unordered_set<std::string> newIds;
723 for (
const auto &
c :
d.children) collect(
c);
728 for (
const auto &kv : oldNodes) {
729 if (!newIds.count(kv.first)) {
738 std::vector<scene::SceneNode>
nodes;
739 nodes.reserve(newIds.size());
741 int parentIndex) ->
int {
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;
759 n.world = glm::mat4(1.f);
762 n.parent = parentIndex;
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;
777 nodes.push_back(std::move(
n));
781 for (
const auto &
c :
d.children) {
783 if (firstChild < 0) firstChild = ci;
784 if (prevChild >= 0)
nodes[size_t(prevChild)].nextSibling = ci;
787 nodes[size_t(
idx)].firstChild = firstChild;
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;
802 r = makeRenderable(gfx, sit->second[0], unused,
true);
814 host->invalidateIndex();
815 host->markTransformDirty();
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]);
828 if (
t->root >= 0) unionChildBounds(*
t,
t->root);
836 TextureCache &textures, MeshCache &shared,
837 const CpuImageMap *predecoded) {
839 for (
const auto &kv :
slots) {
841 if (!
n || kv.second.empty())
continue;
842 if (std::find(
n->tags.begin(),
n->tags.end(),
"collision") !=
n->tags.end())
continue;
846 auto it = shared.find(
slot.mesh);
847 if (
options.sharedMeshes && it != shared.end()) {
858 auto *
r = graphics::Renderable3D::create();
859 r->meshRenderer()->visible =
true;
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);
868 if (mat->Get(AI_MATKEY_BASE_COLOR, base) != AI_SUCCESS)
869 mat->Get(AI_MATKEY_COLOR_DIFFUSE, base);
872 mat->Get(AI_MATKEY_METALLIC_FACTOR,
metallic);
873 mat->Get(AI_MATKEY_ROUGHNESS_FACTOR,
roughness);
877 graphics::Texture *
albedo = resolveTexture(gfx, scene, mat, aiTextureType_BASE_COLOR,
878 textures,
options.mipmaps, predecoded);
880 albedo = resolveTexture(gfx, scene, mat, aiTextureType_DIFFUSE, textures,
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);
894bool SceneLoader::decode(
const std::string &
path,
const LoadOptions &
options, DecodedScene *
out) {
895 const std::string
key = normPath(
path);
901 auto *mod3d = ModuleManager::getInstance<model3d::Model3D>(
"Model3D");
902 if (!mod3d) mod3d = model3d::Model3D::create();
903 model3d::ModelData *md =
nullptr;
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();
911 std::lock_guard<std::mutex> lock(pendingMu_);
912 lastErrors_[
key] =
"unknown model decode error";
916 std::lock_guard<std::mutex> lock(pendingMu_);
917 lastErrors_[
key] =
"model decoder returned no scene";
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");
929 std::lock_guard<std::mutex> lock(pendingMu_);
930 lastErrors_.erase(
key);
931 warnings_[
key] = std::move(importWarnings);
938 collectCpuImages(md->getScene(),
out->slots,
options.mipmaps,
out->cpuImages);
942scene::SceneHost *SceneLoader::mount(DecodedScene &
d) {
944 if (!
host)
return nullptr;
945 host->setTree(std::move(*
d.root));
947 graphics::Graphics *gfx = currentGraphics();
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);
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)};
964void SceneLoader::clearTextures() {
965 for (
auto &kv : textures_) delete kv.
second;
973 const std::string
key = normPath(
path);
975 auto warm = prewarmed_.find(
key);
976 if (warm != prewarmed_.end()) {
977 d = std::move(warm->second);
978 prewarmed_.erase(warm);
982 if (!linkRenderables) {
984 if (!
host)
return nullptr;
985 host->setTree(std::move(*
d.root));
999 return load(
path, presetOptions(preset));
1003 const std::string
key = normPath(
path);
1004 auto it = scenes_.find(
key);
1005 if (it == scenes_.end()) {
1010 {},
"sceneloader.reload"));
1022 "sceneloader.reload"));
1030 linkMeshNodes(ld.host,
d.slots, ld.gfx,
options, textures_, shared, &
d.cpuImages);
1038 const std::string
key = normPath(
path);
1040 auto *mod3d = ModuleManager::getInstance<model3d::Model3D>(
"Model3D");
1041 if (!mod3d) mod3d = model3d::Model3D::create();
1044 md = mod3d->newModelDataFromFile(
path);
1052 auto it = scenes_.find(
key);
1053 if (it != scenes_.end() && it->second.host) {
1057 std::function<void(
const scene::NodeDesc &,
const std::string &)> walk =
1061 for (
const auto &
c :
n.children) walk(
c,
n.id);
1070 DecodedScene decoded;
1075 message.empty() ?
"scene inspection failed to decode the source" :
message,
1076 normPath(
path), {},
"sceneloader.inspect"));
1079 const auto mounted = scenes_.find(normPath(
path));
1080 if (mounted != scenes_.end() && mounted->second.host)
1087 for (
const auto& child :
node.children) add(child,
node.id);
1089 add(*decoded.root,
"");
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())
1096 if (std::find(
node.tags.begin(),
node.tags.end(),
"collision") !=
node.tags.end())
1098 for (
const auto& child :
node.children) collect(child);
1100 collect(*decoded.root);
1107 auto it = scenes_.find(normPath(
path));
1108 return (it != scenes_.end()) ? it->second.host :
nullptr;
1113 return h ?
h->getNodeCount() : 0;
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) {
1129 ecs::DestroyEntity(it->second.host);
1133 delete it->second.skeleton;
1142 const std::string
key = normPath(
path);
1144 std::lock_guard<std::mutex> lock(pendingMu_);
1145 if (inFlight_.count(
key))
return false;
1146 inFlight_.insert(
key);
1148 if (!pool_) pool_ = std::make_shared<thread::ThreadPool>(2);
1154 std::lock_guard<std::mutex> lock(self->pendingMu_);
1155 d.done = std::move(done);
1156 self->pending_.push_back(std::move(d));
1158 std::lock_guard<std::mutex> lock(self->pendingMu_);
1159 self->inFlight_.erase(
key);
1169 std::vector<DecodedScene> ready;
1171 std::lock_guard<std::mutex> lock(pendingMu_);
1172 ready.swap(pending_);
1174 for (
auto &
d : ready) {
1175 if (!
d.md)
continue;
1176 if (
d.prewarmOnly) {
1177 prewarmed_[
d.path] = std::move(
d);
1181 if (
d.done)
d.done(
h);
1183 return static_cast<int>(ready.size());
1187 const std::string
key = normPath(
path);
1189 std::lock_guard<std::mutex> lock(pendingMu_);
1190 if (prewarmed_.count(
key) || inFlight_.count(
key))
return false;
1191 inFlight_.insert(
key);
1193 if (!pool_) pool_ = std::make_shared<thread::ThreadPool>(2);
1199 d.prewarmOnly = true;
1200 std::lock_guard<std::mutex> lock(self->pendingMu_);
1201 self->pending_.push_back(std::move(d));
1203 std::lock_guard<std::mutex> lock(self->pendingMu_);
1204 self->inFlight_.erase(
key);
1210 return prewarmed_.count(normPath(
path)) > 0;
1214 auto it = prewarmed_.find(normPath(
path));
1215 if (it == prewarmed_.end())
return;
1216 prewarmed_.erase(it);
1220 std::lock_guard<std::mutex> lock(pendingMu_);
1221 return static_cast<int>(pending_.size() + inFlight_.size());
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;
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());
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())
1241 return it->second[
static_cast<size_t>(
index)];
1246 if (!
h ||
level < 0)
return false;
1248 auto tree =
h->tree();
1251 for (
const std::string &
tag :
node.tags)
1252 if (
tag.rfind(
"lod:", 0) == 0) nodeLod = std::atoi(
tag.c_str() + 4);
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());
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
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());
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");
1292 auto it = scenes_.find(normPath(
path));
1293 return (it != scenes_.end()) ?
static_cast<int>(it->second.lights.size()) : 0;
1297 auto it = scenes_.find(normPath(
path));
1298 if (it == scenes_.end() ||
index < 0 ||
1299 static_cast<size_t>(
index) >= it->second.lights.size())
1301 return it->second.lights[size_t(
index)];
1305 auto it = scenes_.find(normPath(
path));
1306 return (it != scenes_.end()) ?
static_cast<int>(it->second.cameras.size()) : 0;
1310 auto it = scenes_.find(normPath(
path));
1311 if (it == scenes_.end() ||
index < 0 ||
1312 static_cast<size_t>(
index) >= it->second.cameras.size())
1314 return it->second.cameras[size_t(
index)];
1318 auto it = scenes_.find(normPath(
path));
1319 return (it != scenes_.end()) ?
static_cast<int>(it->second.clips.size()) : 0;
1323 auto it = scenes_.find(normPath(
path));
1324 return (it != scenes_.end()) ? it->second.skeleton :
nullptr;
1328 auto it = scenes_.find(normPath(
path));
1329 if (it == scenes_.end() ||
index < 0 ||
1330 static_cast<size_t>(
index) >= it->second.clips.size())
1332 return it->second.clips[size_t(
index)];
1335void SceneLoader::expose(ssq::Table &table) {
1336 auto cls = table.addClass(
name, SceneLoader::create,
false);
1340void SceneLoader::expose(ssq::Class &
cls) {
1345 return sl ? sl->load(
path) : nullptr;
1355 "scene loader must not be null",
"scene")),
1358 [](
bool changed) { return eve::Value::boolean(changed); });
struct SQVM * HSQUIRRELVM
graphics::Texture * albedo
std::array< double, 10 > q
const ColourScope * parent
std::array< float, 3 > scale
#define Module_IMPL(ModuleName, newExpr)
std::weak_ptr< PrimitiveScene > scene
LocalPageCacheEntry slots[ShadowConfig::kLocalSlots]
const SquirrelValueOptions & options
The single Squirrel projection for common Result, Status and Value.
Share string attribute map operations through the Windows Foundation DLL.
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.
virtual std::string getName() const =0
Returns the name.
eve::Result< bool > reload(const std::string &normPath) override
Reloads .
static ResourceManager & getInstance()
Returns the instance.
Move-only operation result carrying either a value or Status.
static Result success(T value)
Construct a successful result owning value.
static Result failure(Status status)
Construct a failed result from a structured status.
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
static Value boolean(bool value)
Compatibility factory for a boolean value.
Keyframed skeletal animation clip (local TRS tracks per bone). Script type: AnimClip.
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).
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" (...
static Light3D * createLight(const std::string &type="point")
GPU mesh handle (+ optional CPU morph targets).
EVENGINE_API_BACKENDS public API.
Represents raw pixel data.
std::string getFormat() const
CPU-side decoded 3D model (Assimp scene owned via medialoader::ModelScene). Does not upload to GPU — ...
const aiScene * getScene() const
Returns the scene.
ECS mount point for one scene graph (full scene or nested subtree root). Isomorphic to eve::ui::UIHos...
static eve::Result< SceneHost * > createHost(const std::string &name="")
Creates an ECS-owned scene host with an explicit Result contract.
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).
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)....
Retained scene node (arena). Conceptual GameObject; isomorphic to eve::ui::UINode.
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...
CPU-only import inspection result used by editor preflight.