载入中...
搜索中...
未找到
GraphicsInternal.h
浏览该文件的文档.
1#pragma once
2
3// Shared implementation helpers for the Vulkan graphics backend.
4// Re-generated from the merged dev single-TU Graphics.cpp (pure move).
5// Anonymous namespace: each TU gets its own internal copy.
6
8#include "common/Exception.h"
10
11#include <algorithm>
12#include <cmath>
13#include <cstdint>
14#include <cstdio>
15#include <cstdlib>
16#include <cstring>
17#include <memory>
18#include <stdexcept>
19#include <string>
20#include <utility>
21#include <vector>
22#if !defined(_WIN32)
23#include <unistd.h>
24#endif
25
26namespace eve::graphics::vulkan {
27namespace {
28
29
30constexpr auto kHostVisibleCoherent = vk::MemoryPropertyFlagBits::eHostVisible |
31 vk::MemoryPropertyFlagBits::eHostCoherent;
32
33template <typename T, size_t N>
35std::vector<T> embeddedSpirv(const T (&words)[N]) {
36 return {words, words + N};
37}
38
39template <typename Slots>
41auto &currentSlot(Slots &slots, size_t slotCount, size_t slotIndex) {
42 if (slots.size() != slotCount) slots.resize(slotCount);
43 return slots[slotIndex];
44}
45
46template <typename FrameBuffers>
48void releaseFrame2dBuffers(FrameBuffers &buffers) {
49 for (auto &buffer : buffers.solidBufs) buffer.release();
50 buffers.solidBufs.clear();
51 for (auto &buffer : buffers.texBufs) buffer.release();
52 buffers.texBufs.clear();
53}
54
56void setViewportAndScissor(vk::CommandBuffer cb, uint32_t width, uint32_t height) {
57 const vk::Viewport viewport{0.f, 0.f, float(width), float(height), 0.f, 1.f};
58 const vk::Rect2D scissor{{0, 0}, {width, height}};
59 cb.setViewport(0, 1, &viewport);
60 cb.setScissor(0, 1, &scissor);
61}
62
64vk::PipelineLayout createPipelineLayout(vkb::Device &device,
65 vk::DescriptorSetLayout setLayout = {},
66 const vk::PushConstantRange *pushConstant = nullptr) {
67 vk::PipelineLayoutCreateInfo info{};
68 if (setLayout) {
69 info.setLayoutCount = 1;
70 info.pSetLayouts = &setLayout;
71 }
72 if (pushConstant) {
73 info.pushConstantRangeCount = 1;
74 info.pPushConstantRanges = pushConstant;
75 }
76 return device->createPipelineLayout(info);
77}
78
80vk::PushConstantRange pushConstantRange(vk::ShaderStageFlags stages, uint32_t size) {
81 vk::PushConstantRange range{};
82 range.stageFlags = stages;
83 range.size = size;
84 return range;
85}
86
88void destroySampler(vkb::Device &device, vk::Sampler &sampler) {
89 if (!sampler) return;
90 device->destroySampler(sampler);
91 sampler = vk::Sampler{};
92}
93
95void destroyPipeline(vkb::Device &device, vk::Pipeline &pipeline) {
96 if (!pipeline) return;
97 device->destroyPipeline(pipeline);
98 pipeline = vk::Pipeline{};
99}
100
102void destroyPipelineLayout(vkb::Device &device, vk::PipelineLayout &layout) {
103 if (!layout) return;
104 device->destroyPipelineLayout(layout);
105 layout = vk::PipelineLayout{};
106}
107
111vkb::HostVertexBuffer &meshDrawVertices(GpuMesh &mesh) {
112 if (!mesh.dynamic) return mesh.vertices;
113 const size_t slot = size_t((mesh.dynamicWriteCount - 1) % GpuMesh::kDynamicVertexCopies);
114 return mesh.dynVertices[slot];
115}
116
118vkb::GenericBuffer &meshDrawIndices(GpuMesh &mesh) {
119 if (!mesh.dynamic) return mesh.indices;
120 const size_t slot = size_t((mesh.dynamicWriteCount - 1) % GpuMesh::kDynamicVertexCopies);
121 return mesh.dynIndices[slot];
122}
123
125void drawIndexedMesh(vk::CommandBuffer cb, GpuMesh &mesh, uint32_t count = 1, uint32_t first = 0) {
126 const vk::DeviceSize offset = 0;
127 if (mesh.residentVertexOverride) {
128 cb.bindVertexBuffers(0, 1, &mesh.residentVertexOverride, &mesh.residentVertexOffset);
129 } else
130 cb.bindVertexBuffers(0, 1, meshDrawVertices(mesh), &offset);
131 cb.bindIndexBuffer(meshDrawIndices(mesh).buffer, 0, mesh.indexType);
132 cb.drawIndexed(mesh.indexCount, count, 0, 0, first);
133}
134
139void ensureDynamicRing(GpuMesh &gpu) {
140 if (gpu.dynamic) return;
141 gpu.dynamic = true;
142 gpu.dynamicWriteCount = 0;
143 gpu.cpuIndices.resize(gpu.indexCount);
144 if (gpu.indexCount > 0 && gpu.indices.buffer) {
145 void *ptr = gpu.indices.map();
146 if (gpu.indexType == vk::IndexType::eUint16) {
147 const auto *src = static_cast<const uint16_t *>(ptr);
148 for (uint32_t i = 0; i < gpu.indexCount; ++i)
149 gpu.cpuIndices[size_t(i)] = src[i];
150 } else {
152 std::memcpy(gpu.cpuIndices.data(), ptr,
154 size_t(gpu.indexCount) * sizeof(uint32_t));
155 }
156 gpu.indices.unmap();
157 }
158 gpu.indexType = vk::IndexType::eUint32;
159}
160
164void writeDynamicMesh(GpuMesh &gpu, const std::vector<MeshVertex> &verts, vkb::Device &device,
165 vkb::FrameSlot frame, const uint32_t *indices, int indexCount) {
166 const size_t slot = size_t(gpu.dynamicWriteCount % GpuMesh::kDynamicVertexCopies);
167 gpu.vertexCount = uint32_t(verts.size());
168 gpu.dynVertices[slot].allocate<MeshVertex>(frame, device, verts);
169 if (indices && indexCount > 0) {
170 gpu.cpuIndices.assign(indices, indices + indexCount);
171 gpu.indexCount = uint32_t(indexCount);
172 }
173 if (!gpu.cpuIndices.empty()) {
174 auto &ib = gpu.dynIndices[slot];
175 ib.allocate(frame, device, vk::BufferUsageFlagBits::eIndexBuffer,
177 vk::DeviceSize(gpu.cpuIndices.size()) * sizeof(uint32_t),
178 kHostVisibleCoherent);
179 ib.updateLocal(frame, gpu.cpuIndices.data(),
181 vk::DeviceSize(gpu.cpuIndices.size()) * sizeof(uint32_t));
182 }
183 ++gpu.dynamicWriteCount;
184}
185
187std::unique_ptr<GpuMesh> uploadGpuMesh(vkb::Device &device, vkb::FrameSlot frame,
188 const std::vector<MeshVertex> &vertices,
189 const std::vector<uint32_t> &indices) {
190 auto gpu = std::make_unique<GpuMesh>();
191 gpu->vertexCount = uint32_t(vertices.size());
192 gpu->vertices.allocate<MeshVertex>(frame, device, vertices);
193 gpu->indices.allocate(frame, device, vk::BufferUsageFlagBits::eIndexBuffer,
194 indices.size() * sizeof(uint32_t), kHostVisibleCoherent);
195 gpu->indices.updateLocal(frame, indices.data(), indices.size() * sizeof(uint32_t));
196 gpu->indexCount = uint32_t(indices.size());
197 return gpu;
198}
199
202std::unique_ptr<GpuMesh> uploadGpuMesh16(vkb::Device &device, vkb::FrameSlot frame,
203 const std::vector<MeshVertex> &vertices,
204 const std::vector<uint16_t> &indices) {
205 auto gpu = std::make_unique<GpuMesh>();
206 gpu->vertexCount = uint32_t(vertices.size());
207 gpu->vertices.allocate<MeshVertex>(frame, device, vertices);
208 gpu->indices.allocate(frame, device, vk::BufferUsageFlagBits::eIndexBuffer,
209 indices.size() * sizeof(uint16_t), kHostVisibleCoherent);
210 gpu->indices.updateLocal(frame, indices.data(), indices.size() * sizeof(uint16_t));
211 gpu->indexCount = uint32_t(indices.size());
212 gpu->indexType = vk::IndexType::eUint16;
213 return gpu;
214}
215
217std::unique_ptr<Mesh> makeMeshHandle(GpuMesh &gpu) {
218 auto mesh = std::make_unique<Mesh>();
219 mesh->indexCount = int(gpu.indexCount);
220 mesh->gpuVertexCount = int(gpu.vertexCount);
221 mesh->gpuHandle = &gpu;
222 return mesh;
223}
224
226void assignMeshBounds(Mesh *mesh, const std::vector<MeshVertex> &verts) {
227 if (!mesh) return;
228 std::vector<float> positions;
229 positions.reserve(verts.size() * 3);
230 for (const auto &v : verts) {
231 positions.push_back(v.pos.x);
232 positions.push_back(v.pos.y);
233 positions.push_back(v.pos.z);
234 }
235 mesh->computeBounds(positions.data(), static_cast<int>(verts.size()));
236}
237
240void updateRingLocal(vkb::GenericBuffer &ring, vk::DeviceSize byteOffset, const void *data,
241 vk::DeviceSize bytes) {
242 if (!ring.buffer || !data || bytes == 0) return;
243 void *ptr = ring.map();
245 std::memcpy(static_cast<char *>(ptr) + byteOffset, data, size_t(bytes));
246 ring.unmap();
247}
248
249template <typename T>
251inline T alignUpValue(T value, T align) {
252 return align > 0 ? (value + align - 1) / align * align : value;
253}
254
256vk::PipelineColorBlendAttachmentState makeBlendAttachment(BlendMode mode) {
257 vk::PipelineColorBlendAttachmentState att{};
258 att.colorWriteMask =
259 vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG |
260 vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA;
261 att.blendEnable = true;
262 if (mode == BlendMode::Additive) {
263 att.srcColorBlendFactor = vk::BlendFactor::eSrcAlpha;
264 att.dstColorBlendFactor = vk::BlendFactor::eOne;
265 att.colorBlendOp = vk::BlendOp::eAdd;
266 att.srcAlphaBlendFactor = vk::BlendFactor::eOne;
267 att.dstAlphaBlendFactor = vk::BlendFactor::eOne;
268 att.alphaBlendOp = vk::BlendOp::eAdd;
269 } else if (mode == BlendMode::Premultiplied) {
270 att.srcColorBlendFactor = vk::BlendFactor::eOne;
271 att.dstColorBlendFactor = vk::BlendFactor::eOneMinusSrcAlpha;
272 att.colorBlendOp = vk::BlendOp::eAdd;
273 att.srcAlphaBlendFactor = vk::BlendFactor::eOne;
274 att.dstAlphaBlendFactor = vk::BlendFactor::eOneMinusSrcAlpha;
275 att.alphaBlendOp = vk::BlendOp::eAdd;
276 } else if (mode == BlendMode::Multiply) {
277 att.srcColorBlendFactor = vk::BlendFactor::eDstColor;
278 att.dstColorBlendFactor = vk::BlendFactor::eOneMinusSrcAlpha;
279 att.colorBlendOp = vk::BlendOp::eAdd;
280 att.srcAlphaBlendFactor = vk::BlendFactor::eOne;
281 att.dstAlphaBlendFactor = vk::BlendFactor::eOneMinusSrcAlpha;
282 att.alphaBlendOp = vk::BlendOp::eAdd;
283 } else {
284 att.srcColorBlendFactor = vk::BlendFactor::eSrcAlpha;
285 att.dstColorBlendFactor = vk::BlendFactor::eOneMinusSrcAlpha;
286 att.colorBlendOp = vk::BlendOp::eAdd;
287 att.srcAlphaBlendFactor = vk::BlendFactor::eOne;
288 att.dstAlphaBlendFactor = vk::BlendFactor::eOneMinusSrcAlpha;
289 att.alphaBlendOp = vk::BlendOp::eAdd;
290 }
291 return att;
292}
293
295class ShaderModulePair {
296public:
298 ShaderModulePair(vkb::Device &device, const std::vector<uint32_t> &vert,
299 const std::vector<uint32_t> &frag)
301 : device(device),
303 vert(vkb::PipelineBuilder::createShaderModule(device.instance, vert)),
305 frag(vkb::PipelineBuilder::createShaderModule(device.instance, frag)) {}
306
308 ~ShaderModulePair() {
309 device->destroyShaderModule(vert);
310 device->destroyShaderModule(frag);
311 }
312
313 ShaderModulePair(const ShaderModulePair &) = delete;
314 ShaderModulePair &operator=(const ShaderModulePair &) = delete;
315
316 vkb::Device &device;
317 vk::ShaderModule vert;
318 vk::ShaderModule frag;
319};
320
321
322
324vk::Format pickGBufferColorFormat(vkb::Device &device) {
325 (void)device;
326 return vk::Format::eR8G8B8A8Unorm;
327}
328
330vk::SampleCountFlagBits sampleCountFlagFor(int samples) {
331 if (samples >= 8) return vk::SampleCountFlagBits::e8;
332 if (samples >= 4) return vk::SampleCountFlagBits::e4;
333 if (samples >= 2) return vk::SampleCountFlagBits::e2;
334 return vk::SampleCountFlagBits::e1;
335}
336
337
338
340uint32_t rgba8MipBytes(uint32_t width, uint32_t height) {
341 // Matches VKBuilder GenericImage::upload packing for eR8G8B8A8Unorm.
342 return 4u * width * height;
343}
344
346void appendBoxFilteredMip(std::vector<uint8_t> &out, const uint8_t *src, uint32_t srcW,
347 uint32_t srcH, uint32_t dstW, uint32_t dstH) {
348 const size_t base = out.size();
349 out.resize(base + size_t(rgba8MipBytes(dstW, dstH)));
350 uint8_t *dst = out.data() + base;
351 for (uint32_t y = 0; y < dstH; ++y) {
352 const uint32_t y0 = std::min(y * 2u, srcH - 1u);
353 const uint32_t y1 = std::min(y0 + 1u, srcH - 1u);
354 for (uint32_t x = 0; x < dstW; ++x) {
355 const uint32_t x0 = std::min(x * 2u, srcW - 1u);
356 const uint32_t x1 = std::min(x0 + 1u, srcW - 1u);
357 uint32_t acc[4] = {0, 0, 0, 0};
358 const uint32_t samples[4][2] = {{x0, y0}, {x1, y0}, {x0, y1}, {x1, y1}};
359 for (const auto &s : samples) {
360 const size_t i = (size_t(s[1]) * srcW + s[0]) * 4u;
361 acc[0] += src[i + 0];
362 acc[1] += src[i + 1];
363 acc[2] += src[i + 2];
364 acc[3] += src[i + 3];
365 }
366 const size_t o = (size_t(y) * dstW + x) * 4u;
367 dst[o + 0] = static_cast<uint8_t>((acc[0] + 2u) / 4u);
368 dst[o + 1] = static_cast<uint8_t>((acc[1] + 2u) / 4u);
369 dst[o + 2] = static_cast<uint8_t>((acc[2] + 2u) / 4u);
370 dst[o + 3] = static_cast<uint8_t>((acc[3] + 2u) / 4u);
371 }
372 }
373}
374
377std::vector<uint8_t> buildMipChain2D(const uint8_t *rgba, uint32_t width, uint32_t height,
378 uint32_t mipLevels) {
379 std::vector<uint8_t> packed;
380 packed.reserve(size_t(width) * size_t(height) * 4u * 2u);
381 packed.insert(packed.end(), rgba, rgba + size_t(rgba8MipBytes(width, height)));
382
383 uint32_t srcW = width;
384 uint32_t srcH = height;
385 size_t srcOffset = 0;
386 for (uint32_t level = 1; level < mipLevels; ++level) {
387 const uint32_t dstW = std::max(srcW >> 1, 1u);
388 const uint32_t dstH = std::max(srcH >> 1, 1u);
389 const uint8_t *src = packed.data() + srcOffset;
390 srcOffset = packed.size();
392 appendBoxFilteredMip(packed, src, srcW, srcH, dstW, dstH);
393 srcW = dstW;
394 srcH = dstH;
395 }
396 return packed;
397}
398
404std::vector<uint8_t> buildMipChainCube(const uint8_t *rgbaFaces, uint32_t faceSize,
405 uint32_t mipLevels) {
407 return eve::graphics::buildGgxCubemapMipChain(rgbaFaces, faceSize, mipLevels);
408}
409
411TextureCreateInfo normalizeTextureInfo(TextureCreateInfo info) {
412 if (info.generateMipmaps && info.sampler.mipmap == MipmapMode::Disabled)
413 info.sampler.mipmap = MipmapMode::Linear;
414 if (info.sampler.maxAnisotropy < 1.f) info.sampler.maxAnisotropy = 1.f;
415 return info;
416}
417
418
419
421std::string normalizeTexPath(std::string path) {
422 for (char &c : path) {
423 if (c == '\\') c = '/';
424 }
425 while (path.size() >= 2 && path[0] == '.' && path[1] == '/') path.erase(0, 2);
426 while (path.size() > 1 && path.back() == '/') path.pop_back();
427 return path;
428}
429
430} // namespace
431} // namespace eve::graphics::vulkan
double y
double x
const std::string & s
std::vector< std::uint32_t > verts
Definition Builder.cpp:27
std::string layout
std::uint32_t indexCount
vkb::Device & device
vk::ShaderModule vert
vk::ShaderModule frag
vk::UniqueSampler sampler
std::vector< std::uint32_t > indices
std::vector< float > positions
float v
std::int32_t c
std::int32_t first
std::uint32_t height
std::uint32_t width
void * ptr
size_t offset
Range range
std::uint64_t bytes
int level
OceanMeshSettings mesh
std::shared_ptr< OceanGpuSpectrum > gpu
ssq::Object frame
std::unique_ptr< gpgpu::GpuBuffer > buffer
Definition OnnxGpgpu.cpp:26
std::string path
Definition PlayHost.cpp:111
Object::Ptr value
std::string slot
ScriptStructure out
LocalPageCacheEntry slots[ShadowConfig::kLocalSlots]
Definition Shadow.cpp:159
int count
std::array< double, 2 > vertices[3]
float size
Definition TreeMesh.cpp:158
std::vector< uint8_t > buildGgxCubemapMipChain(const uint8_t *rgbaFaces, uint32_t faceSize, uint32_t mipLevels, uint32_t sampleCount=32u)
Build a mip-major RGBA8 IBL chain: GGX specular mips plus final diffuse irradiance.
eve::BlendMode BlendMode
Compatibility alias for the shared 2D blend mode.
Definition BlendMode.h:8
std::string pushConstant()
Pushes constant.
WidgetDesc viewport(std::string id, float width, float height)
Viewport.
Definition Widget.cpp:523
static constexpr size_t kDynamicVertexCopies
Ring copies for per-frame updated meshes (skin/morph/sprite stack). Writing the next copy never races...
Definition Graphics.h:303
glm::uvec4 info