5 #include <assimp/cimport.h>
6 //#include <assimp/metadata.h>
7 #include <assimp/postprocess.h>
8 #include <assimp/scene.h>
14 #define IMPORT_DEBUG_ 0
16 static const float smoothingThresholdAngle = TAU / 14.0f;
18 static const struct aiScene* importScene(const char* path);
19 static Vector triangleNormal(Vector v1, Vector v2, Vector v3);
20 static Vector convertAiVector3D(struct aiVector3D vect);
21 static const char* replaceFileExtension(const struct aiString path, const char* ext);
26 static void printMetadata(const struct aiMetadata* meta) {
28 for (size_t i = 0; i < meta->mNumProperties; ++i) {
29 String key = stringFromAiString(meta->mKeys[i]);
30 const struct aiMetadataEntry value = meta->mValues[i];
31 switch (value.mType) {
33 logDebug("\"%s\": (bool) %d", key.cstr, *((int*) value.mData));
36 logDebug("\"%s\": (int32) %d", key.cstr, *((int32_t*) value.mData));
39 logDebug("\"%s\": (uint64) %llu", key.cstr, *((uint64_t*) value.mData));
42 logDebug("\"%s\": (float) %f", key.cstr, *((float*) value.mData));
45 logDebug("\"%s\": (double) %f", key.cstr, *((double*) value.mData));
48 String str = stringFromAiString(*((struct aiString*) value.mData));
49 logDebug("\"%s\": (string) %s", key.cstr, str.cstr);
53 struct aiVector3D vec = *((struct aiVector3D*) value.mData);
54 logDebug("\"%s\": (vector3d) { %f, %f, %f }", key.cstr, vec.x, vec.y, vec.z);
58 logDebug("\"%s\": (unrecognized type)", key.cstr);
66 void printAiNodeMetadata(const struct aiNode* node) {
71 String name = stringFromAiString(node->mName);
72 logDebug("Metadata from node \"%s\": %p", name.cstr, node->mMetaData);
73 printMetadata(node->mMetaData);
75 for (size_t i = 0; i < node->mNumChildren; ++i) {
76 printAiNodeMetadata(node->mChildren[i]);
81 #endif // IMPORT_DEBUG_
83 const Solid* importSolid(const char* path) {
84 const struct aiScene* scene = importScene(path);
86 logError("Failed to import solid from %s", path);
91 const struct aiMetadata* meta = scene->mMetaData;
92 logDebug("Metadata from %s: %p", path, meta);
94 printAiNodeMetadata(scene->mRootNode);
95 #endif // IMPORT_DEBUG_
97 const unsigned int numMeshes = scene->mNumMeshes;
98 const unsigned int numMaterials = scene->mNumMaterials;
100 // TODO Consider assets with some arrays empty, and prevent zero mallocs
102 Solid* solid = malloc(sizeof(Solid));
103 solid->numMeshes = numMeshes;
104 solid->meshes = malloc(numMeshes * sizeof(Mesh));
105 solid->numMaterials = numMaterials;
106 solid->materials = malloc(numMaterials * sizeof(Material));
108 for (unsigned int meshIndex = 0; meshIndex < numMeshes; ++meshIndex) {
109 const struct aiMesh* aiMesh = scene->mMeshes[meshIndex];
110 const unsigned int numVertices = aiMesh->mNumVertices;
111 const unsigned int numFaces = aiMesh->mNumFaces;
113 Mesh mesh = { .numVertices = numVertices,
114 .vertices = malloc(numVertices * sizeof(Vector)),
116 .textureCoords = NULL,
117 .numFaces = numFaces,
118 .faces = malloc(numFaces * sizeof(Face)),
119 .materialIndex = aiMesh->mMaterialIndex };
121 for (unsigned int vertIndex = 0; vertIndex < numVertices; ++vertIndex) {
122 mesh.vertices[vertIndex] = convertAiVector3D(
123 aiMesh->mVertices[vertIndex]);
126 if (aiMesh->mNormals != NULL) {
127 mesh.normals = malloc(numVertices * sizeof(Vector));
128 for (unsigned int normIndex = 0; normIndex < numVertices; ++normIndex) {
129 mesh.normals[normIndex] = convertAiVector3D(
130 aiMesh->mNormals[normIndex]);
134 mesh.textureCoords = malloc(numVertices * sizeof(Vector));
135 for (unsigned int texcIndex = 0; texcIndex < numVertices; ++texcIndex) {
136 mesh.textureCoords[texcIndex] = convertAiVector3D(
137 aiMesh->mTextureCoords[0][texcIndex]);
140 for (unsigned int faceIndex = 0; faceIndex < numFaces; ++faceIndex) {
141 const struct aiFace aiFace = aiMesh->mFaces[faceIndex];
142 const unsigned int numIndices = aiFace.mNumIndices;
144 Face face = { .numIndices = numIndices,
145 .indices = malloc(numIndices * sizeof(size_t)),
146 .normals = malloc(numIndices * sizeof(Vector)) };
148 for (unsigned int i = 0; i < numIndices; ++i) {
149 face.indices[i] = aiFace.mIndices[i];
152 if (numIndices == 3) {
153 Vector normal = triangleNormal(mesh.vertices[face.indices[0]],
154 mesh.vertices[face.indices[1]],
155 mesh.vertices[face.indices[2]]);
156 for (size_t i = 0; i < numIndices; ++i) {
157 face.normals[i] = normal;
162 for (size_t i = 0; i < numIndices; ++i) {
163 face.normals[i] = mesh.normals[face.indices[i]];
172 mesh.faces[faceIndex] = face;
175 float smoothingThreshold = cosf(smoothingThresholdAngle);
176 Face* smoothedFaces = malloc(mesh.numFaces * sizeof(Face));
177 for (size_t faceIndex = 0; faceIndex < mesh.numFaces; ++faceIndex) {
178 Face face = mesh.faces[faceIndex];
181 face.normals = memcpy(malloc(face.numIndices * sizeof(Vector)),
183 face.numIndices * sizeof(Vector));
185 for (size_t indexIndex = 0; indexIndex < face.numIndices; ++indexIndex) {
186 Vector smoothedNormal = face.normals[indexIndex];
188 for (size_t i = 0; i < mesh.numFaces; ++i) {
189 if (i == faceIndex || !mesh.faces[i].normals) {
193 for (size_t k = 0; k < mesh.faces[i].numIndices; ++k) {
194 if (mesh.faces[i].indices[k] == face.indices[indexIndex]
195 && dotProduct(face.normals[indexIndex],
196 mesh.faces[i].normals[k]) >= smoothingThreshold) {
197 smoothedNormal = addVectors(smoothedNormal, mesh.faces[i].normals[k]);
202 face.normals[indexIndex] = normalized(smoothedNormal);
205 smoothedFaces[faceIndex] = face;
207 // TODO Actually clean up the stuff inside
209 mesh.faces = smoothedFaces;
211 solid->meshes[meshIndex] = mesh;
214 GLuint* textureIds = malloc(numMaterials * sizeof(GLuint));
215 glGenTextures(numMaterials, textureIds);
217 for (unsigned int matIndex = 0; matIndex < numMaterials; ++matIndex) {
218 Material material = { .textureId = textureIds[matIndex] };
221 const struct aiMaterialProperty* prop;
222 aiGetMaterialProperty(scene->mMaterials[matIndex],
223 AI_MATKEY_SHADING_MODEL,
226 String key = stringFromAiString(prop->mKey);
228 logDebug("Material property \"%s\": Shading model: (length %u) %d",
231 *((int32_t*) prop->mData));
234 #endif // IMPORT_DEBUG_
236 glBindTexture(GL_TEXTURE_2D, material.textureId);
237 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
239 struct aiString originalTexturePath;
240 if (aiGetMaterialTexture(scene->mMaterials[matIndex],
241 aiTextureType_DIFFUSE,
243 &originalTexturePath,
244 NULL, NULL, NULL, NULL, NULL, NULL) == AI_SUCCESS) {
245 const char* textureFilename = replaceFileExtension(originalTexturePath, ".tga");
246 const size_t textureFilenameLength = strlen(textureFilename);
247 char* texturePath = malloc(strlen("assets/") + textureFilenameLength + 1);
248 strcpy(texturePath, "assets/");
249 strncat(texturePath, textureFilename, textureFilenameLength);
251 TgaImage* textureImage = readTga(texturePath);
252 if (textureImage == NULL) {
253 logError("Importing solid from %s: Cannot read texture file %s", path, texturePath);
256 glTexImage2D(GL_TEXTURE_2D,
258 textureImage->imageComponents,
259 textureImage->header.imageWidth,
260 textureImage->header.imageHeight,
262 textureImage->imageFormat,
264 textureImage->bytes);
265 free(textureImage->bytes);
270 solid->materials[matIndex] = material;
272 glBindTexture(GL_TEXTURE_2D, 0);
274 aiReleaseImport(scene);
278 static const struct aiScene* importScene(const char* path) {
279 const struct aiScene* scene = aiImportFile(path, aiProcess_JoinIdenticalVertices
280 | aiProcess_PreTransformVertices
281 | aiProcess_ValidateDataStructure);
282 if (scene != NULL && scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE) {
283 logError("Incomplete scene imported from %s", path);
284 aiReleaseImport(scene);
290 static Vector triangleNormal(Vector v1, Vector v2, Vector v3) {
291 return normalized(crossProduct(subtractVectors(v2, v1), subtractVectors(v3, v1)));
294 static Vector convertAiVector3D(struct aiVector3D vect) {
295 return (Vector) { .x = vect.x,
302 * The following function will not work properly with texture
303 * file names (excluding directory part) beginning with '.'
305 static const char* replaceFileExtension(const struct aiString path, const char* ext) {
306 size_t lengthToCopy = path.length;
308 char* lastDotSubstr = strrchr(path.data, '.');
309 if (lastDotSubstr != NULL) {
310 if (strpbrk(lastDotSubstr, "\\/") == NULL) {
311 lengthToCopy = lastDotSubstr - path.data;
315 size_t extLength = strlen(ext) + 1;
316 char* newPath = malloc(lengthToCopy + extLength);
317 strncpy(newPath, path.data, lengthToCopy);
318 strncpy(newPath + lengthToCopy, ext, extLength);