载入中...
搜索中...
未找到
GraphicsMeshes.cpp
浏览该文件的文档.
3#include "graphics/Batcher.h"
6#include "graphics/GBuffer.h"
7#include "graphics/Light.h"
8#include "graphics/Mesh.h"
13#include "graphics/Shader.h"
14#include "graphics/Shadow.h"
15#include "graphics/Texture.h"
25
26#include "common/Exception.h"
27#include "common/Resource.h"
28#include "common/config.h"
29#include "filesystem/FileData.h"
31#include "image/Image.h"
32#include "image/ImageData.h"
33
34// Header-only Assimp mesh types for newMeshFromAssimp. The Assimp library is
35// not linked on Emscripten; only these POD headers are required here.
36#include <assimp/matrix3x3.h>
37#include <assimp/matrix4x4.h>
38#include <assimp/mesh.h>
39#include <assimp/vector3.h>
40
41#include <algorithm>
42#include <bit>
43#include <cmath>
44#include <cstdio>
45#include <cstring>
46#include <fstream>
47#include <limits>
48#include <map>
49#include <memory>
50#include <mutex>
51#include <vector>
52
53#include <glm/gtc/constants.hpp>
54
55namespace eve::graphics::webgpu {
56using namespace detail;
57
58Mesh* Graphics::newMeshFromArrays(const float* posXYZ, const float* nrmXYZ, const float* uvST, int vertexCount,
59 const uint32_t* indices, int indexCount) {
60 return newMeshFromArraysColored(posXYZ, nrmXYZ, uvST, nullptr, vertexCount, indices, indexCount);
61}
62
63Mesh* Graphics::newMeshFromArraysColored(const float* posXYZ, const float* nrmXYZ, const float* uvST,
64 const float* colorRGBA, int vertexCount, const uint32_t* indices,
65 int indexCount) {
66 if (vertexCount <= 0 || !posXYZ) throw Exception("newMeshFromArrays: invalid vertex data");
67 if (indexCount < 0 || (indexCount > 0 && (!indices || indexCount % 3 != 0)))
68 throw Exception("newMeshFromArrays: invalid index data");
69 for (int i = 0; i < indexCount; ++i) {
70 if (indices[i] >= uint32_t(vertexCount)) throw Exception("newMeshFromArrays: index out of range");
71 }
72
73 std::vector<MeshVertex> verts(static_cast<size_t>(vertexCount));
74 for (int i = 0; i < vertexCount; ++i) {
75 auto& v = verts[static_cast<size_t>(i)];
76 v.pos = {posXYZ[i * 3 + 0], posXYZ[i * 3 + 1], posXYZ[i * 3 + 2]};
77 if (nrmXYZ) {
78 v.normal = {nrmXYZ[i * 3 + 0], nrmXYZ[i * 3 + 1], nrmXYZ[i * 3 + 2]};
79 } else {
80 v.normal = {0.f, 0.f, 1.f};
81 }
82 if (uvST) {
83 v.uv = {uvST[i * 2 + 0], uvST[i * 2 + 1]};
84 } else {
85 v.uv = {0.f, 0.f};
86 }
87 if (colorRGBA) v.color = {colorRGBA[i * 4], colorRGBA[i * 4 + 1], colorRGBA[i * 4 + 2], colorRGBA[i * 4 + 3]};
88 }
89
90 auto gpu = std::make_unique<GpuMesh>();
91 gpu->vertexCount = uint32_t(vertexCount);
92 gpu->indexCount = indexCount > 0 ? uint32_t(indexCount) : 0;
93 gpu->vertexStride = sizeof(MeshVertex);
94 gpu->cpuVertices = verts;
95
96 WGPUBufferDescriptor vbd{};
97 vbd.label = sv("eve_mesh_vb");
98 vbd.size = verts.size() * sizeof(MeshVertex);
99 vbd.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Vertex | WGPUBufferUsage_Storage;
100 vbd.mappedAtCreation = false;
101 gpu->vertexBuffer = device.CreateBuffer(reinterpret_cast<const wgpu::BufferDescriptor*>(&vbd));
102 queue.WriteBuffer(gpu->vertexBuffer, 0, verts.data(), vbd.size);
103 gpu->vertexCapacity = vbd.size;
104
105 if (indexCount > 0) {
106 // 16-bit index format halves index memory for meshes with <= 65535 verts.
107 if (vertexCount <= 65535) {
108 std::vector<uint16_t> idx16;
109 idx16.reserve(indexCount);
110 for (int i = 0; i < indexCount; ++i) idx16.push_back(uint16_t(indices[i]));
111 WGPUBufferDescriptor ibd{};
112 ibd.label = sv("eve_mesh_ib");
113 if (idx16.size() % 2 != 0) idx16.push_back(0); // WriteBuffer size must align to 4.
114 ibd.size = uint64_t(idx16.size()) * sizeof(uint16_t);
115 ibd.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Index | WGPUBufferUsage_Storage;
116 ibd.mappedAtCreation = false;
117 gpu->indexBuffer = device.CreateBuffer(reinterpret_cast<const wgpu::BufferDescriptor*>(&ibd));
118 queue.WriteBuffer(gpu->indexBuffer, 0, idx16.data(), ibd.size);
119 gpu->indexFormat = wgpu::IndexFormat::Uint16;
120 gpu->indexCapacity = ibd.size;
121 } else {
122 WGPUBufferDescriptor ibd{};
123 ibd.label = sv("eve_mesh_ib");
124 ibd.size = uint64_t(indexCount) * sizeof(uint32_t);
125 ibd.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Index | WGPUBufferUsage_Storage;
126 ibd.mappedAtCreation = false;
127 gpu->indexBuffer = device.CreateBuffer(reinterpret_cast<const wgpu::BufferDescriptor*>(&ibd));
128 queue.WriteBuffer(gpu->indexBuffer, 0, indices, ibd.size);
129 gpu->indexFormat = wgpu::IndexFormat::Uint32;
130 gpu->indexCapacity = ibd.size;
131 }
132 }
133
134 auto* mesh = new Mesh();
135 mesh->indexCount = indexCount;
136 mesh->gpuVertexCount = vertexCount;
137 mesh->gpuHandle = gpu.get();
138 mesh->computeBounds(posXYZ, vertexCount);
139 ownedGpuMeshes.push_back(std::move(gpu));
140 ownedMeshes.push_back(std::unique_ptr<Mesh>(mesh));
141 return mesh;
142}
143
145 if (!mesh || !mesh->gpuHandle)
147 eve::DiagnosticCode::NotFound, "mesh has no backend upload", {}, {}, "graphics.mesh.describe"));
148 const auto* gpu = static_cast<const GpuMesh*>(mesh->gpuHandle);
149 const auto owned =
150 std::find_if(ownedGpuMeshes.begin(), ownedGpuMeshes.end(),
151 [gpu](const std::unique_ptr<GpuMesh>& candidate) { return candidate.get() == gpu; });
152 if (owned == ownedGpuMeshes.end())
154 eve::DiagnosticCode::NotFound, "mesh is not owned by this graphics", {}, {}, "graphics.mesh.describe"));
156 gpu->vertexCount, gpu->indexCount, gpu->vertexStride, gpu->indexFormat == wgpu::IndexFormat::Uint16 ? 2u : 4u});
157}
158
159Mesh* Graphics::newMeshFromAssimp(const ::aiMesh& mesh) { return newMeshFromAssimp(mesh, glm::mat4(1.f)); }
160
161Mesh* Graphics::newMeshFromAssimp(const ::aiMesh& mesh, const glm::mat4& worldTransform) {
162 // glm is column-major; Assimp aiMatrix4x4 is row-major.
163 const aiMatrix4x4 world(worldTransform[0][0], worldTransform[1][0], worldTransform[2][0], worldTransform[3][0],
164 worldTransform[0][1], worldTransform[1][1], worldTransform[2][1], worldTransform[3][1],
165 worldTransform[0][2], worldTransform[1][2], worldTransform[2][2], worldTransform[3][2],
166 worldTransform[0][3], worldTransform[1][3], worldTransform[2][3], worldTransform[3][3]);
167
168 std::vector<float> pos, nrm, uv;
169 std::vector<uint32_t> idx;
170 pos.reserve(mesh.mNumVertices * 3);
171 nrm.reserve(mesh.mNumVertices * 3);
172 uv.reserve(mesh.mNumVertices * 2);
173 idx.reserve(mesh.mNumFaces * 3);
174
175 for (unsigned i = 0; i < mesh.mNumVertices; ++i) {
176 aiVector3D p = world * mesh.mVertices[i];
177 pos.push_back(p.x);
178 pos.push_back(p.y);
179 pos.push_back(p.z);
180 if (mesh.mNormals) {
181 aiMatrix3x3 rot(world);
182 aiVector3D n = rot * mesh.mNormals[i];
183 n.Normalize();
184 nrm.push_back(n.x);
185 nrm.push_back(n.y);
186 nrm.push_back(n.z);
187 } else {
188 nrm.push_back(0.f);
189 nrm.push_back(0.f);
190 nrm.push_back(1.f);
191 }
192 if (mesh.mTextureCoords[0]) {
193 uv.push_back(mesh.mTextureCoords[0][i].x);
194 uv.push_back(mesh.mTextureCoords[0][i].y);
195 } else {
196 uv.push_back(0.f);
197 uv.push_back(0.f);
198 }
199 }
200 for (unsigned f = 0; f < mesh.mNumFaces; ++f) {
201 for (unsigned v = 0; v < mesh.mFaces[f].mNumIndices; ++v) idx.push_back(mesh.mFaces[f].mIndices[v]);
202 }
203 Mesh* m = newMeshFromArrays(pos.data(), nrm.data(), uv.data(), int(mesh.mNumVertices), idx.data(), int(idx.size()));
204 if (m) m->captureImportedAttributes(mesh);
205 if (m && mesh.mNumAnimMeshes > 0) {
206 m->initMorphBase(int(mesh.mNumVertices), pos.data(), nrm.data(), uv.data());
207 for (unsigned a = 0; a < mesh.mNumAnimMeshes; ++a) {
208 const aiAnimMesh* am = mesh.mAnimMeshes[a];
209 std::vector<float> absPos(am->mNumVertices * 3);
210 for (unsigned i = 0; i < am->mNumVertices; ++i) {
211 absPos[i * 3 + 0] = am->mVertices[i].x;
212 absPos[i * 3 + 1] = am->mVertices[i].y;
213 absPos[i * 3 + 2] = am->mVertices[i].z;
214 }
215 std::string name = am->mName.C_Str();
216 if (name.empty()) name = "morph" + std::to_string(a);
217 m->addMorphTargetAbsolute(name, absPos.data());
218 if (am->mNormals) {
219 std::vector<float> deltas(am->mNumVertices * 3u);
220 for (unsigned i = 0; i < am->mNumVertices; ++i) {
221 deltas[i * 3] = am->mNormals[i].x - nrm[i * 3];
222 deltas[i * 3 + 1] = am->mNormals[i].y - nrm[i * 3 + 1];
223 deltas[i * 3 + 2] = am->mNormals[i].z - nrm[i * 3 + 2];
224 }
225 auto normals = m->setMorphNormalDeltas(name, deltas);
226 if (!normals.ok()) throw Exception("Invalid imported morph normals: %s", name.c_str());
227 }
228 }
229 }
230 return m;
231}
232
234 if (!mesh || !mesh->hasMorphData() || !mesh->isMorphDirty()) return false;
235 auto* gpu = static_cast<GpuMesh*>(mesh->gpuHandle);
236 if (!gpu || !gpu->vertexBuffer) return false;
237 std::vector<float> pos, nrm;
238 mesh->computeMorphedPositions(pos, nrm);
239 if (pos.empty()) return false;
240 mesh->computeBounds(pos.data(), mesh->getVertexCount());
241 auto& verts = gpu->cpuVertices;
242 if (verts.size() != static_cast<size_t>(mesh->getVertexCount())) return false;
243 const auto& uvs = mesh->baseUv();
244 for (int i = 0; i < mesh->getVertexCount(); ++i) {
245 auto& v = verts[static_cast<size_t>(i)];
246 v.pos = {pos[i * 3 + 0], pos[i * 3 + 1], pos[i * 3 + 2]};
247 if (nrm.size() >= size_t((i + 1) * 3)) {
248 v.normal = {nrm[i * 3 + 0], nrm[i * 3 + 1], nrm[i * 3 + 2]};
249 } else {
250 v.normal = {0.f, 0.f, 1.f};
251 }
252 if (uvs.size() >= size_t((i + 1) * 2)) {
253 v.uv = {uvs[i * 2 + 0], uvs[i * 2 + 1]};
254 } else {
255 v.uv = {0.f, 0.f};
256 }
257 }
258 queue.WriteBuffer(gpu->vertexBuffer, 0, verts.data(), verts.size() * sizeof(MeshVertex));
259 mesh->markMorphClean();
260 return true;
261}
262
263
264bool Graphics::setMeshSkinningData(Mesh* mesh, const uint16_t* joints4, const float* weights4, int vertexCount) {
265 if (!mesh || !mesh->gpuHandle || !joints4 || !weights4) return false;
266 auto* gpu = static_cast<GpuMesh*>(mesh->gpuHandle);
267 if (vertexCount <= 0 || gpu->cpuVertices.size() != static_cast<size_t>(vertexCount)) return false;
268 for (int i = 0; i < vertexCount; ++i) {
269 const size_t base = static_cast<size_t>(i) * 4u;
270 auto& v = gpu->cpuVertices[static_cast<size_t>(i)];
271 v.joints = glm::u16vec4(joints4[base], joints4[base + 1], joints4[base + 2], joints4[base + 3]);
272 v.weights = glm::vec4(weights4[base], weights4[base + 1], weights4[base + 2], weights4[base + 3]);
273 }
274 queue.WriteBuffer(gpu->vertexBuffer, 0, gpu->cpuVertices.data(), gpu->cpuVertices.size() * sizeof(MeshVertex));
275 mesh->markGpuSkinned(true);
276 return true;
277}
278
280 if (!mesh || !mesh->gpuHandle) return false;
281
282 auto* gpu = static_cast<GpuMesh*>(mesh->gpuHandle);
283 auto gpuIt = std::find_if(ownedGpuMeshes.begin(), ownedGpuMeshes.end(),
284 [&](const std::unique_ptr<GpuMesh>& g) { return g.get() == gpu; });
285 if (gpuIt == ownedGpuMeshes.end()) return false;
286
287 auto meshIt = std::find_if(ownedMeshes.begin(), ownedMeshes.end(),
288 [&](const std::unique_ptr<Mesh>& m) { return m.get() == mesh; });
289 if (meshIt == ownedMeshes.end()) return false;
290
291 mesh->gpuHandle = nullptr;
292 ownedGpuMeshes.erase(gpuIt);
293 // Transfer the CPU facade to the caller instead of destroying it.
294 (void)meshIt->release();
295 ownedMeshes.erase(meshIt);
296 return true;
297}
298
299Mesh* Graphics::newMeshSphere(int slices, int stacks) {
300 std::vector<float> pos, nrm, uv;
301 std::vector<uint32_t> idx;
302 for (int y = 0; y <= stacks; ++y) {
303 for (int x = 0; x <= slices; ++x) {
304 float u = float(x) / float(slices);
305 float v = float(y) / float(stacks);
306 float theta = u * 2.f * glm::pi<float>();
307 float phi = v * glm::pi<float>();
308 float sx = std::sin(phi) * std::cos(theta);
309 float sy = std::cos(phi);
310 float sz = std::sin(phi) * std::sin(theta);
311 pos.push_back(sx);
312 pos.push_back(sy);
313 pos.push_back(sz);
314 nrm.push_back(sx);
315 nrm.push_back(sy);
316 nrm.push_back(sz);
317 uv.push_back(u);
318 uv.push_back(v);
319 }
320 }
321 for (int y = 0; y < stacks; ++y) {
322 for (int x = 0; x < slices; ++x) {
323 int a = y * (slices + 1) + x;
324 int b = a + slices + 1;
325 idx.push_back(a);
326 idx.push_back(a + 1);
327 idx.push_back(b);
328 idx.push_back(b);
329 idx.push_back(a + 1);
330 idx.push_back(b + 1);
331 }
332 }
333 return newMeshFromArrays(pos.data(), nrm.data(), uv.data(), int(pos.size() / 3), idx.data(), int(idx.size()));
334}
335
336Mesh* Graphics::newMeshCylinder(int slices, int stacks, bool caps) {
337 std::vector<float> pos, nrm, uv;
338 std::vector<uint32_t> idx;
339 for (int y = 0; y <= stacks; ++y) {
340 for (int x = 0; x <= slices; ++x) {
341 float u = float(x) / float(slices);
342 float v = float(y) / float(stacks);
343 float theta = u * 2.f * glm::pi<float>();
344 pos.push_back(std::cos(theta));
345 pos.push_back(v * 2.f - 1.f);
346 pos.push_back(std::sin(theta));
347 nrm.push_back(std::cos(theta));
348 nrm.push_back(0.f);
349 nrm.push_back(std::sin(theta));
350 uv.push_back(u);
351 uv.push_back(v);
352 }
353 }
354 for (int y = 0; y < stacks; ++y) {
355 for (int x = 0; x < slices; ++x) {
356 int a = y * (slices + 1) + x;
357 int b = a + slices + 1;
358 idx.push_back(a);
359 idx.push_back(b);
360 idx.push_back(a + 1);
361 idx.push_back(b);
362 idx.push_back(b + 1);
363 idx.push_back(a + 1);
364 }
365 }
366 if (caps) {
367 int base = int(pos.size() / 3);
368 pos.push_back(0.f);
369 pos.push_back(-1.f);
370 pos.push_back(0.f);
371 nrm.push_back(0.f);
372 nrm.push_back(-1.f);
373 nrm.push_back(0.f);
374 uv.push_back(0.5f);
375 uv.push_back(0.5f);
376 for (int x = 0; x < slices; ++x) {
377 float theta0 = float(x) / float(slices) * 2.f * glm::pi<float>();
378 float theta1 = float(x + 1) / float(slices) * 2.f * glm::pi<float>();
379 int i0 = int(pos.size() / 3);
380 pos.push_back(std::cos(theta0));
381 pos.push_back(-1.f);
382 pos.push_back(std::sin(theta0));
383 nrm.push_back(0.f);
384 nrm.push_back(-1.f);
385 nrm.push_back(0.f);
386 uv.push_back(0.5f + 0.5f * std::cos(theta0));
387 uv.push_back(0.5f + 0.5f * std::sin(theta0));
388 int i1 = int(pos.size() / 3);
389 pos.push_back(std::cos(theta1));
390 pos.push_back(-1.f);
391 pos.push_back(std::sin(theta1));
392 nrm.push_back(0.f);
393 nrm.push_back(-1.f);
394 nrm.push_back(0.f);
395 uv.push_back(0.5f + 0.5f * std::cos(theta1));
396 uv.push_back(0.5f + 0.5f * std::sin(theta1));
397 idx.push_back(base);
398 idx.push_back(i0);
399 idx.push_back(i1);
400 }
401 base = int(pos.size() / 3);
402 pos.push_back(0.f);
403 pos.push_back(1.f);
404 pos.push_back(0.f);
405 nrm.push_back(0.f);
406 nrm.push_back(1.f);
407 nrm.push_back(0.f);
408 uv.push_back(0.5f);
409 uv.push_back(0.5f);
410 for (int x = 0; x < slices; ++x) {
411 float theta0 = float(x) / float(slices) * 2.f * glm::pi<float>();
412 float theta1 = float(x + 1) / float(slices) * 2.f * glm::pi<float>();
413 int i0 = int(pos.size() / 3);
414 pos.push_back(std::cos(theta0));
415 pos.push_back(1.f);
416 pos.push_back(std::sin(theta0));
417 nrm.push_back(0.f);
418 nrm.push_back(1.f);
419 nrm.push_back(0.f);
420 uv.push_back(0.5f + 0.5f * std::cos(theta0));
421 uv.push_back(0.5f + 0.5f * std::sin(theta0));
422 int i1 = int(pos.size() / 3);
423 pos.push_back(std::cos(theta1));
424 pos.push_back(1.f);
425 pos.push_back(std::sin(theta1));
426 nrm.push_back(0.f);
427 nrm.push_back(1.f);
428 nrm.push_back(0.f);
429 uv.push_back(0.5f + 0.5f * std::cos(theta1));
430 uv.push_back(0.5f + 0.5f * std::sin(theta1));
431 idx.push_back(base);
432 idx.push_back(i1);
433 idx.push_back(i0);
434 }
435 }
436 return newMeshFromArrays(pos.data(), nrm.data(), uv.data(), int(pos.size() / 3), idx.data(), int(idx.size()));
437}
438
439} // namespace eve::graphics::webgpu
double y
double m[16]
double x
ActiveSource owned
std::vector< std::uint32_t > verts
Definition Builder.cpp:27
float uv
glm::vec4 p[6]
std::string name
Definition ECS.cpp:154
std::uint32_t vertexCount
std::uint32_t indexCount
tensor::Graph g
Definition GpuGraph.cpp:7
uint32_t i1
Definition Grass.cpp:61
uint32_t i0
Definition Grass.cpp:61
float u
Definition Grass.cpp:233
glm::vec3 n
Definition Grass.cpp:63
std::vector< std::uint32_t > indices
std::vector< float > normals
float v
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
OceanMeshSettings mesh
std::shared_ptr< OceanGpuSpectrum > gpu
int idx
float f
int detail
Local-probe upload record kept off the high-fanout IGraphics3D header.
int caps
Definition TreeMesh.cpp:164
std::vector< double > phi
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
EVENGINE_API_FOUNDATION public API.
Definition Exception.h:13
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
GPU mesh handle (+ optional CPU morph targets).
Definition Mesh.h:26
Mesh * newMeshSphere(int slices=32, int stacks=16) override
Creates a mesh sphere. @ownership Caller deletes unless documented otherwise.
eve::Result< eve::graphics::MeshBackendDescriptor > describeMesh(Mesh *mesh) const override
Return layout facts from the owned WebGPU mesh upload.
Mesh * newMeshFromArraysColored(const float *posXYZ, const float *nrmXYZ, const float *uvST, const float *colorRGBA, int vertexCount, const uint32_t *indices, int indexCount) override
Create a mesh with a packed linear RGBA vertex-color stream.
Mesh * newMeshFromAssimp(const ::aiMesh &mesh) override
Creates a mesh from assimp. @ownership Caller deletes unless documented otherwise.
bool bakeMeshMorph(Mesh *mesh) override
If mesh morph weights are dirty, bake blended positions and upload to the GPU VBO....
Mesh * newMeshCylinder(int slices=32, int stacks=1, bool caps=true) override
Creates a mesh cylinder. @ownership Caller deletes unless documented otherwise.
Mesh * newMeshFromArrays(const float *posXYZ, const float *nrmXYZ, const float *uvST, int vertexCount, const uint32_t *indices, int indexCount) override
Creates a mesh from arrays. @ownership Caller deletes unless documented otherwise.
bool setMeshSkinningData(Mesh *mesh, const uint16_t *joints4, const float *weights4, int vertexCount) override
Sets the mesh skinning data.
bool releaseMesh(Mesh *mesh) override
Release mesh.
WGPUStringView sv(const char *s)
Build a WGPUStringView from a C string (null-safe, length auto-computed).
Definition wgpu_types.h:20
Backend-owned layout facts for a mesh uploaded through Graphics.
Definition Graphics.h:92
Vertex/index buffers for one mesh.
Definition Graphics.h:159
std::vector< MeshVertex > cpuVertices
Definition Graphics.h:168
MeshVertex public API.
Definition Graphics.h:88