TerraForge3D  2.3.1
3D Terrain And Landscape Generator
ModelImporter.cpp
1#include "ModelImporter.h"
2
3#include <string>
4
5#include <Utils.h>
6
7#include <assimp/Importer.hpp> // C++ importer interface
8#include <assimp/scene.h> // Output data structure
9#include <assimp/postprocess.h> // Post processing flags
10
11
12Mesh *LoadMesh(aiMesh *paiMesh)
13{
14 Mesh mesh;
15 const aiVector3D Zero3D(0.0f, 0.0f, 0.0f);
16 Vert *verts = new Vert[paiMesh->mNumVertices];
17 mesh.vertexCount = paiMesh->mNumVertices;
18
19 for (unsigned int i = 0; i < paiMesh->mNumVertices; i++)
20 {
21 const aiVector3D *pPos = &(paiMesh->mVertices[i]);
22 const aiVector3D *pNormal = &(paiMesh->mNormals[i]);
23 const aiVector3D *pTexCoord = paiMesh->HasTextureCoords(0) ? &(paiMesh->mTextureCoords[0][i]) : &Zero3D;
24 Vert tmp;
25 tmp.position = glm::vec4(0.0f);
26 tmp.position.x = pPos->x;
27 tmp.position.y = pPos->y;
28 tmp.position.z = pPos->z;
29 tmp.texCoord = glm::vec2(1.0f);
30
31 if (pTexCoord)
32 {
33 tmp.texCoord.x = pTexCoord->x;
34 tmp.texCoord.y = pTexCoord->y;
35 }
36
37 tmp.normal = glm::vec4(1.0f);
38
39 if (pNormal)
40 {
41 tmp.normal.x = pNormal->x;
42 tmp.normal.y = pNormal->y;
43 tmp.normal.z = pNormal->z;
44 }
45
46 verts[i] = tmp;
47 }
48
49 mesh.vert = verts;
50 mesh.indexCount = paiMesh->mNumFaces * 3;
51 mesh.indices = new int[mesh.indexCount];
52 int co = 0;
53
54 for (unsigned int i = 0; i < paiMesh->mNumFaces; i++)
55 {
56 const aiFace &Face = paiMesh->mFaces[i];
57 mesh.indices[co++] = Face.mIndices[0];
58 mesh.indices[co++] = Face.mIndices[1];
59 mesh.indices[co++] = Face.mIndices[2];
60 }
61
62 return mesh.Clone();
63}
64
65Model *LoadModel(std::string path)
66{
67 Assimp::Importer importer;
68 // And have it read the given file with some example postprocessing
69 // Usually - if speed is not the most important aspect for you - you'll
70 // probably to request more postprocessing than we do in this example.
71 const aiScene *scene = importer.ReadFile(path,
72 aiProcess_CalcTangentSpace |
73 aiProcess_Triangulate |
74 aiProcess_GenSmoothNormals |
75 aiProcess_JoinIdenticalVertices |
76 aiProcess_GenUVCoords |
77 aiProcess_SortByPType);
78
79 if (nullptr == scene)
80 {
81 Log("Assimp Error : " + std::string(importer.GetErrorString()));
82 return nullptr;
83 }
84
85 aiMesh *paiMesh = scene->mMeshes[0];
86 Model *model = new Model(std::string(paiMesh->mName.C_Str()));
87 model->SetupMeshOnGPU();
88 model->mesh = LoadMesh(paiMesh);
89 return model;
90}
Definition: Mesh.h:21
Definition: Model.h:9
Definition: Mesh.h:13