NoJobEngine 2.0.7
Loading...
Searching...
No Matches
Mesh.cpp
Go to the documentation of this file.
5#include <fstream>
6#include <sstream>
7#include <string>
8#include <stdexcept>
9#include <glm/geometric.hpp>
10#include <assimp/Importer.hpp>
11#include <assimp/scene.h>
12#include <assimp/postprocess.h>
13#include <unordered_map>
14
15namespace NoJob
16{
17 Mesh::Mesh(const std::vector<MeshVertex>& vertices,
18 const std::vector<std::uint32_t>& indices)
19 {
20 std::vector<float> data;
21 data.reserve(vertices.size() * 16);
22
23 for (const MeshVertex& vertex : vertices)
24 {
25 data.insert(data.end(),
26 {
27 vertex.Position.x, vertex.Position.y, vertex.Position.z,
28 vertex.Normal.x, vertex.Normal.y, vertex.Normal.z,
29 vertex.TexCoord.x, vertex.TexCoord.y,
30 vertex.BoneIDs.x, vertex.BoneIDs.y, vertex.BoneIDs.z, vertex.BoneIDs.w,
31 vertex.BoneWeights.x, vertex.BoneWeights.y, vertex.BoneWeights.z, vertex.BoneWeights.w
32 });
33 }
34
35 m_VertexBuffer = VertexBuffer::Create(
36 data.data(),
37 static_cast<std::uint32_t>(data.size() * sizeof(float)));
38
39 m_IndexBuffer = IndexBuffer::Create(
40 indices.data(),
41 static_cast<std::uint32_t>(indices.size()));
42
43 m_VertexArray = VertexArray::Create();
44 m_VertexArray->SetVertexBuffer(
45 m_VertexBuffer,
47 { ShaderDataType::Float3, "a_Position" },
48 { ShaderDataType::Float3, "a_Normal" },
49 { ShaderDataType::Float2, "a_TexCoord" },
50 { ShaderDataType::Float4, "a_BoneIDs" },
51 { ShaderDataType::Float4, "a_BoneWeights" }
52 });
53 m_VertexArray->SetIndexBuffer(m_IndexBuffer);
54 }
55
56
57 std::shared_ptr<Mesh> Mesh::LoadOBJ(const std::filesystem::path& path)
58 {
59 std::ifstream input(path); if(!input) throw std::runtime_error("Could not open OBJ: "+path.string());
60 std::vector<glm::vec3> ps,ns; std::vector<glm::vec2> uvs; std::vector<MeshVertex> vs; std::vector<std::uint32_t> is;
61 struct C{int p=0,t=0,n=0;};
62 auto parse=[](const std::string& q){C c{};std::stringstream s(q);std::string x;if(std::getline(s,x,'/')&&!x.empty())c.p=std::stoi(x);if(std::getline(s,x,'/')&&!x.empty())c.t=std::stoi(x);if(std::getline(s,x,'/')&&!x.empty())c.n=std::stoi(x);return c;};
63 auto idx=[](int i,std::size_t n){return i>0?std::size_t(i-1):(i<0?std::size_t((long long)n+i):n);};
64 std::string line;while(std::getline(input,line)){if(line.empty()||line[0]=='#')continue;std::istringstream s(line);std::string k;s>>k;
65 if(k=="v"){glm::vec3 v{};s>>v.x>>v.y>>v.z;ps.push_back(v);}else if(k=="vn"){glm::vec3 n{};s>>n.x>>n.y>>n.z;ns.push_back(n);}else if(k=="vt"){glm::vec2 u{};s>>u.x>>u.y;u.y=1-u.y;uvs.push_back(u);}
66 else if(k=="f"){std::vector<C> f;std::string q;while(s>>q)f.push_back(parse(q));for(std::size_t a=1;a+1<f.size();++a){C cs[3]={f[0],f[a],f[a+1]};MeshVertex v[3]{};bool hn=true;
67 for(int j=0;j<3;++j){auto pi=idx(cs[j].p,ps.size());if(pi>=ps.size())throw std::runtime_error("Bad OBJ index");v[j].Position=ps[pi];if(cs[j].t){auto ti=idx(cs[j].t,uvs.size());if(ti<uvs.size())v[j].TexCoord=uvs[ti];}if(cs[j].n){auto ni=idx(cs[j].n,ns.size());if(ni<ns.size())v[j].Normal=ns[ni];else hn=false;}else hn=false;}
68 if(!hn){auto n=glm::cross(v[1].Position-v[0].Position,v[2].Position-v[0].Position);n=glm::dot(n,n)>.000001f?glm::normalize(n):glm::vec3(0,1,0);v[0].Normal=v[1].Normal=v[2].Normal=n;}for(auto& x:v){is.push_back((std::uint32_t)vs.size());vs.push_back(x);}}}}
69 if(vs.empty())throw std::runtime_error("OBJ has no triangles");return std::make_shared<Mesh>(vs,is);
70 }
71
72
73 std::shared_ptr<Mesh> Mesh::LoadModel(const std::filesystem::path& path)
74 {
75 Assimp::Importer importer;
76 const aiScene* scene = importer.ReadFile(
77 path.string(),
78 aiProcess_Triangulate | aiProcess_JoinIdenticalVertices |
79 aiProcess_GenSmoothNormals | aiProcess_ImproveCacheLocality |
80 aiProcess_SortByPType | aiProcess_LimitBoneWeights);
81 if (!scene || !scene->HasMeshes())
82 throw std::runtime_error("Assimp import failed: " + std::string(importer.GetErrorString()));
83
84 std::vector<MeshVertex> vertices;
85 std::vector<std::uint32_t> indices;
86 std::vector<Submesh> submeshes;
87 std::unordered_map<std::string, std::uint32_t> boneIndices;
88 bool hasSkinning = false;
89
90 // Match AnimationAsset's stable bone-index order: first appearance while
91 // walking Assimp meshes/bones.
92 for (unsigned mi=0; mi<scene->mNumMeshes; ++mi)
93 {
94 const aiMesh* sourceMesh = scene->mMeshes[mi];
95 for (unsigned bi=0; bi<sourceMesh->mNumBones; ++bi)
96 {
97 const std::string name = sourceMesh->mBones[bi]->mName.C_Str();
98 if (!boneIndices.contains(name))
99 boneIndices[name] = static_cast<std::uint32_t>(boneIndices.size());
100 }
101 }
102
103 for (unsigned mi=0; mi<scene->mNumMeshes; ++mi)
104 {
105 const aiMesh* s=scene->mMeshes[mi];
106 const std::uint32_t base=static_cast<std::uint32_t>(vertices.size());
107 const std::uint32_t first=static_cast<std::uint32_t>(indices.size());
108 for(unsigned i=0;i<s->mNumVertices;++i)
109 {
110 MeshVertex v{};
111 v.Position={s->mVertices[i].x,s->mVertices[i].y,s->mVertices[i].z};
112 if(s->HasNormals()) v.Normal={s->mNormals[i].x,s->mNormals[i].y,s->mNormals[i].z};
113 if(s->HasTextureCoords(0)) v.TexCoord={s->mTextureCoords[0][i].x,s->mTextureCoords[0][i].y};
114 vertices.push_back(v);
115 }
116
117 for (unsigned bi=0; bi<s->mNumBones; ++bi)
118 {
119 const aiBone* bone = s->mBones[bi];
120 const auto found = boneIndices.find(bone->mName.C_Str());
121 if (found == boneIndices.end()) continue;
122 const float boneID = static_cast<float>(found->second);
123 for (unsigned wi=0; wi<bone->mNumWeights; ++wi)
124 {
125 const aiVertexWeight& weight = bone->mWeights[wi];
126 if (weight.mVertexId >= s->mNumVertices || weight.mWeight <= 0.0f) continue;
127 MeshVertex& vertex = vertices[base + weight.mVertexId];
128 for (int slot=0; slot<4; ++slot)
129 {
130 if (vertex.BoneWeights[slot] == 0.0f)
131 {
132 vertex.BoneIDs[slot] = boneID;
133 vertex.BoneWeights[slot] = weight.mWeight;
134 hasSkinning = true;
135 break;
136 }
137 }
138 }
139 }
140
141 // Normalize weights after Assimp's LimitBoneWeights pass.
142 for (unsigned vi=0; vi<s->mNumVertices; ++vi)
143 {
144 auto& w = vertices[base + vi].BoneWeights;
145 const float sum = w.x + w.y + w.z + w.w;
146 if (sum > 0.000001f) w /= sum;
147 }
148
149 for(unsigned f=0;f<s->mNumFaces;++f)
150 {
151 const aiFace& face=s->mFaces[f];
152 if(face.mNumIndices!=3) continue;
153 indices.push_back(base+face.mIndices[0]);
154 indices.push_back(base+face.mIndices[1]);
155 indices.push_back(base+face.mIndices[2]);
156 }
157 const auto count=static_cast<std::uint32_t>(indices.size())-first;
158 if(count) submeshes.push_back({first,count,s->mMaterialIndex});
159 }
160 if(vertices.empty()||indices.empty()) throw std::runtime_error("Imported model has no triangles.");
161 auto mesh=std::make_shared<Mesh>(vertices,indices);
162 mesh->SetSubmeshes(std::move(submeshes));
163 mesh->SetHasSkinning(hasSkinning);
164 return mesh;
165 }
166
167 std::shared_ptr<Mesh> Mesh::CreateCube()
168 {
169 constexpr float h = 0.5f;
170 const std::vector<MeshVertex> vertices =
171 {
172 // Front
173 {{-h,-h, h},{ 0, 0, 1},{0,0}}, {{ h,-h, h},{ 0, 0, 1},{1,0}},
174 {{ h, h, h},{ 0, 0, 1},{1,1}}, {{-h, h, h},{ 0, 0, 1},{0,1}},
175 // Back
176 {{ h,-h,-h},{ 0, 0,-1},{0,0}}, {{-h,-h,-h},{ 0, 0,-1},{1,0}},
177 {{-h, h,-h},{ 0, 0,-1},{1,1}}, {{ h, h,-h},{ 0, 0,-1},{0,1}},
178 // Left
179 {{-h,-h,-h},{-1, 0, 0},{0,0}}, {{-h,-h, h},{-1, 0, 0},{1,0}},
180 {{-h, h, h},{-1, 0, 0},{1,1}}, {{-h, h,-h},{-1, 0, 0},{0,1}},
181 // Right
182 {{ h,-h, h},{ 1, 0, 0},{0,0}}, {{ h,-h,-h},{ 1, 0, 0},{1,0}},
183 {{ h, h,-h},{ 1, 0, 0},{1,1}}, {{ h, h, h},{ 1, 0, 0},{0,1}},
184 // Top
185 {{-h, h, h},{ 0, 1, 0},{0,0}}, {{ h, h, h},{ 0, 1, 0},{1,0}},
186 {{ h, h,-h},{ 0, 1, 0},{1,1}}, {{-h, h,-h},{ 0, 1, 0},{0,1}},
187 // Bottom
188 {{-h,-h,-h},{ 0,-1, 0},{0,0}}, {{ h,-h,-h},{ 0,-1, 0},{1,0}},
189 {{ h,-h, h},{ 0,-1, 0},{1,1}}, {{-h,-h, h},{ 0,-1, 0},{0,1}}
190 };
191
192 std::vector<std::uint32_t> indices;
193 indices.reserve(36);
194 for (std::uint32_t face = 0; face < 6; ++face)
195 {
196 const std::uint32_t b = face * 4;
197 indices.insert(indices.end(), { b, b+1, b+2, b+2, b+3, b });
198 }
199
200 return std::make_shared<Mesh>(vertices, indices);
201 }
202}
Buffer declarations for the Rendering subsystem.
BufferLayout declarations for the Rendering subsystem.
Mesh declarations for the Rendering subsystem.
VertexArray declarations for the Rendering subsystem.
static std::shared_ptr< IndexBuffer > Create(const std::uint32_t *indices, std::uint32_t count)
Definition Buffer.cpp:20
static std::shared_ptr< Mesh > CreateCube()
Definition Mesh.cpp:167
static std::shared_ptr< Mesh > LoadOBJ(const std::filesystem::path &path)
Definition Mesh.cpp:57
Mesh(const std::vector< MeshVertex > &vertices, const std::vector< std::uint32_t > &indices)
Definition Mesh.cpp:17
static std::shared_ptr< Mesh > LoadModel(const std::filesystem::path &path)
Definition Mesh.cpp:73
static std::shared_ptr< VertexArray > Create()
static std::shared_ptr< VertexBuffer > Create(const float *vertices, std::uint32_t size)
Definition Buffer.cpp:8
glm::vec3 Normal
Definition Mesh.h:22
glm::vec2 TexCoord
Definition Mesh.h:23
glm::vec4 BoneIDs
Definition Mesh.h:26
glm::vec3 Position
Definition Mesh.h:21
glm::vec4 BoneWeights
Definition Mesh.h:27