A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(webgpu): backend skeleton against real Dawn headers — WGSL phase 2 slice 1
yhh4c8d14df1050
diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex a04f59953..00930799b 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -71,7 +71,7 @@ jobs:test_ecs test_events test_particle test_tilemap test_sparse_set \test_resource_pool test_shader_variant test_log_format test_registry_safety \test_shader_device test_draw_params test_texture_fb test_buffer_device \- test_compressed_format test_batch_builder test_boundary_span+ test_compressed_format test_batch_builder test_boundary_span test_webgpu_device# The root package.json is ESM, so the emscripten-emitted .js must run as .cjs.- name: Run C++ test harnesses@@ -79,7 +79,7 @@ jobs:for t in test_ecs test_events test_particle test_tilemap test_sparse_set \test_resource_pool test_shader_variant test_log_format test_registry_safety \test_shader_device test_draw_params test_texture_fb test_buffer_device \- test_compressed_format test_batch_builder test_boundary_span; do+ test_compressed_format test_batch_builder test_boundary_span test_webgpu_device; docp "build/wasm/web-tests/bin/$t.js" "build/wasm/web-tests/bin/$t.cjs"echo "=== $t"node "build/wasm/web-tests/bin/$t.cjs"diff --git a/docs/REARCHITECTURE.md b/docs/REARCHITECTURE.mdindex 5e8ac7318..e2c307d10 100644--- a/docs/REARCHITECTURE.md+++ b/docs/REARCHITECTURE.md@@ -184,9 +184,10 @@ TS 驱动的主 pass clear 退出边界,`clear` 家族退出公共 RHI:- **方法论教训(已入记忆)**:排查期间多次实验跑在陈旧 wasm 上导致结论互相矛盾;现在的协议是每轮 bisect 在源里嵌标记字符串、grep 部署产物 + 比对双份 md5 后才采信结果。- 验证(全部本地、BelowNormal):13 个 headless 场景全 PASS(含 postprocess-effects/lut-grade 两个后处理场景、mesh2d、ui-mask、lit×2);6 套 MockGfxDevice harness、SDK 241 测试文件(renderer/renderPipeline 测试更新为 load-op 契约)、desktop 63 文件、双侧 tsc、24 examples 全绿。**WebGPU 前仅剩一片**:GLSL-only `createProgram` → WGSL 通路。-### WGSL/WebGPU 通路 — 🟡 进行中:Phase 0+1 已落地(2026-07-07,`d01992f4` + Phase 1)+### WGSL/WebGPU 通路 — 🟡 进行中:Phase 0+1 + Phase 2 切片 1 已落地(2026-07-07)见 `REARCH_WGSL.md`(本地 gitignore,同 RC6/2D_PARITY 约定):着色器版图盘点(uniform 数据已全后端中立,剩程序文本)、岔路拍板(有限集人工孪生 / 图材质 AST 双发射 / 用户材质 cook 期转换——拒绝运行时翻译器的 MB 级体积代价)、四期计划(源语言接缝 → WebGPUDevice 原型 → 双语发射 → cook 期用户材质)。**Phase 0 已落地**:最后 3 个 GLSL ES 1.00 残留(SDK outline/drop-shadow/color-matrix 滤镜)重写为 fragment-only `.esshader` 反射路径——顺带修复其设计性破损(raw 形态无 `u_projection` 来源、无属性绑定、mat4 超 `setMaterialUniform` 的 vec4 上限**从未能传入**;色彩矩阵改为 4×vec4 行 + 偏移列,新增 `Filters.colorMatrixUniforms` 助手)。全仓每个程序自此都在现代缝上(300 es + UBO 反射)。**Phase 1(源语言接缝)已落地**:RHI 补上最后一块后端中立拼图——`createProgram` 收语言标签的 `GfxShaderSource`,新增 `supportsShaderLanguage` 能力查询(GL = 仅 GLSL ES 300;`Shader::compile` 在任何 GPU 调用前对不支持的语言快速失败);语言贯穿 Shader/ResourceManager(DrawParams 重写仅对 GLSL 生效);`ShaderParser::assembleStage` 获得 `ShaderTargetLanguage` 参数(WGSL 发射 = Phase 3)。MockGfxDevice 新增 `wgslSupported` 开关 + 语言门用例;行为零变化(8 harness + 场景抽样等价)。+**Phase 2 切片 1(WebGPU 后端启动)已落地**:emdawnwebgpu 端口(Dawn)集成为测试目标独立依赖(主构建零影响);`renderer/webgpu/` 新增纯映射层(GfxEnums→WGPU 全翻译,blend/模板表镜像 GLDevice 语义,load-op 规则与 RenderPassDesc 契约一致)+ 空设备安全的 `WebGPUDevice` 骨架(缓冲/纹理/WGSL 模块真实现,布局/管线描述符保留待惰性构建,pass/draw 为切片 2 结构化桩);`test_webgpu_device` 用真 Dawn 头编译验证全部描述符拼写,入 CI。### CI 常绿门禁(push-gated invariants)— ✅ 已落地(2026-07-07)此前 `build.yml` 仅 `workflow_dispatch`——boundary guards、全组件 ABI `static_assert`、各测试套件全是"约定"而非"机制"。现在**每次 push master 自动跑**:① web/playable/wechat 构建(编译期即验证生成断言 + ABI 哈希)+ 全部 15 个 C++ doctest harness(node 下执行);② 双 boundary guard + SDK tsc/构建/vitest + examples 检查 + desktop tsc/vitest(后两者此前完全不在 CI);③ headless 像素验证(sprite/mesh2d/parallax-shape/tilemap-flip/ui-mask,electron + xvfb + SwiftShader,需 `ELECTRON_DISABLE_SANDBOX`)。落地即抓到并修复三处腐化:`test_registry.cpp` 用已删除的 `View::sizeHint`、`test_sparse_set.cpp` 的局部常量撞 emscripten `PAGE_SIZE` 宏、以及一个**真回归**——单组件 `View::each` 活迭代(中途 emplace 会重访、swap-pop 移除会跳漏),多组件版早有快照契约,现已对齐。diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.cpp b/src/esengine/renderer/webgpu/WebGPUDevice.cppnew file mode 100644index 000000000..c844fc325--- /dev/null+++ b/src/esengine/renderer/webgpu/WebGPUDevice.cpp@@ -0,0 +1,412 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file WebGPUDevice.cpp+ * @brief WebGPU backend skeleton (REARCH_WGSL Phase 2, slice 1).+ */+#include "WebGPUDevice.hpp"+#include "WebGPUMappings.hpp"+#include "../../core/Log.hpp"++#include <algorithm>+#include <cstring>++namespace esengine {++using namespace webgpu;++namespace {+WGPUStringView sv(const char* text) {+ WGPUStringView view{};+ view.data = text;+ view.length = text ? std::strlen(text) : 0;+ return view;+}+} // namespace++WebGPUDevice::WebGPUDevice(WGPUDevice device) : device_(device) {+ if (device_) queue_ = wgpuDeviceGetQueue(device_);+}++WebGPUDevice::~WebGPUDevice() {+ shutdown();+}++void WebGPUDevice::init() {}++void WebGPUDevice::shutdown() {+ for (auto& [id, rec] : buffers_) {+ if (rec.buffer) wgpuBufferRelease(rec.buffer);+ }+ buffers_.clear();+ for (auto& [id, rec] : textures_) {+ if (rec.texture) wgpuTextureRelease(rec.texture);+ }+ textures_.clear();+ for (auto& [id, rec] : programs_) {+ if (rec.vertex) wgpuShaderModuleRelease(rec.vertex);+ if (rec.fragment) wgpuShaderModuleRelease(rec.fragment);+ }+ programs_.clear();+ layouts_.clear();+ pipelines_.clear();+}++void WebGPUDevice::stubOnce(const char* what) {+ for (const auto& logged : stub_logged_) {+ if (logged == what) return;+ }+ stub_logged_.emplace_back(what);+ ES_LOG_WARN("WebGPUDevice: {} not implemented yet (REARCH_WGSL Phase 2 slice 2)", what);+}++// =============================================================================+// Dynamic state (recorded in slice 2's pass encoder)+// =============================================================================++void WebGPUDevice::setViewport(i32, i32, u32, u32) { stubOnce("setViewport"); }+void WebGPUDevice::clearStencil(i32) { stubOnce("clearStencil"); }+void WebGPUDevice::setScissorTest(bool) { stubOnce("setScissorTest"); }+void WebGPUDevice::setScissor(i32, i32, i32, i32) { stubOnce("setScissor"); }++// =============================================================================+// Buffers+// =============================================================================++BufferHandle WebGPUDevice::createBuffer(const BufferDesc& desc, const void* initialData) {+ if (!device_) {+ ES_LOG_ERROR("WebGPUDevice::createBuffer: no device");+ return BufferHandle::Invalid;+ }++ WGPUBufferDescriptor bd{};+ bd.usage = toWGPUBufferUsage(desc.usage);+ // WriteBuffer requires 4-byte multiples; keep the GL-side size contract by+ // rounding the allocation, never the caller's data.+ bd.size = (desc.size + 3u) & ~3u;++ WGPUBuffer buffer = wgpuDeviceCreateBuffer(device_, &bd);+ if (!buffer) {+ ES_LOG_ERROR("WebGPUDevice::createBuffer: creation failed ({} bytes)", desc.size);+ return BufferHandle::Invalid;+ }++ const u32 id = next_id_++;+ buffers_[id] = BufferRec{buffer, desc.size, desc.usage};++ if (initialData && desc.size > 0) {+ wgpuQueueWriteBuffer(queue_, buffer, 0, initialData, (desc.size + 3u) & ~3u);+ }+ return BufferHandle{id};+}++void WebGPUDevice::deleteBuffer(BufferHandle buffer) {+ auto it = buffers_.find(static_cast<u32>(buffer));+ if (it == buffers_.end()) return;+ if (it->second.buffer) wgpuBufferRelease(it->second.buffer);+ buffers_.erase(it);+}++void WebGPUDevice::updateBuffer(BufferHandle buffer, u32 offsetBytes, const void* data, u32 sizeBytes) {+ auto it = buffers_.find(static_cast<u32>(buffer));+ if (it == buffers_.end() || !data || sizeBytes == 0) return;+ if (offsetBytes + sizeBytes > it->second.size) {+ ES_LOG_ERROR("WebGPUDevice::updateBuffer: range {}+{} exceeds buffer size {}",+ offsetBytes, sizeBytes, it->second.size);+ return;+ }+ wgpuQueueWriteBuffer(queue_, it->second.buffer, offsetBytes, data, sizeBytes);+}++void WebGPUDevice::resizeBuffer(BufferHandle buffer, u32 sizeBytes, const void* data) {+ auto it = buffers_.find(static_cast<u32>(buffer));+ if (it == buffers_.end()) return;++ // The RHI contract: the handle stays stable across growth. WebGPU buffers are+ // fixed-size, so re-create the WGPUBuffer behind the same id.+ if (it->second.buffer) wgpuBufferRelease(it->second.buffer);++ WGPUBufferDescriptor bd{};+ bd.usage = toWGPUBufferUsage(it->second.usage);+ bd.size = (sizeBytes + 3u) & ~3u;+ it->second.buffer = wgpuDeviceCreateBuffer(device_, &bd);+ it->second.size = sizeBytes;++ if (data && sizeBytes > 0 && it->second.buffer) {+ wgpuQueueWriteBuffer(queue_, it->second.buffer, 0, data, (sizeBytes + 3u) & ~3u);+ }+}++void WebGPUDevice::setUniformBuffer(u32, BufferHandle) { stubOnce("setUniformBuffer (bind groups)"); }++// =============================================================================+// Vertex layouts (descriptors retained; pipelines consume them at build time)+// =============================================================================++VertexLayoutHandle WebGPUDevice::createVertexLayout(const VertexLayoutDesc& desc) {+ // Validate every attribute has a WebGPU spelling up front — a mismatch is an+ // engine bug, not a runtime condition.+ for (u32 i = 0; i < desc.attributeCount; ++i) {+ const auto& a = desc.attributes[i];+ if (toWGPUVertexFormat(a.components, a.type, a.normalized) == kInvalidVertexFormat) {+ ES_LOG_ERROR("WebGPUDevice::createVertexLayout: attribute {} ({} x type {}) has no WGPU format",+ i, a.components, static_cast<u32>(a.type));+ return VertexLayoutHandle::Invalid;+ }+ }+ const u32 id = next_id_++;+ layouts_[id] = desc;+ return VertexLayoutHandle{id};+}++void WebGPUDevice::deleteVertexLayout(VertexLayoutHandle layout) {+ layouts_.erase(static_cast<u32>(layout));+}++void WebGPUDevice::setVertexBuffer(u32, BufferHandle, u32) { stubOnce("setVertexBuffer"); }+void WebGPUDevice::setIndexBuffer(BufferHandle) { stubOnce("setIndexBuffer"); }++const VertexLayoutDesc* WebGPUDevice::layoutDesc(VertexLayoutHandle handle) const {+ auto it = layouts_.find(static_cast<u32>(handle));+ return it != layouts_.end() ? &it->second : nullptr;+}++const PipelineDesc* WebGPUDevice::pipelineDesc(PipelineHandle handle) const {+ auto it = pipelines_.find(static_cast<u32>(handle));+ return it != pipelines_.end() ? &it->second : nullptr;+}++// =============================================================================+// Textures+// =============================================================================++TextureHandle WebGPUDevice::createTexture(const TextureDesc& desc, const void* pixels) {+ if (!device_) {+ ES_LOG_ERROR("WebGPUDevice::createTexture: no device");+ return TextureHandle::Invalid;+ }++ WGPUTextureDescriptor td{};+ td.dimension = WGPUTextureDimension_2D;+ td.format = toWGPUTextureFormat(desc.format);+ td.size = WGPUExtent3D{desc.width, desc.height, 1};+ td.mipLevelCount = 1;+ td.sampleCount = 1;+ td.usage = WGPUTextureUsage_TextureBinding | WGPUTextureUsage_CopyDst |+ WGPUTextureUsage_RenderAttachment;++ WGPUTexture texture = wgpuDeviceCreateTexture(device_, &td);+ if (!texture) {+ ES_LOG_ERROR("WebGPUDevice::createTexture: creation failed ({}x{})", desc.width, desc.height);+ return TextureHandle::Invalid;+ }++ const u32 id = next_id_++;+ textures_[id] = TextureRec{texture, desc.width, desc.height};++ if (pixels) {+ updateTexture(TextureHandle{id}, 0, 0, desc.width, desc.height, pixels, false);+ }+ return TextureHandle{id};+}++TextureHandle WebGPUDevice::createCompressedTexture(const TextureDesc&, GfxCompressedFormat,+ const void*, u32) {+ stubOnce("createCompressedTexture");+ return TextureHandle::Invalid;+}++TextureHandle WebGPUDevice::importExternalTexture(u32, const TextureDesc&) {+ // GL-id import has no WebGPU meaning; external surfaces arrive as WGPUTexture+ // in a later slice (canvas/video import path).+ stubOnce("importExternalTexture");+ return TextureHandle::Invalid;+}++void WebGPUDevice::deleteTexture(TextureHandle texture) {+ auto it = textures_.find(static_cast<u32>(texture));+ if (it == textures_.end()) return;+ if (it->second.texture) wgpuTextureRelease(it->second.texture);+ textures_.erase(it);+}++void WebGPUDevice::updateTexture(TextureHandle texture, i32 x, i32 y, u32 width, u32 height,+ const void* pixels, bool flipY) {+ auto it = textures_.find(static_cast<u32>(texture));+ if (it == textures_.end() || !pixels || !queue_) return;+ if (flipY) {+ // The GL backend flips via UNPACK_FLIP_Y_WEBGL; WebGPU has no upload flip.+ // Slice 2 decides the single flip point (CPU pre-flip at the loader).+ stubOnce("updateTexture(flipY)");+ }++ WGPUTexelCopyTextureInfo dst{};+ dst.texture = it->second.texture;+ dst.origin = WGPUOrigin3D{static_cast<u32>(x), static_cast<u32>(y), 0};++ WGPUTexelCopyBufferLayout layout{};+ layout.bytesPerRow = width * 4; // RGBA8 — the engine's only uncompressed upload format+ layout.rowsPerImage = height;++ WGPUExtent3D extent{width, height, 1};+ wgpuQueueWriteTexture(queue_, &dst, pixels,+ static_cast<usize>(width) * height * 4, &layout, &extent);+}++void WebGPUDevice::setTextureParams(TextureHandle, TextureFilter, TextureFilter,+ TextureWrap, TextureWrap) {+ // Sampler state is a bind-group object on WebGPU, not texture state; the+ // sampler cache keyed by (filter, wrap) lands with bind groups in slice 2.+ stubOnce("setTextureParams (sampler objects)");+}++void WebGPUDevice::generateMipmaps(TextureHandle) { stubOnce("generateMipmaps"); }+void WebGPUDevice::bindTexture(u32, TextureHandle) { stubOnce("bindTexture (bind groups)"); }++bool WebGPUDevice::supportsCompressedFormat(GfxCompressedFormat format) {+ // Real capability negotiation (adapter features) arrives with the adapter+ // plumbing; ETC2 is core on WebGPU-with-compat targets we care about.+ return toWGPUCompressedFormat(format) != WGPUTextureFormat_Undefined;+}++// =============================================================================+// Programs (WGSL shader modules)+// =============================================================================++ShaderHandle WebGPUDevice::createProgram(const GfxShaderSource& source,+ const GfxAttribBinding*, u32,+ std::string* outLog, GfxShaderStage* outFailedStage) {+ if (source.language != GfxShaderLanguage::WGSL) {+ if (outLog) *outLog = "WebGPUDevice compiles WGSL only";+ if (outFailedStage) *outFailedStage = GfxShaderStage::Vertex;+ ES_LOG_ERROR("WebGPUDevice::createProgram: unsupported shader language");+ return ShaderHandle::Invalid;+ }+ if (!device_) {+ if (outLog) *outLog = "no WGPUDevice";+ ES_LOG_ERROR("WebGPUDevice::createProgram: no device");+ return ShaderHandle::Invalid;+ }++ auto makeModule = [&](const char* code) -> WGPUShaderModule {+ WGPUShaderSourceWGSL wgsl{};+ wgsl.chain.sType = WGPUSType_ShaderSourceWGSL;+ wgsl.code = sv(code);+ WGPUShaderModuleDescriptor md{};+ md.nextInChain = &wgsl.chain;+ return wgpuDeviceCreateShaderModule(device_, &md);+ };++ ProgramRec rec{};+ rec.vertex = makeModule(source.vertexSrc);+ rec.fragment = makeModule(source.fragmentSrc);+ if (!rec.vertex || !rec.fragment) {+ if (rec.vertex) wgpuShaderModuleRelease(rec.vertex);+ if (rec.fragment) wgpuShaderModuleRelease(rec.fragment);+ if (outLog) *outLog = "shader module creation failed";+ if (outFailedStage) *outFailedStage = rec.vertex ? GfxShaderStage::Fragment : GfxShaderStage::Vertex;+ return ShaderHandle::Invalid;+ }++ const u32 id = next_id_++;+ programs_[id] = rec;+ return ShaderHandle{id};+}++void WebGPUDevice::deleteProgram(ShaderHandle program) {+ auto it = programs_.find(static_cast<u32>(program));+ if (it == programs_.end()) return;+ if (it->second.vertex) wgpuShaderModuleRelease(it->second.vertex);+ if (it->second.fragment) wgpuShaderModuleRelease(it->second.fragment);+ programs_.erase(it);+}++void WebGPUDevice::useProgram(ShaderHandle) { /* programs bind via pipelines */ }++// Loose uniforms do not exist on WebGPU: all uniform data rides the UBO bindings+// (0-4) and samplers ride bind groups. The engine reaches these only for sampler+// seeding on GLSL-shaped programs, which a WGSL pipeline never has.+i32 WebGPUDevice::getUniformLocation(ShaderHandle, const char*) { return -1; }+i32 WebGPUDevice::getAttribLocation(ShaderHandle, const char*) { return -1; }+void WebGPUDevice::setUniform1i(i32, i32) {}+void WebGPUDevice::setUniform1f(i32, f32) {}+void WebGPUDevice::setUniform2f(i32, f32, f32) {}+void WebGPUDevice::setUniform3f(i32, f32, f32, f32) {}+void WebGPUDevice::setUniform4f(i32, f32, f32, f32, f32) {}+void WebGPUDevice::setUniformMat3(i32, const f32*) {}+void WebGPUDevice::setUniformMat4(i32, const f32*) {}+std::vector<GfxUniformInfo> WebGPUDevice::getActiveUniforms(ShaderHandle) { return {}; }++u32 WebGPUDevice::getUniformBlockIndex(ShaderHandle, const char*) {+ // Blocks bind by @group/@binding in WGSL; Shader::compile skips GL-style+ // block wiring when this reports "absent".+ return GFX_INVALID_UNIFORM_BLOCK;+}+void WebGPUDevice::uniformBlockBinding(ShaderHandle, u32, u32) {}++// =============================================================================+// Pipelines (descriptors retained; WGPURenderPipeline builds in slice 2 where+// bind-group layouts exist)+// =============================================================================++PipelineHandle WebGPUDevice::createPipeline(const PipelineDesc& desc) {+ const u32 id = next_id_++;+ pipelines_[id] = desc;+ return static_cast<PipelineHandle>(id);+}++void WebGPUDevice::setPipeline(PipelineHandle) { stubOnce("setPipeline"); }+void WebGPUDevice::setStencilReference(i32) { stubOnce("setStencilReference"); }+void WebGPUDevice::invalidatePipelineCache() {}++// =============================================================================+// Draws / passes — slice 2 (per-frame command encoder + surface plumbing)+// =============================================================================++void WebGPUDevice::drawElements(u32, GfxDataType, u32) { stubOnce("drawElements"); }+void WebGPUDevice::drawArrays(u32, u32) { stubOnce("drawArrays"); }+void WebGPUDevice::drawElementsInstanced(u32, GfxDataType, u32, u32) { stubOnce("drawElementsInstanced"); }++FramebufferHandle WebGPUDevice::createFramebuffer(const FramebufferDesc&) {+ stubOnce("createFramebuffer");+ return FramebufferHandle::Default;+}+void WebGPUDevice::deleteFramebuffer(FramebufferHandle) {}+void WebGPUDevice::beginRenderPass(const RenderPassDesc&) { stubOnce("beginRenderPass"); }+void WebGPUDevice::endRenderPass() { stubOnce("endRenderPass"); }++void WebGPUDevice::readPixels(i32, i32, u32, u32, GfxPixelFormat, void*) { stubOnce("readPixels"); }++// =============================================================================+// Timing / queries / debug+// =============================================================================++u32 WebGPUDevice::createTimerQuery() { return 0; } // "no GPU timing" — same contract as a bare GL backend+void WebGPUDevice::beginTimerQuery(u32) {}+void WebGPUDevice::endTimerQuery() {}+bool WebGPUDevice::timerDisjoint() { return false; }+bool WebGPUDevice::getTimerQueryNs(u32, u64*) { return false; }++void WebGPUDevice::setWireframe(bool) {}+u32 WebGPUDevice::getError() { return 0; }++std::string WebGPUDevice::getString(GfxStringName name) {+ switch (name) {+ case GfxStringName::Renderer: return "WebGPU (Dawn/emdawnwebgpu)";+ case GfxStringName::Vendor: return "WebGPU";+ case GfxStringName::Version: return "WebGPU 1.0";+ case GfxStringName::ShadingLanguageVersion: return "WGSL";+ default: return {};+ }+}++i32 WebGPUDevice::getInt(GfxIntParam param) {+ switch (param) {+ case GfxIntParam::MaxTextureSize: return 8192;+ case GfxIntParam::MaxTextureImageUnits: return 16;+ case GfxIntParam::MaxVertexAttribs: return 16;+ default: return 0;+ }+}++} // namespace esenginediff --git a/src/esengine/renderer/webgpu/WebGPUDevice.hpp b/src/esengine/renderer/webgpu/WebGPUDevice.hppnew file mode 100644index 000000000..972f66c78--- /dev/null+++ b/src/esengine/renderer/webgpu/WebGPUDevice.hpp@@ -0,0 +1,166 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file WebGPUDevice.hpp+ * @brief WebGPU (Dawn / emdawnwebgpu) backend skeleton for GfxDevice (REARCH_WGSL Phase 2).+ * @details Slice 1: resource creation (buffers / textures / shader modules /+ * layout+pipeline descriptors) is implemented against the real Dawn C API;+ * pass encoding and draws are structured stubs for slice 2 (they need the+ * per-frame command-encoder model wired to a surface). The class is+ * null-device safe: constructed without a WGPUDevice it degrades every+ * entry point to a logged no-op, so handle bookkeeping and the language+ * gate are testable without an adapter.+ *+ * Compiled only under ES_ENABLE_WEBGPU; never part of the GL build.+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the Apache License, Version 2.0.+ */+#pragma once++#include "../GfxDevice.hpp"++#include <webgpu/webgpu.h>++#include <string>+#include <unordered_map>+#include <vector>++namespace esengine {++class WebGPUDevice final : public GfxDevice {+public:+ /** @brief @p device may be null for bookkeeping-only use (tests, bring-up). */+ explicit WebGPUDevice(WGPUDevice device = nullptr);+ ~WebGPUDevice() override;++ void init() override;+ void shutdown() override;++ void setViewport(i32 x, i32 y, u32 w, u32 h) override;+ void clearStencil(i32 value) override;++ void setScissorTest(bool enabled) override;+ void setScissor(i32 x, i32 y, i32 w, i32 h) override;++ BufferHandle createBuffer(const BufferDesc& desc, const void* initialData) override;+ void deleteBuffer(BufferHandle buffer) override;+ void updateBuffer(BufferHandle buffer, u32 offsetBytes, const void* data, u32 sizeBytes) override;+ void resizeBuffer(BufferHandle buffer, u32 sizeBytes, const void* data) override;+ void setUniformBuffer(u32 slot, BufferHandle buffer) override;++ VertexLayoutHandle createVertexLayout(const VertexLayoutDesc& desc) override;+ void deleteVertexLayout(VertexLayoutHandle layout) override;+ void setVertexBuffer(u32 slot, BufferHandle buffer, u32 offsetBytes) override;+ void setIndexBuffer(BufferHandle buffer) override;++ TextureHandle createTexture(const TextureDesc& desc, const void* pixels) override;+ TextureHandle createCompressedTexture(const TextureDesc& desc, GfxCompressedFormat format,+ const void* data, u32 byteLength) override;+ TextureHandle importExternalTexture(u32 nativeId, const TextureDesc& desc) override;+ void deleteTexture(TextureHandle texture) override;+ void updateTexture(TextureHandle texture, i32 x, i32 y, u32 width, u32 height,+ const void* pixels, bool flipY) override;+ void setTextureParams(TextureHandle texture, TextureFilter minFilter, TextureFilter magFilter,+ TextureWrap wrapS, TextureWrap wrapT) override;+ void generateMipmaps(TextureHandle texture) override;+ void bindTexture(u32 slot, TextureHandle texture) override;+ bool supportsCompressedFormat(GfxCompressedFormat format) override;++ bool supportsShaderLanguage(GfxShaderLanguage language) const override {+ return language == GfxShaderLanguage::WGSL;+ }+ ShaderHandle createProgram(const GfxShaderSource& source,+ const GfxAttribBinding* bindings, u32 bindingCount,+ std::string* outLog, GfxShaderStage* outFailedStage) override;+ void deleteProgram(ShaderHandle program) override;+ void useProgram(ShaderHandle program) override;+ i32 getUniformLocation(ShaderHandle program, const char* name) override;+ i32 getAttribLocation(ShaderHandle program, const char* name) override;+ void setUniform1i(i32 location, i32 value) override;+ void setUniform1f(i32 location, f32 value) override;+ void setUniform2f(i32 location, f32 x, f32 y) override;+ void setUniform3f(i32 location, f32 x, f32 y, f32 z) override;+ void setUniform4f(i32 location, f32 x, f32 y, f32 z, f32 w) override;+ void setUniformMat3(i32 location, const f32* value) override;+ void setUniformMat4(i32 location, const f32* value) override;+ std::vector<GfxUniformInfo> getActiveUniforms(ShaderHandle program) override;++ u32 getUniformBlockIndex(ShaderHandle program, const char* blockName) override;+ void uniformBlockBinding(ShaderHandle program, u32 blockIndex, u32 bindingPoint) override;++ PipelineHandle createPipeline(const PipelineDesc& desc) override;+ void setPipeline(PipelineHandle pipeline) override;+ void setStencilReference(i32 reference) override;+ void invalidatePipelineCache() override;++ void drawElements(u32 indexCount, GfxDataType indexType, u32 indexByteOffset) override;+ void drawArrays(u32 firstVertex, u32 vertexCount) override;+ void drawElementsInstanced(u32 indexCount, GfxDataType indexType, u32 indexByteOffset,+ u32 instanceCount) override;++ FramebufferHandle createFramebuffer(const FramebufferDesc& desc) override;+ void deleteFramebuffer(FramebufferHandle framebuffer) override;+ void beginRenderPass(const RenderPassDesc& desc) override;+ void endRenderPass() override;++ void readPixels(i32 x, i32 y, u32 w, u32 h, GfxPixelFormat format, void* data) override;++ u32 createTimerQuery() override;+ void beginTimerQuery(u32 query) override;+ void endTimerQuery() override;+ bool timerDisjoint() override;+ bool getTimerQueryNs(u32 query, u64* outNs) override;++ void setWireframe(bool enabled) override;+ u32 getError() override;+ std::string getString(GfxStringName name) override;+ i32 getInt(GfxIntParam param) override;++ // -------------------------------------------------------------------------+ // Bring-up introspection (tests / slice-2 plumbing)+ // -------------------------------------------------------------------------++ bool hasDevice() const { return device_ != nullptr; }+ usize bufferCount() const { return buffers_.size(); }+ usize textureCount() const { return textures_.size(); }+ usize layoutCount() const { return layouts_.size(); }+ usize pipelineDescCount() const { return pipelines_.size(); }+ const VertexLayoutDesc* layoutDesc(VertexLayoutHandle handle) const;+ const PipelineDesc* pipelineDesc(PipelineHandle handle) const;++private:+ struct BufferRec {+ WGPUBuffer buffer = nullptr;+ u32 size = 0;+ GfxBufferUsage usage = GfxBufferUsage::Vertex;+ };+ struct TextureRec {+ WGPUTexture texture = nullptr;+ u32 width = 0;+ u32 height = 0;+ };+ struct ProgramRec {+ WGPUShaderModule vertex = nullptr;+ WGPUShaderModule fragment = nullptr;+ };++ /** @brief Logs the slice-2 stub once per entry point (draws/passes). */+ void stubOnce(const char* what);++ WGPUDevice device_ = nullptr;+ WGPUQueue queue_ = nullptr;++ u32 next_id_ = 1;+ std::unordered_map<u32, BufferRec> buffers_;+ std::unordered_map<u32, TextureRec> textures_;+ std::unordered_map<u32, ProgramRec> programs_;+ std::unordered_map<u32, VertexLayoutDesc> layouts_;+ std::unordered_map<u32, PipelineDesc> pipelines_;+ std::vector<std::string> stub_logged_;+};++} // namespace esenginediff --git a/src/esengine/renderer/webgpu/WebGPUMappings.hpp b/src/esengine/renderer/webgpu/WebGPUMappings.hppnew file mode 100644index 000000000..c322e2ad7--- /dev/null+++ b/src/esengine/renderer/webgpu/WebGPUMappings.hpp@@ -0,0 +1,280 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file WebGPUMappings.hpp+ * @brief Pure RHI-enum → WebGPU translations (REARCH_WGSL Phase 2).+ * @details Every GfxEnums/PipelineState concept the GL backend consumes has its+ * WebGPU spelling here, as free functions with no device dependency — so+ * the mapping layer is unit-testable long before a live adapter exists,+ * and WebGPUDevice stays a thin orchestration shell over these.+ *+ * Compiled only under ES_ENABLE_WEBGPU (emdawnwebgpu port supplies+ * <webgpu/webgpu.h>); never part of the GL build.+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the Apache License, Version 2.0.+ */+#pragma once++#include "../../core/Types.hpp"+#include "../GfxEnums.hpp"+#include "../BlendMode.hpp"+#include "../PipelineState.hpp"++#include <webgpu/webgpu.h>++namespace esengine::webgpu {++// =============================================================================+// Blend+// =============================================================================++/** @brief One RHI blend mode as a full WebGPU blend state (color + alpha). */+struct BlendStateWGPU {+ WGPUBlendComponent color;+ WGPUBlendComponent alpha;+};++/** @brief Maps BlendMode to its WebGPU blend components — mirrors GLDevice's+ * setBlendMode table (Overlay renders as Normal there too; the real+ * overlay math lives in shaders). */+inline BlendStateWGPU toWGPUBlend(BlendMode mode) {+ auto comp = [](WGPUBlendOperation op, WGPUBlendFactor src, WGPUBlendFactor dst) {+ WGPUBlendComponent c{};+ c.operation = op;+ c.srcFactor = src;+ c.dstFactor = dst;+ return c;+ };+ const auto add = WGPUBlendOperation_Add;+ switch (mode) {+ case BlendMode::Additive:+ return { comp(add, WGPUBlendFactor_SrcAlpha, WGPUBlendFactor_One),+ comp(add, WGPUBlendFactor_One, WGPUBlendFactor_One) };+ case BlendMode::Multiply:+ return { comp(add, WGPUBlendFactor_Dst, WGPUBlendFactor_OneMinusSrcAlpha),+ comp(add, WGPUBlendFactor_One, WGPUBlendFactor_OneMinusSrcAlpha) };+ case BlendMode::Screen:+ return { comp(add, WGPUBlendFactor_One, WGPUBlendFactor_OneMinusSrc),+ comp(add, WGPUBlendFactor_One, WGPUBlendFactor_OneMinusSrcAlpha) };+ case BlendMode::PremultipliedAlpha:+ return { comp(add, WGPUBlendFactor_One, WGPUBlendFactor_OneMinusSrcAlpha),+ comp(add, WGPUBlendFactor_One, WGPUBlendFactor_OneMinusSrcAlpha) };+ case BlendMode::PmaAdditive:+ return { comp(add, WGPUBlendFactor_One, WGPUBlendFactor_One),+ comp(add, WGPUBlendFactor_One, WGPUBlendFactor_One) };+ case BlendMode::Lighten:+ return { comp(WGPUBlendOperation_Max, WGPUBlendFactor_One, WGPUBlendFactor_One),+ comp(WGPUBlendOperation_Max, WGPUBlendFactor_One, WGPUBlendFactor_One) };+ case BlendMode::Darken:+ return { comp(WGPUBlendOperation_Min, WGPUBlendFactor_One, WGPUBlendFactor_One),+ comp(WGPUBlendOperation_Min, WGPUBlendFactor_One, WGPUBlendFactor_One) };+ case BlendMode::Normal:+ case BlendMode::Overlay:+ default:+ return { comp(add, WGPUBlendFactor_SrcAlpha, WGPUBlendFactor_OneMinusSrcAlpha),+ comp(add, WGPUBlendFactor_One, WGPUBlendFactor_OneMinusSrcAlpha) };+ }+}++// =============================================================================+// Vertex layout+// =============================================================================++/** @brief Sentinel for "no WGPU spelling": the header defines no Undefined vertex+ * format, so the enum's non-value stands in. Callers treat it as a hard error. */+inline constexpr WGPUVertexFormat kInvalidVertexFormat = WGPUVertexFormat_Force32;++/** @brief Maps one RHI attribute (components × type × normalized) to a+ * WGPUVertexFormat, or kInvalidVertexFormat for combinations the engine+ * never produces. */+inline WGPUVertexFormat toWGPUVertexFormat(u8 components, GfxDataType type, bool normalized) {+ switch (type) {+ case GfxDataType::Float:+ switch (components) {+ case 1: return WGPUVertexFormat_Float32;+ case 2: return WGPUVertexFormat_Float32x2;+ case 3: return WGPUVertexFormat_Float32x3;+ case 4: return WGPUVertexFormat_Float32x4;+ default: return kInvalidVertexFormat;+ }+ case GfxDataType::UnsignedByte:+ // The engine's u8 attributes are colors (normalized RGBA8) — 4 lanes only.+ if (components == 4) return normalized ? WGPUVertexFormat_Unorm8x4 : WGPUVertexFormat_Uint8x4;+ if (components == 2) return normalized ? WGPUVertexFormat_Unorm8x2 : WGPUVertexFormat_Uint8x2;+ return kInvalidVertexFormat;+ case GfxDataType::UnsignedShort:+ if (components == 2) return normalized ? WGPUVertexFormat_Unorm16x2 : WGPUVertexFormat_Uint16x2;+ if (components == 4) return normalized ? WGPUVertexFormat_Unorm16x4 : WGPUVertexFormat_Uint16x4;+ return kInvalidVertexFormat;+ case GfxDataType::Int:+ switch (components) {+ case 1: return WGPUVertexFormat_Sint32;+ case 2: return WGPUVertexFormat_Sint32x2;+ case 3: return WGPUVertexFormat_Sint32x3;+ case 4: return WGPUVertexFormat_Sint32x4;+ default: return kInvalidVertexFormat;+ }+ case GfxDataType::UnsignedInt:+ switch (components) {+ case 1: return WGPUVertexFormat_Uint32;+ case 2: return WGPUVertexFormat_Uint32x2;+ case 3: return WGPUVertexFormat_Uint32x3;+ case 4: return WGPUVertexFormat_Uint32x4;+ default: return kInvalidVertexFormat;+ }+ default:+ return kInvalidVertexFormat;+ }+}++/** @brief Index type for drawElements' GfxDataType. */+inline WGPUIndexFormat toWGPUIndexFormat(GfxDataType type) {+ switch (type) {+ case GfxDataType::UnsignedShort: return WGPUIndexFormat_Uint16;+ case GfxDataType::UnsignedInt: return WGPUIndexFormat_Uint32;+ default: return WGPUIndexFormat_Undefined;+ }+}++// =============================================================================+// Textures / samplers+// =============================================================================++inline WGPUTextureFormat toWGPUTextureFormat(GfxPixelFormat fmt) {+ switch (fmt) {+ // WebGPU has no 3-channel color format; RGB8 sources upload as RGBA8+ // (the GL backend's swizzle-free equivalent — expansion happens at upload).+ case GfxPixelFormat::RGB8: return WGPUTextureFormat_RGBA8Unorm;+ case GfxPixelFormat::RGBA8: return WGPUTextureFormat_RGBA8Unorm;+ case GfxPixelFormat::DepthComponent24: return WGPUTextureFormat_Depth24Plus;+ case GfxPixelFormat::Depth24Stencil8: return WGPUTextureFormat_Depth24PlusStencil8;+ default: return WGPUTextureFormat_RGBA8Unorm;+ }+}++inline WGPUTextureFormat toWGPUCompressedFormat(GfxCompressedFormat fmt) {+ switch (fmt) {+ case GfxCompressedFormat::ETC2_RGB8: return WGPUTextureFormat_ETC2RGB8Unorm;+ case GfxCompressedFormat::ETC2_RGBA8: return WGPUTextureFormat_ETC2RGBA8Unorm;+ case GfxCompressedFormat::ASTC_4x4: return WGPUTextureFormat_ASTC4x4Unorm;+ case GfxCompressedFormat::ASTC_8x8: return WGPUTextureFormat_ASTC8x8Unorm;+ case GfxCompressedFormat::S3TC_DXT1: return WGPUTextureFormat_BC1RGBAUnorm;+ case GfxCompressedFormat::S3TC_DXT5: return WGPUTextureFormat_BC3RGBAUnorm;+ default: return WGPUTextureFormat_Undefined;+ }+}++inline WGPUFilterMode toWGPUFilter(TextureFilter filter) {+ return filter == TextureFilter::Nearest ? WGPUFilterMode_Nearest : WGPUFilterMode_Linear;+}++inline WGPUAddressMode toWGPUAddressMode(TextureWrap wrap) {+ switch (wrap) {+ case TextureWrap::ClampToEdge: return WGPUAddressMode_ClampToEdge;+ case TextureWrap::MirroredRepeat: return WGPUAddressMode_MirrorRepeat;+ case TextureWrap::Repeat:+ default: return WGPUAddressMode_Repeat;+ }+}++// =============================================================================+// Buffers+// =============================================================================++inline WGPUBufferUsage toWGPUBufferUsage(GfxBufferUsage usage) {+ switch (usage) {+ case GfxBufferUsage::Vertex: return WGPUBufferUsage_Vertex | WGPUBufferUsage_CopyDst;+ case GfxBufferUsage::Index: return WGPUBufferUsage_Index | WGPUBufferUsage_CopyDst;+ case GfxBufferUsage::Uniform: return WGPUBufferUsage_Uniform | WGPUBufferUsage_CopyDst;+ default: return WGPUBufferUsage_CopyDst;+ }+}++// =============================================================================+// Depth / stencil (PipelineDesc → WGPUDepthStencilState pieces)+// =============================================================================++inline WGPUCompareFunction toWGPUCompare(GfxStencilFunc func) {+ switch (func) {+ case GfxStencilFunc::Never: return WGPUCompareFunction_Never;+ case GfxStencilFunc::Less: return WGPUCompareFunction_Less;+ case GfxStencilFunc::Equal: return WGPUCompareFunction_Equal;+ case GfxStencilFunc::LEqual: return WGPUCompareFunction_LessEqual;+ case GfxStencilFunc::Greater: return WGPUCompareFunction_Greater;+ case GfxStencilFunc::NotEqual: return WGPUCompareFunction_NotEqual;+ case GfxStencilFunc::GEqual: return WGPUCompareFunction_GreaterEqual;+ case GfxStencilFunc::Always:+ default: return WGPUCompareFunction_Always;+ }+}++inline WGPUStencilOperation toWGPUStencilOp(GfxStencilOp op) {+ switch (op) {+ case GfxStencilOp::Zero: return WGPUStencilOperation_Zero;+ case GfxStencilOp::Replace: return WGPUStencilOperation_Replace;+ case GfxStencilOp::Incr: return WGPUStencilOperation_IncrementClamp;+ case GfxStencilOp::Decr: return WGPUStencilOperation_DecrementClamp;+ case GfxStencilOp::Invert: return WGPUStencilOperation_Invert;+ case GfxStencilOp::IncrWrap: return WGPUStencilOperation_IncrementWrap;+ case GfxStencilOp::DecrWrap: return WGPUStencilOperation_DecrementWrap;+ case GfxStencilOp::Keep:+ default: return WGPUStencilOperation_Keep;+ }+}++/** @brief The engine's two stencil modes as WebGPU face states (same table as+ * GLDevice::applyPipeline: Write = Always/Replace + no color write,+ * Test = Equal/Keep). */+inline WGPUStencilFaceState toWGPUStencilFace(GfxStencilMode mode) {+ WGPUStencilFaceState face{};+ face.depthFailOp = WGPUStencilOperation_Keep;+ switch (mode) {+ case GfxStencilMode::Write:+ face.compare = WGPUCompareFunction_Always;+ face.failOp = WGPUStencilOperation_Replace;+ face.passOp = WGPUStencilOperation_Replace;+ break;+ case GfxStencilMode::Test:+ face.compare = WGPUCompareFunction_Equal;+ face.failOp = WGPUStencilOperation_Keep;+ face.passOp = WGPUStencilOperation_Keep;+ break;+ case GfxStencilMode::Off:+ default:+ face.compare = WGPUCompareFunction_Always;+ face.failOp = WGPUStencilOperation_Keep;+ face.passOp = WGPUStencilOperation_Keep;+ break;+ }+ return face;+}++// =============================================================================+// Render pass load-ops (RenderPassDesc carries the values since the load-op+// unification; a scoped clear region has NO load-op equivalent — the device+// emulates it with a scissored clear-quad, exactly as documented in GfxEnums).+// =============================================================================++inline WGPULoadOp toWGPULoadOp(bool clearRequested, bool scoped) {+ // A region-scoped clear must LOAD the attachment and clear the region by+ // other means; only a full-target clear maps to a real load-op.+ return (clearRequested && !scoped) ? WGPULoadOp_Clear : WGPULoadOp_Load;+}++inline WGPUColor toWGPUClearColor(const RenderPassDesc& desc) {+ return WGPUColor{ desc.clearColorValue[0], desc.clearColorValue[1],+ desc.clearColorValue[2], desc.clearColorValue[3] };+}++/** @brief Cull state (PipelineDesc.cullEnabled/cullFront). Front face is CCW,+ * matching the GL backend's default winding. */+inline WGPUCullMode toWGPUCullMode(bool enabled, bool front) {+ if (!enabled) return WGPUCullMode_None;+ return front ? WGPUCullMode_Front : WGPUCullMode_Back;+}++} // namespace esengine::webgpudiff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txtindex e20855c6a..94652f627 100644--- a/tests/CMakeLists.txt+++ b/tests/CMakeLists.txt@@ -111,6 +111,25 @@ add_executable(test_buffer_devicetarget_include_directories(test_buffer_device PRIVATE ${CMAKE_SOURCE_DIR}/src)add_test(NAME test_buffer_device COMMAND test_buffer_device)+# WebGPU backend slice 1 (REARCH_WGSL Phase 2): the enum→WGPU mapping layer ++# the null-device-safe WebGPUDevice skeleton, compiled against the REAL Dawn C+# headers via the emdawnwebgpu port (emscripten-only; the port supplies+# <webgpu/webgpu.h> and its JS glue).+if(EMSCRIPTEN)+ add_executable(test_webgpu_device+ renderer/test_webgpu_device.cpp+ ${CMAKE_SOURCE_DIR}/src/esengine/renderer/webgpu/WebGPUDevice.cpp+ ${CMAKE_SOURCE_DIR}/src/esengine/core/Log.cpp+ )+ target_include_directories(test_webgpu_device PRIVATE+ ${CMAKE_SOURCE_DIR}/src+ ${CMAKE_SOURCE_DIR}/third_party/glm+ )+ target_compile_options(test_webgpu_device PRIVATE --use-port=emdawnwebgpu)+ target_link_options(test_webgpu_device PRIVATE --use-port=emdawnwebgpu)+ add_test(NAME test_webgpu_device COMMAND test_webgpu_device)+endif()+# Boundary-span validation (RC3): JS-supplied pointer+length pairs are null-,# overflow-, and heap-range-checked ALWAYS ON. Header-only + Log.cpp; under# emscripten the heap-range cases exercise the real linear-memory bound.diff --git a/tests/renderer/test_webgpu_device.cpp b/tests/renderer/test_webgpu_device.cppnew file mode 100644index 000000000..e731627e3--- /dev/null+++ b/tests/renderer/test_webgpu_device.cpp@@ -0,0 +1,126 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+// WebGPU backend slice 1 (REARCH_WGSL Phase 2): the pure enum→WGPU mapping layer+// and the null-device-safe WebGPUDevice skeleton, compiled against the REAL Dawn+// C headers (emdawnwebgpu port) so every descriptor spelling is checked by the+// compiler long before a live adapter exists.+#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN+#include <doctest.h>++#include "esengine/renderer/webgpu/WebGPUDevice.hpp"+#include "esengine/renderer/webgpu/WebGPUMappings.hpp"++using namespace esengine;+using namespace esengine::webgpu;++TEST_CASE("blend table mirrors the GL backend's semantics") {+ auto normal = toWGPUBlend(BlendMode::Normal);+ CHECK(normal.color.srcFactor == WGPUBlendFactor_SrcAlpha);+ CHECK(normal.color.dstFactor == WGPUBlendFactor_OneMinusSrcAlpha);++ auto additive = toWGPUBlend(BlendMode::Additive);+ CHECK(additive.color.dstFactor == WGPUBlendFactor_One);++ auto lighten = toWGPUBlend(BlendMode::Lighten);+ CHECK(lighten.color.operation == WGPUBlendOperation_Max);+ auto darken = toWGPUBlend(BlendMode::Darken);+ CHECK(darken.color.operation == WGPUBlendOperation_Min);++ // Overlay has no fixed-function form — renders as Normal, like GLDevice.+ auto overlay = toWGPUBlend(BlendMode::Overlay);+ CHECK(overlay.color.srcFactor == WGPUBlendFactor_SrcAlpha);+}++TEST_CASE("vertex formats cover every attribute the engine's streams declare") {+ // Batch: f32x2 pos, unorm8x4 color, f32x2 uv, f32 texIndex.+ CHECK(toWGPUVertexFormat(2, GfxDataType::Float, false) == WGPUVertexFormat_Float32x2);+ CHECK(toWGPUVertexFormat(4, GfxDataType::UnsignedByte, true) == WGPUVertexFormat_Unorm8x4);+ CHECK(toWGPUVertexFormat(1, GfxDataType::Float, false) == WGPUVertexFormat_Float32);+ // Shape: f32x4 ×2. Particle instance: f32x2/f32/unorm8x4 mix — all covered above.+ CHECK(toWGPUVertexFormat(4, GfxDataType::Float, false) == WGPUVertexFormat_Float32x4);+ // A combination no engine stream produces must map to Undefined (hard error).+ CHECK(toWGPUVertexFormat(3, GfxDataType::UnsignedByte, true) == kInvalidVertexFormat);+}++TEST_CASE("index, texture, sampler, and buffer mappings") {+ CHECK(toWGPUIndexFormat(GfxDataType::UnsignedInt) == WGPUIndexFormat_Uint32);+ CHECK(toWGPUIndexFormat(GfxDataType::UnsignedShort) == WGPUIndexFormat_Uint16);+ CHECK(toWGPUIndexFormat(GfxDataType::Float) == WGPUIndexFormat_Undefined);++ CHECK(toWGPUTextureFormat(GfxPixelFormat::RGBA8) == WGPUTextureFormat_RGBA8Unorm);+ CHECK(toWGPUTextureFormat(GfxPixelFormat::Depth24Stencil8) == WGPUTextureFormat_Depth24PlusStencil8);+ CHECK(toWGPUCompressedFormat(GfxCompressedFormat::ETC2_RGBA8) == WGPUTextureFormat_ETC2RGBA8Unorm);++ CHECK(toWGPUAddressMode(TextureWrap::ClampToEdge) == WGPUAddressMode_ClampToEdge);+ CHECK(toWGPUFilter(TextureFilter::Nearest) == WGPUFilterMode_Nearest);++ CHECK((toWGPUBufferUsage(GfxBufferUsage::Uniform) & WGPUBufferUsage_Uniform) != 0);+ CHECK((toWGPUBufferUsage(GfxBufferUsage::Index) & WGPUBufferUsage_CopyDst) != 0);+}++TEST_CASE("stencil modes translate to the same table GLDevice applies") {+ auto write = toWGPUStencilFace(GfxStencilMode::Write);+ CHECK(write.compare == WGPUCompareFunction_Always);+ CHECK(write.passOp == WGPUStencilOperation_Replace);++ auto test = toWGPUStencilFace(GfxStencilMode::Test);+ CHECK(test.compare == WGPUCompareFunction_Equal);+ CHECK(test.passOp == WGPUStencilOperation_Keep);+}++TEST_CASE("pass load-ops: full-target clear is a real load-op, a scoped clear is not") {+ CHECK(toWGPULoadOp(/*clear*/ true, /*scoped*/ false) == WGPULoadOp_Clear);+ CHECK(toWGPULoadOp(true, true) == WGPULoadOp_Load); // region clear → emulate, load first+ CHECK(toWGPULoadOp(false, false) == WGPULoadOp_Load);++ RenderPassDesc desc{};+ desc.clearColorValue[0] = 0.25f;+ desc.clearColorValue[3] = 0.5f;+ auto color = toWGPUClearColor(desc);+ CHECK(color.r == doctest::Approx(0.25));+ CHECK(color.a == doctest::Approx(0.5));+}++TEST_CASE("null-device skeleton: language gate + graceful degradation + bookkeeping") {+ WebGPUDevice device; // no WGPUDevice — bookkeeping-only mode+ CHECK(!device.hasDevice());++ // The capability gate is the WGSL mirror of GLDevice's.+ CHECK(device.supportsShaderLanguage(GfxShaderLanguage::WGSL));+ CHECK(!device.supportsShaderLanguage(GfxShaderLanguage::GLSL_ES300));++ // GPU-touching creation degrades to Invalid with a log, never UB.+ CHECK(device.createBuffer({GfxBufferUsage::Vertex, 256, true}, nullptr) == BufferHandle::Invalid);+ CHECK(device.createTexture({}, nullptr) == TextureHandle::Invalid);++ // Descriptor-only bookkeeping works without a device: layouts validate their+ // attributes against the WGPU format table and round-trip.+ VertexLayoutDesc batch{};+ batch.attributeCount = 4;+ batch.strides[0] = 24;+ batch.attributes[0] = {0, 2, GfxDataType::Float, false, 0, 0};+ batch.attributes[1] = {1, 4, GfxDataType::UnsignedByte, true, 8, 0};+ batch.attributes[2] = {2, 2, GfxDataType::Float, false, 12, 0};+ batch.attributes[3] = {3, 1, GfxDataType::Float, false, 20, 0};+ auto layout = device.createVertexLayout(batch);+ REQUIRE(layout != VertexLayoutHandle::Invalid);+ REQUIRE(device.layoutDesc(layout) != nullptr);+ CHECK(device.layoutDesc(layout)->strides[0] == 24);++ VertexLayoutDesc bad{};+ bad.attributeCount = 1;+ bad.attributes[0] = {0, 3, GfxDataType::UnsignedByte, true, 0, 0}; // no WGPU spelling+ CHECK(device.createVertexLayout(bad) == VertexLayoutHandle::Invalid);++ // Pipelines retain their descriptors for the slice-2 lazy build.+ PipelineDesc pd{};+ pd.blend = BlendMode::Additive;+ pd.vertexLayout = layout;+ auto pipeline = device.createPipeline(pd);+ REQUIRE(device.pipelineDesc(pipeline) != nullptr);+ CHECK(device.pipelineDesc(pipeline)->blend == BlendMode::Additive);++ // GL-shaped introspection reports "absent" so Shader::compile skips block wiring.+ CHECK(device.getUniformBlockIndex(ShaderHandle{1}, "FrameConstants") == GFX_INVALID_UNIFORM_BLOCK);+ CHECK(device.getString(GfxStringName::ShadingLanguageVersion) == "WGSL");+}