17#include <glm/gtc/matrix_access.hpp>
22WGPUStringView
label(
const char*
s) {
25 out.length = WGPU_STRLEN;
29wgpu::ShaderModule shaderModule(wgpu::Device
device,
const char*
source) {
30 WGPUShaderSourceWGSL wgsl{};
31 wgsl.chain.sType = WGPUSType_ShaderSourceWGSL;
33 WGPUShaderModuleDescriptor
desc{};
34 desc.nextInChain = &wgsl.chain;
35 return device.CreateShaderModule(
reinterpret_cast<const wgpu::ShaderModuleDescriptor*
>(&
desc));
38wgpu::ShaderModule shaderModule(wgpu::Device
device,
const std::string&
source) {
39 WGPUShaderSourceWGSL wgsl{};
40 wgsl.chain.sType = WGPUSType_ShaderSourceWGSL;
41 wgsl.code.data =
source.data();
42 wgsl.code.length =
source.size();
43 WGPUShaderModuleDescriptor
desc{};
44 desc.nextInChain = &wgsl.chain;
45 return device.CreateShaderModule(
reinterpret_cast<const wgpu::ShaderModuleDescriptor*
>(&
desc));
58static_assert(
sizeof(CullInput) == 144);
61static_assert(
sizeof(VisibleInstance) == 208);
72static_assert(
sizeof(CullParams) == 240);
74struct VisIndirectCommand {
80static_assert(
sizeof(VisIndirectCommand) == 16);
82struct HzbBuildParams {
86static_assert(
sizeof(HzbBuildParams) == 32);
89constexpr uint32_t kHzbHeaderWords = 16;
91constexpr const char* kHzbBuildWgsl = R
"wgsl(
92struct BuildParams { info: vec4u, source: vec4u };
93@group(0) @binding(0) var<uniform> params: BuildParams;
94@group(0) @binding(1) var sourceDepth: texture_depth_2d;
95@group(0) @binding(2) var<storage, read_write> hzb: array<u32>;
97fn readHzb(base: u32, width: u32, height: u32, p: vec2i) -> f32 {
98 let q = clamp(p, vec2i(0), vec2i(i32(width) - 1, i32(height) - 1));
99 return bitcast<f32>(hzb[base + u32(q.y) * width + u32(q.x)]);
102@compute @workgroup_size(8, 8)
103fn cs_main(@builtin(global_invocation_id) gid: vec3u) {
104 let mip = params.info.x;
105 let width = params.info.y;
106 let height = params.info.z;
107 if (gid.x >= width || gid.y >= height) { return; }
110 depth = textureLoad(sourceDepth, vec2i(gid.xy), 0);
112 let previousWidth = params.source.x;
113 let previousHeight = params.source.y;
114 let previousBase = 16u + params.info.w;
115 let p = vec2i(gid.xy * 2u);
116 depth = max(readHzb(previousBase, previousWidth, previousHeight, p),
117 max(readHzb(previousBase, previousWidth, previousHeight, p + vec2i(1, 0)),
118 max(readHzb(previousBase, previousWidth, previousHeight, p + vec2i(0, 1)),
119 readHzb(previousBase, previousWidth, previousHeight, p + vec2i(1, 1)))));
121 let outputBase = 16u + hzb[mip];
122 hzb[outputBase + gid.y * width + gid.x] = bitcast<u32>(depth);
126constexpr const char* kCullWgsl = R
"wgsl(
132 terrainWaveTint: vec4f,
138struct VisibleInstance {
144 reflectionProbeSlots: vec4u,
145 reflectionProbeCenter: array<vec4f, 2>,
146 reflectionProbeExtent: array<vec4f, 2>,
149 terrainWaveTint: vec4f,
153 planes: array<vec4f, 6>,
160struct IndirectCommand {
162 instanceCount: atomic<u32>,
167struct VisIndirectCommand {
169 instanceCount: atomic<u32>,
173@group(0) @binding(0) var<uniform> params: CullParams;
174@group(0) @binding(1) var<storage, read> inputs: array<CullInput>;
175@group(0) @binding(2) var<storage, read_write> visibleInstances: array<VisibleInstance>;
176@group(0) @binding(3) var<storage, read_write> commands: array<IndirectCommand>;
177@group(0) @binding(4) var<storage, read_write> visCommands: array<VisIndirectCommand>;
178@group(0) @binding(5) var<storage, read> hzb: array<u32>;
180fn remainsVisibleAgainstDepth(center: vec3f, radius: f32) -> bool {
181 if (params.clipNearFar.w < 0.5) { return true; }
182 let clip = params.viewProj * vec4f(center, 1.0);
183 if (clip.w <= params.clipNearFar.x) { return true; }
184 let ndc = clip.xyz / clip.w;
185 if (abs(ndc.x) > 1.0 || abs(ndc.y) > 1.0 || ndc.z > 1.0) { return true; }
187 let toEye = normalize(params.cameraPos.xyz - center);
188 let frontClip = params.viewProj * vec4f(center + toEye * radius, 1.0);
189 let frontZ = frontClip.z / max(frontClip.w, 1e-6);
190 let viewDepth = max(length(center - params.cameraPos.xyz), 1e-4);
191 let radiusPx = radius * params.clipNearFar.z / viewDepth;
192 let diameterPx = max(radiusPx * 2.0, 1.0);
193 let mip = min(u32(ceil(log2(diameterPx))), u32(params.hzbInfo.x));
194 let width = max(u32(params.hzbInfo.z) >> mip, 1u);
195 let height = max(u32(params.hzbInfo.w) >> mip, 1u);
196 let uv = vec2f(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5);
197 let p0 = clamp(vec2i(uv * vec2f(f32(width), f32(height))) - vec2i(1),
198 vec2i(0), vec2i(i32(width) - 1, i32(height) - 1));
199 let p1 = min(p0 + vec2i(1), vec2i(i32(width) - 1, i32(height) - 1));
200 let base = 16u + hzb[mip];
201 let a = bitcast<f32>(hzb[base + u32(p0.y) * width + u32(p0.x)]);
202 let b = bitcast<f32>(hzb[base + u32(p0.y) * width + u32(p1.x)]);
203 let c = bitcast<f32>(hzb[base + u32(p1.y) * width + u32(p0.x)]);
204 let d = bitcast<f32>(hzb[base + u32(p1.y) * width + u32(p1.x)]);
205 let blocker = min(min(a, b), min(c, d));
206 // All conservative samples must contain geometry closer than the sphere.
207 // The epsilon prevents the object's own previous-frame depth from culling it.
208 return blocker >= 0.9999 || frontZ <= blocker + 0.002;
211@compute @workgroup_size(64)
212fn cs_main(@builtin(global_invocation_id) gid: vec3u) {
214 if (index >= params.counts.x) { return; }
215 let input = inputs[index];
216 let center = (input.model * vec4f(input.bounds.xyz, 1.0)).xyz;
217 let scale = max(length(input.model[0].xyz),
218 max(length(input.model[1].xyz), length(input.model[2].xyz)));
219 let radius = input.bounds.w * scale;
220 for (var p = 0u; p < 6u; p = p + 1u) {
221 let plane = params.planes[p];
222 if (dot(plane.xyz, center) + plane.w < -radius) { return; }
224 if (!remainsVisibleAgainstDepth(center, radius)) { return; }
225 let local = atomicAdd(&commands[input.bucket].instanceCount, 1u);
226 atomicAdd(&visCommands[input.bucket].instanceCount, 1u);
227 var visible: VisibleInstance;
228 visible.model = input.model;
230 visible.materialId = 0u;
232 visible.lodGroupId = 0u;
233 visible.reflectionProbeSlots = vec4u(0u);
234 visible.reflectionProbeCenter[0] = vec4f(0.0);
235 visible.reflectionProbeCenter[1] = vec4f(0.0);
236 visible.reflectionProbeExtent[0] = vec4f(0.0);
237 visible.reflectionProbeExtent[1] = vec4f(0.0);
238 visible.color = input.color;
239 visible.terrainWave = input.terrainWave;
240 visible.terrainWaveTint = input.terrainWaveTint;
241 visibleInstances[input.outputBase + local] = visible;
245constexpr const char* kGpuDrivenVertWgsl = R
"wgsl(
246struct Light3D { posRadius: vec4f, color: vec4f };
255 lights: array<Light3D, 8>,
265 @location(0) pos: vec3f,
266 @location(1) normal: vec3f,
267 @location(2) uv: vec2f,
270 @builtin(position) pos: vec4f,
271 @location(0) vNormal: vec3f,
272 @location(1) vUV: vec2f,
273 @location(2) vTint: vec4f,
274 @location(3) vWorldPos: vec3f,
275 @location(4) vCameraPos: vec3f,
276 @location(5) vViewPos: vec3f,
278@group(0) @binding(0) var<uniform> ubo: Frame;
279struct VisibleInstance {
285 reflectionProbeSlots: vec4u,
286 reflectionProbeCenter: array<vec4f, 2>,
287 reflectionProbeExtent: array<vec4f, 2>,
290 terrainWaveTint: vec4f,
292@group(1) @binding(0) var<storage, read> visibleInstances: array<VisibleInstance>;
294fn inverse3x3(m: mat3x3f) -> mat3x3f {
295 let a = m[0].x; let b = m[1].x; let c = m[2].x;
296 let d = m[0].y; let e = m[1].y; let f = m[2].y;
297 let g = m[0].z; let h = m[1].z; let i = m[2].z;
298 let det = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g);
300 vec3f((e * i - f * h) / det, (f * g - d * i) / det, (d * h - e * g) / det),
301 vec3f((c * h - b * i) / det, (a * i - c * g) / det, (b * g - a * h) / det),
302 vec3f((b * f - c * e) / det, (c * d - a * f) / det, (a * e - b * d) / det));
305fn terrainFastSinCos(value: vec4f) -> vec4f {
306 var x = fract(value * 0.15915494309189535);
309 let sine = x * (7.61 - 35.2 * x2) / (1.0 + x2 * (11.2 + 3.6 * x2));
313fn terrainDetailWave(worldPosition: ptr<function, vec3f>, heightMask: f32,
314 terrainWave: vec4f, terrainWaveTint: vec4f) -> vec3f {
315 if (terrainWave.w < 0.5) { return vec3f(1.0); }
316 let waveXSize = vec4f(0.012, 0.02, 0.06, 0.024) * terrainWave.y;
317 let waveZSize = vec4f(0.006, 0.02, 0.02, 0.05) * terrainWave.y;
318 var waves = (*worldPosition).x * waveXSize + (*worldPosition).z * waveZSize;
319 waves += terrainWave.x * vec4f(0.3, 0.5, 0.4, 1.2) * 4.0;
320 waves = terrainFastSinCos(waves);
321 let lighting = dot(waves, vec4f(0.6742, 0.6742, 0.2697, 0.1349)) * 0.7;
322 let displacement = vec2f(dot(waves, vec4f(0.024, 0.04, -0.12, 0.096)),
323 dot(waves, vec4f(0.006, 0.02, -0.02, 0.1))) * heightMask;
324 let offset = displacement * terrainWave.z;
325 *worldPosition = vec3f((*worldPosition).x - offset.x, (*worldPosition).y,
326 (*worldPosition).z - offset.y);
327 return 2.0 * mix(vec3f(0.5), terrainWaveTint.rgb, vec3f(lighting));
331fn vs_main(in: VSIn, @builtin(instance_index) instanceIndex: u32) -> VSOut {
332 let sourceModel = visibleInstances[instanceIndex].model;
333 let instanceColor = visibleInstances[instanceIndex].color;
334 let terrainWave = visibleInstances[instanceIndex].terrainWave;
335 let terrainWaveTint = visibleInstances[instanceIndex].terrainWaveTint;
336 var model = sourceModel;
337 if (ubo.surface.w > 0.5) {
338 let origin = sourceModel[3].xyz;
339 var forward = vec3f(ubo.cameraPos.x - origin.x, 0.0, ubo.cameraPos.z - origin.z);
340 forward = select(vec3f(0, 0, 1), normalize(forward), length(forward) > 1e-6);
341 let right = vec3f(forward.z, 0, -forward.x);
342 model = mat4x4f(vec4f(right * length(sourceModel[0].xyz), 0),
343 vec4f(0, length(sourceModel[1].xyz), 0, 0),
344 vec4f(forward * length(sourceModel[2].xyz), 0), sourceModel[3]);
346 var worldPosition = (model * vec4f(in.pos, 1.0)).xyz;
347 let waveTint = terrainDetailWave(&worldPosition, in.uv.y, terrainWave, terrainWaveTint);
348 let world = vec4f(worldPosition, 1.0);
350 out.pos = ubo.mvp * world;
351 out.pos.y = -out.pos.y;
352 out.vWorldPos = world.xyz;
353 out.vViewPos = (ubo.view * world).xyz;
354 let normalMatrix = transpose(inverse3x3(mat3x3f(model[0].xyz, model[1].xyz,
356 out.vNormal = normalize(normalMatrix * in.normal);
358 out.vTint = ubo.tint * instanceColor * vec4f(waveTint, 1.0);
359 out.vCameraPos = ubo.cameraPos.xyz;
374 auto found = gpuDrivenMeshIds_.find(
mesh);
375 if (
found != gpuDrivenMeshIds_.end())
return found->second;
376 const uint32_t
id =
static_cast<uint32_t
>(gpuDrivenMeshes_.size());
377 gpuDrivenMeshes_.push_back(
mesh);
378 gpuDrivenMeshIds_.emplace(
mesh,
id);
385 if (
found != gpuDrivenMaterialIds_.end())
return found->second;
387 if (!gpuDrivenMaterialFree_.empty()) {
388 id = gpuDrivenMaterialFree_.back();
389 gpuDrivenMaterialFree_.pop_back();
392 id =
static_cast<uint32_t
>(gpuDrivenMaterials_.size());
393 gpuDrivenMaterials_.push_back(
material);
395 gpuDrivenMaterialIds_.emplace(
material,
id);
410 "cannot release a null GPU-driven material"));
414 gpuDrivenMaterialIds_.erase(
found);
415 gpuDrivenMaterials_[
slot] =
nullptr;
416 gpuDrivenMaterialFree_.push_back(
slot);
421 if (!gpuDrivenEnabled_ || !
device || gpuDrivenComputePending_ || gpuDrivenDrawPending_ || !instances ||
424 using BucketKey = std::pair<uint32_t, uint32_t>;
425 std::map<BucketKey, std::vector<const GpuInstance*>> grouped;
428 if (instance.
meshId >= gpuDrivenMeshes_.size() || instance.
materialId >= gpuDrivenMaterials_.size())
437 grouped.begin(), grouped.end(), 0
u, [](uint32_t
count,
const auto& entry) {
438 return count + ((static_cast<uint32_t>(entry.second.size()) + 15u) & ~uint32_t(15u));
440 ensureGpuDrivenResources(
paddedCount,
static_cast<uint32_t
>(grouped.size()));
441 if (!gpuDrivenRenderPipeline_ || !gpuDrivenVisibleBuffer_ || !gpuDrivenIndirectBuffer_)
return false;
444 std::vector<GpuIndirectCommand>
commands;
446 gpuDrivenBuckets_.clear();
448 for (
const auto& [
key, bucketInstances] : grouped) {
453 if (!bound)
throw Exception(
"%s", bound.error()->message().c_str());
456 command.instanceCount =
static_cast<uint32_t
>(bucketInstances.size());
458 gpuDrivenBuckets_.push_back(
460 for (uint32_t i = 0; i < bucketInstances.size(); ++i) {
464 outputBase += (
static_cast<uint32_t
>(bucketInstances.size()) + 15u) & ~uint32_t(15u);
466 queue.WriteBuffer(gpuDrivenVisibleBuffer_, 0,
visible.data(),
visible.size() *
sizeof(VisibleInstance));
468 gpuDrivenDrawPending_ =
true;
469 frameHad3DThisFrame =
true;
475 if (!gpuDrivenEnabled_ || !
device || gpuDrivenComputePending_ || gpuDrivenDrawPending_)
483 if (required < batch.buffer.offsetBytes || required > batch.
buffer.
sizeBytes)
487 std::vector<GpuDrivenBucket> buckets(batch.
bucketCount);
488 uint64_t coveredInstances = 0;
493 bucket.meshId >= gpuDrivenMeshes_.size() ||
bucket.materialId >= gpuDrivenMaterials_.size())
502 coveredInstances =
end;
507 if (!gpuDrivenResidentRenderPipeline_ || !gpuDrivenIndirectBuffer_)
510 WGPUBuffer rawBuffer{};
514 gpuDrivenBuckets_ = std::move(buckets);
515 gpuDrivenResidentBuffer_ = rawBuffer;
518 gpuDrivenResidentDrawPending_ =
true;
519 gpuDrivenDrawPending_ =
true;
520 frameHad3DThisFrame =
true;
525void Graphics::ensureGpuDrivenResources(uint32_t
instanceCount, uint32_t bucketCount) {
526 if (!gpuDrivenCullPipeline_) {
527 WGPUBindGroupLayoutEntry computeEntries[6]{};
528 computeEntries[0].binding = 0;
529 computeEntries[0].visibility = WGPUShaderStage_Compute;
530 computeEntries[0].buffer.type = WGPUBufferBindingType_Uniform;
531 computeEntries[0].buffer.minBindingSize =
sizeof(CullParams);
532 for (uint32_t i = 1; i < 5; ++i) {
533 computeEntries[i].binding = i;
534 computeEntries[i].visibility = WGPUShaderStage_Compute;
535 computeEntries[i].buffer.type =
536 i == 1 ? WGPUBufferBindingType_ReadOnlyStorage : WGPUBufferBindingType_Storage;
538 computeEntries[1].buffer.minBindingSize =
sizeof(CullInput);
539 computeEntries[2].buffer.minBindingSize =
sizeof(VisibleInstance);
540 computeEntries[3].buffer.minBindingSize =
sizeof(uint32_t) * 5;
541 computeEntries[4].buffer.minBindingSize =
sizeof(VisIndirectCommand);
542 WGPUBindGroupLayoutDescriptor cbgl{};
543 cbgl.label =
label(
"eve_gpu_driven_compute_bgl");
544 computeEntries[5].binding = 5;
545 computeEntries[5].visibility = WGPUShaderStage_Compute;
546 computeEntries[5].buffer.type = WGPUBufferBindingType_ReadOnlyStorage;
548 cbgl.entries = computeEntries;
549 gpuDrivenComputeSetLayout_ =
550 device.CreateBindGroupLayout(
reinterpret_cast<const wgpu::BindGroupLayoutDescriptor*
>(&cbgl));
552 WGPUBindGroupLayoutEntry renderEntry{};
553 renderEntry.binding = 0;
554 renderEntry.visibility = WGPUShaderStage_Vertex;
555 renderEntry.buffer.type = WGPUBufferBindingType_ReadOnlyStorage;
556 renderEntry.buffer.minBindingSize =
sizeof(VisibleInstance);
557 WGPUBindGroupLayoutDescriptor rbgl{};
558 rbgl.label =
label(
"eve_gpu_driven_render_bgl");
560 rbgl.entries = &renderEntry;
561 gpuDrivenRenderSetLayout_ =
562 device.CreateBindGroupLayout(
reinterpret_cast<const wgpu::BindGroupLayoutDescriptor*
>(&rbgl));
564 WGPUBindGroupLayout computeLayout = gpuDrivenComputeSetLayout_.Get();
565 WGPUPipelineLayoutDescriptor cpl{};
566 cpl.label =
label(
"eve_gpu_driven_compute_layout");
567 cpl.bindGroupLayoutCount = 1;
568 cpl.bindGroupLayouts = &computeLayout;
569 gpuDrivenComputePipelineLayout_ =
570 device.CreatePipelineLayout(
reinterpret_cast<const wgpu::PipelineLayoutDescriptor*
>(&cpl));
572 WGPUBindGroupLayout renderLayouts[2] = {mesh3dSetLayout.Get(), gpuDrivenRenderSetLayout_.Get()};
573 WGPUPipelineLayoutDescriptor rpl{};
574 rpl.label =
label(
"eve_gpu_driven_render_layout");
575 rpl.bindGroupLayoutCount = 2;
576 rpl.bindGroupLayouts = renderLayouts;
577 gpuDrivenRenderPipelineLayout_ =
578 device.CreatePipelineLayout(
reinterpret_cast<const wgpu::PipelineLayoutDescriptor*
>(&rpl));
580 wgpu::ShaderModule cullModule = shaderModule(device, kCullWgsl);
581 WGPUComputePipelineDescriptor cpd{};
582 cpd.label =
label(
"eve_gpu_driven_cull");
583 cpd.layout = gpuDrivenComputePipelineLayout_.Get();
584 cpd.compute.module = cullModule.Get();
585 cpd.compute.entryPoint =
label(
"cs_main");
586 gpuDrivenCullPipeline_ =
587 device.CreateComputePipeline(
reinterpret_cast<const wgpu::ComputePipelineDescriptor*
>(&cpd));
589 WGPUBindGroupLayoutEntry hzbEntries[3]{};
590 hzbEntries[0].binding = 0;
591 hzbEntries[0].visibility = WGPUShaderStage_Compute;
592 hzbEntries[0].buffer.type = WGPUBufferBindingType_Uniform;
593 hzbEntries[0].buffer.hasDynamicOffset =
true;
594 hzbEntries[0].buffer.minBindingSize =
sizeof(HzbBuildParams);
595 hzbEntries[1].binding = 1;
596 hzbEntries[1].visibility = WGPUShaderStage_Compute;
597 hzbEntries[1].texture.sampleType = WGPUTextureSampleType_Depth;
598 hzbEntries[1].texture.viewDimension = WGPUTextureViewDimension_2D;
599 hzbEntries[2].binding = 2;
600 hzbEntries[2].visibility = WGPUShaderStage_Compute;
601 hzbEntries[2].buffer.type = WGPUBufferBindingType_Storage;
602 WGPUBindGroupLayoutDescriptor hzbBgl{};
603 hzbBgl.label =
label(
"eve_gpu_driven_hzb_bgl");
604 hzbBgl.entryCount = 3;
605 hzbBgl.entries = hzbEntries;
606 gpuDrivenHzbSetLayout_ =
607 device.CreateBindGroupLayout(
reinterpret_cast<const wgpu::BindGroupLayoutDescriptor*
>(&hzbBgl));
608 WGPUBindGroupLayout hzbLayout = gpuDrivenHzbSetLayout_.Get();
609 WGPUPipelineLayoutDescriptor hzbPl{};
610 hzbPl.bindGroupLayoutCount = 1;
611 hzbPl.bindGroupLayouts = &hzbLayout;
612 gpuDrivenHzbPipelineLayout_ =
613 device.CreatePipelineLayout(
reinterpret_cast<const wgpu::PipelineLayoutDescriptor*
>(&hzbPl));
614 wgpu::ShaderModule hzbModule = shaderModule(device, kHzbBuildWgsl);
615 WGPUComputePipelineDescriptor hzbPd{};
616 hzbPd.label =
label(
"eve_gpu_driven_hzb_build");
617 hzbPd.layout = gpuDrivenHzbPipelineLayout_.Get();
618 hzbPd.compute.module = hzbModule.Get();
619 hzbPd.compute.entryPoint =
label(
"cs_main");
620 gpuDrivenHzbPipeline_ =
621 device.CreateComputePipeline(
reinterpret_cast<const wgpu::ComputePipelineDescriptor*
>(&hzbPd));
623 WGPUVertexAttribute
attrs[3]{};
624 attrs[0].format = WGPUVertexFormat_Float32x3;
626 attrs[0].shaderLocation = 0;
627 attrs[1].format = WGPUVertexFormat_Float32x3;
628 attrs[1].offset = 12;
629 attrs[1].shaderLocation = 1;
630 attrs[2].format = WGPUVertexFormat_Float32x2;
631 attrs[2].offset = 24;
632 attrs[2].shaderLocation = 2;
633 WGPUVertexBufferLayout vb{};
635 vb.stepMode = WGPUVertexStepMode_Vertex;
636 vb.attributeCount = 3;
637 vb.attributes =
attrs;
638 WGPUDepthStencilState
depth{};
639 depth.format = WGPUTextureFormat_Depth32Float;
640 depth.depthWriteEnabled = WGPUOptionalBool_True;
641 depth.depthCompare = WGPUCompareFunction_Less;
642 WGPUColorTargetState
target{};
643 target.format = sceneColorFormat;
644 target.writeMask = WGPUColorWriteMask_All;
645 wgpu::ShaderModule vertModule = shaderModule(device, kGpuDrivenVertWgsl);
646 std::string residentVertSource = kGpuDrivenVertWgsl;
647 const std::string modelsDecl =
648 "struct VisibleInstance {\n"
651 " materialId: u32,\n"
653 " lodGroupId: u32,\n"
654 " reflectionProbeSlots: vec4u,\n"
655 " reflectionProbeCenter: array<vec4f, 2>,\n"
656 " reflectionProbeExtent: array<vec4f, 2>,\n"
658 " terrainWave: vec4f,\n"
659 " terrainWaveTint: vec4f,\n"
661 "@group(1) @binding(0) var<storage, read> visibleInstances: array<VisibleInstance>;";
662 const std::string residentDecl =
663 "struct ResidentInstance { model: mat4x4f, meshId: u32, materialId: u32, "
664 "flags: u32, lodGroupId: u32, reflectionProbeSlots: vec4u, "
665 "reflectionProbeCenter: array<vec4f, 2>, reflectionProbeExtent: array<vec4f, 2>, color: vec4f, "
666 "terrainWave: vec4f, terrainWaveTint: vec4f };\n"
667 "@group(1) @binding(0) var<storage, read> residentInstances: "
668 "array<ResidentInstance>;";
669 residentVertSource.replace(residentVertSource.find(modelsDecl), modelsDecl.size(), residentDecl);
670 const std::string modelRead =
671 "let sourceModel = visibleInstances[instanceIndex].model;\n"
672 " let instanceColor = visibleInstances[instanceIndex].color;\n"
673 " let terrainWave = visibleInstances[instanceIndex].terrainWave;\n"
674 " let terrainWaveTint = visibleInstances[instanceIndex].terrainWaveTint;";
675 residentVertSource.replace(residentVertSource.find(modelRead), modelRead.size(),
676 "let sourceModel = residentInstances[instanceIndex].model;\n"
677 " let instanceColor = residentInstances[instanceIndex].color;\n"
678 " let terrainWave = residentInstances[instanceIndex].terrainWave;\n"
679 " let terrainWaveTint = residentInstances[instanceIndex].terrainWaveTint;");
680 wgpu::ShaderModule residentVertModule = shaderModule(device, residentVertSource);
682 WGPUFragmentState fs{};
683 fs.module = fragModule.Get();
684 fs.entryPoint =
label(
"fs_main");
687 WGPURenderPipelineDescriptor rpd{};
688 rpd.label =
label(
"eve_gpu_driven_render");
689 rpd.layout = gpuDrivenRenderPipelineLayout_.Get();
690 rpd.vertex.module = vertModule.Get();
691 rpd.vertex.entryPoint =
label(
"vs_main");
692 rpd.vertex.bufferCount = 1;
693 rpd.vertex.buffers = &vb;
695 rpd.primitive.topology = WGPUPrimitiveTopology_TriangleList;
696 rpd.primitive.frontFace = WGPUFrontFace_CW;
697 rpd.primitive.cullMode = WGPUCullMode_None;
698 rpd.depthStencil = &
depth;
699 rpd.multisample.count = sceneColorSamples;
700 rpd.multisample.mask = 0xFFFFFFFFu;
701 gpuDrivenRenderPipeline_ =
702 device.CreateRenderPipeline(
reinterpret_cast<const wgpu::RenderPipelineDescriptor*
>(&rpd));
703 rpd.label =
label(
"eve_gpu_driven_resident_render");
704 rpd.vertex.module = residentVertModule.Get();
705 gpuDrivenResidentRenderPipeline_ =
706 device.CreateRenderPipeline(
reinterpret_cast<const wgpu::RenderPipelineDescriptor*
>(&rpd));
707 rpd.label =
label(
"eve_gpu_driven_canvas");
708 rpd.vertex.module = vertModule.Get();
709 target.format = WGPUTextureFormat_RGBA8Unorm;
710 rpd.multisample.count = 1;
711 gpuDrivenCanvasPipeline_ =
712 device.CreateRenderPipeline(
reinterpret_cast<const wgpu::RenderPipelineDescriptor*
>(&rpd));
713 rpd.label =
label(
"eve_gpu_driven_resident_canvas");
714 rpd.vertex.module = residentVertModule.Get();
715 gpuDrivenResidentCanvasPipeline_ =
716 device.CreateRenderPipeline(
reinterpret_cast<const wgpu::RenderPipelineDescriptor*
>(&rpd));
717 rpd.label =
label(
"eve_gpu_driven_hdr_canvas");
718 rpd.vertex.module = vertModule.Get();
719 target.format = WGPUTextureFormat_RGBA16Float;
720 gpuDrivenHdrCanvasPipeline_ =
721 device.CreateRenderPipeline(
reinterpret_cast<const wgpu::RenderPipelineDescriptor*
>(&rpd));
722 rpd.label =
label(
"eve_gpu_driven_resident_hdr_canvas");
723 rpd.vertex.module = residentVertModule.Get();
724 gpuDrivenResidentHdrCanvasPipeline_ =
725 device.CreateRenderPipeline(
reinterpret_cast<const wgpu::RenderPipelineDescriptor*
>(&rpd));
727 WGPUBufferDescriptor pbd{};
728 pbd.label =
label(
"eve_gpu_driven_params");
729 pbd.size =
sizeof(CullParams);
730 pbd.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Uniform;
731 gpuDrivenParamsBuffer_ =
device.CreateBuffer(
reinterpret_cast<const wgpu::BufferDescriptor*
>(&pbd));
732 pbd.label =
label(
"eve_gpu_driven_hzb_params");
734 gpuDrivenHzbParamsBuffer_ =
device.CreateBuffer(
reinterpret_cast<const wgpu::BufferDescriptor*
>(&pbd));
737 bool recreateGroups =
false;
738 const uint32_t hzbWidth = std::max(gbufferWidth, 1);
739 const uint32_t hzbHeight = std::max(gbufferHeight, 1);
740 if (!gpuDrivenHzbBuffer_ || gpuDrivenHzbWidth_ != hzbWidth || gpuDrivenHzbHeight_ != hzbHeight) {
741 gpuDrivenHzbWidth_ = hzbWidth;
742 gpuDrivenHzbHeight_ = hzbHeight;
743 gpuDrivenHzbOffsets_.clear();
744 uint32_t words = kHzbHeaderWords;
745 for (uint32_t
w = hzbWidth,
h = hzbHeight; gpuDrivenHzbOffsets_.size() < kMaxHzbMips;
746 w = std::max(
w >> 1u, 1u),
h = std::max(
h >> 1u, 1u)) {
747 gpuDrivenHzbOffsets_.push_back(words - kHzbHeaderWords);
749 if (
w == 1 &&
h == 1)
break;
751 WGPUBufferDescriptor hzbBd{};
752 hzbBd.label =
label(
"eve_gpu_driven_hzb");
753 hzbBd.size = uint64_t(words) *
sizeof(uint32_t);
754 gpuDrivenHzbCapacity_ = hzbBd.size;
755 hzbBd.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Storage;
756 gpuDrivenHzbBuffer_ =
device.CreateBuffer(
reinterpret_cast<const wgpu::BufferDescriptor*
>(&hzbBd));
757 queue.WriteBuffer(gpuDrivenHzbBuffer_, 0, gpuDrivenHzbOffsets_.data(),
758 gpuDrivenHzbOffsets_.size() *
sizeof(uint32_t));
759 recreateGroups =
true;
762 const uint64_t inputBytes = uint64_t(
instanceCount) *
sizeof(CullInput);
763 if (!gpuDrivenInputBuffer_ || gpuDrivenInputCapacity_ < inputBytes) {
764 gpuDrivenInputCapacity_ = grownCapacity(gpuDrivenInputCapacity_, inputBytes);
765 WGPUBufferDescriptor bd{};
766 bd.label =
label(
"eve_gpu_driven_inputs");
767 bd.size = gpuDrivenInputCapacity_;
768 bd.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Storage;
769 gpuDrivenInputBuffer_ =
device.CreateBuffer(
reinterpret_cast<const wgpu::BufferDescriptor*
>(&bd));
770 recreateGroups =
true;
772 const uint64_t visibleBytes = uint64_t(
instanceCount) *
sizeof(VisibleInstance);
773 if (!gpuDrivenVisibleBuffer_ || gpuDrivenVisibleCapacity_ < visibleBytes) {
774 gpuDrivenVisibleCapacity_ = grownCapacity(gpuDrivenVisibleCapacity_, visibleBytes);
775 WGPUBufferDescriptor bd{};
776 bd.label =
label(
"eve_gpu_driven_visible");
777 bd.size = gpuDrivenVisibleCapacity_;
778 bd.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Storage;
779 gpuDrivenVisibleBuffer_ =
device.CreateBuffer(
reinterpret_cast<const wgpu::BufferDescriptor*
>(&bd));
780 recreateGroups =
true;
783 if (!gpuDrivenIndirectBuffer_ || gpuDrivenIndirectCapacity_ < indirectBytes) {
784 gpuDrivenIndirectCapacity_ = grownCapacity(gpuDrivenIndirectCapacity_, indirectBytes);
785 WGPUBufferDescriptor bd{};
786 bd.label =
label(
"eve_gpu_driven_indirect");
787 bd.size = gpuDrivenIndirectCapacity_;
789 WGPUBufferUsage_CopyDst | WGPUBufferUsage_CopySrc | WGPUBufferUsage_Storage | WGPUBufferUsage_Indirect;
790 gpuDrivenIndirectBuffer_ =
device.CreateBuffer(
reinterpret_cast<const wgpu::BufferDescriptor*
>(&bd));
791 recreateGroups =
true;
793 const uint64_t visIndirectBytes = uint64_t(bucketCount) *
sizeof(VisIndirectCommand);
794 if (!gpuDrivenVisIndirectBuffer_ || gpuDrivenVisIndirectCapacity_ < visIndirectBytes) {
795 gpuDrivenVisIndirectCapacity_ = grownCapacity(gpuDrivenVisIndirectCapacity_, visIndirectBytes);
796 WGPUBufferDescriptor bd{};
797 bd.label =
label(
"eve_gpu_driven_vis_indirect");
798 bd.size = gpuDrivenVisIndirectCapacity_;
799 bd.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Storage | WGPUBufferUsage_Indirect;
800 gpuDrivenVisIndirectBuffer_ =
device.CreateBuffer(
reinterpret_cast<const wgpu::BufferDescriptor*
>(&bd));
801 recreateGroups =
true;
805 recreateGroups =
true;
806 if (recreateGroups || !gpuDrivenComputeBindGroup_) {
807 WGPUBindGroupEntry
entries[6]{};
809 entries[0].buffer = gpuDrivenParamsBuffer_.Get();
810 entries[0].size =
sizeof(CullParams);
812 entries[1].buffer = gpuDrivenInputBuffer_.Get();
813 entries[1].size = gpuDrivenInputCapacity_;
815 entries[2].buffer = gpuDrivenVisibleBuffer_.Get();
816 entries[2].size = gpuDrivenVisibleCapacity_;
818 entries[3].buffer = gpuDrivenIndirectBuffer_.Get();
819 entries[3].size = gpuDrivenIndirectCapacity_;
821 entries[4].buffer = gpuDrivenVisIndirectBuffer_.Get();
822 entries[4].size = gpuDrivenVisIndirectCapacity_;
824 const uint32_t depthSlot = gbufferDepthValid_ ? lastGbufferSlot : currentFrameSlot();
825 entries[5].buffer = gpuDrivenHzbBuffer_.Get();
826 entries[5].size = gpuDrivenHzbCapacity_;
827 WGPUBindGroupDescriptor bgd{};
828 bgd.label =
label(
"eve_gpu_driven_compute_bg");
829 bgd.layout = gpuDrivenComputeSetLayout_.Get();
832 gpuDrivenComputeBindGroup_ =
device.CreateBindGroup(
reinterpret_cast<const wgpu::BindGroupDescriptor*
>(&bgd));
834 WGPUBindGroupEntry renderEntry{};
835 renderEntry.binding = 0;
836 renderEntry.buffer = gpuDrivenVisibleBuffer_.Get();
837 renderEntry.size = gpuDrivenVisibleCapacity_;
838 WGPUBindGroupDescriptor rbgd{};
839 rbgd.label =
label(
"eve_gpu_driven_render_bg");
840 rbgd.layout = gpuDrivenRenderSetLayout_.Get();
842 rbgd.entries = &renderEntry;
843 gpuDrivenRenderBindGroup_ =
device.CreateBindGroup(
reinterpret_cast<const wgpu::BindGroupDescriptor*
>(&rbgd));
845 WGPUBindGroupEntry hzbEntries[3]{};
846 hzbEntries[0].binding = 0;
847 hzbEntries[0].buffer = gpuDrivenHzbParamsBuffer_.Get();
848 hzbEntries[0].size =
sizeof(HzbBuildParams);
849 hzbEntries[1].binding = 1;
850 hzbEntries[1].textureView = gbufferSlots[depthSlot].depthView.Get();
851 hzbEntries[2].binding = 2;
852 hzbEntries[2].buffer = gpuDrivenHzbBuffer_.Get();
853 hzbEntries[2].size = gpuDrivenHzbCapacity_;
854 WGPUBindGroupDescriptor hzbBg{};
855 hzbBg.label =
label(
"eve_gpu_driven_hzb_bg");
856 hzbBg.layout = gpuDrivenHzbSetLayout_.Get();
857 hzbBg.entryCount = 3;
858 hzbBg.entries = hzbEntries;
859 gpuDrivenHzbBindGroup_ =
device.CreateBindGroup(
reinterpret_cast<const wgpu::BindGroupDescriptor*
>(&hzbBg));
864 if (!gpuDrivenEnabled_ || !instances ||
instanceCount == 0)
return false;
866 if (instances[i].meshId >= gpuDrivenMeshes_.size())
return false;
867 auto*
gpu =
static_cast<GpuMesh*
>(gpuDrivenMeshes_[instances[i].
meshId]->gpuHandle);
868 if (!
gpu || !
gpu->indexBuffer)
return false;
870 gpuDrivenPending_.assign(instances, instances +
instanceCount);
871 gpuDrivenVisible_.clear();
872 gpuDrivenBuckets_.clear();
873 gpuDrivenComputePending_ =
false;
874 gpuDrivenDrawPending_ =
false;
880 if (sceneColorWidth > 0 && sceneColorHeight > 0) createSceneColorResources(sceneColorWidth, sceneColorHeight);
881 if (gbufferSlots.empty() && sceneColorWidth > 0 && sceneColorHeight > 0)
882 createGbufferResources(sceneColorWidth, sceneColorHeight);
891 for (glm::vec4& plane :
params.planes) {
892 const float length = glm::length(glm::vec3(plane));
897 glm::vec4(
float(gbufferWidth),
float(gbufferHeight), gbufferWidth > 0 ? 1.f /
float(gbufferWidth) : 0.f,
898 gbufferHeight > 0 ? 1.f / float(gbufferHeight) : 0.f);
899 const float projScaleY = float(gbufferHeight) / (2.f * std::tan(glm::radians(fovYDeg) * 0.5f));
900 params.clipNearFar = glm::vec4(nearZ, farZ, projScaleY, gbufferDepthValid_ ? 1.f : 0.f);
902 glm::vec4(
float(gpuDrivenHzbOffsets_.size() - 1u), 0.f,
float(gpuDrivenHzbWidth_),
float(gpuDrivenHzbHeight_));
903 uint32_t mipWidth = gpuDrivenHzbWidth_;
904 uint32_t mipHeight = gpuDrivenHzbHeight_;
905 uint32_t previousWidth = mipWidth;
906 uint32_t previousHeight = mipHeight;
907 for (uint32_t mip = 0; mip < gpuDrivenHzbOffsets_.size(); ++mip) {
908 HzbBuildParams
build{};
909 build.info = glm::uvec4(mip, mipWidth, mipHeight, mip == 0 ? 0
u : gpuDrivenHzbOffsets_[mip - 1]);
910 build.source = glm::uvec4(previousWidth, previousHeight, 0
u, 0
u);
911 queue.WriteBuffer(gpuDrivenHzbParamsBuffer_, uint64_t(mip) * 256u, &
build,
sizeof(
build));
912 previousWidth = mipWidth;
913 previousHeight = mipHeight;
914 mipWidth = std::max(mipWidth >> 1u, 1u);
915 mipHeight = std::max(mipHeight >> 1u, 1u);
918 using BucketKey = std::pair<uint32_t, uint32_t>;
919 std::map<BucketKey, std::vector<const GpuInstance*>> grouped;
920 for (
const GpuInstance& instance : gpuDrivenPending_)
921 grouped[{instance.meshId, instance.materialId}].push_back(&instance);
923 std::vector<CullInput>
inputs;
924 std::vector<GpuIndirectCommand>
commands;
925 std::vector<VisIndirectCommand> visCommands;
926 inputs.reserve(gpuDrivenPending_.size());
928 visCommands.reserve(grouped.size());
930 for (
const auto& [
key, bucketInstances] : grouped) {
934 const uint32_t bucketIndex =
static_cast<uint32_t
>(gpuDrivenBuckets_.size());
942 command.firstInstance = 0;
944 VisIndirectCommand visCommand{};
945 visCommand.vertexCount =
gpu->indexCount;
946 visCommand.firstInstance = 0;
947 visCommands.push_back(visCommand);
948 for (
const GpuInstance* instance : bucketInstances) {
950 input.model = instance->model;
951 input.color = instance->color;
952 input.terrainWave = instance->terrainWave;
953 input.terrainWaveTint = instance->terrainWaveTint;
955 ? glm::vec4(
mesh->boundsCx,
mesh->boundsCy,
mesh->boundsCz,
mesh->boundsRadius)
956 : glm::vec4(0.f, 0.f, 0.f, 1e20f);
957 input.bucket = bucketIndex;
961 const glm::vec3
center = glm::vec3(
input.model * glm::vec4(glm::vec3(
input.bounds), 1.f));
963 std::max({glm::length(glm::vec3(
input.model[0])), glm::length(glm::vec3(
input.model[1])),
964 glm::length(glm::vec3(
input.model[2]))});
966 for (
const glm::vec4& plane :
params.planes) {
967 if (glm::dot(glm::vec3(plane),
center) + plane.w < -
input.bounds.w *
scale) {
972 if (
visible) gpuDrivenVisible_.push_back(*instance);
977 outputBase += (
static_cast<uint32_t
>(bucketInstances.size()) + 15u) & ~uint32_t(15u);
982 queue.WriteBuffer(gpuDrivenParamsBuffer_, 0, &
params,
sizeof(
params));
983 queue.WriteBuffer(gpuDrivenInputBuffer_, 0,
inputs.data(),
inputs.size() *
sizeof(CullInput));
985 queue.WriteBuffer(gpuDrivenVisIndirectBuffer_, 0, visCommands.data(),
986 visCommands.size() *
sizeof(VisIndirectCommand));
987 gpuDrivenDispatchCount_ =
static_cast<uint32_t
>(
inputs.size());
988 gpuDrivenLastBucketCount_ =
static_cast<uint32_t
>(
commands.size());
993#if defined(__EMSCRIPTEN__)
994 return static_cast<uint32_t
>(gpuDrivenVisible_.size());
996 if (!gpuDrivenIndirectBuffer_ || gpuDrivenLastBucketCount_ == 0)
return 0;
998 WGPUBufferDescriptor bd{};
999 bd.label =
label(
"eve_gpu_driven_debug_readback");
1001 bd.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_MapRead;
1002 wgpu::Buffer dst =
device.CreateBuffer(
reinterpret_cast<const wgpu::BufferDescriptor*
>(&bd));
1003 wgpu::CommandEncoder encoder =
device.CreateCommandEncoder();
1004 encoder.CopyBufferToBuffer(gpuDrivenIndirectBuffer_, 0, dst, 0,
size);
1005 wgpu::CommandBuffer command = encoder.Finish();
1006 queue.Submit(1, &command);
1011 WGPUBufferMapCallbackInfo
callback{};
1012 callback.mode = WGPUCallbackMode_WaitAnyOnly;
1013 callback.callback = [](WGPUMapAsyncStatus
status, WGPUStringView,
void* userdata1,
void*) {
1014 static_cast<MapState*
>(userdata1)->
ok =
status == WGPUMapAsyncStatus_Success;
1017 WGPUFuture
future = wgpuBufferMapAsync(dst.Get(), WGPUMapMode_Read, 0,
size,
callback);
1018 WGPUFutureWaitInfo wait{};
1020 (void)wgpuInstanceWaitAny(instance.Get(), 1, &wait, UINT64_MAX);
1021 if (!
state.ok)
return 0;
1033 if (!gpuDrivenComputePending_ || gpuDrivenBuckets_.empty())
return;
1034 frameHad3DThisFrame =
true;
1036 gpuDrivenDrawPending_ =
true;
1037 gpuDrivenPending_.clear();
1040void Graphics::recordGpuDrivenCompute(wgpu::CommandEncoder encoder) {
1041 if ((gpuDrivenComputePending_ || gpuDrivenVgComputePending_) && gbufferDepthValid_ && gpuDrivenHzbPipeline_ &&
1042 gpuDrivenHzbBindGroup_) {
1043 uint32_t
width = gpuDrivenHzbWidth_;
1044 uint32_t
height = gpuDrivenHzbHeight_;
1045 for (uint32_t mip = 0; mip < gpuDrivenHzbOffsets_.size(); ++mip) {
1046 wgpu::ComputePassEncoder hzbPass = encoder.BeginComputePass();
1047 hzbPass.SetPipeline(gpuDrivenHzbPipeline_);
1048 const uint32_t dynamicOffset = mip * 256u;
1049 hzbPass.SetBindGroup(0, gpuDrivenHzbBindGroup_, 1, &dynamicOffset);
1050 hzbPass.DispatchWorkgroups((
width + 7u) / 8u, (
height + 7u) / 8u, 1);
1056 if (gpuDrivenComputePending_ && gpuDrivenCullPipeline_ && gpuDrivenComputeBindGroup_) {
1057 wgpu::ComputePassEncoder pass = encoder.BeginComputePass();
1058 pass.SetPipeline(gpuDrivenCullPipeline_);
1059 pass.SetBindGroup(0, gpuDrivenComputeBindGroup_, 0,
nullptr);
1060 pass.DispatchWorkgroups((gpuDrivenDispatchCount_ + 63u) / 64u, 1, 1);
1062 gpuDrivenComputePending_ =
false;
1064 recordGpuDrivenVgCompute(encoder);
1067void Graphics::flushGpuDrivenDraws(wgpu::RenderPassEncoder pass,
bool canvasTarget,
bool hdrCanvas) {
1068 if (!gpuDrivenDrawPending_ ||
1069 (gpuDrivenResidentDrawPending_ ? !gpuDrivenResidentBuffer_ : !gpuDrivenVisibleBuffer_))
1071 auto& arena = currentUboArena();
1072 ensureUboArena(arena, arena.used + gpuDrivenBuckets_.size() * 2048);
1073 const wgpu::RenderPipeline& pipeline =
1074 gpuDrivenResidentDrawPending_
1075 ? (canvasTarget ? (hdrCanvas ? gpuDrivenResidentHdrCanvasPipeline_
1076 : gpuDrivenResidentCanvasPipeline_)
1077 : gpuDrivenResidentRenderPipeline_)
1078 : (canvasTarget ? (hdrCanvas ? gpuDrivenHdrCanvasPipeline_ : gpuDrivenCanvasPipeline_)
1079 : gpuDrivenRenderPipeline_);
1080 if (!pipeline)
return;
1081 pass.SetPipeline(pipeline);
1082 gpuDrivenLastIndirectDrawCount_ = 0;
1084 for (uint32_t i = 0; i < gpuDrivenBuckets_.size(); ++i) {
1085 const GpuDrivenBucket&
bucket = gpuDrivenBuckets_[i];
1086 auto*
gpu =
static_cast<GpuMesh*
>(
bucket.mesh->gpuHandle);
1091 ubo.mvp = mesh3dViewProj;
1092 ubo.model = glm::mat4(1.f);
1093 ubo.lightDir = glm::vec4(glm::vec3(mesh3dLighting.
lights[0].
posRadius),
float(mesh3dLighting.
count));
1095 ubo.lightColor.w = mesh3dEnvIntensity;
1097 ubo.cameraPos = glm::vec4(mesh3dCameraPos,
material->getRoughness());
1098 ubo.ambient = glm::vec4(glm::vec3(mesh3dLighting.
ambient),
material->getMetallic());
1101 ubo.texBomb = glm::vec4(
material->getTexCellBombScale(),
material->getTexCellBombStrength(),
1102 material->getTexCellBombRotation(), 0.f);
1103 ubo.parallax = glm::vec4(
material->getParallaxScale(),
material->getParallaxMinLayers(),
1104 material->getParallaxMaxLayers(), 0.f);
1107 ubo.surface = glm::vec4(surfaceCode,
material->getAlphaCutoff(),
ao,
1108 material->getCameraFacing() ? 1.f : 0.f);
1109 ubo.view = mesh3dView;
1110 ubo.clipInfo = glm::vec4(mesh3dNear, mesh3dFar, 0.f, 0.f);
1111 ubo.cloud = mesh3dCloud;
1112 ubo.cloudWind = mesh3dCloudWind;
1113 ubo.envProbeCenter = glm::vec4(mesh3dEnvProbeCenter, 1.f);
1114 ubo.envProbeExtent = glm::vec4(mesh3dEnvProbeExtent, 0.f);
1116 if (probeIndex >= mesh3dReflectionProbes.
count)
continue;
1117 const auto& probe = mesh3dReflectionProbes.
probes[probeIndex];
1118 GpuTexture* gpuProbe = gpuForTexture(probe.cubemap);
1119 if (!gpuProbe || !gpuProbe->isCube)
continue;
1120 ubo.reflectionProbeCenter[probeIndex] = glm::vec4(probe.center, probe.intensity);
1121 ubo.reflectionProbeExtent[probeIndex] = glm::vec4(probe.extent, probe.blendDistance);
1124 const uint32_t frameOffset = arena.alloc(
sizeof(Mesh3DUBO), 256);
1125 const uint32_t shadowOffset = arena.alloc(
sizeof(ShadowUBO), 256);
1126 queue.WriteBuffer(arena.buffer, frameOffset, &ubo,
sizeof(ubo));
1127 ShadowUBO shadow = mesh3dShadows.
ubo;
1129 queue.WriteBuffer(arena.buffer, shadowOffset, &shadow,
sizeof(shadow));
1131 GpuTexture*
depth = mesh3dSceneDepthTexture ? gpuForTexture(mesh3dSceneDepthTexture) : flatDepthTexture3D;
1132 wgpu::BindGroup bindGroup =
1133 makeMeshBindGroup(gpuForTexture(
material->getAlbedoTexture()), gpuForTexture(
material->getNormalTexture()),
1134 gpuForTexture(mesh3dEnvTexture), gpuForTexture(
material->getHeightTexture()),
depth,
1135 nullptr, frameOffset, shadowOffset, 0, uploadSkinPalette(
nullptr));
1136 const uint32_t offsets[3] = {frameOffset, shadowOffset, 0};
1137 pass.SetBindGroup(0, bindGroup, 3, offsets);
1138 WGPUBindGroupEntry modelEntry{};
1139 modelEntry.binding = 0;
1140 modelEntry.buffer = gpuDrivenResidentDrawPending_ ? gpuDrivenResidentBuffer_ : gpuDrivenVisibleBuffer_.Get();
1142 gpuDrivenResidentDrawPending_ ? gpuDrivenResidentOffset_ :
1143 uint64_t(
bucket.outputBase) *
sizeof(VisibleInstance);
1145 gpuDrivenResidentDrawPending_ ? gpuDrivenResidentSize_ :
1146 uint64_t(
bucket.inputCount) *
sizeof(VisibleInstance);
1147 WGPUBindGroupDescriptor modelDesc{};
1148 modelDesc.layout = gpuDrivenRenderSetLayout_.Get();
1149 modelDesc.entryCount = 1;
1150 modelDesc.entries = &modelEntry;
1151 wgpu::BindGroup modelGroup =
1152 device.CreateBindGroup(
reinterpret_cast<const wgpu::BindGroupDescriptor*
>(&modelDesc));
1153 pass.SetBindGroup(1, modelGroup, 0,
nullptr);
1154 pass.SetVertexBuffer(0,
gpu->vertexBuffer, 0,
gpu->vertexCount * 32ull);
1155 const uint64_t indexBytes =
gpu->indexFormat == wgpu::IndexFormat::Uint16 ? 2u : 4u;
1156 pass.SetIndexBuffer(
gpu->indexBuffer,
gpu->indexFormat, 0, uint64_t(
gpu->indexCount) * indexBytes);
1157 pass.DrawIndexedIndirect(gpuDrivenIndirectBuffer_, uint64_t(i) *
sizeof(
GpuIndirectCommand));
1158 ++gpuDrivenLastIndirectDrawCount_;
1160 gpuDrivenDrawPending_ =
false;
1161 gpuDrivenResidentDrawPending_ =
false;
1162 gpuDrivenResidentBuffer_ =
nullptr;
1163 gpuDrivenResidentOffset_ = 0;
1164 gpuDrivenResidentSize_ = 0;
1165 gpuDrivenBuckets_.clear();
std::unordered_map< std::string, QuestRuntime > entries
std::uint32_t vertexCount
std::uint32_t firstVertex
std::uint32_t firstInstance
std::uint32_t paddedCount
std::uint32_t instanceCount
wgpu::PopErrorScopeStatus status
std::array< float, 3 > scale
std::future< JobOutput > future
std::shared_ptr< OceanGpuSpectrum > gpu
std::array< uint32_t, 16 > material
Local-probe upload record kept off the high-fanout IGraphics3D header.
std::vector< VegetationPresetCommand > commands
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.
Move-only operation result carrying either a value or Status.
static Result success(T value)
Construct a successful result owning value.
static Result failure(Status status)
Construct a failed result from a structured status.
std::unique_ptr< RenderControl > renderControl_
Packages shading method + surface parameters into one attachable asset.
GPU mesh handle (+ optional CPU morph targets).
void gpuDrivenCullEmit(const glm::mat4 &viewProj, const glm::vec3 &eye, float fovYDeg, float nearZ, float farZ) override
Gpu driven cull emit.
void gpuDrivenDrawOpaque() override
Gpu driven draw opaque.
uint32_t gpuDrivenMaterialRecord(Material *material) override
Gpu driven material record.
bool gpuDrivenCullBegin(const GpuInstance *instances, uint32_t instanceCount) override
Gpu driven cull begin.
bool gpuDrivenMaterialUsable(Material *material) override
Gpu driven material usable.
uint32_t gpuDrivenMeshRecord(Mesh *mesh) override
Gpu driven mesh record.
Result< void > gpuDrivenReleaseMaterialRecord(Material *material) override
Gpu driven release material record.
GpuResidentSubmitStatus gpuDrivenSubmitResident(const GpuResidentInstanceBatch &batch) override
Gpu driven submit resident.
bool gpuDrivenSubmitOpaque(const GpuInstance *instances, uint32_t instanceCount) override
Gpu driven submit opaque.
uint32_t debugGpuDrivenGpuVisibleCount()
Read back the last GPU-written indirect instance total (native tests).
eve::graphics::GpuIndirectCommand GpuIndirectCommand
constexpr uint32_t kMaxHzbMips
eve::graphics::GpuInstance GpuInstance
const char * kMesh3DFragWgsl
constexpr uint32_t kInvalidGpuDrivenSlot
GPU-driven API surface without GLM layout records.
GpuResidentSubmitStatus
Structured result for direct resident-instance submission.
std::vector< int64_t > attrs(const Node &n, const char *key, std::vector< int64_t > fallback)
Attrs.
constexpr uint64_t kGpuResidentStorageOffsetAlignment
Portable alignment required for resident storage-buffer slice offsets.
GpuResidentBackend backend
Indirect draw command; layout identical to VkDrawIndexedIndirectCommand.
Per-instance GPU record (std430). Mirrors GLSL GpuInstance.
Direct-render description for a GPU-authored array of GpuInstance records. @ownership buckets and buf...
GpuResidentBufferView buffer
const GpuResidentInstanceBucket * buckets
One contiguous mesh/material bucket in a sorted resident instance buffer.
static constexpr int kMaxLights
Light3DGpu lights[kMaxLights]
static constexpr int kMaxProbes
Vertex/index buffers for one mesh.
glm::vec4 terrainWaveTint