载入中...
搜索中...
未找到
GraphicsShaders.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
48#if defined(__EMSCRIPTEN__)
49#include <emscripten/emscripten.h>
50#endif
51
52namespace eve::graphics::webgpu {
53using namespace detail;
54
55namespace {
56template <class Build>
57std::string checkedShaderBuild(wgpu::Device& device, wgpu::Instance& instance, Build&& build) {
58 device.PushErrorScope(wgpu::ErrorFilter::Validation);
59 std::string preparationError;
60 try {
61 build();
62 } catch (const std::exception& error) {
63 preparationError = error.what();
64 } catch (...) {
65 preparationError = "unknown pipeline preparation error";
66 }
67 bool done = false;
68 wgpu::ErrorType type = wgpu::ErrorType::Unknown;
69 wgpu::PopErrorScopeStatus status = wgpu::PopErrorScopeStatus::Error;
70 std::string message;
71 device.PopErrorScope(wgpu::CallbackMode::AllowProcessEvents, [&](wgpu::PopErrorScopeStatus result,
72 wgpu::ErrorType error, wgpu::StringView detail) {
73 status = result;
74 type = error;
75 if (detail.data) {
76 const auto length = detail.length == WGPU_STRLEN ? std::strlen(detail.data) : detail.length;
77 message.assign(detail.data, length);
78 }
79 done = true;
80 });
81 while (!done) {
82#if defined(__EMSCRIPTEN__)
83 emscripten_sleep(0);
84#endif
85 wgpuInstanceProcessEvents(instance.Get());
86 }
87 if (!preparationError.empty()) return preparationError;
88 if (status != wgpu::PopErrorScopeStatus::Success || type != wgpu::ErrorType::NoError)
89 return message.empty() ? "WebGPU rejected shader pipeline" : message;
90 return {};
91}
92
93} // namespace
94namespace {
95
96wgpu::RenderPipeline buildPipelineFromWgsl(wgpu::Device& dev, wgpu::PipelineLayout layout, WGPUTextureFormat format,
97 const std::string& vert, const std::string& frag, bool depth, bool blend,
98 bool mesh3d, bool hair, bool shadow, bool gbuffer, uint32_t sampleCount,
99 bool depthWrite = true) {
100 WGPURenderPipelineDescriptor pd{};
101 pd.label = sv("eve_custom_shader");
102 pd.layout = layout.Get();
103
104 WGPUVertexAttribute attrs[6]{};
105 WGPUVertexBufferLayout vb{};
106 if (mesh3d || shadow || gbuffer) {
107 fillMeshAttributes(attrs);
108 attrs[0].format = WGPUVertexFormat_Float32x3;
109 attrs[0].offset = 0;
110 attrs[0].shaderLocation = 0;
111 attrs[1].format = WGPUVertexFormat_Float32x3;
112 attrs[1].offset = 12;
113 attrs[1].shaderLocation = 1;
114 attrs[2].format = WGPUVertexFormat_Float32x2;
115 attrs[2].offset = 24;
116 attrs[2].shaderLocation = 2;
117 vb.arrayStride = sizeof(MeshVertex);
118 vb.stepMode = WGPUVertexStepMode_Vertex;
119 vb.attributeCount = 6;
120 vb.attributes = attrs;
121 } else {
122 attrs[0].format = WGPUVertexFormat_Float32x2;
123 attrs[0].offset = 0;
124 attrs[0].shaderLocation = 0;
125 attrs[1].format = WGPUVertexFormat_Float32x4;
126 attrs[1].offset = 8;
127 attrs[1].shaderLocation = 1;
128 attrs[2].format = WGPUVertexFormat_Float32x2;
129 attrs[2].offset = 24;
130 attrs[2].shaderLocation = 2;
131 vb.arrayStride = 32;
132 vb.stepMode = WGPUVertexStepMode_Vertex;
133 vb.attributeCount = 3;
134 vb.attributes = attrs;
135 }
136 pd.vertex.bufferCount = 1;
137 pd.vertex.buffers = &vb;
138
139 // Keep both modules alive until CreateRenderPipeline has consumed the
140 // descriptor. Storing only their raw handles in pd and destroying the
141 // wrappers at the end of these branches leaves dangling handles for Dawn.
142 wgpu::ShaderModule vertexModule;
143 wgpu::ShaderModule fragmentModule;
144 if (!vert.empty()) {
145 WGPUShaderModuleDescriptor md = mdDesc(vert);
146 vertexModule = dev.CreateShaderModule(reinterpret_cast<const wgpu::ShaderModuleDescriptor*>(&md));
147 pd.vertex.module = vertexModule.Get();
148 pd.vertex.entryPoint = sv("vs_main");
149 } else {
150 // Default textured vertex shader.
151 WGPUShaderModuleDescriptor md = mdDesc(kTexturedVertWgsl);
152 vertexModule = dev.CreateShaderModule(reinterpret_cast<const wgpu::ShaderModuleDescriptor*>(&md));
153 pd.vertex.module = vertexModule.Get();
154 pd.vertex.entryPoint = sv("vs_main");
155 }
156
157 // The descriptor borrows these until CreateRenderPipeline returns.
158 WGPUFragmentState fs{};
159 WGPUColorTargetState target{};
160 if (!frag.empty()) {
161 WGPUShaderModuleDescriptor md = mdDesc(frag);
162 fragmentModule = dev.CreateShaderModule(reinterpret_cast<const wgpu::ShaderModuleDescriptor*>(&md));
163 fs.module = fragmentModule.Get();
164 fs.entryPoint = sv("fs_main");
165 fs.targetCount = 1;
166 target.format = format;
167 target.writeMask = WGPUColorWriteMask_All;
168 if (blend) {
169 static WGPUBlendState bs = alphaBlend();
170 target.blend = &bs;
171 }
172 fs.targets = &target;
173 pd.fragment = &fs;
174 } else {
175 pd.fragment = nullptr;
176 }
177
178 pd.primitive.topology = WGPUPrimitiveTopology_TriangleList;
179 pd.primitive.frontFace = WGPUFrontFace_CCW;
180 pd.primitive.cullMode = hair ? WGPUCullMode_None : WGPUCullMode_None;
181 pd.primitive.stripIndexFormat = WGPUIndexFormat_Undefined;
182
183 if (depth && !shadow) {
184 static WGPUDepthStencilState ds{};
185 ds.format = WGPUTextureFormat_Depth32Float;
186 ds.depthWriteEnabled = depthWrite ? WGPUOptionalBool_True : WGPUOptionalBool_False;
187 ds.depthCompare = hair ? WGPUCompareFunction_Less : WGPUCompareFunction_LessEqual;
188 pd.depthStencil = &ds;
189 }
190 pd.multisample.count = sampleCount ? sampleCount : 1;
191 // mask=0 (zero-init) silently discards all fragments; use all-samples.
192 pd.multisample.mask = 0xFFFFFFFFu;
193 return dev.CreateRenderPipeline(reinterpret_cast<const wgpu::RenderPipelineDescriptor*>(&pd));
194}
195
196} // namespace
197
198Shader* Graphics::newShaderFromSpv(const std::vector<uint32_t>& vertSpv, const std::vector<uint32_t>& fragSpv) {
199 if (!device) throw Exception("newShaderFromSpv: device not initialized");
200 // Native Dawn can consume Vulkan SPIR-V directly; the browser build cannot
201 // (browsers only accept WGSL). The WebGPU backend therefore requires WGSL
202 // for custom shaders; SPIR-V input is rejected with a clear message.
203 throw Exception(
204 "newShaderFromSpv: SPIR-V custom shaders are not supported on the "
205 "WebGPU backend (browsers accept WGSL only). Recompile the shader "
206 "with the WebGPU toolchain (glslc+tint) and use newShaderFromWgsl.");
207}
208
209Shader* Graphics::newShaderFromSpvFile(const std::string& vertPath, const std::string& fragPath) {
210 throw Exception(
211 "newShaderFromSpvFile: SPIR-V custom shaders are not supported on the "
212 "WebGPU backend. Use WGSL shaders instead.");
213}
214
216 if (!shader || !shader->gpuHandle) return false;
217
218 auto* gpu = static_cast<GpuShader*>(shader->gpuHandle);
219 auto gpuIt = std::find_if(ownedGpuShaders.begin(), ownedGpuShaders.end(),
220 [&](const std::unique_ptr<GpuShader>& g) { return g.get() == gpu; });
221 if (gpuIt == ownedGpuShaders.end()) return false;
222
223 auto shIt = std::find_if(ownedShaders.begin(), ownedShaders.end(),
224 [&](const std::unique_ptr<Shader>& s) { return s.get() == shader; });
225 if (shIt == ownedShaders.end()) return false;
226
227 shader->gpuHandle = nullptr;
228 ownedGpuShaders.erase(gpuIt);
229 // Transfer the CPU facade to the caller instead of destroying it.
230 (void)shIt->release();
231 ownedShaders.erase(shIt);
232 return true;
233}
234
235Shader* Graphics::newShader(const std::string& vertGlsl, const std::string& fragGlsl) {
236 (void)vertGlsl;
237 (void)fragGlsl;
238 throw Exception(
239 "newShader: runtime GLSL compilation is not available on the WebGPU "
240 "backend (browser WGSL only). Ship pre-compiled WGSL shaders.");
241}
242
243Shader* Graphics::newMeshShaderFromSpv(const std::vector<uint32_t>& vertSpv, const std::vector<uint32_t>& fragSpv) {
244 (void)vertSpv;
245 (void)fragSpv;
246 throw Exception(
247 "newMeshShaderFromSpv: SPIR-V custom mesh shaders are not supported on the "
248 "WebGPU backend. Use WGSL shaders instead.");
249}
250
251Shader* Graphics::newMeshShaderFromWgsl(const std::string& vertWgsl, const std::string& fragWgsl) {
252 if (!device) throw Exception("newMeshShaderFromWgsl: device not initialized");
253 if (!mesh3dSetLayout) throw Exception("newMeshShaderFromWgsl: mesh3d layout missing");
254
255 std::string vert = vertWgsl.empty() ? kMesh3DVertWgsl : vertWgsl;
256 std::string frag = fragWgsl.empty() ? kMesh3DFragWgsl : fragWgsl;
257
258 auto gpu = std::make_unique<GpuShader>();
259 gpu->isMesh3D = true;
260 gpu->wgslVert = vert;
261 gpu->wgslFrag = frag;
262 auto error = checkedShaderBuild(device, instance, [&] {
263 gpu->mesh3dPipeline = buildPipelineFromWgsl(device, mesh3dPipelineLayout, sceneColorFormat, vert, frag,
264 /*depth*/ true, /*blend*/ false, /*mesh3d*/ true, /*hair*/ false,
265 /*shadow*/ false, /*gbuffer*/ false,
266 /*sampleCount*/ sceneColorSamples);
267 });
268 if (!error.empty() || !gpu->mesh3dPipeline)
269 throw Exception("newMeshShaderFromWgsl: %s", error.empty() ? "pipeline allocation failed" : error.c_str());
270 // X-ray variant: depth test/write off + alpha blend so occluded silhouettes
271 // paint over the building (the shader discards visible fragments itself).
272 error = checkedShaderBuild(device, instance, [&] {
273 gpu->mesh3dXrayPipeline = buildPipelineFromWgsl(device, mesh3dPipelineLayout, sceneColorFormat, vert, frag,
274 /*depth*/ false, /*blend*/ true, /*mesh3d*/ true,
275 /*hair*/ false, /*shadow*/ false, /*gbuffer*/ false,
276 /*sampleCount*/ sceneColorSamples);
277 });
278 if (!error.empty() || !gpu->mesh3dXrayPipeline)
279 throw Exception("newMeshShaderFromWgsl: %s", error.empty() ? "xray pipeline allocation failed" : error.c_str());
280
281 auto sh = std::make_unique<Shader>();
282 sh->setKind(Shader::Kind::eMesh3D);
283 sh->gpuHandle = gpu.get();
284
285 Shader* raw = sh.get();
286 ownedShaders.push_back(std::move(sh));
287 ownedGpuShaders.push_back(std::move(gpu));
288 return raw;
289}
290
292 bool doubleSided) {
293 auto found = std::find_if(ownedGpuShaders.begin(), ownedGpuShaders.end(),
294 [&](const auto& gpu) { return gpu.get() == shader.gpuHandle; });
295 if (found == ownedGpuShaders.end() || !(*found)->isMesh3D)
297 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "Expected an owned WebGPU mesh shader"));
298 auto& gpu = **found;
299 const bool alphaBlend = blend == BlendMode::Alpha;
300 wgpu::RenderPipeline candidate;
301 auto error = checkedShaderBuild(device, instance, [&] {
302 candidate =
303 buildPipelineFromWgsl(device, mesh3dPipelineLayout, sceneColorFormat, gpu.wgslVert, gpu.wgslFrag, true,
304 alphaBlend, true, doubleSided, false, false, sceneColorSamples, depthWrite);
305 });
306 if (!error.empty() || !candidate)
308 eve::DiagnosticCode::Failed, error.empty() ? "WebGPU rejected mesh surface pipeline" : error));
309 gpu.mesh3dPipeline = std::move(candidate);
310 shader.meshBlend = blend;
311 shader.meshDepthWrite = depthWrite;
312 shader.meshDoubleSided = doubleSided;
314}
315
316Shader* Graphics::newMeshShader(const std::string& vertGlsl, const std::string& fragGlsl) {
317 (void)vertGlsl;
318 (void)fragGlsl;
319 throw Exception(
320 "newMeshShader: runtime GLSL compilation is not available on the WebGPU "
321 "backend. Ship pre-compiled WGSL shaders.");
322}
323
324Shader* Graphics::newShaderFromWgsl(const std::string& vertWgsl, const std::string& fragWgsl) {
325 if (!device) throw Exception("newShaderFromWgsl: device not initialized");
326 if (fragWgsl.empty()) throw Exception("newShaderFromWgsl: empty fragment WGSL");
327 if (!tex2DPipelineLayout) throw Exception("newShaderFromWgsl: 2D pipeline layout missing");
328
329 std::string vert = vertWgsl.empty() ? kTexturedVertWgsl : vertWgsl;
330
331 auto gpu = std::make_unique<GpuShader>();
332 gpu->isMesh3D = false;
333 gpu->wgslVert = vert;
334 gpu->wgslFrag = fragWgsl;
335 // 2D custom shader: alpha blend, no depth; one pipeline per target format
336 // (swapchain surface vs RGBA8Unorm offscreen canvas).
337 auto error = checkedShaderBuild(device, instance, [&] {
338 gpu->swapchainPipeline = createPipelineForShader(gpu.get(), wgpu::TextureFormat(surfaceFormat),
339 /*depth*/ false, /*mesh3d*/ false,
340 /*hair*/ false, /*shadow*/ false,
341 /*gbuffer*/ false, tex2DPipelineLayout);
342 });
343 if (!error.empty() || !gpu->swapchainPipeline)
344 throw Exception("newShaderFromWgsl: %s", error.empty() ? "pipeline allocation failed" : error.c_str());
345 error = checkedShaderBuild(device, instance, [&] {
346 gpu->offscreenPipeline = createPipelineForShader(gpu.get(), wgpu::TextureFormat::RGBA8Unorm,
347 /*depth*/ false, /*mesh3d*/ false,
348 /*hair*/ false, /*shadow*/ false,
349 /*gbuffer*/ false, tex2DPipelineLayout);
350 gpu->swapchainOpaquePipeline =
351 buildPipelineFromWgsl(device, tex2DPipelineLayout, WGPUTextureFormat(surfaceFormat), vert, fragWgsl, false,
352 false, false, false, false, false, 1u);
353 gpu->offscreenOpaquePipeline =
354 buildPipelineFromWgsl(device, tex2DPipelineLayout, WGPUTextureFormat_RGBA8Unorm, vert, fragWgsl, false,
355 false, false, false, false, false, 1u);
356 gpu->hdrOffscreenPipeline = createPipelineForShader(gpu.get(), wgpu::TextureFormat::RGBA16Float, false, false,
357 false, false, false, tex2DPipelineLayout);
358 gpu->hdrOffscreenOpaquePipeline =
359 buildPipelineFromWgsl(device, tex2DPipelineLayout, WGPUTextureFormat_RGBA16Float, vert, fragWgsl, false,
360 false, false, false, false, false, 1u);
361 });
362 if (!error.empty() || !gpu->offscreenPipeline || !gpu->swapchainOpaquePipeline || !gpu->offscreenOpaquePipeline ||
363 !gpu->hdrOffscreenPipeline || !gpu->hdrOffscreenOpaquePipeline)
364 throw Exception("newShaderFromWgsl: %s", error.empty() ? "pipeline allocation failed" : error.c_str());
365
366 auto sh = std::make_unique<Shader>();
367 sh->setKind(Shader::Kind::eSprite2D);
368 sh->gpuHandle = gpu.get();
369
370 Shader* raw = sh.get();
371 ownedShaders.push_back(std::move(sh));
372 ownedGpuShaders.push_back(std::move(gpu));
373 return raw;
374}
375
376wgpu::RenderPipeline Graphics::createPipelineForShader(GpuShader* gs, wgpu::TextureFormat format, bool depth,
377 bool mesh3d, bool hair, bool shadow, bool gbuffer,
378 wgpu::PipelineLayout layout) {
379 if (!gs || gs->wgslFrag.empty()) return {};
380 // Custom 2D/mesh shaders blend only when the caller asks (x-ray / 2D UI);
381 // opaque meshes and shadow/gbuffer variants keep write-through targets.
382 const bool blend = !depth;
383 const uint32_t samples = mesh3d || hair || shadow || gbuffer ? sceneColorSamples : 1u;
384 return buildPipelineFromWgsl(device, layout, WGPUTextureFormat(format), gs->wgslVert, gs->wgslFrag, depth, blend,
385 mesh3d, hair, shadow, gbuffer, samples);
386}
387
388Shader* Graphics::newHairShaderFromSpv(const std::vector<uint32_t>& vertSpv, const std::vector<uint32_t>& fragSpv) {
389 (void)vertSpv;
390 (void)fragSpv;
391 throw Exception(
392 "newHairShaderFromSpv: SPIR-V hair shaders are not supported on WebGPU; "
393 "use newHairShaderFromWgsl");
394}
395
396Shader* Graphics::newHairShaderFromWgsl(const std::string& vertWgsl, const std::string& fragWgsl) {
397 if (!device) throw Exception("newHairShaderFromWgsl: device not initialized");
398 if (fragWgsl.empty()) throw Exception("newHairShaderFromWgsl: empty fragment WGSL");
399 auto gpu = std::make_unique<GpuShader>();
400 gpu->isMesh3D = true;
401 gpu->isHair3D = true;
402 gpu->wgslVert = vertWgsl.empty() ? kMesh3DVertWgsl : vertWgsl;
403 gpu->wgslFrag = fragWgsl;
404 auto error = checkedShaderBuild(device, instance, [&] {
405 gpu->mesh3dPipeline =
406 buildPipelineFromWgsl(device, mesh3dPipelineLayout, sceneColorFormat, gpu->wgslVert, gpu->wgslFrag, true,
407 true, true, true, false, false, sceneColorSamples);
408 });
409 if (!error.empty() || !gpu->mesh3dPipeline)
410 throw Exception("newHairShaderFromWgsl: %s", error.empty() ? "pipeline allocation failed" : error.c_str());
411 auto shader = std::make_unique<Shader>();
413 shader->gpuHandle = gpu.get();
414 Shader* raw = shader.get();
415 ownedShaders.push_back(std::move(shader));
416 ownedGpuShaders.push_back(std::move(gpu));
417 return raw;
418}
419
420
421} // namespace eve::graphics::webgpu
LogicalId target
const std::string & s
double raw
std::string layout
std::string message
tensor::Graph g
Definition GpuGraph.cpp:7
vkb::Device & device
vk::ShaderModule vert
vk::ShaderModule frag
wgpu::PopErrorScopeStatus status
float blend
Poco::JSON::Object::Ptr result
bool done
bool doubleSided
std::shared_ptr< OceanGpuSpectrum > gpu
std::string error
Definition Package.cpp:174
int detail
std::string build
Local-probe upload record kept off the high-fanout IGraphics3D header.
Shader * shader
bool hair
bool found
std::uint32_t depth
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
EVENGINE_API_FOUNDATION public API.
Definition Exception.h:13
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
Custom GPU program.
Definition Shader.h:41
Shader * newMeshShader(const std::string &vertGlsl, const std::string &fragGlsl) override
Creates a mesh shader. @ownership Caller deletes unless documented otherwise.
Shader * newShaderFromSpvFile(const std::string &vertPath, const std::string &fragPath) override
Creates a shader from spv file. @ownership Caller deletes unless documented otherwise.
Shader * newMeshShaderFromWgsl(const std::string &vertWgsl, const std::string &fragWgsl) override
Creates a mesh shader from wgsl. @ownership Caller deletes unless documented otherwise.
Shader * newHairShaderFromWgsl(const std::string &vertWgsl, const std::string &fragWgsl) override
Creates a hair shader from wgsl. @ownership Caller deletes unless documented otherwise.
Shader * newMeshShaderFromSpv(const std::vector< uint32_t > &vertSpv, const std::vector< uint32_t > &fragSpv) override
Creates a mesh shader from spv. @ownership Caller deletes unless documented otherwise.
Shader * newHairShaderFromSpv(const std::vector< uint32_t > &vertSpv, const std::vector< uint32_t > &fragSpv) override
Creates a hair shader from spv. @ownership Caller deletes unless documented otherwise.
Shader * newShaderFromSpv(const std::vector< uint32_t > &vertSpv, const std::vector< uint32_t > &fragSpv) override
Creates a shader from spv. @ownership Caller deletes unless documented otherwise.
bool releaseShader(Shader *shader) override
Release shader.
eve::Result< void > configureMeshShaderSurface(Shader &shader, BlendMode blend, bool depthWrite, bool doubleSided) override
Configure mesh shader surface.
Shader * newShader(const std::string &vertGlsl, const std::string &fragGlsl) override
Creates a shader. @ownership Caller deletes unless documented otherwise.
Shader * newShaderFromWgsl(const std::string &vertWgsl, const std::string &fragWgsl) override
Creates a shader from wgsl. @ownership Caller deletes unless documented otherwise.
void fillMeshAttributes(WGPUVertexAttribute(&attrs)[6])
Internal WebGPU pipeline/descriptor helper; render-thread only.
WGPUBlendState alphaBlend()
Internal WebGPU pipeline/descriptor helper; render-thread only.
WGPUShaderModuleDescriptor mdDesc(const std::string &code)
Internal WebGPU pipeline/descriptor helper; render-thread only.
const char * kMesh3DFragWgsl
const char * kTexturedVertWgsl
WGPUStringView sv(const char *s)
Build a WGPUStringView from a C string (null-safe, length auto-computed).
Definition wgpu_types.h:20
const char * kMesh3DVertWgsl
Immutable shader source. @borrowed Static storage; valid for the process lifetime.
std::vector< int64_t > attrs(const Node &n, const char *key, std::vector< int64_t > fallback)
Attrs.
BlendMode
Render-neutral 2D blend mode shared by graphics-facing modules.
Definition RenderTypes.h:11
A compiled shader: one WebGPU pipeline + layout. Also holds the WGSL sources so custom shaders can be...
Definition Graphics.h:177