载入中...
搜索中...
未找到
GraphicsMesh.cpp
浏览该文件的文档.
1// eve-hot-path
2// Vulkan backend implementation — mesh creation and drawing.
3//
4// Re-split from the merged dev single-TU Graphics.cpp (pure move;
5// dev changes preserved). Shared helpers live in GraphicsInternal.h.
6
8#include "graphics/Light.h"
13
14#include <SDL2/SDL.h>
15#include <SDL2/SDL_vulkan.h>
16
17#include <algorithm>
18#include <array>
19#include <cmath>
20#include <cstdio>
21#include <cstdlib>
22#include <cstring>
23#include <functional>
24#include <stdexcept>
25#include <string>
26#include <vector>
27#if !defined(_WIN32)
28#include <unistd.h>
29#endif
30
31#include "common/Exception.h"
33#include "common/config.h"
35#include "image/Image.h"
36#include "image/ImageData.h"
37#include "zeroerr/assert.h"
38
39#include <memory>
40
41
42#include <assimp/mesh.h>
43#include <assimp/matrix3x3.h>
44#include <assimp/matrix4x4.h>
45#include <assimp/vector3.h>
46#include <glm/gtc/matrix_transform.hpp>
47
49
50namespace eve::graphics::vulkan {
51
52// --- Mesh creation and drawing ------------------------------------------------
53
55 ASSERT(initialized);
56 if (!initialized) throw Exception("newMeshFromAssimp: graphics not initialized");
57 if (mesh.mNumVertices == 0 || mesh.mNumFaces == 0)
58 throw Exception("newMeshFromAssimp: empty mesh");
59
60 std::vector<MeshVertex> verts;
61 verts.reserve(mesh.mNumVertices);
62 std::vector<float> basePos;
63 std::vector<float> baseNrm;
64 std::vector<float> baseUv;
65 if (mesh.mNumAnimMeshes > 0) {
66 basePos.reserve(mesh.mNumVertices * 3);
67 baseNrm.reserve(mesh.mNumVertices * 3);
68 baseUv.reserve(mesh.mNumVertices * 2);
69 }
70 for (unsigned i = 0; i < mesh.mNumVertices; ++i) {
71 MeshVertex v{};
72 v.pos = {mesh.mVertices[i].x, mesh.mVertices[i].y, mesh.mVertices[i].z};
73 if (mesh.HasNormals())
74 v.normal = {mesh.mNormals[i].x, mesh.mNormals[i].y, mesh.mNormals[i].z};
75 else
76 v.normal = {0.f, 1.f, 0.f};
77 if (mesh.HasTangentsAndBitangents()) {
78 const auto &tangent = mesh.mTangents[i];
79 const auto &bitangent = mesh.mBitangents[i];
80 const glm::vec3 t(tangent.x, tangent.y, tangent.z);
81 const glm::vec3 b(bitangent.x, bitangent.y, bitangent.z);
82 v.tangent = glm::vec4(t, glm::dot(glm::cross(v.normal, t), b) < 0.f ? -1.f : 1.f);
83 }
84 if (mesh.HasTextureCoords(0))
85 v.uv = {mesh.mTextureCoords[0][i].x, mesh.mTextureCoords[0][i].y};
86 else
87 v.uv = {0.f, 0.f};
88 verts.push_back(v);
89 if (mesh.mNumAnimMeshes > 0) {
90 basePos.push_back(v.pos.x);
91 basePos.push_back(v.pos.y);
92 basePos.push_back(v.pos.z);
93 baseNrm.push_back(v.normal.x);
94 baseNrm.push_back(v.normal.y);
95 baseNrm.push_back(v.normal.z);
96 baseUv.push_back(v.uv.x);
97 baseUv.push_back(v.uv.y);
98 }
99 }
100
101 std::vector<uint32_t> indices;
102 indices.reserve(mesh.mNumFaces * 3);
103 for (unsigned f = 0; f < mesh.mNumFaces; ++f) {
104 const aiFace &face = mesh.mFaces[f];
105 if (face.mNumIndices != 3) continue;
106 indices.push_back(face.mIndices[0]);
107 indices.push_back(face.mIndices[1]);
108 indices.push_back(face.mIndices[2]);
109 }
110 if (indices.empty()) throw Exception("newMeshFromAssimp: no triangle faces");
111
112 std::unique_ptr<GpuMesh> gpu;
113 if (mesh.mNumVertices <= 65535u) {
114 std::vector<uint16_t> idx16;
115 idx16.reserve(indices.size());
116 for (uint32_t i : indices) idx16.push_back(uint16_t(i));
117 gpu = uploadGpuMesh16(device, frameToken(), verts, idx16);
118 } else {
119 gpu = uploadGpuMesh(device, frameToken(), verts, indices);
120 }
121 auto handle = makeMeshHandle(*gpu);
122 handle->captureImportedAttributes(mesh);
123 // Retain the CPU morph base pose only when the mesh actually has morphs;
124 // otherwise the base pos/nrm/uv copies would linger at ~32B/vertex for no reason.
125 if (mesh.mNumAnimMeshes > 0) {
126 handle->initMorphBase(int(mesh.mNumVertices), basePos.data(), baseNrm.data(), baseUv.data());
127 }
128 // Assimp morph targets (VRM / glTF blend shapes often land here).
129 for (unsigned m = 0; m < mesh.mNumAnimMeshes; ++m) {
130 const aiAnimMesh *am = mesh.mAnimMeshes[m];
131 if (!am || !am->mVertices || am->mNumVertices != mesh.mNumVertices) continue;
132 std::string morphName =
133 am->mName.length ? am->mName.C_Str() : ("morph" + std::to_string(m));
134 std::vector<float> absPos(size_t(am->mNumVertices) * 3u);
135 for (unsigned i = 0; i < am->mNumVertices; ++i) {
136 absPos[size_t(i) * 3u + 0] = am->mVertices[i].x;
137 absPos[size_t(i) * 3u + 1] = am->mVertices[i].y;
138 absPos[size_t(i) * 3u + 2] = am->mVertices[i].z;
139 }
140 handle->addMorphTargetAbsolute(morphName, absPos.data());
141 if (am->mNormals) {
142 std::vector<float> deltaNormals(size_t(am->mNumVertices) * 3u);
143 for (unsigned i = 0; i < am->mNumVertices; ++i) {
144 deltaNormals[size_t(i) * 3] = am->mNormals[i].x - baseNrm[size_t(i) * 3];
145 deltaNormals[size_t(i) * 3 + 1] = am->mNormals[i].y - baseNrm[size_t(i) * 3 + 1];
146 deltaNormals[size_t(i) * 3 + 2] = am->mNormals[i].z - baseNrm[size_t(i) * 3 + 2];
147 }
148 auto normalResult = handle->setMorphNormalDeltas(morphName, deltaNormals);
149 if (!normalResult.ok()) throw Exception("Invalid imported morph normals: %s", morphName.c_str());
150 }
151 }
152 handle->markMorphClean();
153 Mesh *raw = handle.get();
154 assignMeshBounds(raw, verts);
155 registerMeshRecord(gpu.get(), &verts, &indices);
156 ownedGpuMeshes.push_back(std::move(gpu));
157 ownedMeshes.push_back(std::move(handle));
158 return raw;
159}
160
161Mesh* Graphics::newMeshFromAssimp(const ::aiMesh& mesh, const glm::mat4& worldTransform) {
162 ASSERT(initialized);
163 if (!initialized) throw Exception("newMeshFromAssimp: graphics not initialized");
164 if (mesh.mNumVertices == 0 || mesh.mNumFaces == 0)
165 throw Exception("newMeshFromAssimp: empty mesh");
166
167 // glm is column-major; Assimp aiMatrix4x4 is row-major.
168 const aiMatrix4x4 world(worldTransform[0][0], worldTransform[1][0], worldTransform[2][0], worldTransform[3][0],
169 worldTransform[0][1], worldTransform[1][1], worldTransform[2][1], worldTransform[3][1],
170 worldTransform[0][2], worldTransform[1][2], worldTransform[2][2], worldTransform[3][2],
171 worldTransform[0][3], worldTransform[1][3], worldTransform[2][3], worldTransform[3][3]);
172
173 std::vector<aiVector3D> positions(mesh.mNumVertices);
174 std::vector<aiVector3D> normals(mesh.mNumVertices);
175 std::vector<aiVector3D> tangents;
176 std::vector<aiVector3D> bitangents;
177 if (mesh.HasTangentsAndBitangents()) {
178 tangents.resize(mesh.mNumVertices);
179 bitangents.resize(mesh.mNumVertices);
180 const aiMatrix3x3 linear(world);
181 for (unsigned i = 0; i < mesh.mNumVertices; ++i) {
182 tangents[i] = linear * mesh.mTangents[i];
183 bitangents[i] = linear * mesh.mBitangents[i];
184 tangents[i].Normalize();
185 bitangents[i].Normalize();
186 }
187 }
188 aiMatrix3x3 nmat(world);
189 const float ndet = nmat.Determinant();
190 if (std::fabs(ndet) > 1e-8f) {
191 nmat.Inverse();
192 nmat.Transpose();
193 }
194 for (unsigned i = 0; i < mesh.mNumVertices; ++i) {
195 positions[i] = world * mesh.mVertices[i];
196 if (mesh.HasNormals()) {
197 normals[i] = nmat * mesh.mNormals[i];
198 normals[i].Normalize();
199 } else {
200 normals[i] = aiVector3D(0.f, 1.f, 0.f);
201 }
202 }
203
204 // Negative determinant mirrors the mesh: winding flips while inverse-transpose
205 // keeps normals consistent, so back-face cull would hide the visible side.
206 const bool flipWinding = world.Determinant() < 0.f;
207 std::vector<aiFace> flippedFaces;
208 std::vector<unsigned> flippedIdx;
209 if (flipWinding) {
210 flippedFaces.resize(mesh.mNumFaces);
211 flippedIdx.resize(size_t(mesh.mNumFaces) * 3u);
212 for (unsigned f = 0; f < mesh.mNumFaces; ++f) {
213 const aiFace &src = mesh.mFaces[f];
214 aiFace &dst = flippedFaces[f];
215 dst.mNumIndices = src.mNumIndices;
216 if (src.mNumIndices == 3 && src.mIndices) {
217 unsigned *idx = flippedIdx.data() + size_t(f) * 3u;
218 idx[0] = src.mIndices[0];
219 idx[1] = src.mIndices[2];
220 idx[2] = src.mIndices[1];
221 dst.mIndices = idx;
222 } else {
223 dst.mIndices = src.mIndices;
224 }
225 }
226 }
227
228 // Non-owning view — do not let aiMesh destructor free borrowed pointers.
229 aiMesh tmp{};
230 tmp.mPrimitiveTypes = mesh.mPrimitiveTypes;
231 tmp.mNumVertices = mesh.mNumVertices;
232 tmp.mVertices = positions.data();
233 tmp.mNormals = normals.data();
234 tmp.mTangents = tangents.empty() ? nullptr : tangents.data();
235 tmp.mBitangents = bitangents.empty() ? nullptr : bitangents.data();
236 tmp.mNumFaces = mesh.mNumFaces;
237 tmp.mFaces = flipWinding ? flippedFaces.data() : mesh.mFaces;
238 tmp.mMaterialIndex = mesh.mMaterialIndex;
239 tmp.mNumAnimMeshes = mesh.mNumAnimMeshes;
240 tmp.mAnimMeshes = mesh.mAnimMeshes;
241 if (mesh.HasTextureCoords(0)) {
242 tmp.mTextureCoords[0] = mesh.mTextureCoords[0];
243 tmp.mNumUVComponents[0] = mesh.mNumUVComponents[0];
244 }
245 const auto detach = [&]() {
246 tmp.mVertices = nullptr;
247 tmp.mNormals = nullptr;
248 tmp.mTangents = nullptr;
249 tmp.mBitangents = nullptr;
250 tmp.mFaces = nullptr;
251 tmp.mTextureCoords[0] = nullptr;
252 tmp.mAnimMeshes = nullptr;
253 };
254 Mesh *out = nullptr;
255 try {
256 out = newMeshFromAssimp(tmp);
257 } catch (...) {
258 detach();
259 throw;
260 }
261 detach();
262 return out;
263}
264
265Mesh *Graphics::newMeshFromArrays(const float *posXYZ, const float *nrmXYZ, const float *uvST,
266 int vertexCount, const uint32_t *indices, int indexCount) {
267 return newMeshFromArraysColored(posXYZ,nrmXYZ,uvST,nullptr,vertexCount,indices,indexCount);
268}
269
270Mesh *Graphics::newMeshFromArraysColored(const float *posXYZ, const float *nrmXYZ, const float *uvST,
271 const float *colorRGBA, int vertexCount,
272 const uint32_t *indices, int indexCount) {
273 ASSERT(initialized);
274 if (!initialized) throw Exception("newMeshFromArrays: graphics not initialized");
275 if (!posXYZ || vertexCount <= 0) throw Exception("newMeshFromArrays: empty positions");
276 if (!indices || indexCount < 3) throw Exception("newMeshFromArrays: empty indices");
277 if (indexCount % 3 != 0) throw Exception("newMeshFromArrays: indexCount must be multiple of 3");
278
279 std::vector<MeshVertex> verts(static_cast<size_t>(vertexCount));
280 for (int i = 0; i < vertexCount; ++i) {
281 MeshVertex &v = verts[static_cast<size_t>(i)];
282 v.pos = {posXYZ[size_t(i) * 3u], posXYZ[size_t(i) * 3u + 1u], posXYZ[size_t(i) * 3u + 2u]};
283 if (nrmXYZ)
284 v.normal = {nrmXYZ[size_t(i) * 3u], nrmXYZ[size_t(i) * 3u + 1u],
285 nrmXYZ[size_t(i) * 3u + 2u]};
286 else
287 v.normal = {0.f, 1.f, 0.f};
288 if (uvST)
289 v.uv = {uvST[size_t(i) * 2u], uvST[size_t(i) * 2u + 1u]};
290 else
291 v.uv = {0.f, 0.f};
292 if (colorRGBA)
293 v.color = {colorRGBA[size_t(i)*4u],colorRGBA[size_t(i)*4u+1u],
294 colorRGBA[size_t(i)*4u+2u],colorRGBA[size_t(i)*4u+3u]};
295 }
296
297 std::vector<uint32_t> idx(indices, indices + indexCount);
298 for (uint32_t id : idx) {
299 if (int(id) >= vertexCount) throw Exception("newMeshFromArrays: index out of range");
300 }
301
302 auto gpu = uploadGpuMesh(device, frameToken(), verts, idx);
303 auto handle = makeMeshHandle(*gpu);
304 Mesh *raw = handle.get();
305 raw->computeBounds(posXYZ, vertexCount);
306 registerMeshRecord(gpu.get());
307 ownedGpuMeshes.push_back(std::move(gpu));
308 ownedMeshes.push_back(std::move(handle));
309 return raw;
310}
311
313 if (!mesh || !mesh->gpuHandle)
315 eve::DiagnosticCode::NotFound, "mesh has no backend upload", {}, {}, "graphics.mesh.describe"));
316 const auto *gpu = static_cast<const GpuMesh *>(mesh->gpuHandle);
317 const auto owned =
318 std::find_if(ownedGpuMeshes.begin(), ownedGpuMeshes.end(),
319 [gpu](const std::unique_ptr<GpuMesh> &candidate) { return candidate.get() == gpu; });
320 if (owned == ownedGpuMeshes.end())
322 eve::DiagnosticCode::NotFound, "mesh is not owned by this graphics", {}, {}, "graphics.mesh.describe"));
324 gpu->vertexCount, gpu->indexCount, static_cast<std::uint32_t>(sizeof(MeshVertex)),
325 gpu->indexType == vk::IndexType::eUint16 ? 2u : 4u});
326}
327
329 if (!mesh || !mesh->gpuHandle || !mesh->hasMorphData() || !mesh->isMorphDirty()) return false;
330 if (!initialized) return false;
331
332 std::vector<float> pos;
333 std::vector<float> nrm;
334 mesh->computeMorphedPositions(pos, nrm);
335 const int vc = mesh->getVertexCount();
336 if (vc <= 0 || int(pos.size()) < vc * 3) return false;
337 mesh->computeBounds(pos.data(), vc);
338
339 std::vector<MeshVertex> verts(static_cast<size_t>(vc));
340 auto *gpu = static_cast<GpuMesh *>(mesh->gpuHandle);
341 if (mesh->hasGpuSkinning()) {
342 // Morphs change positions/normals only; retain the authored skin influences.
343 auto &source = meshDrawVertices(*gpu);
344 void *mapped = source.map();
345 if (!mapped) return false;
346 std::memcpy(verts.data(), mapped, verts.size() * sizeof(MeshVertex));
347 source.unmap();
348 }
349 const auto &uv = mesh->baseUv();
350 for (int i = 0; i < vc; ++i) {
351 MeshVertex &v = verts[static_cast<size_t>(i)];
352 v.pos = {pos[size_t(i) * 3u + 0], pos[size_t(i) * 3u + 1], pos[size_t(i) * 3u + 2]};
353 if (int(nrm.size()) >= (i + 1) * 3)
354 v.normal = {nrm[size_t(i) * 3u + 0], nrm[size_t(i) * 3u + 1], nrm[size_t(i) * 3u + 2]};
355 else
356 v.normal = {0.f, 1.f, 0.f};
357 if (int(uv.size()) >= (i + 1) * 2)
358 v.uv = {uv[size_t(i) * 2u + 0], uv[size_t(i) * 2u + 1]};
359 else
360 v.uv = {0.f, 0.f};
361 }
362
363 // Ring-buffered host-visible VBO: the next copy is kDynamicVertexCopies
364 // frames old, so overwriting it never races with in-flight draws — no
365 // device-wide wait (see writeDynamicMesh).
366 ensureDynamicRing(*gpu);
367 writeDynamicMesh(*gpu, verts, getDevice(), frameToken(), nullptr, 0);
368 mesh->markMorphClean();
369 return true;
370}
371
372bool Graphics::updateMeshVertices(Mesh *mesh, const float *posXYZ, const float *nrmXYZ,
373 const float *uvST, int vertexCount, const uint32_t *indices,
374 int indexCount) {
375 if (!initialized || !mesh || !mesh->gpuHandle) return false;
376 if (!posXYZ || vertexCount <= 0 || indexCount < 0) return false;
377 if (indexCount > 0 && (indexCount % 3 != 0 || !indices)) return false;
378 for (int i = 0; i < indexCount; ++i) {
379 if (indices[i] >= uint32_t(vertexCount)) return false;
380 }
381
382 auto *gpu = static_cast<GpuMesh *>(mesh->gpuHandle);
383 auto &verts = gpu->updateVertices;
384 verts.resize(static_cast<size_t>(vertexCount));
385 for (int i = 0; i < vertexCount; ++i) {
386 MeshVertex &v = verts[static_cast<size_t>(i)];
387 v.pos = {posXYZ[size_t(i) * 3u], posXYZ[size_t(i) * 3u + 1u], posXYZ[size_t(i) * 3u + 2u]};
388 if (nrmXYZ)
389 v.normal = {nrmXYZ[size_t(i) * 3u], nrmXYZ[size_t(i) * 3u + 1u],
390 nrmXYZ[size_t(i) * 3u + 2u]};
391 else
392 v.normal = {0.f, 1.f, 0.f};
393 if (uvST)
394 v.uv = {uvST[size_t(i) * 2u], uvST[size_t(i) * 2u + 1u]};
395 else
396 v.uv = {0.f, 0.f};
397 }
398
399 mesh->computeBounds(posXYZ, vertexCount);
400 // Same ring-buffer approach as bakeMeshMorph: never wait on in-flight
401 // frames, just write the next copy.
402 ensureDynamicRing(*gpu);
403 writeDynamicMesh(*gpu, verts, getDevice(), frameToken(), indices, indexCount);
404 mesh->gpuVertexCount = int(gpu->vertexCount);
405 mesh->indexCount = int(gpu->indexCount);
406 return true;
407}
408
409bool Graphics::setMeshSkinningData(Mesh *mesh, const uint16_t *joints4, const float *weights4,
410 int vertexCount) {
411 if (!initialized || !mesh || !mesh->gpuHandle || !joints4 || !weights4) return false;
412 auto *gpu = static_cast<GpuMesh *>(mesh->gpuHandle);
413 if (vertexCount <= 0 || uint32_t(vertexCount) != gpu->vertexCount) return false;
414
415 std::vector<MeshVertex> verts(static_cast<size_t>(vertexCount));
416 auto &source = meshDrawVertices(*gpu);
417 void *mapped = source.map();
418 if (!mapped) return false;
419 std::memcpy(verts.data(), mapped, verts.size() * sizeof(MeshVertex));
420 source.unmap();
421 for (int i = 0; i < vertexCount; ++i) {
422 const size_t base = static_cast<size_t>(i) * 4u;
423 verts[static_cast<size_t>(i)].joints =
424 glm::u16vec4(joints4[base], joints4[base + 1], joints4[base + 2], joints4[base + 3]);
425 verts[static_cast<size_t>(i)].weights =
426 glm::vec4(weights4[base], weights4[base + 1], weights4[base + 2], weights4[base + 3]);
427 }
428 ensureDynamicRing(*gpu);
429 writeDynamicMesh(*gpu, verts, getDevice(), frameToken(), nullptr, 0);
430 mesh->markGpuSkinned(true);
431 return true;
432}
433
435 if (!mesh || !mesh->gpuHandle) return false;
436
437 auto *gpu = static_cast<GpuMesh *>(mesh->gpuHandle);
438 auto gpuIt = std::find_if(ownedGpuMeshes.begin(), ownedGpuMeshes.end(),
439 [&](const std::unique_ptr<GpuMesh> &g) {
440 return g.get() == gpu;
441 });
442 if (gpuIt == ownedGpuMeshes.end()) return false;
443
444 auto meshIt = std::find_if(ownedMeshes.begin(), ownedMeshes.end(),
445 [&](const std::unique_ptr<Mesh> &m) {
446 return m.get() == mesh;
447 });
448 if (meshIt == ownedMeshes.end()) return false;
449
450 // An in-flight draw may still read the vertex/index buffers; drain first.
451 waitForSharedGpuResources();
452 mesh->gpuHandle = nullptr;
453 ownedGpuMeshes.erase(gpuIt);
454 // Transfer the CPU facade to the caller instead of destroying it.
455 (void)meshIt->release();
456 ownedMeshes.erase(meshIt);
457 return true;
458}
459
460Mesh *Graphics::newMeshSphere(int slices, int stacks) {
461 ASSERT(initialized);
462 if (!initialized) throw Exception("newMeshSphere: graphics not initialized");
463 if (slices < 3) slices = 3;
464 if (stacks < 2) stacks = 2;
465 if (slices > 256) slices = 256;
466 if (stacks > 128) stacks = 128;
467
468 constexpr float kPi = 3.14159265358979323846f;
469 constexpr float kTwoPi = kPi * 2.f;
470
471 // Layout (stride = slices+1, seam column duplicated for continuous U):
472 // row 0: north pole verts (same pos, unique U)
473 // row 1..stacks-1: latitude rings
474 // row stacks: south pole verts
475 // One pole vertex per longitude avoids a single-fan UV singularity and
476 // keeps every triangle non-degenerate.
477 const int stride = slices + 1;
478 const int rows = stacks + 1; // includes both pole rows
479 std::vector<MeshVertex> verts;
480 verts.reserve(size_t(stride) * size_t(rows));
481
482 auto pushVert = [&](float px, float py, float pz, float u, float v) {
484 vert.pos = {px, py, pz};
485 vert.normal = {px, py, pz}; // unit sphere
486 vert.uv = {u, v};
487 verts.push_back(vert);
488 };
489
490 for (int y = 0; y <= stacks; ++y) {
491 const float fv = float(y) / float(stacks);
492 const float phi = fv * kPi;
493 const float sinPhi = std::sin(phi);
494 const float cosPhi = std::cos(phi);
495 for (int x = 0; x <= slices; ++x) {
496 const float u = float(x) / float(slices);
497 const float theta = u * kTwoPi;
498 // Exact poles: collapse ring to a point but keep per-slice UVs.
499 if (y == 0)
500 pushVert(0.f, 1.f, 0.f, u, 0.f);
501 else if (y == stacks)
502 pushVert(0.f, -1.f, 0.f, u, 1.f);
503 else
504 pushVert(sinPhi * std::cos(theta), cosPhi, sinPhi * std::sin(theta), u, fv);
505 }
506 }
507
508 std::vector<uint32_t> indices;
509 indices.reserve(size_t(slices) * size_t(stacks) * 6u);
510
511 // Quads between consecutive rows use outward object-space CCW winding.
512 for (int y = 0; y < stacks; ++y) {
513 const uint32_t row0 = uint32_t(y * stride);
514 const uint32_t row1 = uint32_t((y + 1) * stride);
515 for (int x = 0; x < slices; ++x) {
516 const uint32_t i0 = row0 + uint32_t(x);
517 const uint32_t i1 = row0 + uint32_t(x + 1);
518 const uint32_t i2 = row1 + uint32_t(x);
519 const uint32_t i3 = row1 + uint32_t(x + 1);
520 indices.push_back(i0);
521 indices.push_back(i1);
522 indices.push_back(i2);
523 indices.push_back(i1);
524 indices.push_back(i3);
525 indices.push_back(i2);
526 }
527 }
528
529 auto gpu = uploadGpuMesh(device, frameToken(), verts, indices);
530 auto handle = makeMeshHandle(*gpu);
531 Mesh *raw = handle.get();
532 assignMeshBounds(raw, verts);
533 registerMeshRecord(gpu.get());
534 ownedGpuMeshes.push_back(std::move(gpu));
535 ownedMeshes.push_back(std::move(handle));
536 return raw;
537}
538
539Mesh *Graphics::newMeshCylinder(int slices, int stacks, bool caps) {
540 ASSERT(initialized);
541 if (!initialized) throw Exception("newMeshCylinder: graphics not initialized");
542 if (slices < 3) slices = 3;
543 if (stacks < 1) stacks = 1;
544 if (slices > 256) slices = 256;
545 if (stacks > 128) stacks = 128;
546
547 constexpr float kPi = 3.14159265358979323846f;
548 constexpr float kTwoPi = kPi * 2.f;
549 constexpr float kRadius = 1.f;
550 constexpr float kHalfH = 1.f; // height 2, Y from -1..1
551
552 const int stride = slices + 1; // duplicated seam for continuous U
553 const int sideRows = stacks + 1;
554 std::vector<MeshVertex> verts;
555 verts.reserve(size_t(stride) * size_t(sideRows) + size_t(caps ? 2 * (slices + 2) : 0));
556
557 auto pushVert = [&](float px, float py, float pz, float nx, float ny, float nz, float u,
558 float v) {
560 vert.pos = {px, py, pz};
561 vert.normal = {nx, ny, nz};
562 vert.uv = {u, v};
563 verts.push_back(vert);
564 };
565
566 // Side wall: outward normals in XZ.
567 for (int y = 0; y <= stacks; ++y) {
568 const float fv = float(y) / float(stacks);
569 const float py = kHalfH - fv * (2.f * kHalfH);
570 for (int x = 0; x <= slices; ++x) {
571 const float u = float(x) / float(slices);
572 const float theta = u * kTwoPi;
573 const float cx = std::cos(theta);
574 const float sz = std::sin(theta);
575 pushVert(kRadius * cx, py, kRadius * sz, cx, 0.f, sz, u, fv);
576 }
577 }
578
579 std::vector<uint32_t> indices;
580 indices.reserve(size_t(slices) * size_t(stacks) * 6u +
581 size_t(caps ? slices * 2 * 3 : 0));
582
583 for (int y = 0; y < stacks; ++y) {
584 const uint32_t row0 = uint32_t(y * stride);
585 const uint32_t row1 = uint32_t((y + 1) * stride);
586 for (int x = 0; x < slices; ++x) {
587 const uint32_t i0 = row0 + uint32_t(x);
588 const uint32_t i1 = row0 + uint32_t(x + 1);
589 const uint32_t i2 = row1 + uint32_t(x);
590 const uint32_t i3 = row1 + uint32_t(x + 1);
591 indices.push_back(i0);
592 indices.push_back(i1);
593 indices.push_back(i2);
594 indices.push_back(i1);
595 indices.push_back(i3);
596 indices.push_back(i2);
597 }
598 }
599
600 if (caps) {
601 // Top cap (y = +1, normal +Y) — fan from center.
602 const uint32_t topCenter = uint32_t(verts.size());
603 pushVert(0.f, kHalfH, 0.f, 0.f, 1.f, 0.f, 0.5f, 0.5f);
604 const uint32_t topRing = uint32_t(verts.size());
605 for (int x = 0; x <= slices; ++x) {
606 const float u = float(x) / float(slices);
607 const float theta = u * kTwoPi;
608 const float cx = std::cos(theta);
609 const float sz = std::sin(theta);
610 pushVert(kRadius * cx, kHalfH, kRadius * sz, 0.f, 1.f, 0.f, 0.5f + 0.5f * cx,
611 0.5f + 0.5f * sz);
612 }
613 for (int x = 0; x < slices; ++x) {
614 indices.push_back(topCenter);
615 indices.push_back(topRing + uint32_t(x + 1));
616 indices.push_back(topRing + uint32_t(x));
617 }
618
619 // Bottom cap (y = -1, normal -Y).
620 const uint32_t botCenter = uint32_t(verts.size());
621 pushVert(0.f, -kHalfH, 0.f, 0.f, -1.f, 0.f, 0.5f, 0.5f);
622 const uint32_t botRing = uint32_t(verts.size());
623 for (int x = 0; x <= slices; ++x) {
624 const float u = float(x) / float(slices);
625 const float theta = u * kTwoPi;
626 const float cx = std::cos(theta);
627 const float sz = std::sin(theta);
628 pushVert(kRadius * cx, -kHalfH, kRadius * sz, 0.f, -1.f, 0.f, 0.5f + 0.5f * cx,
629 0.5f + 0.5f * sz);
630 }
631 for (int x = 0; x < slices; ++x) {
632 indices.push_back(botCenter);
633 indices.push_back(botRing + uint32_t(x));
634 indices.push_back(botRing + uint32_t(x + 1));
635 }
636 }
637
638 auto gpu = uploadGpuMesh(device, frameToken(), verts, indices);
639 auto handle = makeMeshHandle(*gpu);
640 Mesh *raw = handle.get();
641 assignMeshBounds(raw, verts);
642 registerMeshRecord(gpu.get());
643 ownedGpuMeshes.push_back(std::move(gpu));
644 ownedMeshes.push_back(std::move(handle));
645 return raw;
646}
647
649 static_assert(sizeof(MeshVertex) == 88 && offsetof(MeshVertex, color) == 56 &&
650 offsetof(MeshVertex, weights) == 40 && offsetof(MeshVertex, tangent) == 72);
651 auto owned =
652 std::find_if(ownedMeshes.begin(), ownedMeshes.end(), [&](const auto &item) { return item.get() == &mesh; });
653 if (!initialized || owned == ownedMeshes.end() || !mesh.gpuHandle || source.backend != GpuResidentBackend::Vulkan ||
654 !source.nativeHandle || source.strideBytes != sizeof(MeshVertex) || source.offsetBytes % 4 ||
655 mesh.hasGpuSkinning() || (!swapchainPassOpen && !offscreen3DPassOpen))
657 "Expected same-device resident vertices in an open pass",
658 "graphics.residentMesh"));
659 auto &gpu = *static_cast<GpuMesh *>(mesh.gpuHandle);
660 if (source.offsetBytes > source.sizeBytes ||
661 uint64_t(gpu.vertexCount) * sizeof(MeshVertex) > source.sizeBytes - source.offsetBytes)
663 "Resident vertex stream is too small", "graphics.residentMesh"));
664 VkBuffer raw{};
665 static_assert(sizeof(raw) <= sizeof(source.nativeHandle));
666 std::memcpy(&raw, &source.nativeHandle, sizeof(raw));
667 gpu.residentVertexOverride = raw;
668 gpu.residentVertexOffset = source.offsetBytes;
669 struct ClearOverride {
670 GpuMesh &mesh;
671 ~ClearOverride() {
672 mesh.residentVertexOverride = vk::Buffer{};
673 mesh.residentVertexOffset = 0;
674 }
675 } clear{gpu};
676 try {
677 drawMesh(&mesh, glm::mat4(1.f), nullptr, Color(1.f, 1.f, 1.f, 1.f));
678 return Result<void>::success();
679 } catch (const std::exception &e) {
680 return Result<void>::failure(Diagnostic::error(DiagnosticCode::Failed, e.what(), "graphics.residentMesh"));
681 }
682}
683
684void Graphics::drawMesh(Mesh *mesh, const glm::mat4 &model, Texture *texture, const Color &tint) {
685 drawMeshShader(mesh, model, texture, tint, nullptr);
686}
687
689 Shader *shader) {
690 drawMeshShaderRange(mesh, model, texture, tint, shader, 0, 1, {});
691}
692
694 const Color &tint) {
695 const auto invalid = [](const char *message) {
697 Diagnostic::error(DiagnosticCode::InvalidArgument, message, "graphics.meshInstances"));
698 };
699 if (!initialized || !mesh.gpuHandle ||
700 std::none_of(ownedMeshes.begin(), ownedMeshes.end(), [&](const auto &owned) { return owned.get() == &mesh; }) ||
701 (!swapchainPassOpen && !offscreen3DPassOpen))
702 return invalid("Expected an owned mesh inside an open 3D pass");
703 if (texture &&
704 (!texture->get().gpuHandle || std::none_of(ownedTextures.begin(), ownedTextures.end(),
705 [&](const auto &owned) { return owned.get() == &texture->get(); })))
706 return invalid("Albedo texture belongs to another provider");
707 if (mesh.hasGpuSkinning() || pbrSurface_ || mesh3dClusteredActive || mesh3dSurfaceMode != SurfaceMode::Opaque)
709 DiagnosticCode::Unsupported, "Ordinary instancing requires a static opaque nonclustered material",
710 "graphics.meshInstances"));
711 if (models.size() > UINT32_MAX ||
712 models.size_bytes() > device.physical_device.properties.limits.maxStorageBufferRange)
713 return invalid("Transform batch exceeds device storage range");
714 for (const auto &model : models)
715 for (int column = 0; column < 4; ++column)
716 for (int row = 0; row < 4; ++row)
717 if (!std::isfinite(model[column][row])) return invalid("Nonfinite instance transform");
718 for (int i = 0; i < 4; ++i)
719 if (!std::isfinite(tint[i])) return invalid("Nonfinite instance tint");
720 if (models.empty()) return Result<void>::success();
721 const auto &slots = currentMesh3dFrameSlots();
722 if (slots.drawIndex >= slots.capacity)
723 return Result<void>::failure(Diagnostic::error(DiagnosticCode::Failed, "Ordinary mesh uniform ring exhausted",
724 "graphics.meshInstances"));
725 try {
726 drawMeshShaderRange(&mesh, glm::mat4(1.f), texture ? &texture->get() : nullptr, tint, nullptr, 0,
727 uint32_t(models.size()), models);
728 return Result<void>::success();
729 } catch (const std::exception &error) {
730 return Result<void>::failure(Diagnostic::error(DiagnosticCode::Failed, error.what(), "graphics.meshInstances"));
731 }
732}
733
735 uint32_t first, uint32_t count) {
736 auto fail = [](const char *message) {
738 };
739 auto ownedShader = std::find_if(ownedGpuShaders.begin(), ownedGpuShaders.end(),
740 [&](const auto &item) { return item->owner == &shader; });
741 auto ownedMesh =
742 std::find_if(ownedMeshes.begin(), ownedMeshes.end(), [&](const auto &item) { return item.get() == &mesh; });
743 if (!initialized || ownedShader == ownedGpuShaders.end() || ownedMesh == ownedMeshes.end() ||
744 !(*ownedShader)->isMesh3D || (*ownedShader)->isHair3D || shader.isXray() || !mesh.gpuHandle ||
745 (!swapchainPassOpen && !offscreen3DPassOpen))
746 return fail("Expected owned mesh resources inside an open 3D pass");
747 const auto size = meshResourceInstanceCount(**ownedShader);
748 if (!size || first > size || count > size - first)
749 return fail("Instance range exceeds the immutable matrix buffer");
750 for (int col = 0; col < 4; ++col)
751 for (int row = 0; row < 4; ++row)
752 if (!std::isfinite(model[col][row])) return fail("Nonfinite model matrix");
753 for (int i = 0; i < 4; ++i)
754 if (!std::isfinite(tint[i])) return fail("Nonfinite instance tint");
755 if (!count) return Result<void>::success();
756 try {
757 drawMeshShaderRange(&mesh, model, nullptr, tint, &shader, first, count, {});
758 return Result<void>::success();
759 } catch (const std::exception &error) {
760 return Result<void>::failure(Diagnostic::error(DiagnosticCode::Failed, error.what(), "graphics.instances"));
761 }
762}
763
764void Graphics::drawMeshShaderRange(Mesh *mesh, const glm::mat4 &model, Texture *texture, const Color &tint,
765 Shader *shader, uint32_t firstInstance, uint32_t instanceCount,
766 std::span<const glm::mat4> models) {
767 ASSERT(initialized);
768 ASSERT(mesh != nullptr);
769 if (!initialized) throw Exception("drawMesh: graphics not initialized");
770 if (!mesh || !mesh->gpuHandle) throw Exception("drawMesh: null mesh");
771 if (!swapchainPassOpen && !offscreen3DPassOpen)
772 throw Exception("drawMesh: call begin3DFrame first");
773 createMesh3DPipeline();
774 if (!mesh3dPipeline) throw Exception("drawMesh: mesh3d pipeline missing");
775
776 if (shader) {
777 if (shader->getKind() != Shader::Kind::eMesh3D)
778 throw Exception("drawMesh: shader is not a Mesh3D shader (use newMeshShader*)");
779 if (!shader->gpuHandle) throw Exception("drawMesh: shader has no GPU pipeline");
780 }
781
782 if (pbrSurface_ && !shader) {
783 drawPbrMesh(mesh, model, tint);
784 return;
785 }
786 auto *gpuMesh = static_cast<GpuMesh *>(mesh->gpuHandle);
787 Texture *tex = texture ? texture : whiteTexture;
788 if (!tex || !tex->gpuHandle) throw Exception("drawMesh: missing texture");
789 auto *gpuTex = static_cast<GpuTexture *>(tex->gpuHandle);
790
791 ensureFlatNormalTexture3D();
792 Texture *ntex = mesh3dNormalTexture ? mesh3dNormalTexture : flatNormalTexture3D;
793 if (!ntex || !ntex->gpuHandle) throw Exception("drawMesh: missing normal texture");
794 auto *gpuNormal = static_cast<GpuTexture *>(ntex->gpuHandle);
795
796 ensureFlatHeightTexture3D();
797 Texture *htex = mesh3dHeightTexture ? mesh3dHeightTexture : flatHeightTexture3D;
798 if (!htex || !htex->gpuHandle) throw Exception("drawMesh: missing height texture");
799 auto *gpuHeight = static_cast<GpuTexture *>(htex->gpuHandle);
800
801 Texture *depthTex = mesh3dSceneDepthTexture ? mesh3dSceneDepthTexture : whiteTexture;
802 if (!depthTex || !depthTex->gpuHandle) throw Exception("drawMesh: missing scene depth texture");
803 auto *gpuDepth = static_cast<GpuTexture *>(depthTex->gpuHandle);
804
805 // Screen-space decal layer (bindings 8/9/10). Only sampled when the decal
806 // pass actually recorded this frame; otherwise the transparent/flat
807 // placeholders make the blend a no-op.
808 ensureDecalPlaceholders();
809 GpuTexture *gpuDecalAlb = nullptr;
810 GpuTexture *gpuDecalNrm = nullptr;
811 GpuTexture *gpuDecalPrm = nullptr;
812 if (decalLayerFresh) {
813 if (auto *dslot = currentDecalSlot()) {
814 gpuDecalAlb = &dslot->albedoGpu;
815 gpuDecalNrm = &dslot->normalGpu;
816 gpuDecalPrm = &dslot->paramsGpu;
817 }
818 }
819 if (!gpuDecalAlb) {
820 gpuDecalAlb = static_cast<GpuTexture *>(decalFlatAlbedo->gpuHandle);
821 gpuDecalNrm = static_cast<GpuTexture *>(decalFlatNormal->gpuHandle);
822 gpuDecalPrm = static_cast<GpuTexture *>(decalFlatParams->gpuHandle);
823 }
824
825 ensureDefaultEnvCubemap();
826 Texture *envTex = mesh3dEnvTexture ? mesh3dEnvTexture : defaultEnvCubemap;
827 if (!envTex || !envTex->gpuHandle) throw Exception("drawMesh: missing env cubemap");
828 auto *gpuEnv = static_cast<GpuTexture *>(envTex->gpuHandle);
829 if (!gpuEnv->isCube) throw Exception("drawMesh: env texture is not a cubemap");
830 const float envIntensity = (mesh3dEnvTexture && mesh3dEnvIntensity > 0.f) ? mesh3dEnvIntensity : 0.f;
831
832 const bool useClustered = mesh3dClusteredActive && !shader && mesh3dClusteredPipeline &&
833 mesh3dSurfaceMode != SurfaceMode::Transparent && !mesh->hasGpuSkinning();
834 auto &cb = currentPresentCb();
835
836 auto makeShadowUbo = [&]() {
837 ShadowUBO s = mesh3dShadows.ubo;
838 if (!mesh3dShadows.active) {
839 s.bias.y = 0.f;
840 s.splits.w = 0.f;
841 }
842 s.bias.z = mesh3dShadowReceive ? 1.f : 0.f;
843 return s;
844 };
845
846 if (useClustered) {
847 Mesh3DClusteredUBO ubo{};
848 ubo.model = model;
849 ubo.mvp = mesh3dFrameUbo.mvp * model;
850 ubo.view = mesh3dClustered.view;
851 ubo.lightDir = mesh3dClustered.primaryDir;
852 ubo.lightColor = glm::vec4(glm::vec3(mesh3dClustered.primaryColor), envIntensity);
853 ubo.tint = glm::vec4(tint.r, tint.g, tint.b, tint.a);
854 ubo.cameraPos = glm::vec4(glm::vec3(mesh3dFrameUbo.cameraPos), mesh3dRoughness);
855 ubo.ambient = glm::vec4(glm::vec3(mesh3dClustered.ambient), mesh3dMetallic);
856 ubo.gridInfo = mesh3dClustered.gridInfo;
857 ubo.clipInfo = mesh3dClustered.clipInfo;
858 float surfaceCode = float(int(mesh3dSurfaceMode));
859 if (mesh3dSurfaceMode == SurfaceMode::Masked && mesh3dAlphaTechnique == "dither")
860 surfaceCode = 3.f;
861 else if (mesh3dSurfaceMode == SurfaceMode::Masked &&
862 mesh3dAlphaTechnique == "coverage")
863 surfaceCode = 4.f;
864 ubo.texBomb = glm::vec4(mesh3dTexBombScale, mesh3dTexBombStrength, mesh3dTexBombRot,
865 surfaceCode);
866 ubo.parallax =
867 glm::vec4(mesh3dParallaxScale, mesh3dParallaxMinLayers, mesh3dParallaxMaxLayers,
868 mesh3dAlphaCutoff);
869 ubo.virtualTexture = mesh3dVirtualTexture;
870 ubo.virtualAtlas = mesh3dVirtualAtlas;
871 ubo.envProbeCenter = glm::vec4(mesh3dEnvProbeCenter, 1.f);
872 ubo.envProbeExtent = glm::vec4(mesh3dEnvProbeExtent, 0.f);
873 for (int i = 0; i < ReflectionProbeUpload::kMaxProbes; ++i) {
874 if (i >= mesh3dReflectionProbes.count) continue;
875 const auto &probe = mesh3dReflectionProbes.probes[i];
876 if (!probe.cubemap || !probe.cubemap->gpuHandle ||
877 !static_cast<GpuTexture *>(probe.cubemap->gpuHandle)->isCube)
878 continue;
879 ubo.reflectionProbeCenter[i] = glm::vec4(probe.center, probe.intensity);
880 ubo.reflectionProbeExtent[i] = glm::vec4(probe.extent, probe.blendDistance);
881 }
882
883 auto &cfslots = currentMesh3dClusteredFrameSlots();
884 if (cfslots.drawIndex >= cfslots.capacity) {
885 std::fprintf(stderr,
886 "[vulkan] clustered mesh3d UBO ring exhausted (%zu draws); draw skipped\n",
887 cfslots.capacity);
888 return;
889 }
890 const size_t slot = cfslots.drawIndex++;
891 ensureMesh3dStrides();
892 const uint32_t uboOffset = uint32_t(slot) * mesh3dClusteredUboStride;
893 const uint32_t shadowOffset = uint32_t(slot) * shadowUboStride;
894 updateRingLocal(cfslots.uboRing, uboOffset, &ubo, sizeof(ubo));
895 const ShadowUBO shadow = makeShadowUbo();
896 updateRingLocal(cfslots.shadowRing, shadowOffset, &shadow, sizeof(shadow));
897 vk::DescriptorSet set =
898 mesh3dClusteredSetFor(gpuTex, gpuNormal, gpuEnv, gpuHeight, gpuDecalAlb, gpuDecalNrm,
899 gpuDecalPrm, cfslots);
900 const uint32_t dynOffsets[2] = {uboOffset, shadowOffset};
901
902 if (mesh3dClusteredPipeline != lastMesh3dClusteredPipeline) {
903 cb.bindPipeline(vk::PipelineBindPoint::eGraphics, mesh3dClusteredPipeline);
904 lastMesh3dClusteredPipeline = mesh3dClusteredPipeline;
905 }
906 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, mesh3dClusteredPipelineLayout, 0, 1,
907 &set, 2, dynOffsets);
908 drawIndexedMesh(cb, *gpuMesh);
909 return;
910 }
911
912 Mesh3DUBO ubo = mesh3dFrameUbo;
913 ubo.model = model;
914 ubo.mvp = mesh3dFrameUbo.mvp * model;
915 ubo.skinInfo.z = models.empty() ? 0.f : 1.f;
916 ubo.tint = glm::vec4(tint.r, tint.g, tint.b, tint.a);
917 ubo.ambient = glm::vec4(glm::vec3(mesh3dLighting.ambient), mesh3dMetallic);
918 const int lightCount = std::max(0, std::min(mesh3dLighting.count, Lighting3DPack::kMaxLights));
919 ubo.lightDir.w = float(lightCount);
920 ubo.cameraPos.w = mesh3dRoughness;
921 ubo.lightColor.w = envIntensity;
922 float surfaceCode = float(int(mesh3dSurfaceMode));
923 if (mesh3dSurfaceMode == SurfaceMode::Masked && mesh3dAlphaTechnique == "dither")
924 surfaceCode = 3.f;
925 else if (mesh3dSurfaceMode == SurfaceMode::Masked && mesh3dAlphaTechnique == "coverage")
926 surfaceCode = 4.f;
927 ubo.texBomb = glm::vec4(mesh3dTexBombScale, mesh3dTexBombStrength, mesh3dTexBombRot,
928 surfaceCode);
929 ubo.parallax =
930 glm::vec4(mesh3dParallaxScale, mesh3dParallaxMinLayers, mesh3dParallaxMaxLayers,
931 mesh3dAlphaCutoff);
932 ubo.virtualTexture = mesh3dVirtualTexture;
933 ubo.virtualAtlas = mesh3dVirtualAtlas;
934 ubo.lodFade = mesh3dLodFade;
935 for (int i = 0; i < ReflectionProbeUpload::kMaxProbes; ++i) {
936 if (i >= mesh3dReflectionProbes.count) continue;
937 const auto &probe = mesh3dReflectionProbes.probes[i];
938 if (!probe.cubemap || !probe.cubemap->gpuHandle ||
939 !static_cast<GpuTexture *>(probe.cubemap->gpuHandle)->isCube)
940 continue;
941 ubo.reflectionProbeCenter[i] = glm::vec4(probe.center, probe.intensity);
942 ubo.reflectionProbeExtent[i] = glm::vec4(probe.extent, probe.blendDistance);
943 }
944 if (mesh->hasGpuSkinning()) {
945 ubo.skinInfo.x = static_cast<float>(mesh->getSkinPaletteCount());
946 ubo.skinInfo.y = static_cast<float>(mesh3dSkinInfluenceLimit);
947 }
948 for (int i = 0; i < lightCount; ++i) ubo.lights[i] = mesh3dLighting.lights[i];
949 int dirI = -1;
950 for (int i = 0; i < lightCount; ++i) {
951 if (mesh3dLighting.lights[i].posRadius.w <= 0.f) {
952 dirI = i;
953 break;
954 }
955 }
956 if (dirI >= 0) {
957 glm::vec3 d(mesh3dLighting.lights[dirI].posRadius);
958 if (glm::length(d) < 1e-6f) d = glm::vec3(0.f, 1.f, 0.f);
959 else d = glm::normalize(d);
960 ubo.lightDir = glm::vec4(d, float(lightCount));
961 ubo.lightColor = glm::vec4(glm::vec3(mesh3dLighting.lights[dirI].color), envIntensity);
962 } else {
963 ubo.lightDir = glm::vec4(0.f, 1.f, 0.f, float(lightCount));
964 ubo.lightColor = glm::vec4(0.f, 0.f, 0.f, envIntensity);
965 }
966
967 auto &fslots = currentMesh3dFrameSlots();
968 if (fslots.drawIndex >= fslots.capacity) {
969 std::fprintf(stderr, "[vulkan] mesh3d UBO ring exhausted (%zu draws); draw skipped\n",
970 fslots.capacity);
971 return;
972 }
973 if (models.empty()) {
974 uploadSkinPalette(mesh, fslots);
975 } else {
976 // Binding 21 is an exclusive vertex-transform stream: a skin palette OR
977 // world matrices, selected by skinInfo.z. It adds no sampler bindings.
978 // Every draw owns a separate slot until the frame fence, exactly as skin palettes do.
979 const size_t matrixSlot = fslots.drawIndex + 1;
980 if (fslots.palettes.size() <= matrixSlot) fslots.palettes.resize(matrixSlot + 1);
981 auto &buffer = fslots.palettes[matrixSlot];
982 if (!buffer.buffer || buffer.capacity < models.size_bytes()) {
983 buffer.allocate(frameToken(), device, vk::BufferUsageFlagBits::eStorageBuffer, models.size_bytes(),
984 kHostVisibleCoherent);
985 fslots.sets.clear();
986 fslots.skinSets.clear();
987 }
988 updateRingLocal(buffer, 0, models.data(), models.size_bytes());
989 fslots.activePalette = matrixSlot;
990 }
991 const size_t slot = fslots.drawIndex++;
992 ensureMesh3dStrides();
993 const uint32_t uboOffset = uint32_t(slot) * mesh3dUboStride;
994 const uint32_t shadowOffset = uint32_t(slot) * shadowUboStride;
995 updateRingLocal(fslots.uboRing, uboOffset, &ubo, sizeof(ubo));
996 const ShadowUBO shadow = makeShadowUbo();
997 updateRingLocal(fslots.shadowRing, shadowOffset, &shadow, sizeof(shadow));
998 auto *gpuSceneColor = mesh3dSceneColorTexture && mesh3dSceneColorTexture->gpuHandle
999 ? static_cast<GpuTexture *>(mesh3dSceneColorTexture->gpuHandle)
1000 : sceneColorHistoryValid && completedSceneColorSlot < sceneColorSlots.size()
1001 ? &sceneColorSlots[completedSceneColorSlot].colorGpu
1002 : static_cast<GpuTexture *>(whiteTexture->gpuHandle);
1003 if (shader) {
1004 // Custom meshes reuse the decal/scene-color sampler bindings for their
1005 // four portable textures, keeping the layout within sampler limits.
1006 GpuTexture **slots[] = {&gpuDecalAlb, &gpuDecalNrm, &gpuDecalPrm, &gpuSceneColor};
1007 for (std::size_t index = 0; index < Shader::kMaxMeshTextures; ++index) {
1008 if (auto *custom = shader->meshTexture(index)) {
1009 if (!custom->gpuHandle) throw Exception("drawMesh: custom texture has no GPU resource");
1010 auto *gpuCustom = static_cast<GpuTexture *>(custom->gpuHandle);
1011 if (gpuCustom->isCube) throw Exception("drawMesh: custom texture must be two-dimensional");
1012 *slots[index] = gpuCustom;
1013 }
1014 }
1015 }
1016 vk::DescriptorSet set = mesh3dSetFor(
1017 gpuTex, gpuNormal, gpuEnv, gpuHeight, gpuDepth, gpuSceneColor, gpuDecalAlb, gpuDecalNrm, gpuDecalPrm, fslots,
1018 shader ? static_cast<GpuShader *>(shader->gpuHandle)->resourceFrameLayout : vk::DescriptorSetLayout{});
1019 const uint32_t dynOffsets[2] = {uboOffset, shadowOffset};
1020
1021 if (shader) {
1022 auto *gs = static_cast<GpuShader *>(shader->gpuHandle);
1023 vk::Pipeline activePipeline = offscreen3DPassOpen
1024 ? (offscreen3DHDRActive
1025 ? gs->mesh3dHdrOffscreenPipeline
1026 : gs->mesh3dOffscreenPipeline)
1027 : gs->mesh3dPipeline;
1028 if (shader->isXray() && !offscreen3DPassOpen) {
1029 // X-ray silhouette pass: depth test/write off + alpha blend so the
1030 // occluded part paints over the building. The pipeline is created
1031 // with the shader (see newMeshShaderFromSpv); do not compile it
1032 // here — a render pass is already open.
1033 activePipeline = gs->mesh3dXrayPipeline;
1034 }
1035 if (!activePipeline) return;
1036 if (activePipeline != lastMesh3dPipeline) {
1037 cb.bindPipeline(vk::PipelineBindPoint::eGraphics, activePipeline);
1038 lastMesh3dPipeline = activePipeline;
1039 }
1040 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, gs->pipelineLayout, 0, 1, &set, 2, dynOffsets);
1041 if (gs->resources)
1042 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, gs->pipelineLayout, 1, 1, &gs->resourceSet, 0,
1043 nullptr);
1044 cb.pushConstants(gs->pipelineLayout, vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment, 0,
1045 Shader::kPushConstantBytes, shader->pushConstantData());
1046 } else {
1047 const bool transparent = mesh3dSurfaceMode == SurfaceMode::Transparent;
1048 const BlendMode blend = transparent ? mesh3dSurfaceBlend : BlendMode::Opaque;
1049 const bool depthWrite = !transparent || mesh3dSurfaceDepthWrite;
1050 const size_t pipelineIndex =
1051 mesh3dPipelineIndex(blend, depthWrite, mesh3dSurfaceDoubleSided);
1052 const vk::Pipeline pipe = offscreen3DPassOpen
1053 ? (offscreen3DHDRActive
1054 ? hdrOffscreen3DSurfacePipelines[pipelineIndex]
1055 : offscreen3DSurfacePipelines[pipelineIndex])
1056 : mesh3dSurfacePipelines[pipelineIndex];
1057 if (pipe != lastMesh3dPipeline) {
1058 cb.bindPipeline(vk::PipelineBindPoint::eGraphics, pipe);
1059 lastMesh3dPipeline = pipe;
1060 }
1061 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, mesh3dPipelineLayout, 0, 1, &set, 2,
1062 dynOffsets);
1063 }
1064 drawIndexedMesh(cb, *gpuMesh, instanceCount, firstInstance);
1065}
1066
1067
1068} // namespace eve::graphics::vulkan
double y
double m[16]
double x
ActiveSource owned
const std::string & s
std::vector< std::uint32_t > verts
Definition Builder.cpp:27
float cx
Definition CardTypes.cpp:36
float uv
double raw
int rows
float linear
std::string message
std::uint32_t vertexCount
std::uint32_t indexCount
tensor::Graph g
Definition GpuGraph.cpp:7
vkb::Device & device
vk::ShaderModule vert
std::uint32_t firstInstance
std::uint32_t instanceCount
glm::vec4 tint
uint32_t i1
Definition Grass.cpp:61
uint32_t i2
Definition Grass.cpp:61
uint32_t i0
Definition Grass.cpp:61
float u
Definition Grass.cpp:233
std::vector< std::uint32_t > indices
std::vector< float > normals
std::vector< float > positions
float v
std::int32_t first
float blend
std::vector< Colorf > px
MeleePoint3 b
Definition MeleeHit.cpp:41
OceanMeshSettings mesh
std::shared_ptr< OceanGpuSpectrum > gpu
std::unique_ptr< gpgpu::GpuBuffer > buffer
Definition OnnxGpgpu.cpp:26
std::string error
Definition Package.cpp:174
Texture * texture
int idx
float f
PrimitiveHandle handle
float d
float t
std::string slot
Local-probe upload record kept off the high-fanout IGraphics3D header.
Shader * shader
glm::mat4 model
ScriptStructure out
std::string_view source
unsigned column
LocalPageCacheEntry slots[ShadowConfig::kLocalSlots]
Definition Shadow.cpp:159
int count
float weights[3]
float size
Definition TreeMesh.cpp:158
int caps
Definition TreeMesh.cpp:164
uint32_t index
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
virtual void clear(std::optional< Color > color, std::optional< int > stencil, std::optional< double > depth)=0
Clears .
virtual bool releaseMesh(Mesh *mesh)
Eagerly releases a mesh created by this Graphics.
Definition Graphics.h:935
virtual Mesh * newMeshCylinder(int slices=32, int stacks=1, bool caps=true)=0
Procedural Y-up cylinder (radius 1, height 2 centered at origin). slices = longitude divisions; stack...
virtual void drawMesh(Mesh *mesh, const glm::mat4 &model, Texture *texture, const Color &tint)=0
Draw one mesh with model matrix. Requires begin3DFrame() (or an open swapchain pass).
virtual Mesh * newMeshFromAssimp(const ::aiMesh &mesh)=0
Creates a mesh from assimp. @ownership Caller deletes unless documented otherwise.
virtual bool updateMeshVertices(Mesh *mesh, const float *posXYZ, const float *nrmXYZ, const float *uvST, int vertexCount, const uint32_t *indices, int indexCount)=0
In-place update of a mesh's vertex/index data (CPU -> host-visible VBO). Only call when content chang...
virtual Result< void > drawMeshInstances(Mesh &mesh, std::span< const glm::mat4 > models, OptionalRef< Texture > texture, const Color &tint)
Draw a batch of static meshes using the current ordinary material and lighting bindings.
Definition Graphics.h:1151
virtual Result< void > drawMeshShaderInstances(Mesh &mesh, Shader &shader, const glm::mat4 &model, const Color &tint, std::uint32_t first, std::uint32_t count)
Draw a checked range from a resource shader's immutable instance matrix buffer. @ownership Mesh and S...
Definition Graphics.h:1175
virtual bool setMeshSkinningData(Mesh *mesh, const uint16_t *joints4, const float *weights4, int vertexCount)
Upload four joint indices and weights per vertex for built-in GPU skinning.
Definition Graphics.h:890
virtual bool bakeMeshMorph(Mesh *mesh)=0
If mesh morph weights are dirty, bake blended positions and upload to the GPU VBO....
virtual Result< void > drawMeshResidentVertices(Mesh &mesh, const GpuResidentBufferView &source)
Draw a mesh using a producer-owned packed resident vertex stream. Stream ABI: 22 float words per vert...
Definition Graphics.h:1119
virtual void drawMeshShader(Mesh *mesh, const glm::mat4 &model, Texture *texture, const Color &tint, Shader *shader)=0
Draw mesh with an explicit Mesh3D Shader (nullptr = default PBR pipeline).
virtual Mesh * newMeshFromArrays(const float *posXYZ, const float *nrmXYZ, const float *uvST, int vertexCount, const uint32_t *indices, int indexCount)=0
Upload a triangle mesh from packed CPU arrays. Owned by Graphics. posXYZ required (vertexCount*3)....
virtual eve::Result< MeshBackendDescriptor > describeMesh(Mesh *mesh) const
Describe a live mesh created by this Graphics backend.
Definition Graphics.h:863
virtual Mesh * newMeshFromArraysColored(const float *posXYZ, const float *nrmXYZ, const float *uvST, const float *colorRGBA, int vertexCount, const uint32_t *indices, int indexCount)=0
Upload a triangle mesh with an optional packed RGBA color per vertex.
virtual Mesh * newMeshSphere(int slices=32, int stacks=16)=0
Procedural UV sphere (radius 1, Y-up). Owned by Graphics. slices = longitude divisions,...
GPU mesh handle (+ optional CPU morph targets).
Definition Mesh.h:26
void computeBounds(const float *posXYZ, int vertexCount)
Compute the bounding sphere (centroid + max radius) from positions.
Definition Mesh.cpp:108
Custom GPU program.
Definition Shader.h:41
static constexpr uint32_t kPushConstantBytes
Definition Shader.h:45
static constexpr std::size_t kMaxMeshTextures
Definition Shader.h:44
GPU texture created via Graphics::newTexture. Owns GPU resources through an opaque backend handle.
Definition Texture.h:15
Mesh * newMeshFromAssimp(const ::aiMesh &mesh) override
Creates a mesh from assimp. @ownership Caller deletes unless documented otherwise.
eve::Color Color
RGBA color used by every graphics draw call. Lives inside eve::graphics so including a graphics heade...
Definition Color.h:13
eve::BlendMode BlendMode
Compatibility alias for the shared 2D blend mode.
Definition BlendMode.h:8
std::optional< std::reference_wrapper< T > > OptionalRef
Optional borrowed reference; it does not extend T's lifetime.
Definition BorrowedRef.h:24
Transient backend buffer slice shared between sibling GPU modules. @ownership Non-owning; nativeHandl...
static constexpr int kMaxLights
Definition Light.h:172
Backend-owned layout facts for a mesh uploaded through Graphics.
Definition Graphics.h:92
GpuMesh public API.
Definition Graphics.h:298
std::vector< MeshVertex > updateVertices
Definition Graphics.h:311
MeshVertex public API.
Definition Graphics.h:148
glm::vec4 color