载入中...
搜索中...
未找到
GraphicsDraw.cpp
浏览该文件的文档.
3#include "graphics/Batcher.h"
6#include "graphics/GBuffer.h"
7#include "graphics/Light.h"
8#include "graphics/Mesh.h"
13#include "graphics/Shader.h"
14#include "graphics/Shadow.h"
15#include "graphics/Texture.h"
25
26#include "common/Exception.h"
27#include "common/Resource.h"
28#include "common/config.h"
29#include "filesystem/FileData.h"
31#include "image/Image.h"
32#include "image/ImageData.h"
33
34#include <algorithm>
35#include <bit>
36#include <cmath>
37#include <cstdio>
38#include <cstring>
39#include <fstream>
40#include <limits>
41#include <map>
42#include <memory>
43#include <mutex>
44#include <vector>
45
46#include <glm/gtc/constants.hpp>
47
48namespace eve::graphics::webgpu {
49using namespace detail;
50
51uint32_t Graphics::UboArena::alloc(uint64_t size, uint64_t alignment) {
52 uint64_t aligned = (used + alignment - 1) / alignment * alignment;
53 used = aligned + size;
54 return static_cast<uint32_t>(aligned);
55}
56
57uint64_t Graphics::VertexArena::alloc(uint64_t bytes) {
58 uint64_t at = used;
59 used += bytes;
60 return at;
61}
62
63Graphics::UboArena& Graphics::currentUboArena() { return uboArenas[currentFrameSlot()]; }
64Graphics::VertexArena& Graphics::currentVertexArena() { return vertexArenas[currentFrameSlot()]; }
65
66void Graphics::ensureUboArena(UboArena& arena, uint64_t bytes) {
67 if (arena.buffer && arena.capacity >= bytes) return;
68 uint64_t size = arena.capacity;
69 while (size < bytes) size = size ? size * 2 : (64u << 10);
70 WGPUBufferDescriptor bd{};
71 bd.label = sv("eve_ubo_arena");
72 bd.size = size;
73 bd.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Uniform;
74 bd.mappedAtCreation = false;
75 arena.buffer = device.CreateBuffer(reinterpret_cast<const wgpu::BufferDescriptor*>(&bd));
76 arena.capacity = size;
77 arena.used = 0;
78}
79
80void Graphics::ensureVertexArena(VertexArena& arena, uint64_t bytes) {
81 if (arena.buffer && arena.capacity >= bytes) return;
82 uint64_t size = arena.capacity;
83 while (size < bytes) size = size ? size * 2 : (256u << 10);
84 WGPUBufferDescriptor bd{};
85 bd.label = sv("eve_vertex_arena");
86 bd.size = size;
87 bd.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Vertex;
88 bd.mappedAtCreation = false;
89 arena.buffer = device.CreateBuffer(reinterpret_cast<const wgpu::BufferDescriptor*>(&bd));
90 arena.capacity = size;
91 arena.used = 0;
92}
93
94
95// ---------------------------------------------------------------------------
96// 2D drawing
97// ---------------------------------------------------------------------------
98
99void Graphics::clear2DBatches() {
100 solidBatches.clear();
101 texturedBatches.clear();
102 litBatches.clear();
103 overlaySpans.clear();
104 sceneColorComposited = false;
105}
106
107void Graphics::noteSolidOverlay(uint32_t idx) {
108 if (idx >= solidBatches.size()) return;
109 const uint32_t n = uint32_t(solidBatches[idx].batch.vertices().size());
110 if (!overlaySpans.empty() && overlaySpans.back().kind == OverlayKind::Solid && overlaySpans.back().index == idx) {
111 overlaySpans.back().vertCount = n - overlaySpans.back().vertBegin;
112 return;
113 }
114 const uint32_t begin = n >= 6u ? n - 6u : 0u;
115 overlaySpans.push_back({OverlayKind::Solid, idx, begin, n - begin});
116}
117
118void Graphics::noteTexturedOverlay(Texture* tex, uint32_t idx) {
119 if (tex && tex == getSceneColorTexture()) sceneColorComposited = true;
120 if (!overlaySpans.empty() && overlaySpans.back().kind == OverlayKind::Textured && overlaySpans.back().index == idx)
121 return;
122 overlaySpans.push_back({OverlayKind::Textured, idx, 0, 0});
123}
124
125void Graphics::noteLitOverlay(uint32_t idx) {
126 if (!overlaySpans.empty() && overlaySpans.back().kind == OverlayKind::Lit && overlaySpans.back().index == idx)
127 return;
128 overlaySpans.push_back({OverlayKind::Lit, idx, 0, 0});
129}
130
131void Graphics::drawSolidRect(float x, float y, float w, float h, const Color& color, BlendMode blend) {
132 auto it =
133 std::find_if(solidBatches.begin(), solidBatches.end(), [&](const SolidBatch& sb) { return sb.blend == blend; });
134 if (it == solidBatches.end()) {
135 solidBatches.push_back(SolidBatch{blend, Batcher{}});
136 it = solidBatches.end() - 1;
137 }
138 it->batch.addRect(x, y, w, h, color);
139 noteSolidOverlay(uint32_t(it - solidBatches.begin()));
140}
141
143 const int targetWidth = activeCanvas ? activeCanvas->getWidth() : getWidth();
144 const int targetHeight = activeCanvas ? activeCanvas->getHeight() : getHeight();
145 const auto triangles = resolvePrimitiveStrokes2D(canvas, {targetWidth, targetHeight});
146 if (triangles.vertices.empty()) return;
147 auto logicalPoint = [targetWidth, targetHeight](const PrimitiveTriangleVertex& vertex) {
148 const glm::vec2 ndc = glm::vec2(vertex.clipPosition) / vertex.clipPosition.w;
149 return glm::vec2((ndc.x + 1.f) * 0.5f * static_cast<float>(targetWidth),
150 (ndc.y + 1.f) * 0.5f * static_cast<float>(targetHeight));
151 };
152 for (const ResolvedPrimitiveBatch2D& resolvedBatch : triangles.batches2D) {
153 auto it = std::find_if(solidBatches.begin(), solidBatches.end(),
154 [&](const SolidBatch& batch) { return batch.blend == resolvedBatch.blend; });
155 if (it == solidBatches.end()) {
156 solidBatches.push_back(SolidBatch{resolvedBatch.blend, Batcher{}});
157 it = solidBatches.end() - 1;
158 }
159 for (std::size_t i = resolvedBatch.firstVertex; i < resolvedBatch.firstVertex + resolvedBatch.vertexCount;
160 i += 3) {
161 it->batch.addTriangle(logicalPoint(triangles.vertices[i]), logicalPoint(triangles.vertices[i + 1]),
162 logicalPoint(triangles.vertices[i + 2]), triangles.vertices[i].color,
163 triangles.vertices[i + 1].color, triangles.vertices[i + 2].color);
164 }
165 const auto batchIndex = static_cast<std::uint32_t>(it - solidBatches.begin());
166 const std::uint32_t count = static_cast<std::uint32_t>(resolvedBatch.vertexCount);
167 const std::uint32_t end = static_cast<std::uint32_t>(it->batch.vertices().size());
168 overlaySpans.push_back({OverlayKind::Solid, batchIndex, end - count, count});
169 }
170}
171
172void Graphics::drawSolidRectRotated(float cx, float cy, float w, float h, float degrees, const Color& color,
174 auto it =
175 std::find_if(solidBatches.begin(), solidBatches.end(), [&](const SolidBatch& sb) { return sb.blend == blend; });
176 if (it == solidBatches.end()) {
177 solidBatches.push_back(SolidBatch{blend, Batcher{}});
178 it = solidBatches.end() - 1;
179 }
180 it->batch.addRectRotated(cx, cy, w, h, degrees, color);
181 noteSolidOverlay(uint32_t(it - solidBatches.begin()));
182}
183
184void Graphics::drawTexturedRect(Texture* texture, float x, float y, float w, float h, const Color& color) {
185 drawTexturedRectUV(texture, x, y, w, h, 0.f, 0.f, 1.f, 1.f, color);
186}
187
188void Graphics::drawTexturedRectShader(Texture* texture, Shader* shader, float x, float y, float w, float h,
189 const Color& color) {
190 drawTexturedRectShaderUV(texture, shader, x, y, w, h, 0.f, 0.f, 1.f, 1.f, color);
191}
192
193void Graphics::drawTexturedRectUV(Texture* texture, float x, float y, float w, float h, float u0, float v0, float u1,
194 float v1, const Color& color) {
195 drawTexturedRectShaderUV(texture, currentShader, x, y, w, h, u0, v0, u1, v1, color);
196}
197
198void Graphics::drawTexturedRectShaderUV(Texture* texture, Shader* shader, float x, float y, float w, float h, float u0,
199 float v0, float u1, float v1, const Color& color, bool rotatedUV,
201 if (!texture) {
202 drawSolidRect(x, y, w, h, color, blend);
203 return;
204 }
205 if (texturedBatches.empty() || texturedBatches.back().texture != texture ||
206 texturedBatches.back().shader != shader || texturedBatches.back().depth != nullptr ||
207 texturedBatches.back().blend != blend) {
208 texturedBatches.push_back(TexturedBatch{texture, nullptr, shader, blend, Batcher{}});
209 }
210 texturedBatches.back().batch.addTexturedRect(x, y, w, h, color, u0, v0, u1, v1, rotatedUV);
211 noteTexturedOverlay(texture, uint32_t(texturedBatches.size() - 1));
212}
213
215 float degrees, float u0, float v0, float u1, float v1,
216 const Color& color, bool rotatedUV, BlendMode blend) {
217 if (!texture) {
218 drawSolidRect(cx - w * 0.5f, cy - h * 0.5f, w, h, color, blend);
219 return;
220 }
221 if (texturedBatches.empty() || texturedBatches.back().texture != texture ||
222 texturedBatches.back().shader != shader || texturedBatches.back().depth != nullptr ||
223 texturedBatches.back().blend != blend) {
224 texturedBatches.push_back(TexturedBatch{texture, nullptr, shader, blend, Batcher{}});
225 }
226 texturedBatches.back().batch.addTexturedRectRotated(cx, cy, w, h, degrees, color, u0, v0, u1, v1, rotatedUV);
227 noteTexturedOverlay(texture, uint32_t(texturedBatches.size() - 1));
228}
229
231 float h, const Color& tint) {
232 if (!color) {
233 drawSolidRect(x, y, w, h, tint);
234 return;
235 }
236 if (texturedBatches.empty() || texturedBatches.back().texture != color || texturedBatches.back().shader != shader ||
237 texturedBatches.back().depth != depth || texturedBatches.back().blend != BlendMode::Alpha) {
238 texturedBatches.push_back(TexturedBatch{color, depth, shader, BlendMode::Alpha, Batcher{}});
239 }
240 texturedBatches.back().batch.addTexturedRect(x, y, w, h, tint, 0.f, 0.f, 1.f, 1.f, false);
241 noteTexturedOverlay(color, uint32_t(texturedBatches.size() - 1));
242}
243
245 float x, float y, float w, float h, const Color& tint) {
246 if (!color) {
247 drawSolidRect(x, y, w, h, tint);
248 return;
249 }
250 if (texturedBatches.empty() || texturedBatches.back().texture != color || texturedBatches.back().shader != shader ||
251 texturedBatches.back().depth != depth || texturedBatches.back().motion != motion ||
252 texturedBatches.back().blend != BlendMode::Opaque) {
254 batch.motion = motion;
255 texturedBatches.push_back(std::move(batch));
256 }
257 texturedBatches.back().batch.addTexturedRect(x, y, w, h, tint, 0.f, 0.f, 1.f, 1.f, false);
258 noteTexturedOverlay(color, uint32_t(texturedBatches.size() - 1));
259}
260
262 float x, float y, float w, float h, const Color& tint) {
263 if (!color) {
264 drawSolidRect(x, y, w, h, tint);
265 return;
266 }
267 if (texturedBatches.empty() || texturedBatches.back().texture != color || texturedBatches.back().shader != shader ||
268 texturedBatches.back().depth != depth || texturedBatches.back().motion != motion ||
269 texturedBatches.back().extra != extra || texturedBatches.back().blend != BlendMode::Opaque) {
271 batch.motion = motion;
272 batch.extra = extra;
273 texturedBatches.push_back(std::move(batch));
274 }
275 texturedBatches.back().batch.addTexturedRect(x, y, w, h, tint, 0.f, 0.f, 1.f, 1.f, false);
276 noteTexturedOverlay(color, uint32_t(texturedBatches.size() - 1));
277}
278
280 Texture* specular, Shader* shader, float x, float y, float w, float h,
281 const Color& tint) {
282 if (!color) {
283 drawSolidRect(x, y, w, h, tint);
284 return;
285 }
286 if (texturedBatches.empty() || texturedBatches.back().texture != color || texturedBatches.back().shader != shader ||
287 texturedBatches.back().depth != depth || texturedBatches.back().motion != motion ||
288 texturedBatches.back().extra != extra || texturedBatches.back().specular != specular ||
289 texturedBatches.back().blend != BlendMode::Opaque) {
291 batch.motion = motion;
292 batch.extra = extra;
293 batch.specular = specular;
294 texturedBatches.push_back(std::move(batch));
295 }
296 texturedBatches.back().batch.addTexturedRect(x, y, w, h, tint, 0.f, 0.f, 1.f, 1.f, false);
297 noteTexturedOverlay(color, uint32_t(texturedBatches.size() - 1));
298}
299
300void Graphics::drawTexturedRectLitUV(Texture* albedo, Texture* normal, float x, float y, float w, float h, float u0,
301 float v0, float u1, float v1, const Color& color, BlendMode blend) {
302 if (!albedo) {
303 drawSolidRect(x, y, w, h, color, blend);
304 return;
305 }
306 if (litBatches.empty() || litBatches.back().albedo != albedo || litBatches.back().normal != normal ||
307 litBatches.back().blend != blend) {
308 litBatches.push_back(LitBatch{albedo, normal, blend, Batcher{}});
309 }
310 litBatches.back().batch.addTexturedRect(x, y, w, h, color, u0, v0, u1, v1, false);
311 noteLitOverlay(uint32_t(litBatches.size() - 1));
312}
313
315 float degrees, float u0, float v0, float u1, float v1, const Color& color,
317 if (!albedo) {
319 return;
320 }
321 if (litBatches.empty() || litBatches.back().albedo != albedo || litBatches.back().normal != normal ||
322 litBatches.back().blend != blend) {
323 litBatches.push_back(LitBatch{albedo, normal, blend, Batcher{}});
324 }
325 litBatches.back().batch.addTexturedRectRotated(cx, cy, w, h, degrees, color, u0, v0, u1, v1, false);
326 noteLitOverlay(uint32_t(litBatches.size() - 1));
327}
328
330 // Uploaded on demand before flushing lit batches.
331 lighting2dFrame = ubo;
332}
333
334void Graphics::flush2D(wgpu::RenderPassEncoder pass, int viewW, int viewH, WGPUTextureFormat format) {
336 applyPendingResourceChanges();
337 auto spans = std::move(overlaySpans);
338 const bool offscreen = uint32_t(format) != uint32_t(surfaceFormat);
339
340 struct SolidUpload {
341 BlendMode blend = BlendMode::Alpha;
342 uint64_t offset = 0;
343 uint64_t bytes = 0;
344 };
345 std::vector<SolidUpload> solidUploads;
346 solidUploads.reserve(solidBatches.size());
347 for (const auto& sb : solidBatches) {
348 if (sb.batch.empty()) {
349 solidUploads.push_back(SolidUpload{sb.blend, 0, 0});
350 continue;
351 }
352 Batcher ndc = sb.batch;
353 ndc.toNDC(viewW, viewH);
354 auto verts = ndc.vertices();
355 // Batcher::toNDC targets Vulkan's Y-down NDC ((-1,-1)=top-left), but
356 // WebGPU's clip space is Y-up ((-1,-1)=bottom-left). Flip Y so logical
357 // top-left maps to the swapchain's top-left.
358 for (auto& v : verts) v.pos.y = -v.pos.y;
359 std::vector<float> data;
360 data.reserve(verts.size() * 6);
361 for (const auto& v : verts) {
362 data.push_back(v.pos.x);
363 data.push_back(v.pos.y);
364 data.push_back(v.color.r);
365 data.push_back(v.color.g);
366 data.push_back(v.color.b);
367 data.push_back(v.color.a);
368 }
369 const uint64_t bytes = data.size() * sizeof(float);
370 auto& arena = currentVertexArena();
371 ensureVertexArena(arena, arena.used + bytes);
372 const uint64_t offset = arena.alloc(bytes);
373 queue.WriteBuffer(arena.buffer, offset, data.data(), bytes);
374 solidUploads.push_back(SolidUpload{sb.blend, offset, bytes});
375 }
376
377 auto solidPipe = [&](BlendMode mode) -> wgpu::RenderPipeline { return get2DColorPipeline(mode, offscreen); };
378
379 auto drawSolid = [&](uint32_t batchIndex, uint32_t first, uint32_t count) {
380 if (batchIndex >= solidUploads.size()) return;
381 const SolidUpload& u = solidUploads[batchIndex];
382 if (u.bytes == 0 || count == 0) return;
383 pass.SetPipeline(solidPipe(u.blend));
384 pass.SetVertexBuffer(0, currentVertexArena().buffer, u.offset, u.bytes);
385 pass.Draw(count, 1, first, 0);
386 };
387
388 if (!spans.empty()) {
389 for (const auto& sp : spans) {
390 if (sp.kind == OverlayKind::Solid)
391 drawSolid(sp.index, sp.vertBegin, sp.vertCount);
392 else if (sp.kind == OverlayKind::Textured && sp.index < texturedBatches.size())
393 drawTexturedBatch(pass, texturedBatches[sp.index], viewW, viewH, format, offscreen);
394 else if (sp.kind == OverlayKind::Lit && sp.index < litBatches.size())
395 drawLitBatch(pass, litBatches[sp.index], viewW, viewH, format);
396 }
397 } else {
398 for (size_t i = 0; i < solidUploads.size(); ++i) {
399 if (solidUploads[i].bytes > 0) drawSolid(uint32_t(i), 0, uint32_t(solidBatches[i].batch.vertices().size()));
400 }
401 for (auto& tb : texturedBatches) {
402 if (tb.batch.empty()) continue;
403 drawTexturedBatch(pass, tb, viewW, viewH, format, offscreen);
404 }
405 for (auto& lb : litBatches) {
406 if (lb.batch.empty()) continue;
407 drawLitBatch(pass, lb, viewW, viewH, format);
408 }
409 }
410 clear2DBatches();
411}
412
413void Graphics::drawTexturedBatch(wgpu::RenderPassEncoder pass, TexturedBatch& tb, int viewW, int viewH,
414 WGPUTextureFormat format, bool offscreen) {
415 Batcher ndc = tb.batch;
416 ndc.toNDC(viewW, viewH);
417 auto verts = ndc.vertices();
418 for (auto& v : verts) v.pos.y = -v.pos.y;
419 if (verts.empty()) return;
420
421 std::vector<float> data;
422 data.reserve(verts.size() * 8);
423 for (const auto& v : verts) {
424 data.push_back(v.pos.x);
425 data.push_back(v.pos.y);
426 data.push_back(v.color.r);
427 data.push_back(v.color.g);
428 data.push_back(v.color.b);
429 data.push_back(v.color.a);
430 data.push_back(v.uv.x);
431 data.push_back(v.uv.y);
432 }
433 uint64_t bytes = data.size() * sizeof(float);
434 auto& arena = currentVertexArena();
435 ensureVertexArena(arena, arena.used + bytes);
436 uint64_t vtxOffset = arena.alloc(bytes);
437 queue.WriteBuffer(arena.buffer, vtxOffset, data.data(), bytes);
438
439 GpuTexture* gpu = gpuForTexture(tb.texture);
440 GpuTexture* depthGpu = gpuForTexture(tb.depth);
441 GpuTexture* motionGpu = gpuForTexture(tb.motion);
442 GpuTexture* extraGpu = gpuForTexture(tb.extra);
443 GpuTexture* specularGpu = gpuForTexture(tb.specular);
444 auto& uboArena = currentUboArena();
445 ensureUboArena(uboArena, uboArena.used + 256);
446
447 // Push-constant (Externals) block for custom shaders.
448 uint32_t pushOffset = 0;
449 if (tb.shader && tb.shader->pushConstantSize() > 0) {
450 pushOffset = uboArena.alloc(Shader::kPushConstantBytes, 256);
451 queue.WriteBuffer(uboArena.buffer, pushOffset, tb.shader->pushConstantData(), Shader::kPushConstantBytes);
452 }
453
454 wgpu::BindGroup bg = makeTex2DBindGroup(gpu, depthGpu, motionGpu, extraGpu, specularGpu);
455 uint32_t offsets[1] = {pushOffset};
456
457 wgpu::RenderPipeline pipe;
458 if (tb.shader && tb.shader->gpuHandle) {
459 auto* gs = static_cast<GpuShader*>(tb.shader->gpuHandle);
460 const bool hdr = format == WGPUTextureFormat_RGBA16Float;
461 if (tb.blend == BlendMode::Opaque)
462 pipe = hdr ? gs->hdrOffscreenOpaquePipeline
463 : (offscreen ? gs->offscreenOpaquePipeline : gs->swapchainOpaquePipeline);
464 else
465 pipe = hdr ? gs->hdrOffscreenPipeline : (offscreen ? gs->offscreenPipeline : gs->swapchainPipeline);
466 } else {
467 switch (tb.blend) {
469 pipe = offscreen ? offscreenTexturedAdditivePipeline : texturedAdditivePipeline;
470 break;
472 pipe = offscreen ? offscreenTexturedPremultipliedPipeline : texturedPremultipliedPipeline;
473 break;
475 pipe = offscreen ? offscreenTexturedMultiplyPipeline : texturedMultiplyPipeline;
476 break;
478 pipe = format == WGPUTextureFormat_RGBA16Float
479 ? hdrOffscreenTexturedOpaquePipeline
480 : (offscreen ? offscreenTexturedOpaquePipeline : texturedOpaquePipeline);
481 break;
482 case BlendMode::Alpha:
483 default:
484 pipe = format == WGPUTextureFormat_RGBA16Float
485 ? hdrOffscreenTexturedPipeline
486 : (offscreen ? offscreenTexturedPipeline : texturedPipeline);
487 break;
488 }
489 }
490 if (!pipe) return;
491 pass.SetPipeline(pipe);
492 pass.SetBindGroup(0, bg, 1, offsets);
493 pass.SetVertexBuffer(0, arena.buffer, vtxOffset, bytes);
494 pass.Draw(static_cast<uint32_t>(verts.size()), 1, 0, 0);
495}
496
497void Graphics::drawLitBatch(wgpu::RenderPassEncoder pass, LitBatch& lb, int viewW, int viewH,
498 WGPUTextureFormat format) {
499 Batcher ndc = lb.batch;
500 ndc.toNDC(viewW, viewH);
501 auto verts = ndc.vertices();
502 for (auto& v : verts) v.pos.y = -v.pos.y;
503 if (verts.empty()) return;
504
505 std::vector<float> data;
506 data.reserve(verts.size() * 8);
507 for (const auto& v : verts) {
508 data.push_back(v.pos.x);
509 data.push_back(v.pos.y);
510 data.push_back(v.color.r);
511 data.push_back(v.color.g);
512 data.push_back(v.color.b);
513 data.push_back(v.color.a);
514 data.push_back(v.uv.x);
515 data.push_back(v.uv.y);
516 }
517 uint64_t bytes = data.size() * sizeof(float);
518 auto& arena = currentVertexArena();
519 ensureVertexArena(arena, arena.used + bytes);
520 uint64_t vtxOffset = arena.alloc(bytes);
521 queue.WriteBuffer(arena.buffer, vtxOffset, data.data(), bytes);
522
523 GpuTexture* albedoGpu = gpuForTextureOrWhite(lb.albedo);
524 // Null / missing normal → flat +Z (128,128,255), not white (which is a
525 // bright wrong normal and washes out lit sprites without a map).
526 GpuTexture* normalGpu = gpuForTexture(lb.normal);
527 if (!normalGpu) normalGpu = flatNormalTexture ? flatNormalTexture : whiteTexture;
528
529 auto& uboArena = currentUboArena();
530 ensureUboArena(uboArena, uboArena.used + 512);
531 uint32_t uboOffset = uboArena.alloc(sizeof(Lighting2DUBO), 256);
532 queue.WriteBuffer(uboArena.buffer, uboOffset, &lighting2dFrame, sizeof(Lighting2DUBO));
533
534 wgpu::BindGroup bg = makeTex2DBindGroup(albedoGpu, normalGpu);
535 uint32_t offsets[1] = {uboOffset};
536 wgpu::RenderPipeline pipe = get2DLitPipeline(lb.blend, format);
537 if (!pipe) return;
538 pass.SetPipeline(pipe);
539 pass.SetBindGroup(0, bg, 1, offsets);
540 pass.SetVertexBuffer(0, arena.buffer, vtxOffset, bytes);
541 pass.Draw(static_cast<uint32_t>(verts.size()), 1, 0, 0);
542}
543
544// ---------------------------------------------------------------------------
545// 3D rendering
546// ---------------------------------------------------------------------------
547
549 if (!initialized || !device) return;
551 applyPendingResourceChanges();
552 frame3DStarted = true;
553 frameHad3DThisFrame = true;
554 // Match the desktop (Vulkan) backend: had3DThisFrame() must return true
555 // once a 3D frame begins, or RenderSystem3D::render bails out before any
556 // mesh is drawn.
557 frameHad3D = true;
558 sceneColorPassOpen = false;
559 mesh3dDraws.clear();
560 primitive3DDraws.clear();
561 shadowPassDraws.clear();
562 voxelDraws.clear();
563 if (surfaceNeedsRecreate.load()) {
564 surfaceNeedsRecreate.store(false);
565 markSwapchainDirty();
566 }
567 rebuildSwapchainIfNeeded();
568}
569
570
572 if (!canvas) throw Exception("begin3DFrameToCanvas: null canvas");
573 if (!device) throw Exception("begin3DFrameToCanvas: device not initialized");
574 auto* offscreen = dynamic_cast<OffscreenCanvas*>(canvas);
575 if (!offscreen) throw Exception("begin3DFrameToCanvas: not an offscreen canvas");
576 clearColor = backgroundColor;
577 active3DCanvas = offscreen;
578 begin3DFrame();
579}
581 OffscreenCanvas* canvas = active3DCanvas;
582 if (!canvas || !device) return;
583 auto& uboArena = currentUboArena();
584 uboArena.reset();
585 ensureUboArena(uboArena, 4096);
586 auto& vertexArena = currentVertexArena();
587 vertexArena.reset();
588
589 wgpuInstanceProcessEvents(instance.Get());
590 OffscreenTimestampReadback* timestampSlot = nullptr;
591 if (offscreenTimestampSupported && offscreenTimestampQuerySet && offscreenTimestampResolveBuffer) {
592 for (size_t candidate = 0; candidate < offscreenTimestampReadbacks.size(); ++candidate) {
593 const size_t index = (offscreenTimestampReadbackCursor + candidate) % offscreenTimestampReadbacks.size();
594 if (!offscreenTimestampReadbacks[index].pending) {
595 timestampSlot = &offscreenTimestampReadbacks[index];
596 offscreenTimestampReadbackCursor = (index + 1) % offscreenTimestampReadbacks.size();
597 break;
598 }
599 }
600 }
601
602 wgpu::CommandEncoder encoder = device.CreateCommandEncoder();
603 recordDirectionalShadowPasses(encoder);
604 WGPURenderPassColorAttachment color{};
605 color.view = canvas->colorView.Get();
606 color.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED;
607 color.loadOp = WGPULoadOp_Clear;
608 color.storeOp = WGPUStoreOp_Store;
609 const Color canvasClear = canvas->clearRequested ? canvas->clearColor : clearColor;
610 color.clearValue = {canvasClear.r, canvasClear.g, canvasClear.b, canvasClear.a};
611 WGPURenderPassDepthStencilAttachment depth{};
612 depth.view = canvas->depthView.Get();
613 depth.depthClearValue = 1.f;
614 depth.depthLoadOp = WGPULoadOp_Clear;
615 depth.depthStoreOp = WGPUStoreOp_Store;
616 depth.stencilLoadOp = WGPULoadOp_Undefined;
617 depth.stencilStoreOp = WGPUStoreOp_Undefined;
618 WGPURenderPassDescriptor descriptor{};
619 descriptor.colorAttachmentCount = 1;
620 descriptor.colorAttachments = &color;
621 descriptor.depthStencilAttachment = &depth;
622 WGPUPassTimestampWrites timestampWrites{};
623 if (timestampSlot) {
624 timestampWrites.querySet = offscreenTimestampQuerySet.Get();
625 timestampWrites.beginningOfPassWriteIndex = 0;
626 timestampWrites.endOfPassWriteIndex = 1;
627 descriptor.timestampWrites = &timestampWrites;
628 }
629 wgpu::RenderPassEncoder pass =
630 encoder.BeginRenderPass(reinterpret_cast<const wgpu::RenderPassDescriptor*>(&descriptor));
631 flushMesh3D(pass, canvas->isHDR() ? WGPUTextureFormat_RGBA16Float : WGPUTextureFormat_RGBA8Unorm, true);
632 flushPrimitive3D(pass, canvas->isHDR() ? WGPUTextureFormat_RGBA16Float : WGPUTextureFormat_RGBA8Unorm, 1);
633 pass.End();
634 if (timestampSlot) {
635 encoder.ResolveQuerySet(offscreenTimestampQuerySet, 0, 2, offscreenTimestampResolveBuffer, 0);
636 encoder.CopyBufferToBuffer(offscreenTimestampResolveBuffer, 0, timestampSlot->buffer, 0, sizeof(uint64_t) * 2);
637 }
638 wgpu::CommandBuffer command = encoder.Finish();
639 queue.Submit(1, &command);
640 if (timestampSlot) {
641 timestampSlot->pending = true;
642 WGPUBufferMapCallbackInfo callback{};
643 callback.mode = WGPUCallbackMode_AllowProcessEvents;
644 callback.callback = [](WGPUMapAsyncStatus status, WGPUStringView, void* userdata1, void*) {
645 auto* slot = static_cast<OffscreenTimestampReadback*>(userdata1);
646 if (status == WGPUMapAsyncStatus_Success && slot && slot->owner) {
647 const auto* ticks =
648 static_cast<const uint64_t*>(slot->buffer.GetConstMappedRange(0, sizeof(uint64_t) * 2));
649 if (ticks && ticks[1] >= ticks[0]) {
650 const float milliseconds = float(ticks[1] - ticks[0]) * 1.0e-6f;
651 slot->owner->completedOffscreenTimestampMs.fetch_add(milliseconds);
652 }
653 slot->buffer.Unmap();
654 }
655 if (slot) slot->pending = false;
656 };
657 callback.userdata1 = timestampSlot;
658 wgpuBufferMapAsync(timestampSlot->buffer.Get(), WGPUMapMode_Read, 0, sizeof(uint64_t) * 2, callback);
659 }
660 canvas->clearRequested = false;
661 active3DCanvas = nullptr;
662 frame3DStarted = false;
663 frameHad3DThisFrame = false;
664 frameHad3D = false;
665}
666
667void Graphics::setMesh3DViewProj(const glm::mat4& viewProj) { mesh3dViewProj = viewProj; }
668void Graphics::setMesh3DView(const glm::mat4& view) { mesh3dView = view; }
669void Graphics::setMesh3DClip(float nearZ, float farZ) {
670 mesh3dNear = nearZ;
671 mesh3dFar = farZ;
672}
673
674Texture* Graphics::getSceneColorTexture() { return sceneColorTexture; }
675
677 GBuffer* gbuffer = renderControl_ ? renderControl_->getGBuffer() : nullptr;
678 return gbuffer && gbuffer->isValid() ? gbuffer->getDepthTexture() : nullptr;
679}
680
681void Graphics::drawMesh(Mesh* mesh, const glm::mat4& model, Texture* texture, const Color& tint) {
682 drawMeshShader(mesh, model, texture, tint, nullptr);
683}
684
686 if (!mesh || !mesh->gpuHandle) return;
687 frameHad3DThisFrame = true;
688 frameHad3D = true;
689 Mesh3dDraw d;
690 d.mesh = mesh;
691 d.texture = texture;
692 d.normalTexture = mesh3dNormalTexture;
693 d.heightTexture = mesh3dHeightTexture;
694 d.virtualTexture = mesh3dVirtualTexture;
695 d.virtualAtlas = mesh3dVirtualAtlas;
696 d.model = model;
697 d.tint = tint;
698 d.shader = shader;
699 d.surfaceMode = mesh3dSurfaceMode;
700 d.surfaceBlend = mesh3dSurfaceBlend;
701 d.depthWrite = mesh3dSurfaceDepthWrite;
702 d.doubleSided = mesh3dSurfaceDoubleSided;
703 d.shadowReceive = mesh3dShadowReceive;
704 d.metallic = mesh3dMetallic;
705 d.roughness = mesh3dRoughness;
706 d.viewProj = mesh3dViewProj;
707 d.view = mesh3dView;
708 d.cameraPos = mesh3dCameraPos;
709 d.lighting = mesh3dLighting;
710 d.shadows = mesh3dShadows;
711 d.environment = mesh3dEnvTexture;
712 d.environmentIntensity = mesh3dEnvIntensity;
713 d.skinInfluenceLimit = mesh3dSkinInfluenceLimit;
714 d.alphaCutoff = mesh3dAlphaCutoff;
715 d.alphaTechnique = mesh3dAlphaTechnique;
716 d.lodFade = mesh3dLodFade;
717 d.pbrSurface = mesh3dPbrSurface;
718 mesh3dDraws.push_back(d);
719}
720
721void Graphics::setMesh3DNormalTexture(Texture* normal) { mesh3dNormalTexture = normal; }
722void Graphics::setMesh3DPackedNormalMask(bool enabled) { mesh3dVirtualAtlas.z = enabled ? 1.f : 0.f; }
723void Graphics::setMesh3DHeightTexture(Texture* height) { mesh3dHeightTexture = height; }
724
725void Graphics::setMesh3DVirtualTexture(bool enabled, int pageCountX, int pageCountY, int atlasSlotsX, int atlasSlotsY,
726 float borderFraction) {
727 mesh3dVirtualTexture =
728 enabled ? glm::vec4(1.f, float(pageCountX), float(pageCountY), borderFraction) : glm::vec4(0.f);
729 const float packedNormalMask = mesh3dVirtualAtlas.z;
730 mesh3dVirtualAtlas = enabled ? glm::vec4(float(atlasSlotsX), float(atlasSlotsY), packedNormalMask, 0.f)
731 : glm::vec4(0.f, 0.f, packedNormalMask, 0.f);
732}
733void Graphics::setMesh3DSceneDepth(Texture* depth) { mesh3dSceneDepthTexture = depth; }
734void Graphics::setMesh3DSceneColor(Texture* color) { mesh3dSceneColorTexture = color; }
735
737 if (mesh3dSceneColorTexture) return Mesh3DSceneColorCaptureStatus::ExplicitOverride;
738 if (active3DCanvas)
739 return sceneColorHistoryValid ? Mesh3DSceneColorCaptureStatus::HistoryReuse
741 if (sceneColorSlots.size() < 2 || sceneColorSamples != 1)
742 return sceneColorHistoryValid ? Mesh3DSceneColorCaptureStatus::HistoryReuse
744 if (!mesh3dSceneColorCaptureIndex) mesh3dSceneColorCaptureIndex = mesh3dDraws.size();
746}
748 mesh3dMetallic = metallic;
749 mesh3dRoughness = roughness;
750}
752 const std::string& alphaTechnique) {
753 mesh3dSurfaceMode = mode;
754 mesh3dSurfaceBlend = blend;
755 mesh3dSurfaceDepthWrite = depthWrite;
756 mesh3dSurfaceDoubleSided = doubleSided;
757 mesh3dAlphaCutoff = std::clamp(alphaCutoff, 0.f, 1.f);
758 mesh3dAlphaTechnique = alphaTechnique;
759}
760void Graphics::setMesh3DTexCellBomb(float cellScale, float strength, float rotAmount) {
761 mesh3dTexBombScale = cellScale;
762 mesh3dTexBombStrength = strength;
763 mesh3dTexBombRot = rotAmount;
764}
765void Graphics::setMesh3DParallax(float scale, float minLayers, float maxLayers) {
766 mesh3dParallaxScale = scale;
767 mesh3dParallaxMin = minLayers;
768 mesh3dParallaxMax = maxLayers;
769}
770void Graphics::setMesh3DLodDither(float weight, bool reverse, bool enabled) {
771 mesh3dLodFade = glm::vec4(std::clamp(weight, 0.f, 1.f), reverse ? 1.f : 0.f, enabled ? 1.f : 0.f, 0.f);
772}
773void Graphics::setMesh3DLighting(const Lighting3DPack& pack) { mesh3dLighting = pack; }
774void Graphics::setCloudShadows(float strength, float worldCell, float time, float windSpeed, float windAngle,
775 float coverage, float detail) {
776 mesh3dCloud = glm::vec4(std::clamp(strength, 0.f, 1.f), std::max(worldCell, 1e-4f), time, 0.f);
777 mesh3dCloudWind = glm::vec4(std::cos(windAngle) * windSpeed, std::sin(windAngle) * windSpeed,
778 std::clamp(coverage, 0.f, 1.f), std::clamp(detail, 0.f, 1.f));
779}
781 mesh3dClustered = upload;
782 mesh3dClusteredActive = upload.active;
783 if (upload.active) uploadClusteredLighting(upload);
784}
785void Graphics::setMesh3DClusteredActive(bool active) { mesh3dClusteredActive = active; }
786void Graphics::setMesh3DSSAO(float intensity) { mesh3dSsaoIntensity = std::clamp(intensity, 0.f, 1.f); }
787
788void Graphics::uploadClusteredLighting(const ClusteredLightingUpload& upload) {
789 if (!device) return;
790 ClusteredStorage& st = clusteredStorage[currentFrameSlot()];
791 auto ensure = [&](wgpu::Buffer& buf, uint64_t& cap, uint64_t need) {
792 if (need == 0) need = 4;
793 if (buf && cap >= need) return;
794 WGPUBufferDescriptor bd{};
795 bd.label = sv("eve_clustered_ssbo");
796 bd.size = std::max(need, cap ? cap * 2 : need);
797 bd.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Storage;
798 bd.mappedAtCreation = false;
799 buf = device.CreateBuffer(reinterpret_cast<const wgpu::BufferDescriptor*>(&bd));
800 cap = bd.size;
801 };
802 const uint64_t lightsBytes = std::max<uint64_t>(1, upload.lights.size()) * sizeof(ClusteredLightGpu);
803 const uint64_t tableBytes = std::max<uint64_t>(1, upload.clusterTable.size()) * sizeof(ClusterTableEntry);
804 const uint64_t indicesBytes = std::max<uint64_t>(1, upload.lightIndices.size()) * sizeof(uint32_t);
805 ensure(st.lights, st.lightsCap, lightsBytes);
806 ensure(st.table, st.tableCap, tableBytes);
807 ensure(st.indices, st.indicesCap, indicesBytes);
808
809 ClusteredLightGpu zero{};
810 if (!upload.lights.empty())
811 queue.WriteBuffer(st.lights, 0, upload.lights.data(), lightsBytes);
812 else
813 queue.WriteBuffer(st.lights, 0, &zero, sizeof(zero));
814 if (!upload.clusterTable.empty()) queue.WriteBuffer(st.table, 0, upload.clusterTable.data(), tableBytes);
815 if (!upload.lightIndices.empty()) queue.WriteBuffer(st.indices, 0, upload.lightIndices.data(), indicesBytes);
816}
817void Graphics::setMesh3DLight(const glm::vec3& dir, const glm::vec3& color) {
818 mesh3dLighting.lights[0].posRadius = glm::vec4(dir, 0.f);
819 mesh3dLighting.lights[0].color = glm::vec4(color, 1.f);
820}
821void Graphics::setMesh3DCameraPos(const glm::vec3& eye) { mesh3dCameraPos = eye; }
822void Graphics::setMesh3DEnv(Texture* cube, float intensity) {
823 mesh3dEnvTexture = cube;
824 mesh3dEnvIntensity = intensity;
825}
826
827void Graphics::setMesh3DEnvProbe(const glm::vec3& center, const glm::vec3& extent) {
828 mesh3dEnvProbeCenter = center;
829 mesh3dEnvProbeExtent = glm::max(extent, glm::vec3(0.f));
830}
831
832void Graphics::setMesh3DReflectionProbes(const ReflectionProbeUpload& upload) { mesh3dReflectionProbes = upload; }
833void Graphics::setMesh3DShadows(const ShadowUpload& upload) { mesh3dShadows = upload; }
834void Graphics::setMesh3DShadowReceive(bool receive) { mesh3dShadowReceive = receive; }
836 mesh3dSkinInfluenceLimit = static_cast<int>(count);
837}
838
839void Graphics::beginShadowPass(int cascadeIndex) {
840 createShadowResources();
841 shadowPassCascade = cascadeIndex;
842 shadowPassDraws.clear();
843}
844
845void Graphics::drawMeshShadow(Mesh* mesh, const glm::mat4& lightMVP, bool doubleSided) {
846 if (!mesh || !mesh->gpuHandle) return;
847 ShadowDraw d;
848 d.mesh = mesh;
849 d.mvp = lightMVP;
850 d.doubleSided = doubleSided;
851 d.skinInfluenceLimit = mesh3dSkinInfluenceLimit;
852 shadowPassDraws.push_back(d);
853}
854
855void Graphics::drawMeshShadowAlpha(Mesh* mesh, const glm::mat4& lightMVP, Texture* albedo, bool doubleSided,
856 float lodWeight, bool lodFadeReverse, bool lodDither) {
857 if (!mesh || !mesh->gpuHandle) return;
858 ShadowDraw d;
859 d.mesh = mesh;
860 d.albedo = albedo;
861 d.mvp = lightMVP;
862 d.alphaTest = true;
863 d.doubleSided = doubleSided;
864 d.skinInfluenceLimit = mesh3dSkinInfluenceLimit;
865 d.lodFade = glm::vec4(std::clamp(lodWeight, 0.f, 1.f), lodFadeReverse ? 1.f : 0.f, lodDither ? 1.f : 0.f, 0.f);
866 shadowPassDraws.push_back(d);
867}
868
870 if (shadowPassCascade < 0 || shadowPassCascade >= ShadowConfig::kTotalLayers) {
871 shadowPassCascade = -1;
872 shadowPassDraws.clear();
873 return;
874 }
875 shadowCascadeDraws[shadowPassCascade] = shadowPassDraws;
876 shadowPassDraws.clear();
877 shadowPassCascade = -1;
878}
879
880// ---------------------------------------------------------------------------
881// GBuffer pass
882// ---------------------------------------------------------------------------
883
885 if (!device) return;
886 if (!caps.supportsFiveTargetGBuffer())
887 throw Exception("WebGPU: five-target GBuffer requires 40 color attachment bytes per sample");
888 createGbufferResources(width, height);
889 gbufferPassActive = true;
890 gbufferPassPending = true;
891 gbufferPassDraws.clear();
892}
893
894void Graphics::drawMeshGBuffer(Mesh* mesh, const glm::mat4& mvp, const glm::mat4& model, float nearZ, float farZ,
895 Texture* albedo, float tintR, float tintG, float tintB, float motionX, float motionY,
896 float roughness, float metallic, float tintA) {
897 if (!mesh || !mesh->gpuHandle) return;
898 GbufferDraw d;
899 d.mesh = mesh;
900 d.albedo = albedo;
901 d.mvp = mvp;
902 d.model = model;
903 d.nearZ = nearZ;
904 d.farZ = farZ;
905 d.tint = glm::vec4(tintR, tintG, tintB, 1.f);
906 d.motion = glm::vec2(motionX, motionY);
907 d.roughness = roughness;
908 d.metallic = metallic;
909 d.skinInfluenceLimit = mesh3dSkinInfluenceLimit;
910 if (mesh3dPbrSurface) {
911 auto& pbr = d.pbrDraw.emplace();
912 pbr.mesh = mesh;
913 pbr.model = model;
914 pbr.tint = Color(tintR, tintG, tintB, tintA);
915 pbr.pbrSurface = mesh3dPbrSurface;
916 pbr.gbufferClip = glm::vec4(nearZ, farZ, motionX, motionY);
917 pbr.gbufferMvp = mvp;
918 pbr.view = mesh3dView;
919 pbr.cameraPos = mesh3dCameraPos;
920 pbr.metallic = metallic;
921 pbr.roughness = roughness;
922 pbr.surfaceMode = d.alphaTest ? SurfaceMode::Masked : SurfaceMode::Opaque;
923 pbr.alphaCutoff = mesh3dAlphaCutoff;
924 pbr.doubleSided = mesh3dSurfaceDoubleSided;
925 pbr.skinInfluenceLimit = mesh3dSkinInfluenceLimit;
926 }
927 gbufferPassDraws.push_back(d);
928}
929
930void Graphics::drawMeshGBufferAlpha(Mesh* mesh, const glm::mat4& mvp, const glm::mat4& model, float nearZ, float farZ,
931 Texture* albedo, float tintR, float tintG, float tintB, float motionX,
932 float motionY, float roughness, float metallic, float tintA) {
933 if (!mesh || !mesh->gpuHandle) return;
934 GbufferDraw d;
935 d.mesh = mesh;
936 d.albedo = albedo;
937 d.mvp = mvp;
938 d.model = model;
939 d.nearZ = nearZ;
940 d.farZ = farZ;
941 d.tint = glm::vec4(tintR, tintG, tintB, 1.f);
942 d.motion = glm::vec2(motionX, motionY);
943 d.roughness = roughness;
944 d.metallic = metallic;
945 d.alphaTest = true;
946 d.skinInfluenceLimit = mesh3dSkinInfluenceLimit;
947 if (mesh3dPbrSurface) {
948 auto& pbr = d.pbrDraw.emplace();
949 pbr.mesh = mesh;
950 pbr.model = model;
951 pbr.tint = Color(tintR, tintG, tintB, tintA);
952 pbr.pbrSurface = mesh3dPbrSurface;
953 pbr.gbufferClip = glm::vec4(nearZ, farZ, motionX, motionY);
954 pbr.gbufferMvp = mvp;
955 pbr.view = mesh3dView;
956 pbr.cameraPos = mesh3dCameraPos;
957 pbr.metallic = metallic;
958 pbr.roughness = roughness;
959 pbr.surfaceMode = d.alphaTest ? SurfaceMode::Masked : SurfaceMode::Opaque;
960 pbr.alphaCutoff = mesh3dAlphaCutoff;
961 pbr.doubleSided = mesh3dSurfaceDoubleSided;
962 pbr.skinInfluenceLimit = mesh3dSkinInfluenceLimit;
963 }
964 gbufferPassDraws.push_back(d);
965}
966
968 gbufferPassActive = false;
969 // Expose the G-buffer textures (depth/normal/albedo/hwDepth/pbr/emissive) to
970 // RenderControl so post passes (AO, X-ray scene depth) can sample them this frame.
971 if (!gbufferSlots.empty()) {
972 GbufferSlot& slot = gbufferSlots[currentFrameSlot()];
973 getRenderControl()->getGBuffer()->setTargets(gbufferWidth, gbufferHeight, &slot.depthColorTex, &slot.normalTex,
974 &slot.albedoTex, &slot.depthTex, &slot.pbrParamsTex,
975 &slot.emissiveTex);
976 }
977}
978
980 if (!device || width <= 0 || height <= 0) return;
981 createDecalResources(width, height);
982 if (!decalFlatAlbedo) {
983 const uint8_t transparent[4] = {0, 0, 0, 0};
984 const uint8_t flatNormal[4] = {128, 128, 255, 255};
985 const uint8_t neutralParams[4] = {128, 128, 0, 255};
986 decalFlatAlbedo = newTexture(1, 1, transparent);
987 decalFlatNormal = newTexture(1, 1, flatNormal);
988 decalFlatParams = newTexture(1, 1, neutralParams);
989 }
990 decalPassActive = true;
991 decalPassPending = false;
992 decalPassDraws.clear();
993}
994
995void Graphics::setDecalCamera(const glm::mat4& viewProj, float nearZ, float farZ) {
996 (void)nearZ;
997 (void)farZ;
998 decalViewProj = viewProj;
999}
1000
1002 const float uvRect[4], float fade, float normalStrength, float roughnessStrength,
1003 float metalStrength, float emissiveStrength, int blendMode, int projectionMode,
1004 float blendSharpness, float parallaxScale, float parallaxMinLayers, float parallaxMaxLayers,
1005 float edgeFadeWidth) {
1006 if (!decalPassActive) return;
1007 DecalDraw draw;
1008 draw.model = model;
1009 draw.albedo = albedo ? albedo : decalFlatAlbedo;
1010 draw.normal = normal ? normal : decalFlatNormal;
1011 draw.params = params ? params : decalFlatParams;
1012 if (uvRect) draw.uvRect = glm::vec4(uvRect[0], uvRect[1], uvRect[2], uvRect[3]);
1013 draw.fadeParams = glm::vec4(fade, normalStrength, roughnessStrength, metalStrength);
1014 draw.extraParams = glm::vec4(emissiveStrength, float(blendMode == 1), float(std::clamp(projectionMode, 0, 3)),
1015 blendSharpness > 0.f ? blendSharpness : 4.f);
1016 const float minLayers = std::clamp(parallaxMinLayers, 1.f, 64.f);
1017 draw.surfaceParams =
1018 glm::vec4(std::clamp(parallaxScale, 0.f, 1.f), minLayers, std::clamp(parallaxMaxLayers, minLayers, 64.f),
1019 std::clamp(edgeFadeWidth, 0.f, 0.49f));
1020 decalPassDraws.push_back(draw);
1021}
1022
1024 if (!decalPassActive) return;
1025 decalPassActive = false;
1026 decalPassPending = true;
1027}
1028
1029// ---------------------------------------------------------------------------
1030// Voxel
1031// ---------------------------------------------------------------------------
1032
1033
1034// ---------------------------------------------------------------------------
1035// Scene color / shadow / gbuffer resources
1036// ---------------------------------------------------------------------------
1037
1039 auto* c = new OffscreenCanvas(this, width, height);
1040 ownedCanvases.push_back(std::unique_ptr<eve::graphics::Canvas>(c));
1041 return c;
1042}
1043
1045 auto* c = new OffscreenCanvas(this, width, height, true);
1046 ownedCanvases.push_back(std::unique_ptr<eve::graphics::Canvas>(c));
1047 return c;
1048}
1049
1051 if (activeCanvas && canvas != activeCanvas) {
1052 flush2DToCanvas(static_cast<OffscreenCanvas*>(activeCanvas));
1053 }
1054 activeCanvas = canvas;
1055}
1056
1057bool Graphics::isCanvasActive() const { return activeCanvas != nullptr; }
1058Canvas* Graphics::getCanvas() const { return activeCanvas; }
1059
1061 if (!canvas || !canvas->getTexture()) return;
1062 auto& uboArena = currentUboArena();
1063 uboArena.reset();
1064 auto& vtxArena = currentVertexArena();
1065 vtxArena.reset();
1066
1067 wgpu::CommandEncoder enc = device.CreateCommandEncoder();
1068 WGPURenderPassColorAttachment ca{};
1069 ca.view = canvas->colorView.Get();
1070 ca.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED;
1071 ca.loadOp = canvas->clearRequested ? WGPULoadOp_Clear : WGPULoadOp_Load;
1072 ca.storeOp = WGPUStoreOp_Store;
1073 ca.clearValue = {canvas->clearColor.r, canvas->clearColor.g, canvas->clearColor.b, canvas->clearColor.a};
1074 WGPURenderPassDescriptor rp{};
1075 rp.colorAttachmentCount = 1;
1076 rp.colorAttachments = &ca;
1077 wgpu::RenderPassEncoder pass = enc.BeginRenderPass(reinterpret_cast<const wgpu::RenderPassDescriptor*>(&rp));
1078 flush2D(pass, canvas->getWidth(), canvas->getHeight(),
1079 canvas->isHDR() ? WGPUTextureFormat_RGBA16Float : WGPUTextureFormat_RGBA8Unorm);
1080 pass.End();
1081 wgpu::CommandBuffer cmd = enc.Finish();
1082 queue.Submit(1, &cmd);
1083 canvas->clearRequested = false;
1084}
1085
1087 if (activeCanvas) return activeCanvas->getTexture();
1088 return sceneColorTexture;
1089}
1090
1091void Graphics::draw(eve::graphics::Graphics* gfx, const glm::mat4& matrix) const {
1092 (void)gfx;
1093 (void)matrix;
1094}
1095
1096void Graphics::draw(Canvas* C, const glm::mat4& matrix) const {
1097 (void)C;
1098 (void)matrix;
1099}
1100
1101void Graphics::clear(std::optional<Color> color, std::optional<int> /*stencil*/, std::optional<double> /*depth*/) {
1102 if (frameHad3D && activeCanvas == nullptr) return;
1103 clearColor = color.value_or(backgroundColor);
1104 hasPendingClear = true;
1105 clear2DBatches();
1106 if (auto* canvas = dynamic_cast<OffscreenCanvas*>(activeCanvas)) {
1107 canvas->clear(clearColor, std::nullopt, std::nullopt);
1108 }
1109}
1110
1111
1112} // namespace eve::graphics::webgpu
double y
double x
bool & active
float w
Definition AnimClip.cpp:738
std::string descriptor
std::vector< QuestEvent > pending
std::vector< std::uint32_t > verts
Definition Builder.cpp:27
float normalStrength
float cx
Definition CardTypes.cpp:36
float cy
Definition CardTypes.cpp:37
float degrees
Definition CardTypes.cpp:38
graphics::Texture * albedo
float strength
wgpu::PopErrorScopeStatus status
glm::vec4 tint
glm::mat4 mvp
float u
Definition Grass.cpp:233
glm::vec3 n
Definition Grass.cpp:63
float v
std::int32_t c
std::int32_t first
float blend
int h
std::uint32_t height
std::uint32_t width
size_t offset
std::array< float, 3 > scale
ActionGuidePack pack
std::string coverage
uint64_t used
std::vector< RecipeParam > params
std::uint64_t bytes
std::vector< TriangleRef > triangles
MeshVfxBatchedDraw draw
float roughness
float tb
graphics::PbrSurface pbr
bool doubleSided
Texture * normal
float alphaCutoff
float metallic
OceanMeshSettings mesh
std::shared_ptr< OceanGpuSpectrum > gpu
glm::dvec2 center
OceanSprayView view
double & milliseconds
Definition OnnxGpgpu.cpp:19
Texture * texture
int idx
float d
int detail
std::string slot
Local-probe upload record kept off the high-fanout IGraphics3D header.
bool lodFadeReverse
glm::vec3 eye
float lodWeight
glm::mat4 viewProj
Shader * shader
glm::mat4 model
glm::dmat4 matrix
size_t begin
size_t end
int count
float size
Definition TreeMesh.cpp:158
V3 dir
Definition TreeMesh.cpp:151
std::uint32_t depth
std::size_t at
double weight
uint32_t index
ViewPreparation callback
EVENGINE_API_FOUNDATION public API.
Definition Exception.h:13
Accumulates solid / textured quads in logical (Y-down) coordinates. Used by RenderSystem; not a publi...
Definition Batcher.h:23
Canvas public API.
Definition Canvas.h:17
virtual int getWidth() const =0
Returns the width.
virtual Texture * getTexture()=0
Sampleable color buffer; screen Canvas returns nullptr.
virtual int getHeight() const =0
Returns the height.
Screen-space buffers for mid/post effects and Hybrid deferred lighting.
Definition GBuffer.h:28
Texture * getDepthTexture() const
Returns the depth texture.
Definition GBuffer.h:51
void setTargets(int width, int height, Texture *depth, Texture *normal, Texture *albedo, Texture *hwDepth=nullptr, Texture *pbrParams=nullptr, Texture *emissive=nullptr)
Called by Graphics after a G-buffer pass (or clear).
Definition GBuffer.cpp:31
bool isValid() const
True when valid.
Definition GBuffer.cpp:5
int getWidth() const
Returns the width.
Definition Graphics.h:489
void ensureFileTexturesReady()
Finish CPU decode and GPU upload for outstanding newTextureFromFile results. @thread Game/render thre...
void setCanvas()
Sets the canvas.
Definition Graphics.h:2060
std::unique_ptr< RenderControl > renderControl_
Definition Graphics.h:2340
Mesh3DSceneColorCaptureStatus
Observable result of requesting a same-frame mesh SceneColor snapshot.
Definition Graphics.h:1227
RenderControl * getRenderControl()
Shared compilable 3D render control (features → pass list + GBuffer). Owned by Graphics; valid for th...
Definition Graphics.cpp:279
int getHeight() const
Returns the height.
Definition Graphics.h:491
GPU mesh handle (+ optional CPU morph targets).
Definition Mesh.h:26
Frame-local Skia-style recorder for 2D line primitives.
GBuffer * getGBuffer()
Returns the g buffer.
Custom GPU program.
Definition Shader.h:41
static constexpr uint32_t kPushConstantBytes
Definition Shader.h:45
GPU texture created via Graphics::newTexture. Owns GPU resources through an opaque backend handle.
Definition Texture.h:15
bool supportsFiveTargetGBuffer() const
True when the granted device limit supports five RGBA8 GBuffer targets.
void setMesh3DLodDither(float weight, bool reverse, bool enabled) override
Sets the mesh 3 d lod dither.
void setMesh3DEnv(Texture *cube, float intensity) override
Sets the mesh 3 d env.
void setMesh3DLight(const glm::vec3 &dir, const glm::vec3 &color) override
Sets the mesh 3 d light.
void setMesh3DPackedNormalMask(bool enabled) override
Sets the mesh 3 d packed normal mask.
void setMesh3DReflectionProbes(const ReflectionProbeUpload &upload) override
Sets the mesh 3 d reflection probes.
void drawTexturedRectLitUVRotated(Texture *albedo, Texture *normal, float cx, float cy, float w, float h, float degrees, float u0, float v0, float u1, float v1, const Color &color, BlendMode blend=BlendMode::Alpha) override
Draws textured rect lit uv rotated.
void flush2DToCanvas(OffscreenCanvas *canvas)
Flush accumulated 2D batches into an offscreen canvas target.
Mesh3DSceneColorCaptureStatus captureMesh3DSceneColor() override
Capture mesh 3 d scene color.
void setMesh3DViewProj(const glm::mat4 &viewProj) override
Sets the mesh 3 d view proj.
void draw(eve::graphics::Graphics *gfx, const glm::mat4 &matrix) const override
Draws .
void endDecalPass() override
Ends decal pass.
void setMesh3DShadowReceive(bool receive) override
Sets the mesh 3 d shadow receive.
void clear(std::optional< Color > color, std::optional< int > stencil, std::optional< double > depth) override
Clears .
void setMesh3DNormalTexture(Texture *normal) override
Sets the mesh 3 d normal texture.
void setMesh3DHeightTexture(Texture *height) override
Sets the mesh 3 d height texture.
void begin3DFrame() override
Begins 3 d frame.
void drawTexturedRectLitUV(Texture *albedo, Texture *normal, float x, float y, float w, float h, float u0, float v0, float u1, float v1, const Color &color, BlendMode blend=BlendMode::Alpha) override
Draws textured rect lit uv.
void setMesh3DCameraPos(const glm::vec3 &eye) override
Sets the mesh 3 d camera pos.
void beginGBufferPass(int width, int height) override
Begins g buffer pass.
void drawMeshGBuffer(Mesh *mesh, const glm::mat4 &mvp, const glm::mat4 &model, float nearZ, float farZ, Texture *albedo=nullptr, float tintR=1.f, float tintG=1.f, float tintB=1.f, float motionX=0.f, float motionY=0.f, float roughness=0.45f, float metallic=0.f, float tintA=1.f) override
Draws mesh g buffer.
void setMesh3DVirtualTexture(bool enabled, int pageCountX, int pageCountY, int atlasSlotsX, int atlasSlotsY, float borderFraction) override
Sets the mesh 3 d virtual texture.
void setMesh3DEnvProbe(const glm::vec3 &center, const glm::vec3 &extent) override
Sets the mesh 3 d env probe.
void drawTexturedRectShader5(Texture *color, Texture *depth, Texture *motion, Texture *extra, Texture *specular, Shader *shader, float x, float y, float w, float h, const Color &tint) override
Draws textured rect shader 5.
void setMesh3DLighting(const Lighting3DPack &pack) override
Sets the mesh 3 d lighting.
void drawMeshShader(Mesh *mesh, const glm::mat4 &model, Texture *texture, const Color &tint, Shader *shader) override
Draws mesh shader.
void setMesh3DMaterial(float metallic, float roughness) override
Sets the mesh 3 d material.
void drawSolidRectRotated(float cx, float cy, float w, float h, float degrees, const Color &color, BlendMode blend=BlendMode::Alpha) override
Draws solid rect rotated.
void setMesh3DSkinInfluenceLimit(SkinInfluenceLimit count) override
Sets the mesh 3 d skin influence limit.
void setLighting2D(const Lighting2DUBO &ubo) override
Sets the lighting 2 d.
void endGBufferPass() override
Ends g buffer pass.
void setMesh3DShadows(const ShadowUpload &upload) override
Sets the mesh 3 d shadows.
Texture * newTexture(int width, int height, const uint8_t *rgba, bool repeatU=false, bool repeatV=false) override
Creates a texture. @ownership Caller deletes unless documented otherwise.
void end3DFrameToCanvas() override
Ends 3 d frame to canvas.
void drawTexturedRectShader4(Texture *color, Texture *depth, Texture *motion, Texture *extra, Shader *shader, float x, float y, float w, float h, const Color &tint) override
Draws textured rect shader 4.
void drawMesh(Mesh *mesh, const glm::mat4 &model, Texture *texture, const Color &tint) override
Draws mesh.
void setMesh3DView(const glm::mat4 &view) override
Sets the mesh 3 d view.
void drawTexturedRect(Texture *texture, float x, float y, float w, float h, const Color &color) override
Draws textured rect.
void begin3DFrameToCanvas(Canvas *canvas) override
Begins 3 d frame to canvas.
void drawTexturedRectUV(Texture *texture, float x, float y, float w, float h, float u0, float v0, float u1, float v1, const Color &color) override
Draws textured rect uv.
void setMesh3DClusteredLighting(const ClusteredLightingUpload &upload) override
Sets the mesh 3 d clustered lighting.
void setMesh3DTexCellBomb(float cellScale, float strength, float rotAmount=1.f) override
Sets the mesh 3 d tex cell bomb.
void setMesh3DSceneColor(Texture *color) override
Sets the mesh 3 d scene color.
void beginDecalPass(int width, int height) override
Begins decal pass.
void drawTexturedRectShaderUVRotated(Texture *texture, Shader *shader, float cx, float cy, float w, float h, float degrees, float u0, float v0, float u1, float v1, const Color &color, bool rotatedUV=false, BlendMode blend=BlendMode::Alpha) override
Draws textured rect shader uv rotated.
void setMesh3DParallax(float scale, float minLayers=8.f, float maxLayers=32.f) override
Sets the mesh 3 d parallax.
void drawTexturedRectShaderDepthMotion(Texture *color, Texture *depth, Texture *motion, Shader *shader, float x, float y, float w, float h, const Color &tint) override
Draws textured rect shader depth motion.
Texture * getSceneLinearDepthTexture() override
Return the active sampleable scene linear-depth texture when available. @ownership Borrowed from the ...
void drawMeshShadow(Mesh *mesh, const glm::mat4 &lightMVP, bool doubleSided=true) override
Draws mesh shadow.
void setMesh3DClusteredActive(bool active) override
Sets the mesh 3 d clustered active.
void drawPrimitiveCanvas(const PrimitiveCanvas2D &canvas) override
Draws primitive canvas.
void drawMeshShadowAlpha(Mesh *mesh, const glm::mat4 &lightMVP, Texture *albedo=nullptr, bool doubleSided=true, float lodWeight=1.f, bool lodFadeReverse=false, bool lodDither=false) override
Draws mesh shadow alpha.
void setCloudShadows(float strength, float worldCell, float time, float windSpeed, float windAngle, float coverage, float detail) override
Sets the cloud shadows.
void drawMeshGBufferAlpha(Mesh *mesh, const glm::mat4 &mvp, const glm::mat4 &model, float nearZ, float farZ, Texture *albedo=nullptr, float tintR=1.f, float tintG=1.f, float tintB=1.f, float motionX=0.f, float motionY=0.f, float roughness=0.45f, float metallic=0.f, float tintA=1.f) override
Draws mesh g buffer alpha.
void setMesh3DClip(float nearZ, float farZ) override
Sets the mesh 3 d clip.
void endShadowPass() override
Ends shadow pass.
void drawDecal(const glm::mat4 &model, Texture *albedo, Texture *normal, Texture *params, const float uvRect[4], float fade, float normalStrength, float roughnessStrength, float metalStrength, float emissiveStrength, int blendMode=0, int projectionMode=0, float blendSharpness=4.f, float parallaxScale=0.f, float parallaxMinLayers=8.f, float parallaxMaxLayers=24.f, float edgeFadeWidth=0.06f) override
Draws decal.
void setDecalCamera(const glm::mat4 &viewProj, float nearZ, float farZ) override
Sets the decal camera.
void setMesh3DSceneDepth(Texture *depth) override
Sets the mesh 3 d scene depth.
void drawTexturedRectShaderUV(Texture *texture, Shader *shader, float x, float y, float w, float h, float u0, float v0, float u1, float v1, const Color &color, bool rotatedUV=false, BlendMode blend=BlendMode::Alpha) override
Draws textured rect shader uv.
Texture * getTexture() override
Returns the texture.
Canvas * newHDRCanvas(int width, int height) override
Creates a hdr canvas. @ownership Caller deletes unless documented otherwise.
void drawSolidRect(float x, float y, float w, float h, const Color &color, BlendMode blend=BlendMode::Alpha) override
Draws solid rect.
Canvas * newCanvas(int width, int height) override
Creates a canvas. @ownership Caller deletes unless documented otherwise.
void drawTexturedRectShader(Texture *texture, Shader *shader, float x, float y, float w, float h, const Color &color) override
Draws textured rect shader.
void drawTexturedRectShaderDepth(Texture *color, Texture *depth, Shader *shader, float x, float y, float w, float h, const Color &tint) override
Draws textured rect shader depth.
Canvas * getCanvas() const override
Returns the canvas.
void setMesh3DSSAO(float intensity) override
Sets the mesh 3 dssao.
bool isCanvasActive() const override
True when canvas active.
void setMesh3DSurface(SurfaceMode mode, BlendMode blend, bool depthWrite, bool doubleSided, float alphaCutoff, const std::string &alphaTechnique="cutoff") override
Sets the mesh 3 d surface.
void beginShadowPass(int cascadeIndex) override
Begins shadow pass.
Texture * getSceneColorTexture() override
Returns the scene color texture.
Offscreen render target (RGBA8Unorm color, optional Depth32Float). 2D batches are flushed into the ca...
Definition Canvas.h:17
int getWidth() const override
Returns the width.
Definition Canvas.h:25
int getHeight() const override
Returns the height.
Definition Canvas.h:27
Texture * getTexture() override
Returns the texture.
Definition Canvas.h:29
bool isHDR() const
True when hdr.
Definition Canvas.h:31
WGPUStringView sv(const char *s)
Build a WGPUStringView from a C string (null-safe, length auto-computed).
Definition wgpu_types.h:20
SurfaceMode
How a 3D surface contributes to depth and color passes.
Definition SurfaceMode.h:6
ResolvedPrimitiveTriangles resolvePrimitiveStrokes2D(const PrimitiveCanvas2D &canvas, glm::ivec2 viewport)
Resolves 2D stroke segment bodies into clip-space triangles.
eve::Color Color
RGBA color used by every graphics draw call. Lives inside eve::graphics so including a graphics heade...
Definition Color.h:13
Light3DGpu ClusteredLightGpu
eve::BlendMode BlendMode
Compatibility alias for the shared 2D blend mode.
Definition BlendMode.h:8
SkinInfluenceLimit
Number of strongest vertex influences retained by GPU skinning.
Definition IGraphics3D.h:20
BlendMode
Render-neutral 2D blend mode shared by graphics-facing modules.
Definition RenderTypes.h:11
bool enabled
CPU-built clustered lighting upload for one frame/camera. Point lights are clustered; directional lig...
std::vector< ClusteredLightGpu > lights
std::vector< ClusterTableEntry > clusterTable
Lighting2DUBO public API.
Definition Light.h:52
Lighting3DPack public API.
Definition Light.h:171
Light3DGpu lights[kMaxLights]
Definition Light.h:174
Resolved triangle vertex consumed by primitive GPU backends.
ReflectionProbeUpload public API.
One contiguous 2D blend/order batch in the resolved vertex stream.
static constexpr int kTotalLayers
Definition Shadow.h:27
ShadowUpload public API.
Definition Shadow.h:62
glm::vec4 color