20#include <assimp/Importer.hpp>
21#include <assimp/scene.h>
22#include <assimp/postprocess.h>
30Math::Matrix4 ModelLoader::ConvertMatrix(
const void* aiMatPtr) {
31 const auto& m = *
static_cast<const aiMatrix4x4*
>(
32 static_cast<const void*
>(aiMatPtr));
37 result(0, 0) = m.a1; result(0, 1) = m.b1; result(0, 2) = m.c1; result(0, 3) = m.d1;
38 result(1, 0) = m.a2; result(1, 1) = m.b2; result(1, 2) = m.c2; result(1, 3) = m.d2;
39 result(2, 0) = m.a3; result(2, 1) = m.b3; result(2, 2) = m.c3; result(2, 3) = m.d3;
40 result(3, 0) = m.a4; result(3, 1) = m.b4; result(3, 2) = m.c4; result(3, 3) = m.d4;
46 Assimp::Importer importer;
48 unsigned int baseFlags = aiProcess_Triangulate
49 | aiProcess_GenSmoothNormals
50 | aiProcess_CalcTangentSpace
51 | aiProcess_JoinIdenticalVertices
52 | aiProcess_OptimizeMeshes;
55 baseFlags |= aiProcess_FlipUVs;
58 constexpr unsigned int rawImportFlags = 0;
59 const aiScene* scene = importer.ReadFile(filePath, rawImportFlags);
61 if (!scene || (scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE) || !scene->mRootNode) {
62 SLEAK_ERROR(
"Assimp: Failed to load model '{}': {}", filePath,
63 importer.GetErrorString());
67 bool hasAnimations = scene->HasAnimations();
70 unsigned int postFlags = baseFlags;
71 if (!hasAnimations) postFlags |= aiProcess_PreTransformVertices;
72 scene = importer.ApplyPostProcessing(postFlags);
74 if (!scene || (scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE) ||
76 SLEAK_ERROR(
"Assimp: Failed to post-process model '{}': {}", filePath,
77 importer.GetErrorString());
81 SLEAK_INFO(
"Model loaded: {} ({} meshes, {} materials, {} textures, {} animations)",
82 filePath, scene->mNumMeshes, scene->mNumMaterials,
83 scene->mNumTextures, scene->mNumAnimations);
85 std::string directory = std::filesystem::path(filePath).parent_path().string();
86 auto* root =
new GameObject(std::filesystem::path(filePath).stem().
string());
91 ProcessNode(scene->mRootNode, scene, root, directory, options,
92 textureCache, materialCache);
95 Skeleton* skeleton = ExtractSkeleton(scene);
96 std::vector<AnimationClip*> clips = ExtractAnimations(scene, skeleton);
98 SLEAK_INFO(
" Skeleton: {} bones, {} animation clips",
101 ProcessNodeAnimated(scene->mRootNode, scene, root, directory, options,
102 textureCache, materialCache, skeleton, clips);
109Skeleton* ModelLoader::ExtractSkeleton(
const aiScene* scene) {
113 for (
unsigned int m = 0; m < scene->mNumMeshes; ++m) {
114 aiMesh* mesh = scene->mMeshes[m];
115 if (!mesh->HasBones())
continue;
117 for (
unsigned int b = 0; b < mesh->mNumBones; ++b) {
118 aiBone* bone = mesh->mBones[b];
119 std::string boneName = bone->mName.C_Str();
121 if (skeleton->FindBoneId(boneName) == -1) {
123 newBone.
name = boneName;
124 newBone.
offsetMatrix = ConvertMatrix(&bone->mOffsetMatrix);
125 skeleton->AddBone(newBone);
131 BuildBoneHierarchy(scene->mRootNode, skeleton, -1);
134 BuildNodeTree(scene->mRootNode, skeleton);
137 aiMatrix4x4 rootTransform = scene->mRootNode->mTransformation;
138 rootTransform.Inverse();
139 skeleton->SetGlobalInverseTransform(ConvertMatrix(&rootTransform));
144int ModelLoader::BuildNodeTree(
const aiNode* node,
Skeleton* skeleton) {
146 nodeData.name = node->mName.C_Str();
147 nodeData.defaultTransform = ConvertMatrix(&node->mTransformation);
148 nodeData.boneIndex = skeleton->FindBoneId(nodeData.name);
150 int nodeIdx = skeleton->AddNode(nodeData);
152 for (
unsigned int i = 0; i < node->mNumChildren; ++i) {
153 int childIdx = BuildNodeTree(node->mChildren[i], skeleton);
154 skeleton->AddNodeChild(nodeIdx, childIdx);
160void ModelLoader::BuildBoneHierarchy(
const aiNode* node,
Skeleton* skeleton,
162 std::string nodeName = node->mName.C_Str();
163 int boneId = skeleton->FindBoneId(nodeName);
166 int nextParent = parentId;
168 skeleton->SetBoneParent(boneId, parentId);
172 for (
unsigned int i = 0; i < node->mNumChildren; ++i) {
173 BuildBoneHierarchy(node->mChildren[i], skeleton, nextParent);
177std::vector<AnimationClip*> ModelLoader::ExtractAnimations(
178 const aiScene* scene,
Skeleton* skeleton) {
179 std::vector<AnimationClip*> clips;
181 for (
unsigned int i = 0; i < scene->mNumAnimations; ++i) {
182 aiAnimation* anim = scene->mAnimations[i];
183 auto* clip =
new AnimationClip();
185 clip->name = anim->mName.C_Str();
186 if (clip->name.empty())
187 clip->name =
"Animation_" + std::to_string(i);
189 clip->duration =
static_cast<float>(anim->mDuration);
190 clip->ticksPerSecond = anim->mTicksPerSecond > 0
191 ?
static_cast<float>(anim->mTicksPerSecond)
194 for (
unsigned int c = 0; c < anim->mNumChannels; ++c) {
195 aiNodeAnim* nodeAnim = anim->mChannels[c];
196 AnimationChannel channel;
198 channel.boneName = nodeAnim->mNodeName.C_Str();
199 channel.boneId = skeleton->FindBoneId(channel.boneName);
202 for (
unsigned int k = 0; k < nodeAnim->mNumPositionKeys; ++k) {
203 auto& key = nodeAnim->mPositionKeys[k];
204 channel.positionKeys.push_back({
205 static_cast<float>(key.mTime),
206 Math::Vector3D(key.mValue.x, key.mValue.y, key.mValue.z)
211 for (
unsigned int k = 0; k < nodeAnim->mNumRotationKeys; ++k) {
212 auto& key = nodeAnim->mRotationKeys[k];
213 channel.rotationKeys.push_back({
214 static_cast<float>(key.mTime),
215 Math::Quaternion(key.mValue.w, key.mValue.x,
216 key.mValue.y, key.mValue.z)
221 for (
unsigned int k = 0; k < nodeAnim->mNumScalingKeys; ++k) {
222 auto& key = nodeAnim->mScalingKeys[k];
223 channel.scaleKeys.push_back({
224 static_cast<float>(key.mTime),
225 Math::Vector3D(key.mValue.x, key.mValue.y, key.mValue.z)
229 clip->channels.push_back(std::move(channel));
234 SLEAK_INFO(
" Animation '{}': {} channels, {:.1f}s",
235 clip->name, clip->channels.size(),
236 clip->GetDurationInSeconds());
238 clips.push_back(clip);
244void ModelLoader::ProcessNode(aiNode* node,
const aiScene* scene,
245 GameObject* parent,
const std::string& directory,
249 std::string nodeName = node->mName.C_Str();
250 if (nodeName.empty()) nodeName =
"Node";
252 for (
unsigned int i = 0; i < node->mNumMeshes; ++i) {
253 aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
255 std::string meshName = mesh->mName.C_Str();
256 if (meshName.empty()) meshName = nodeName +
"_Mesh" + std::to_string(i);
260 float sf = options.scaleFactor;
261 meshObj->AddComponent<TransformComponent>(
264 Math::Vector3D(sf, sf, sf));
266 if (mesh->mMaterialIndex < scene->mNumMaterials) {
267 auto& material = materialCache[uint64_t(mesh->mMaterialIndex) << 1];
270 ProcessMaterial(scene->mMaterials[mesh->mMaterialIndex],
271 scene, directory, textureCache);
272 meshObj->AddComponent<MaterialComponent>(material);
275 MeshData meshData = ProcessMesh(mesh, options);
278 meshObj->AddComponent<MeshComponent>(std::move(meshData));
280 meshObj->SetParent(parent);
283 for (
unsigned int i = 0; i < node->mNumChildren; ++i) {
284 ProcessNode(node->mChildren[i], scene, parent, directory, options,
285 textureCache, materialCache);
289void ModelLoader::ProcessNodeAnimated(
290 aiNode* node,
const aiScene* scene,
GameObject* parent,
293 Skeleton* skeleton, std::vector<AnimationClip*>& clips) {
294 std::string nodeName = node->mName.C_Str();
295 if (nodeName.empty()) nodeName =
"Node";
297 for (
unsigned int i = 0; i < node->mNumMeshes; ++i) {
298 aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
300 std::string meshName = mesh->mName.C_Str();
301 if (meshName.empty()) meshName = nodeName +
"_Mesh" + std::to_string(i);
305 float sf = options.scaleFactor;
306 meshObj->AddComponent<TransformComponent>(
309 Math::Vector3D(sf, sf, sf));
312 bool hasBones = mesh->HasBones();
313 if (mesh->mMaterialIndex < scene->mNumMaterials) {
315 (uint64_t(mesh->mMaterialIndex) << 1) | (hasBones ? 1u : 0u);
316 auto& material = materialCache[key];
319 ProcessMaterial(scene->mMaterials[mesh->mMaterialIndex],
320 scene, directory, textureCache, hasBones);
321 meshObj->AddComponent<MaterialComponent>(material);
325 MeshData meshData = ProcessMesh(mesh, options, skeleton);
328 meshObj->AddComponent<MeshComponent>(std::move(meshData));
331 if (hasBones && skeleton->GetBoneCount() > 0 && !clips.empty()) {
332 meshObj->AddComponent<AnimatorComponent>(skeleton, clips);
335 meshObj->SetParent(parent);
338 for (
unsigned int i = 0; i < node->mNumChildren; ++i) {
339 ProcessNodeAnimated(node->mChildren[i], scene, parent, directory,
340 options, textureCache, materialCache, skeleton,
348 float nSign = options.flipNormals ? -1.0f : 1.0f;
351 for (
unsigned int i = 0; i < mesh->mNumVertices; ++i) {
354 v.px = mesh->mVertices[i].x;
355 v.py = mesh->mVertices[i].y;
356 v.pz = mesh->mVertices[i].z;
358 if (mesh->HasNormals()) {
359 v.nx = nSign * mesh->mNormals[i].x;
360 v.ny = nSign * mesh->mNormals[i].y;
361 v.nz = nSign * mesh->mNormals[i].z;
364 if (mesh->HasTangentsAndBitangents()) {
365 v.tx = mesh->mTangents[i].x;
366 v.ty = mesh->mTangents[i].y;
367 v.tz = mesh->mTangents[i].z;
371 if (mesh->HasVertexColors(0)) {
372 v.r = mesh->mColors[0][i].r;
373 v.g = mesh->mColors[0][i].g;
374 v.b = mesh->mColors[0][i].b;
375 v.a = mesh->mColors[0][i].a;
377 v.r = 1.0f; v.g = 1.0f; v.b = 1.0f; v.a = 1.0f;
380 if (mesh->HasTextureCoords(0)) {
381 v.u = mesh->mTextureCoords[0][i].x;
382 v.v = mesh->mTextureCoords[0][i].y;
386 data.vertices.AddVertex(v);
390 if (mesh->HasBones() && skeleton) {
391 for (
unsigned int b = 0; b < mesh->mNumBones; ++b) {
392 aiBone* bone = mesh->mBones[b];
393 std::string boneName = bone->mName.C_Str();
394 int boneId = skeleton->FindBoneId(boneName);
399 newBone.name = boneName;
400 newBone.offsetMatrix = ConvertMatrix(&bone->mOffsetMatrix);
401 boneId = skeleton->AddBone(newBone);
404 for (
unsigned int w = 0; w < bone->mNumWeights; ++w) {
405 unsigned int vertexId = bone->mWeights[w].mVertexId;
406 float weight = bone->mWeights[w].mWeight;
408 if (vertexId >= data.vertices.GetSize())
continue;
410 Vertex* vPtr = data.vertices.GetMutableData() + vertexId;
413 for (
int s = 0; s < MAX_BONE_INFLUENCE; ++s) {
414 if (vPtr->boneIDs[s] < 0) {
415 vPtr->boneIDs[s] = boneId;
416 vPtr->boneWeights[s] = weight;
425 for (
unsigned int i = 0; i < mesh->mNumFaces; ++i) {
426 const aiFace& face = mesh->mFaces[i];
427 if (options.flipWinding && face.mNumIndices == 3) {
428 data.indices.add(
static_cast<IndexType>(face.mIndices[0]));
429 data.indices.add(
static_cast<IndexType>(face.mIndices[2]));
430 data.indices.add(
static_cast<IndexType>(face.mIndices[1]));
432 for (
unsigned int j = 0; j < face.mNumIndices; ++j) {
433 data.indices.add(
static_cast<IndexType>(face.mIndices[j]));
438 SLEAK_INFO(
" Mesh '{}': {} vertices, {} indices{}",
439 mesh->mName.C_Str(), mesh->mNumVertices,
440 data.indices.GetSize(),
441 mesh->HasBones() ?
" (skinned)" :
"");
447 const aiScene* scene,
448 const std::string& directory,
452 material->SetShader(skinned ?
"assets/shaders/skinned_shader.hlsl"
453 :
"assets/shaders/default_shader.hlsl");
456 if (mat->Get(AI_MATKEY_COLOR_DIFFUSE, color) == AI_SUCCESS) {
457 material->SetDiffuseColor(color.r, color.g, color.b, color.a);
459 if (mat->Get(AI_MATKEY_COLOR_SPECULAR, color) == AI_SUCCESS) {
460 material->SetSpecularColor(Math::Color(
461 static_cast<uint8_t
>(color.r * 255),
462 static_cast<uint8_t
>(color.g * 255),
463 static_cast<uint8_t
>(color.b * 255)));
465 if (mat->Get(AI_MATKEY_COLOR_EMISSIVE, color) == AI_SUCCESS) {
466 material->SetEmissiveColor(color.r, color.g, color.b);
470 if (mat->Get(AI_MATKEY_SHININESS, val) == AI_SUCCESS)
471 material->SetShininess(val);
472 if (mat->Get(AI_MATKEY_OPACITY, val) == AI_SUCCESS)
473 material->SetOpacity(val);
474 if (mat->Get(AI_MATKEY_METALLIC_FACTOR, val) == AI_SUCCESS)
475 material->SetMetallic(val);
476 if (mat->Get(AI_MATKEY_ROUGHNESS_FACTOR, val) == AI_SUCCESS)
477 material->SetRoughness(val);
481 tex = LoadMaterialTexture(mat, aiTextureType_DIFFUSE, scene, directory, textureCache);
482 if (!tex) tex = LoadMaterialTexture(mat, aiTextureType_BASE_COLOR, scene, directory, textureCache);
483 if (tex) material->SetDiffuseTexture(tex);
485 tex = LoadMaterialTexture(mat, aiTextureType_NORMALS, scene, directory, textureCache);
486 if (tex) material->SetNormalTexture(tex);
488 tex = LoadMaterialTexture(mat, aiTextureType_SPECULAR, scene, directory, textureCache);
489 if (tex) material->SetSpecularTexture(tex);
491 tex = LoadMaterialTexture(mat, aiTextureType_EMISSIVE, scene, directory, textureCache);
492 if (tex) material->SetEmissiveTexture(tex);
494 tex = LoadMaterialTexture(mat, aiTextureType_METALNESS, scene, directory, textureCache);
495 if (tex) material->SetMetallicTexture(tex);
497 tex = LoadMaterialTexture(mat, aiTextureType_DIFFUSE_ROUGHNESS, scene, directory, textureCache);
498 if (tex) material->SetRoughnessTexture(tex);
504 aiMaterial* mat,
int type,
const aiScene* scene,
505 const std::string& directory,
TextureCache& textureCache) {
506 auto texType =
static_cast<aiTextureType
>(type);
511 mat->GetTexture(texType, 0, &aiPath);
512 std::string texPath = aiPath.C_Str();
515 std::string cacheKey = texPath +
":" + std::to_string(type);
516 auto it = textureCache.find(cacheKey);
517 if (it != textureCache.end())
521 const aiTexture* embedded = scene->GetEmbeddedTexture(texPath.c_str());
523 ::Sleak::Texture* tex =
nullptr;
524 if (embedded->mHeight == 0) {
527 unsigned char* pixels = stbi_load_from_memory(
528 reinterpret_cast<const unsigned char*
>(embedded->pcData),
529 static_cast<int>(embedded->mWidth),
530 &w, &h, &channels, 4);
533 SLEAK_ERROR(
" Failed to decode embedded texture: {}", texPath);
538 pixels,
static_cast<uint32_t
>(w),
static_cast<uint32_t
>(h),
541 stbi_image_free(pixels);
544 SLEAK_INFO(
" Loaded embedded texture: {} ({}x{})", texPath, w, h);
548 uint32_t w = embedded->mWidth;
549 uint32_t h = embedded->mHeight;
552 std::vector<uint8_t> rgba(w * h * 4);
553 const auto* src =
reinterpret_cast<const uint8_t*
>(embedded->pcData);
554 for (uint32_t i = 0; i < w * h; ++i) {
555 rgba[i * 4 + 0] = src[i * 4 + 1];
556 rgba[i * 4 + 1] = src[i * 4 + 2];
557 rgba[i * 4 + 2] = src[i * 4 + 3];
558 rgba[i * 4 + 3] = src[i * 4 + 0];
565 SLEAK_INFO(
" Loaded embedded raw texture: {} ({}x{})", texPath, w, h);
569 RefPtr<Texture> owned(tex);
570 if (owned) textureCache[cacheKey] = owned;
575 std::string fullPath = directory +
"/" + texPath;
578 std::replace(fullPath.begin(), fullPath.end(),
'\\',
'/');
580 if (!std::filesystem::exists(fullPath)) {
581 SLEAK_WARN(
" Texture file not found: {}", fullPath);
588 textureCache[cacheKey] = tex;
594 const std::string& filePath,
Skeleton* skeleton) {
595 std::vector<AnimationClip*> result;
602 Assimp::Importer importer;
603 unsigned int flags = aiProcess_Triangulate;
605 const aiScene* scene = importer.ReadFile(filePath, flags);
606 if (!scene || !scene->HasAnimations()) {
607 SLEAK_ERROR(
"LoadAnimationsOnly: failed to load or no animations in '{}'",
612 result = ExtractAnimations(scene, skeleton);
615 std::string stem = std::filesystem::path(filePath).stem().string();
616 for (
auto* clip : result) {
617 if (clip->name.empty() || clip->name.find(
"Armature") != std::string::npos
618 || clip->name.find(
"mixamo") != std::string::npos
619 || clip->name.find(
"Animation") != std::string::npos) {
625 SLEAK_INFO(
"LoadAnimationsOnly: '{}' -> {} clips", filePath, result.size());
GameObject(const std::string &name="GameObject")
static GameObject * Load(const std::string &filePath, const ModelLoadOptions &options={})
Imports a model file and returns the root of the resulting GameObject hierarchy.
static std::vector< AnimationClip * > LoadAnimationsOnly(const std::string &filePath, Skeleton *skeleton)
Load only animations from an FBX, reusing an existing skeleton.
static Sleak::Texture * CreateTexture(const std::string &TexturePath)
Loads a texture via the currently registered backend factory.
static Sleak::Texture * CreateTextureFromMemory(const void *data, uint32_t width, uint32_t height, TextureFormat format, uint32_t maxMipLevels=0)
Creates a texture from raw pixel data via the currently registered backend factory.
Matrix< float, 4, 4 > Matrix4
Root namespace for everything the engine exposes.
std::unordered_map< std::string, RefPtr<::Sleak::Texture > > TextureCache
Per-load texture cache to avoid loading the same texture file multiple times.
std::unordered_map< uint64_t, RefPtr< Material > > MaterialCache
Per-load cache so meshes sharing an Assimp material share one Material.
Math::Matrix4 offsetMatrix