Files
Seele/src/Editor/Asset/MeshLoader.cpp
T

543 lines
25 KiB
C++
Raw Normal View History

2020-06-02 11:46:18 +02:00
#include "MeshLoader.h"
2023-02-24 22:09:07 +01:00
#include "Asset/AssetImporter.h"
#include "Asset/MaterialAsset.h"
2024-06-09 12:20:04 +02:00
#include "Asset/MeshAsset.h"
#include "Graphics/Graphics.h"
#include "Graphics/Mesh.h"
2024-05-01 14:10:52 +02:00
#include "Graphics/Shader.h"
2024-06-09 12:20:04 +02:00
#include "Graphics/StaticMeshVertexData.h"
#include <Asset/MaterialLoader.h>
#include <Asset/TextureLoader.h>
#include <assimp/Importer.hpp>
#include <assimp/config.h>
#include <assimp/material.h>
#include <assimp/postprocess.h>
#include <assimp/scene.h>
2024-01-16 19:24:49 +01:00
#include <fmt/core.h>
2020-06-08 01:44:47 +02:00
#include <fstream>
2020-09-19 14:36:50 +02:00
#include <iostream>
2024-06-09 12:20:04 +02:00
#include <set>
2020-06-08 01:44:47 +02:00
#include <stb_image_write.h>
2024-06-09 12:20:04 +02:00
2020-06-02 11:46:18 +02:00
using namespace Seele;
2024-06-09 12:20:04 +02:00
MeshLoader::MeshLoader(Gfx::PGraphics graphics) : graphics(graphics) {}
2020-06-02 11:46:18 +02:00
2024-06-09 12:20:04 +02:00
MeshLoader::~MeshLoader() {}
2020-06-02 11:46:18 +02:00
2024-06-09 12:20:04 +02:00
void MeshLoader::importAsset(MeshImportArgs args) {
2023-02-01 22:13:04 +01:00
std::filesystem::path assetPath = args.filePath.filename();
2021-04-13 23:09:16 +02:00
assetPath.replace_extension("asset");
2023-11-05 10:36:01 +01:00
OMeshAsset asset = new MeshAsset(args.importPath, assetPath.stem().string());
PMeshAsset ref = asset;
2021-11-11 20:12:50 +01:00
asset->setStatus(Asset::Status::Loading);
2023-11-05 10:36:01 +01:00
AssetRegistry::get().registerMesh(std::move(asset));
2024-05-29 10:40:35 +02:00
import(args, ref);
2020-06-02 11:46:18 +02:00
}
2024-06-09 12:20:04 +02:00
void MeshLoader::convertAssimpARGB(unsigned char* dst, aiTexel* src, uint32 numPixels) {
for (uint32 i = 0; i < numPixels; ++i) {
2024-05-01 14:10:52 +02:00
dst[i * 4 + 0] = src[i].r;
dst[i * 4 + 1] = src[i].g;
dst[i * 4 + 2] = src[i].b;
dst[i * 4 + 3] = src[i].a;
}
}
2024-06-09 12:20:04 +02:00
void MeshLoader::loadTextures(const aiScene* scene, const std::filesystem::path& meshDirectory, const std::string& importPath,
Array<PTextureAsset>& textures) {
for (uint32 i = 0; i < scene->mNumTextures; ++i) {
2024-05-01 14:10:52 +02:00
aiTexture* tex = scene->mTextures[i];
auto texPath = std::filesystem::path(tex->mFilename.C_Str());
2024-06-09 12:20:04 +02:00
if (std::filesystem::exists(texPath)) {
} else if (std::filesystem::exists(meshDirectory / texPath)) {
2024-05-01 14:10:52 +02:00
texPath = meshDirectory / texPath;
2024-06-09 12:20:04 +02:00
} else {
2024-05-06 18:36:16 +02:00
texPath = (meshDirectory / texPath).replace_extension("png");
2024-06-09 12:20:04 +02:00
if (tex->mHeight == 0) {
std::cout << "Dumping texture " << texPath << std::endl;
2024-05-01 14:10:52 +02:00
// already compressed, just dump it to the disk
std::ofstream file(texPath, std::ios::binary);
file.write((const char*)tex->pcData, tex->mWidth);
file.flush();
2024-06-09 12:20:04 +02:00
} else {
std::cout << "Writing extracted png " << texPath << std::endl;
2024-05-01 14:10:52 +02:00
// recompress data so that the TextureLoader can read it
unsigned char* texData = new unsigned char[tex->mWidth * tex->mHeight * 4];
convertAssimpARGB(texData, tex->pcData, tex->mWidth * tex->mHeight);
stbi_write_png(texPath.string().c_str(), tex->mWidth, tex->mHeight, 4, tex->pcData, tex->mWidth * 32);
delete[] texData;
2023-12-02 10:55:00 +01:00
}
}
2024-05-01 14:10:52 +02:00
std::cout << "Loading model texture " << texPath.string() << std::endl;
AssetImporter::importTexture(TextureImportArgs{
.filePath = texPath,
2023-02-13 14:56:13 +01:00
.importPath = importPath,
2024-06-09 12:20:04 +02:00
});
2024-05-06 18:36:16 +02:00
textures.add(AssetRegistry::findTexture(importPath, texPath.stem().string()));
2024-05-01 14:10:52 +02:00
}
}
constexpr const char* KEY_DIFFUSE_COLOR = "k_d";
constexpr const char* KEY_SPECULAR_COLOR = "k_s";
constexpr const char* KEY_AMBIENT_COLOR = "k_a";
constexpr const char* KEY_SHININESS = "k_shiny";
constexpr const char* KEY_ROUGHNESS = "k_r";
constexpr const char* KEY_METALLIC = "k_m";
2024-05-01 14:10:52 +02:00
constexpr const char* KEY_DIFFUSE_TEXTURE = "tex_d";
constexpr const char* KEY_SPECULAR_TEXTURE = "tex_s";
constexpr const char* KEY_AMBIENT_TEXTURE = "tex_a";
constexpr const char* KEY_NORMAL_TEXTURE = "tex_n";
constexpr const char* KEY_SHININESS_TEXTURE = "tex_shiny";
constexpr const char* KEY_ROUGHNESS_TEXTURE = "tex_r";
constexpr const char* KEY_METALLIC_TEXTURE = "tex_m";
constexpr const char* KEY_AMBIENT_OCCLUSION_TEXTURE = "tex_ao";
2024-05-01 14:10:52 +02:00
2024-06-09 12:20:04 +02:00
void MeshLoader::loadMaterials(const aiScene* scene, const Array<PTextureAsset>& textures, const std::string& baseName,
const std::filesystem::path& meshDirectory, const std::string& importPath,
Array<PMaterialInstanceAsset>& globalMaterials) {
for (uint32 m = 0; m < scene->mNumMaterials; ++m) {
2024-05-15 15:27:13 +02:00
aiMaterial* material = scene->mMaterials[m];
2024-05-01 14:10:52 +02:00
aiString texPath;
2024-05-15 15:27:13 +02:00
std::string materialName = fmt::format("M{0}{1}{2}", baseName, material->GetName().C_Str(), m);
2024-06-09 12:20:04 +02:00
materialName.erase(std::remove(materialName.begin(), materialName.end(), '.'),
materialName.end()); // dots break adding the .asset extension later
materialName.erase(std::remove(materialName.begin(), materialName.end(), '-'),
materialName.end()); // dots break adding the .asset extension later
materialName.erase(std::remove(materialName.begin(), materialName.end(), ' '),
materialName.end()); // dots break adding the .asset extension later
materialName.erase(std::remove(materialName.begin(), materialName.end(), '('),
materialName.end()); // dots break adding the .asset extension later
materialName.erase(std::remove(materialName.begin(), materialName.end(), ')'),
materialName.end()); // dots break adding the .asset extension later
2024-05-01 14:10:52 +02:00
Array<OShaderExpression> expressions;
Array<std::string> parameters;
2024-06-18 19:19:05 +02:00
uint32 numTextures = 0;
uint32 numSamplers = 0;
uint32 numFloats = 0;
2024-06-09 12:20:04 +02:00
auto addScalarParameter = [&](std::string paramKey, const char* matKey, int type, int index) {
float scalar;
material->Get(matKey, type, index, scalar);
2024-06-18 19:19:05 +02:00
expressions.add(new FloatParameter(paramKey, scalar, numFloats++));
2024-06-09 12:20:04 +02:00
parameters.add(paramKey);
};
2024-06-09 12:20:04 +02:00
auto addVectorParameter = [&](std::string paramKey, const char* matKey, int type, int index) {
aiColor3D color;
material->Get(matKey, type, index, color);
2024-06-18 19:19:05 +02:00
expressions.add(new VectorParameter(paramKey, Vector(color.r, color.g, color.b), numFloats));
numFloats += 3;
2024-06-09 12:20:04 +02:00
parameters.add(paramKey);
};
2024-05-01 14:10:52 +02:00
2024-06-09 12:20:04 +02:00
auto addTextureParameter = [&](std::string paramKey, aiTextureType type, int index, std::string& result,
StaticArray<int32, 4> extractMask = {0, 1, 2, -1}) {
aiString texPath;
aiTextureMapping mapping;
uint32 uvIndex = 0;
aiTextureMapMode mapMode = aiTextureMapMode_Clamp;
float blend = std::numeric_limits<float>::max();
aiTextureOp op;
if (material->GetTexture(type, index, &texPath, &mapping, &uvIndex, nullptr, nullptr, nullptr) != AI_SUCCESS) {
std::cout << "fuck" << std::endl;
}
std::string textureKey = fmt::format("{0}Texture{1}", paramKey, index);
auto texFilename = std::filesystem::path(texPath.C_Str());
PTextureAsset texture;
2024-05-06 18:36:16 +02:00
2024-06-09 12:20:04 +02:00
if (texFilename.string()[0] == '*') {
texture = textures[atoi(texFilename.string().substr(1).c_str())];
} else if (std::filesystem::exists(texFilename)) {
AssetImporter::importTexture(TextureImportArgs{
2024-05-01 14:10:52 +02:00
.filePath = texFilename,
.importPath = importPath,
2024-06-09 12:20:04 +02:00
});
texture = AssetRegistry::findTexture(importPath, texFilename.stem().string());
} else if (std::filesystem::exists(meshDirectory / texFilename)) {
AssetImporter::importTexture(TextureImportArgs{
.filePath = meshDirectory / texFilename,
.importPath = importPath,
.type = type == aiTextureType_NORMALS ? TextureImportType::TEXTURE_NORMAL : TextureImportType::TEXTURE_2D,
2024-06-09 12:20:04 +02:00
});
texture = AssetRegistry::findTexture(importPath, texFilename.stem().string());
} else if (std::filesystem::exists(meshDirectory.parent_path() / "textures" / texFilename)) {
AssetImporter::importTexture(TextureImportArgs{
2024-05-23 14:58:14 +02:00
.filePath = meshDirectory.parent_path() / "textures" / texFilename,
.importPath = importPath,
.type = type == aiTextureType_NORMALS ? TextureImportType::TEXTURE_NORMAL : TextureImportType::TEXTURE_2D,
2024-06-09 12:20:04 +02:00
});
texture = AssetRegistry::findTexture(importPath, texFilename.stem().string());
} else {
std::cout << "couldnt find " << texPath.C_Str() << std::endl;
return;
}
2024-06-18 19:19:05 +02:00
expressions.add(new TextureParameter(textureKey, texture, numTextures++));
2024-06-09 12:20:04 +02:00
parameters.add(textureKey);
2024-05-01 14:10:52 +02:00
2024-06-09 12:20:04 +02:00
std::string samplerKey = fmt::format("{0}Sampler{1}", paramKey, index);
SamplerCreateInfo samplerInfo = {};
switch (mapMode) {
case aiTextureMapMode_Wrap:
samplerInfo.addressModeU = Gfx::SE_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeV = Gfx::SE_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeW = Gfx::SE_SAMPLER_ADDRESS_MODE_REPEAT;
break;
case aiTextureMapMode_Clamp:
samplerInfo.addressModeU = Gfx::SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
samplerInfo.addressModeV = Gfx::SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
samplerInfo.addressModeW = Gfx::SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
break;
case aiTextureMapMode_Decal:
samplerInfo.addressModeU = Gfx::SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER;
samplerInfo.addressModeV = Gfx::SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER;
samplerInfo.addressModeW = Gfx::SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER;
break;
case aiTextureMapMode_Mirror:
samplerInfo.addressModeU = Gfx::SE_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT;
samplerInfo.addressModeV = Gfx::SE_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT;
samplerInfo.addressModeW = Gfx::SE_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT;
break;
}
2024-06-18 19:19:05 +02:00
expressions.add(new SamplerParameter(samplerKey, graphics->createSampler(samplerInfo), numSamplers++));
2024-06-09 12:20:04 +02:00
parameters.add(samplerKey);
2024-05-01 14:10:52 +02:00
2024-06-09 12:20:04 +02:00
std::string sampleKey = fmt::format("{0}Sample{1}", paramKey, index);
expressions.add(new SampleExpression());
expressions.back()->key = sampleKey;
expressions.back()->inputs["texture"].source = textureKey;
expressions.back()->inputs["sampler"].source = samplerKey;
expressions.back()->inputs["coords"].source = fmt::format("input.texCoords[{0}]", uvIndex);
2024-05-01 14:10:52 +02:00
2024-06-09 12:20:04 +02:00
std::string colorExtract = fmt::format("{0}Extract{1}", paramKey, index);
expressions.add(new SwizzleExpression(extractMask));
expressions.back()->key = colorExtract;
expressions.back()->inputs["target"].source = sampleKey;
// TODO: extract alpha, set opacity
2024-05-01 14:10:52 +02:00
2024-06-09 12:20:04 +02:00
if (blend == std::numeric_limits<float>::max()) {
result = colorExtract;
return;
}
std::string blendFactorKey = fmt::format("{0}BlendFactor{1}", paramKey, index);
2024-06-18 19:19:05 +02:00
expressions.add(new FloatParameter(blendFactorKey, blend, numFloats++));
2024-06-09 12:20:04 +02:00
parameters.add(blendFactorKey);
2024-05-01 14:10:52 +02:00
2024-06-09 12:20:04 +02:00
std::string strengthKey = fmt::format("{0}Strength{1}", paramKey, index);
expressions.add(new MulExpression());
expressions.back()->key = strengthKey;
expressions.back()->inputs["lhs"].source = colorExtract;
expressions.back()->inputs["rhs"].source = blendFactorKey;
std::string blendKey = fmt::format("{0}Blend{1}", paramKey, index);
switch (op) {
/** T = T1 * T2 */
case aiTextureOp_Multiply:
2024-05-01 14:10:52 +02:00
expressions.add(new MulExpression());
2024-06-09 12:20:04 +02:00
break;
2024-05-01 14:10:52 +02:00
2024-06-09 12:20:04 +02:00
/** T = T1 - T2 */
case aiTextureOp_Subtract:
expressions.add(new SubExpression());
break;
2024-05-01 14:10:52 +02:00
2024-06-09 12:20:04 +02:00
/** T = T1 / T2 */
case aiTextureOp_Divide:
// expressions[blendKey] = new DivExpression();
throw std::logic_error("Not implemented");
2024-05-01 14:10:52 +02:00
2024-06-09 12:20:04 +02:00
/** T = (T1 + T2) - (T1 * T2) */
case aiTextureOp_SmoothAdd:
throw std::logic_error("Not implemented");
2024-05-01 14:10:52 +02:00
2024-06-09 12:20:04 +02:00
/** T = T1 + (T2-0.5) */
case aiTextureOp_SignedAdd:
throw std::logic_error("Not implemented");
2024-05-01 14:10:52 +02:00
2024-06-09 12:20:04 +02:00
/** T = T1 + T2 */
case aiTextureOp_Add:
default:
expressions.add(new AddExpression());
break;
}
expressions.back()->key = blendKey;
expressions.back()->inputs["lhs"].source = result;
expressions.back()->inputs["rhs"].source = strengthKey;
2024-05-01 14:10:52 +02:00
2024-06-09 12:20:04 +02:00
result = blendKey;
};
2024-05-01 14:10:52 +02:00
// Diffuse
2024-05-01 14:10:52 +02:00
addVectorParameter(KEY_DIFFUSE_COLOR, AI_MATKEY_COLOR_DIFFUSE);
std::string outputDiffuse = KEY_DIFFUSE_COLOR;
uint32 numDiffuseTextures = material->GetTextureCount(aiTextureType_DIFFUSE);
2024-06-09 12:20:04 +02:00
for (uint32 i = 0; i < numDiffuseTextures; ++i) {
2024-05-01 14:10:52 +02:00
addTextureParameter(KEY_DIFFUSE_TEXTURE, aiTextureType_DIFFUSE, i, outputDiffuse);
2024-04-23 17:08:39 +02:00
}
// Specular
addVectorParameter(KEY_SPECULAR_COLOR, AI_MATKEY_COLOR_SPECULAR);
std::string outputSpecular = KEY_SPECULAR_COLOR;
2024-05-01 14:10:52 +02:00
uint32 numSpecular = material->GetTextureCount(aiTextureType_SPECULAR);
2024-06-09 12:20:04 +02:00
for (uint32 i = 0; i < numSpecular; ++i) {
2024-05-01 14:10:52 +02:00
addTextureParameter(KEY_SPECULAR_TEXTURE, aiTextureType_SPECULAR, i, outputSpecular);
2024-04-23 17:08:39 +02:00
}
2024-05-01 14:10:52 +02:00
// Normal
std::string outputNormal = "";
2024-05-01 14:10:52 +02:00
uint32 numNormal = material->GetTextureCount(aiTextureType_NORMALS);
2024-06-09 12:20:04 +02:00
for (uint32 i = 0; i < numNormal; ++i) {
addTextureParameter(KEY_NORMAL_TEXTURE, aiTextureType_NORMALS, i, outputNormal);
2024-05-01 14:10:52 +02:00
}
// Ambient Color
addVectorParameter(KEY_AMBIENT_COLOR, AI_MATKEY_COLOR_AMBIENT);
std::string outputAmbient = KEY_AMBIENT_COLOR;
uint32 numAmbient = material->GetTextureCount(aiTextureType_AMBIENT);
2024-06-09 12:20:04 +02:00
for (uint32 i = 0; i < numAmbient; ++i) {
addTextureParameter(KEY_AMBIENT_TEXTURE, aiTextureType_AMBIENT, i, outputAmbient);
2024-05-01 14:10:52 +02:00
}
// Shininess
addScalarParameter(KEY_SHININESS, AI_MATKEY_SHININESS);
std::string outputShininess = KEY_SHININESS;
uint32 numShiny = material->GetTextureCount(aiTextureType_SHININESS);
2024-06-09 12:20:04 +02:00
for (uint32 i = 0; i < numShiny; ++i) {
addTextureParameter(KEY_SHININESS_TEXTURE, aiTextureType_SHININESS, i, outputShininess, {0, -1, -1, -1});
}
// Roughness
addScalarParameter(KEY_ROUGHNESS, AI_MATKEY_ROUGHNESS_FACTOR);
std::string outputRoughness = KEY_ROUGHNESS;
uint32 numRoughness = material->GetTextureCount(aiTextureType_DIFFUSE_ROUGHNESS);
2024-06-09 12:20:04 +02:00
for (uint32 i = 0; i < numRoughness; ++i) {
addTextureParameter(KEY_ROUGHNESS_TEXTURE, aiTextureType_DIFFUSE_ROUGHNESS, i, outputRoughness, {0, -1, -1, -1});
}
// Metallic
addScalarParameter(KEY_METALLIC, AI_MATKEY_METALLIC_FACTOR);
std::string outputMetallic = KEY_METALLIC;
uint32 numMetallic = material->GetTextureCount(aiTextureType_METALNESS);
2024-06-09 12:20:04 +02:00
for (uint32 i = 0; i < numMetallic; ++i) {
addTextureParameter(KEY_METALLIC_TEXTURE, aiTextureType_METALNESS, i, outputMetallic, {0, -1, -1, -1});
}
// Ambient Occlusion
std::string outputAO = "";
uint32 numAO = material->GetTextureCount(aiTextureType_AMBIENT_OCCLUSION);
2024-06-09 12:20:04 +02:00
for (uint32 i = 0; i < numAO; ++i) {
addTextureParameter(KEY_AMBIENT_OCCLUSION_TEXTURE, aiTextureType_AMBIENT_OCCLUSION, i, outputAO, {0, -1, -1, -1});
}
2024-05-01 14:10:52 +02:00
MaterialNode brdf;
brdf.variables["baseColor"] = outputDiffuse;
2024-06-09 12:20:04 +02:00
if (!outputNormal.empty()) {
2024-05-06 18:36:16 +02:00
expressions.add(new MulExpression());
expressions.back()->key = "NormalMul";
expressions.back()->inputs["lhs"].source = "2";
expressions.back()->inputs["rhs"].source = outputNormal;
2024-05-23 14:58:14 +02:00
2024-05-06 18:36:16 +02:00
expressions.add(new SubExpression());
expressions.back()->key = "NormalSub";
expressions.back()->inputs["lhs"].source = "NormalMul";
expressions.back()->inputs["rhs"].source = "float3(1,1,1)";
brdf.variables["normal"] = "NormalSub";
2024-05-01 14:10:52 +02:00
}
aiShadingMode mode;
material->Get(AI_MATKEY_SHADING_MODEL, mode);
switch (mode) {
case aiShadingMode_Blinn:
2024-05-06 18:36:16 +02:00
brdf.profile = "BlinnPhong";
brdf.variables["specularColor"] = outputSpecular;
brdf.variables["ambient"] = outputAmbient;
brdf.variables["shininess"] = outputShininess;
break;
case aiShadingMode_Phong:
2024-05-06 18:36:16 +02:00
brdf.profile = "Phong";
brdf.variables["specular"] = outputSpecular;
brdf.variables["ambient"] = outputAmbient;
2024-05-06 18:36:16 +02:00
brdf.variables["shininess"] = outputShininess;
break;
case aiShadingMode_Toon:
brdf.profile = "CelShading";
break;
2024-05-04 13:25:19 +02:00
default:
case aiShadingMode_CookTorrance:
brdf.profile = "CookTorrance";
brdf.variables["roughness"] = outputRoughness;
brdf.variables["metallic"] = outputMetallic;
2024-06-09 12:20:04 +02:00
if (!outputAO.empty()) {
brdf.variables["ambientOcclusion"] = outputAmbient;
}
break;
};
2024-05-01 14:10:52 +02:00
OMaterialAsset baseMat = new MaterialAsset(importPath, materialName);
2024-06-18 19:19:05 +02:00
baseMat->material = new Material(graphics, numTextures, numSamplers, numFloats, materialName, std::move(expressions),
2024-06-09 12:20:04 +02:00
std::move(parameters), std::move(brdf));
2024-05-01 14:10:52 +02:00
baseMat->material->compile();
graphics->getShaderCompiler()->registerMaterial(baseMat->material);
2024-05-15 15:27:13 +02:00
globalMaterials[m] = baseMat->instantiate(InstantiationParameter{
2024-01-16 19:24:49 +01:00
.name = fmt::format("{0}_Inst_0", baseMat->getName()),
2023-11-07 16:55:13 +01:00
.folderPath = baseMat->getFolderPath(),
2024-06-09 12:20:04 +02:00
});
2024-05-01 14:10:52 +02:00
AssetRegistry::get().saveAsset(PMaterialAsset(baseMat), MaterialAsset::IDENTIFIER, baseMat->getFolderPath(), baseMat->getName());
AssetRegistry::get().registerMaterial(std::move(baseMat));
}
}
2024-06-09 12:20:04 +02:00
void findMeshRoots(aiNode* node, List<aiNode*>& meshNodes) {
if (node->mNumMeshes > 0) {
2020-06-02 11:46:18 +02:00
meshNodes.add(node);
return;
}
2024-06-09 12:20:04 +02:00
for (uint32 i = 0; i < node->mNumChildren; ++i) {
2020-06-02 11:46:18 +02:00
findMeshRoots(node->mChildren[i], meshNodes);
}
}
2023-10-31 16:16:23 +01:00
2024-06-09 12:20:04 +02:00
void MeshLoader::loadGlobalMeshes(const aiScene* scene, const Array<PMaterialInstanceAsset>& materials, Array<OMesh>& globalMeshes,
Component::Collider& collider) {
for (int32 meshIndex = 0; meshIndex < scene->mNumMeshes; ++meshIndex) {
2023-11-07 16:55:13 +01:00
aiMesh* mesh = scene->mMeshes[meshIndex];
2024-04-23 17:08:39 +02:00
if (!(mesh->mPrimitiveTypes & aiPrimitiveType_TRIANGLE))
continue;
2023-01-21 18:43:21 +01:00
collider.boundingbox.adjust(Vector(mesh->mAABB.mMin.x, mesh->mAABB.mMin.y, mesh->mAABB.mMin.z));
collider.boundingbox.adjust(Vector(mesh->mAABB.mMax.x, mesh->mAABB.mMax.y, mesh->mAABB.mMax.z));
2023-10-31 16:16:23 +01:00
// assume static mesh for now
2024-06-13 22:47:51 +02:00
Array<Vector4> positions(mesh->mNumVertices);
2024-05-06 18:36:16 +02:00
StaticArray<Array<Vector2>, MAX_TEXCOORDS> texCoords;
2024-06-09 12:20:04 +02:00
for (size_t i = 0; i < MAX_TEXCOORDS; ++i) {
2024-05-06 18:36:16 +02:00
texCoords[i].resize(mesh->mNumVertices);
}
2024-06-13 22:47:51 +02:00
Array<Vector4> normals(mesh->mNumVertices);
Array<Vector4> tangents(mesh->mNumVertices);
Array<Vector4> biTangents(mesh->mNumVertices);
Array<Vector4> colors(mesh->mNumVertices);
2023-10-31 16:16:23 +01:00
StaticMeshVertexData* vertexData = StaticMeshVertexData::getInstance();
2024-06-09 12:20:04 +02:00
for (int32 i = 0; i < mesh->mNumVertices; ++i) {
2024-06-13 22:47:51 +02:00
positions[i] = Vector4(mesh->mVertices[i].x, mesh->mVertices[i].y, mesh->mVertices[i].z, 1.0f);
2024-06-09 12:20:04 +02:00
for (size_t j = 0; j < MAX_TEXCOORDS; ++j) {
if (mesh->HasTextureCoords(j)) {
2024-05-06 18:36:16 +02:00
texCoords[j][i] = Vector2(mesh->mTextureCoords[j][i].x, mesh->mTextureCoords[j][i].y);
2024-06-09 12:20:04 +02:00
} else {
2024-05-06 18:36:16 +02:00
texCoords[j][i] = Vector2(0, 0);
}
2024-04-23 17:08:39 +02:00
}
2024-06-13 22:47:51 +02:00
normals[i] = Vector4(mesh->mNormals[i].x, mesh->mNormals[i].y, mesh->mNormals[i].z, 1.0f);
2024-06-09 12:20:04 +02:00
if (mesh->HasTangentsAndBitangents()) {
2024-06-13 22:47:51 +02:00
tangents[i] = Vector4(mesh->mTangents[i].x, mesh->mTangents[i].y, mesh->mTangents[i].z, 1.0f);
biTangents[i] = Vector4(mesh->mBitangents[i].x, mesh->mBitangents[i].y, mesh->mBitangents[i].z, 1.0f);
2024-06-09 12:20:04 +02:00
} else {
2024-06-13 22:47:51 +02:00
tangents[i] = Vector4(0, 0, 1, 1);
biTangents[i] = Vector4(1, 0, 0, 1);
2024-04-23 17:08:39 +02:00
}
2024-06-09 12:20:04 +02:00
if (mesh->HasVertexColors(0)) {
2024-06-13 22:47:51 +02:00
colors[i] = Vector4(mesh->mColors[0][i].r, mesh->mColors[0][i].g, mesh->mColors[0][i].b, 1.0f);
2024-06-09 12:20:04 +02:00
} else {
2024-06-13 22:47:51 +02:00
colors[i] = Vector4(1, 1, 1, 1);
2023-11-11 22:39:17 +01:00
}
2023-01-21 18:43:21 +01:00
}
2023-10-31 16:16:23 +01:00
MeshId id = vertexData->allocateVertexData(mesh->mNumVertices);
vertexData->loadPositions(id, positions);
2024-05-06 18:36:16 +02:00
2024-06-09 12:20:04 +02:00
for (size_t i = 0; i < MAX_TEXCOORDS; ++i) {
2024-05-06 18:36:16 +02:00
vertexData->loadTexCoords(id, i, texCoords[i]);
}
2023-10-31 16:16:23 +01:00
vertexData->loadNormals(id, normals);
vertexData->loadTangents(id, tangents);
vertexData->loadBiTangents(id, biTangents);
2023-11-11 22:39:17 +01:00
vertexData->loadColors(id, colors);
2020-06-08 01:44:47 +02:00
2024-04-07 16:33:32 +02:00
Array<uint32> indices(mesh->mNumFaces * 3);
2024-06-09 12:20:04 +02:00
for (int32 faceIndex = 0; faceIndex < mesh->mNumFaces; ++faceIndex) {
2020-06-08 01:44:47 +02:00
indices[faceIndex * 3 + 0] = mesh->mFaces[faceIndex].mIndices[0];
indices[faceIndex * 3 + 1] = mesh->mFaces[faceIndex].mIndices[1];
indices[faceIndex * 3 + 2] = mesh->mFaces[faceIndex].mIndices[2];
}
2023-01-21 18:43:21 +01:00
2023-11-01 13:38:49 +01:00
Array<Meshlet> meshlets;
meshlets.reserve(indices.size() / (3ull * Gfx::numPrimitivesPerMeshlet));
2023-12-23 18:26:54 +01:00
Meshlet::build(positions, indices, meshlets);
2023-11-26 11:27:39 +01:00
vertexData->loadMesh(id, indices, meshlets);
2023-11-07 16:55:13 +01:00
2024-06-09 12:20:04 +02:00
// collider.physicsMesh.addCollider(positions, indices, Matrix4(1.0f));
2023-01-21 18:43:21 +01:00
2023-11-01 13:38:49 +01:00
globalMeshes[meshIndex] = new Mesh();
globalMeshes[meshIndex]->vertexData = vertexData;
globalMeshes[meshIndex]->id = id;
2023-11-07 16:55:13 +01:00
globalMeshes[meshIndex]->referencedMaterial = materials[mesh->mMaterialIndex];
2023-11-01 13:38:49 +01:00
globalMeshes[meshIndex]->meshlets = std::move(meshlets);
2023-11-10 22:01:58 +01:00
globalMeshes[meshIndex]->indices = std::move(indices);
2023-11-05 11:47:22 +01:00
globalMeshes[meshIndex]->vertexCount = mesh->mNumVertices;
2024-06-13 15:43:03 +02:00
globalMeshes[meshIndex]->blas =
graphics->createBottomLevelAccelerationStructure(Gfx::BottomLevelASCreateInfo(globalMeshes[meshIndex]));
2020-06-08 01:44:47 +02:00
}
}
2023-11-01 13:38:49 +01:00
2024-06-09 12:20:04 +02:00
Matrix4 convertMatrix(aiMatrix4x4 matrix) {
return Matrix4(matrix.a1, matrix.b1, matrix.c1, matrix.d1, matrix.a2, matrix.b2, matrix.c2, matrix.d2, matrix.a3, matrix.b3, matrix.c3,
matrix.d3, matrix.a4, matrix.b4, matrix.c4, matrix.d4);
2024-04-23 23:21:30 +02:00
}
2024-06-09 12:20:04 +02:00
aiMatrix4x4 loadNodeTransform(aiNode* node) {
2024-04-24 23:25:34 +02:00
aiMatrix4x4 parent = aiMatrix4x4();
2024-06-09 12:20:04 +02:00
if (node->mParent != nullptr) {
2024-04-23 23:21:30 +02:00
parent = loadNodeTransform(node->mParent);
}
2024-04-24 23:25:34 +02:00
return node->mTransformation * parent;
2024-04-23 23:21:30 +02:00
}
2024-06-09 12:20:04 +02:00
void MeshLoader::import(MeshImportArgs args, PMeshAsset meshAsset) {
2024-05-23 14:58:14 +02:00
std::cout << "Starting to import " << args.filePath << std::endl;
2021-04-13 23:09:16 +02:00
meshAsset->setStatus(Asset::Status::Loading);
2020-06-02 11:46:18 +02:00
Assimp::Importer importer;
2024-06-09 12:20:04 +02:00
importer.ReadFile(args.filePath.string().c_str(),
(uint32)(aiProcess_JoinIdenticalVertices | aiProcess_FlipUVs | aiProcess_Triangulate | aiProcess_SortByPType |
aiProcess_GenBoundingBoxes | aiProcess_GenSmoothNormals | aiProcess_ImproveCacheLocality |
aiProcess_GenUVCoords | aiProcess_FindDegenerates));
2024-05-23 14:58:14 +02:00
const aiScene* scene = importer.ApplyPostProcessing(aiProcess_CalcTangentSpace);
2024-04-24 23:25:34 +02:00
std::cout << importer.GetErrorString() << std::endl;
2024-05-06 18:36:16 +02:00
Array<PTextureAsset> textures;
2024-05-01 14:10:52 +02:00
loadTextures(scene, args.filePath.parent_path(), args.importPath, textures);
2023-11-07 16:55:13 +01:00
Array<PMaterialInstanceAsset> globalMaterials(scene->mNumMaterials);
2024-05-01 14:10:52 +02:00
loadMaterials(scene, textures, args.filePath.stem().string(), args.filePath.parent_path(), args.importPath, globalMaterials);
2024-05-23 14:58:14 +02:00
2023-11-05 10:36:01 +01:00
Array<OMesh> globalMeshes(scene->mNumMeshes);
2023-01-21 18:43:21 +01:00
Component::Collider collider;
loadGlobalMeshes(scene, globalMaterials, globalMeshes, collider);
2020-06-02 11:46:18 +02:00
2024-05-23 14:58:14 +02:00
List<aiNode*> meshNodes;
2020-06-08 01:44:47 +02:00
findMeshRoots(scene->mRootNode, meshNodes);
2024-05-23 14:58:14 +02:00
2023-11-05 10:36:01 +01:00
Array<OMesh> meshes;
2024-06-09 12:20:04 +02:00
for (auto meshNode : meshNodes) {
for (uint32 i = 0; i < meshNode->mNumMeshes; ++i) {
if (globalMeshes[meshNode->mMeshes[i]] == nullptr) {
2024-04-23 23:21:30 +02:00
continue;
}
2023-11-05 10:36:01 +01:00
meshes.add(std::move(globalMeshes[meshNode->mMeshes[i]]));
2024-04-24 23:25:34 +02:00
meshes.back()->transform = convertMatrix(loadNodeTransform(meshNode));
2020-06-08 01:44:47 +02:00
}
}
2023-11-05 10:36:01 +01:00
meshAsset->meshes = std::move(meshes);
2023-01-21 18:43:21 +01:00
meshAsset->physicsMesh = std::move(collider);
2023-07-31 21:43:20 +02:00
2024-06-09 12:20:04 +02:00
auto stream = AssetRegistry::createWriteStream(
(std::filesystem::path(meshAsset->getFolderPath()) / meshAsset->getName()).replace_extension("asset").string(), std::ios::binary);
2023-07-31 21:43:20 +02:00
ArchiveBuffer archive;
Serialization::save(archive, MeshAsset::IDENTIFIER);
Serialization::save(archive, meshAsset->getName());
Serialization::save(archive, meshAsset->getFolderPath());
meshAsset->save(archive);
archive.writeToStream(stream);
2021-04-13 23:09:16 +02:00
meshAsset->setStatus(Asset::Status::Ready);
2023-07-31 21:43:20 +02:00
std::cout << "Finished loading " << args.filePath << std::endl;
2020-06-02 11:46:18 +02:00
}