Skip to content

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.

feat(webgpu): batch multi-texture works — texture bind groups + batch WGSL twin (WGSL phase 2 slice 3)

yhhd517a4cbe71a
diff --git a/desktop/scripts/webgpu-bringup.mjs b/desktop/scripts/webgpu-bringup.mjs
index 651b85864..0608b5213 100644
--- a/desktop/scripts/webgpu-bringup.mjs
+++ b/desktop/scripts/webgpu-bringup.mjs
@@ -99,15 +99,19 @@ app.whenReady().then(async () => {
const i = (y * image.getSize().width + x) * 4;
return { b: png[i], g: png[i + 1], r: png[i + 2] };
};
- const center = px(128, 128); // inside the circle → red
- const corner = px(8, 8); // outside → dark blue clear
const near = (v, want, tol = 40) => Math.abs(v - want) <= tol;
+ const circle = px(128, 32); // shape twin: magenta SDF circle, top-center
+ const left = px(64, 166); // batch twin: quad sampling slot 0 → red
+ const right = px(192, 166); // batch twin: quad sampling slot 1 → green
+ const corner = px(8, 128); // between the quads' outside → dark blue clear
- const centerOk = near(center.r, 255) && near(center.g, 0) && near(center.b, 0);
+ const circleOk = near(circle.r, 255) && near(circle.g, 0) && near(circle.b, 255);
+ const leftOk = near(left.r, 255) && near(left.g, 0) && near(left.b, 0);
+ const rightOk = near(right.r, 0) && near(right.g, 255) && near(right.b, 0);
const cornerOk = near(corner.r, 13) && near(corner.g, 13) && near(corner.b, 77, 60);
- const ok = framesOk && errors.length === 0 && centerOk && cornerOk;
+ const ok = framesOk && errors.length === 0 && circleOk && leftOk && rightOk && cornerOk;
- console.log(`RESULT center=${JSON.stringify(center)} corner=${JSON.stringify(corner)} framesOk=${framesOk} errors=${errors.length}`);
+ console.log(`RESULT circle=${JSON.stringify(circle)} left=${JSON.stringify(left)} right=${JSON.stringify(right)} corner=${JSON.stringify(corner)} framesOk=${framesOk} errors=${errors.length}`);
console.log(`\n[webgpu-bringup] ${ok ? 'PASS' : 'FAIL'}`);
process.exitCode = ok ? 0 : 1;
try { server.close(); } catch { /* ignore */ }
diff --git a/docs/REARCHITECTURE.md b/docs/REARCHITECTURE.md
index b66735471..04ca76b95 100644
--- a/docs/REARCHITECTURE.md
+++ b/docs/REARCHITECTURE.md
@@ -184,11 +184,12 @@ 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 + Phase 2 切片 1/2 已落地,**首帧点亮**(2026-07-07)
+### WGSL/WebGPU 通路 — 🟡 进行中:Phase 2 切片 1/2/3 已落地——**首帧点亮 + 批多纹理工作**(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。
**Phase 2 切片 2(首帧点亮)**:WebGPUDevice 长出真渲染路径——canvas 表面(页面 JS 异步取 GPUDevice 经 `Module.preinitializedWebGPUDevice` 交接,wasm 全同步零 Asyncify)、帧编码器(load-op 直译 RenderPassDesc)、惰性 pipeline(映射层直译 + 描述符去重)、group-0 UBO bind group、索引/实例化 draw。bring-up:electron 驱动 `webgpu_bringup.wasm` 用引擎同款 RHI 调用序列渲染 **shape.esshader 的 WGSL 孪生**——首次运行即像素级 PASS(SDF 红圆 + 清屏色逐像素命中,零校验错误)。本地命令:`node desktop/scripts/webgpu-bringup.mjs`(CI 暂不跑真 GPU bring-up;null-device 套件在 CI)。
+**Phase 2 切片 3(纹理组)**:group-1 约定(8×`texture_2d` binding 0..7 + 共享 sampler binding 8 = `u_textures[8]` 的 WGSL 拼写;未用槽重复 slot-0 视图同 WebGL2 规则;group 1 仅在 pass 内绑过纹理时设置、每 pass 重置);**batch 默认变体 WGSL 孪生**(`textureSampleLevel` 保 uniform-flow)。bring-up 两幕同 pass(shape + 批双 quad texIndex 选择)再次首跑 PASS——sprite 管线的核心机制(逐顶点采样槽选择)在 WebGPU 上验证通过。
### 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.cpp
index f1fb2d0dd..af1314384 100644
--- a/src/esengine/renderer/webgpu/WebGPUDevice.cpp
+++ b/src/esengine/renderer/webgpu/WebGPUDevice.cpp
@@ -45,6 +45,7 @@ void WebGPUDevice::shutdown() {
}
buffers_.clear();
for (auto& [id, rec] : textures_) {
+ if (rec.view) wgpuTextureViewRelease(rec.view);
if (rec.texture) wgpuTextureRelease(rec.texture);
}
textures_.clear();
@@ -59,6 +60,8 @@ void WebGPUDevice::shutdown() {
}
pipelines_.clear();
if (bind_group_) { wgpuBindGroupRelease(bind_group_); bind_group_ = nullptr; }
+ if (texture_group_) { wgpuBindGroupRelease(texture_group_); texture_group_ = nullptr; }
+ if (sampler_) { wgpuSamplerRelease(sampler_); sampler_ = nullptr; }
if (surface_) { wgpuSurfaceRelease(surface_); surface_ = nullptr; }
if (instance_) { wgpuInstanceRelease(instance_); instance_ = nullptr; }
}
@@ -287,7 +290,8 @@ TextureHandle WebGPUDevice::createTexture(const TextureDesc& desc, const void* p
}
const u32 id = next_id_++;
- textures_[id] = TextureRec{texture, desc.width, desc.height};
+ textures_[id] = TextureRec{texture, wgpuTextureCreateView(texture, nullptr),
+ desc.width, desc.height};
if (pixels) {
updateTexture(TextureHandle{id}, 0, 0, desc.width, desc.height, pixels, false);
@@ -311,6 +315,7 @@ TextureHandle WebGPUDevice::importExternalTexture(u32, const TextureDesc&) {
void WebGPUDevice::deleteTexture(TextureHandle texture) {
auto it = textures_.find(static_cast<u32>(texture));
if (it == textures_.end()) return;
+ if (it->second.view) wgpuTextureViewRelease(it->second.view);
if (it->second.texture) wgpuTextureRelease(it->second.texture);
textures_.erase(it);
}
@@ -346,7 +351,16 @@ void WebGPUDevice::setTextureParams(TextureHandle, TextureFilter, TextureFilter,
}
void WebGPUDevice::generateMipmaps(TextureHandle) { stubOnce("generateMipmaps"); }
-void WebGPUDevice::bindTexture(u32, TextureHandle) { stubOnce("bindTexture (bind groups)"); }
+
+void WebGPUDevice::bindTexture(u32 slot, TextureHandle texture) {
+ if (slot >= kTextureSlots) return;
+ const u32 id = static_cast<u32>(texture);
+ if (texture_slots_[slot] != id) {
+ texture_slots_[slot] = id;
+ bind_group_dirty_ = true;
+ }
+ if (id != 0) any_texture_bound_ = true;
+}
bool WebGPUDevice::supportsCompressedFormat(GfxCompressedFormat format) {
// Real capability negotiation (adapter features) arrives with the adapter
@@ -539,6 +553,25 @@ void WebGPUDevice::setStencilReference(i32 reference) {
void WebGPUDevice::invalidatePipelineCache() {}
+WGPUSampler WebGPUDevice::defaultSampler() {
+ if (!sampler_ && device_) {
+ // Bring-up default: linear filtering, clamped — per-texture sampler state
+ // (setTextureParams) becomes a keyed sampler cache in a later slice.
+ WGPUSamplerDescriptor sd{};
+ sd.addressModeU = WGPUAddressMode_ClampToEdge;
+ sd.addressModeV = WGPUAddressMode_ClampToEdge;
+ sd.addressModeW = WGPUAddressMode_ClampToEdge;
+ sd.magFilter = WGPUFilterMode_Linear;
+ sd.minFilter = WGPUFilterMode_Linear;
+ sd.mipmapFilter = WGPUMipmapFilterMode_Nearest;
+ sd.lodMinClamp = 0.0f;
+ sd.lodMaxClamp = 32.0f;
+ sd.maxAnisotropy = 1;
+ sampler_ = wgpuDeviceCreateSampler(device_, &sd);
+ }
+ return sampler_;
+}
+
void WebGPUDevice::flushBindGroup() {
if (!bind_group_dirty_ || !pass_ || !device_) return;
@@ -573,6 +606,38 @@ void WebGPUDevice::flushBindGroup() {
bind_group_ = wgpuDeviceCreateBindGroup(device_, &bgd);
if (bgd.layout) wgpuBindGroupLayoutRelease(bgd.layout);
if (bind_group_) wgpuRenderPassEncoderSetBindGroup(pass_, 0, bind_group_, 0, nullptr);
+
+ // Group 1: the texture units. The WGSL twin convention is 8 texture_2d at
+ // bindings 0..7 + one shared sampler at binding 8 (the batch shader's
+ // u_textures[8]). Unused slots repeat slot 0's view — the same trick
+ // DrawList::execute uses for WebGL2's complete-texture rule. Only set when
+ // the pass bound textures, so sampler-less shaders keep a group-0-only layout.
+ if (any_texture_bound_) {
+ WGPUTextureView slot0 = nullptr;
+ for (u32 slot = 0; slot < kTextureSlots && !slot0; ++slot) {
+ auto it = textures_.find(texture_slots_[slot]);
+ if (it != textures_.end()) slot0 = it->second.view;
+ }
+ if (slot0) {
+ WGPUBindGroupEntry texEntries[kTextureSlots + 1] = {};
+ for (u32 slot = 0; slot < kTextureSlots; ++slot) {
+ auto it = textures_.find(texture_slots_[slot]);
+ texEntries[slot].binding = slot;
+ texEntries[slot].textureView = (it != textures_.end()) ? it->second.view : slot0;
+ }
+ texEntries[kTextureSlots].binding = kTextureSlots;
+ texEntries[kTextureSlots].sampler = defaultSampler();
+
+ if (texture_group_) { wgpuBindGroupRelease(texture_group_); texture_group_ = nullptr; }
+ WGPUBindGroupDescriptor tgd{};
+ tgd.layout = wgpuRenderPipelineGetBindGroupLayout(p, 1);
+ tgd.entryCount = kTextureSlots + 1;
+ tgd.entries = texEntries;
+ texture_group_ = wgpuDeviceCreateBindGroup(device_, &tgd);
+ if (tgd.layout) wgpuBindGroupLayoutRelease(tgd.layout);
+ if (texture_group_) wgpuRenderPassEncoderSetBindGroup(pass_, 1, texture_group_, 0, nullptr);
+ }
+ }
bind_group_dirty_ = false;
}
@@ -659,6 +724,10 @@ void WebGPUDevice::beginRenderPass(const RenderPassDesc& desc) {
rp.colorAttachments = &color;
pass_ = wgpuCommandEncoderBeginRenderPass(encoder_, &rp);
bind_group_dirty_ = true;
+ // Each pass starts textureless: group 1 only attaches to pipelines whose
+ // draws bind textures (the engine rebinds per draw), never to sampler-less
+ // pipelines from a previous pass's leftovers.
+ any_texture_bound_ = false;
}
void WebGPUDevice::endRenderPass() {
diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.hpp b/src/esengine/renderer/webgpu/WebGPUDevice.hpp
index c64cc8eca..5357fb500 100644
--- a/src/esengine/renderer/webgpu/WebGPUDevice.hpp
+++ b/src/esengine/renderer/webgpu/WebGPUDevice.hpp
@@ -150,6 +150,7 @@ private:
};
struct TextureRec {
WGPUTexture texture = nullptr;
+ WGPUTextureView view = nullptr; ///< Default full view, created with the texture.
u32 width = 0;
u32 height = 0;
};
@@ -167,8 +168,14 @@ private:
/** @brief Builds (once) and returns the WGPURenderPipeline for a handle. */
WGPURenderPipeline ensurePipeline(u32 id);
- /** @brief (Re)creates the group-0 bind group from the recorded UBO slots. */
+ /** @brief (Re)creates the bind groups: group 0 = UBO slots, group 1 = the
+ * texture units (8 texture_2d at bindings 0..7 + one shared sampler at
+ * binding 8 — the WGSL twin convention for the batch sampler array).
+ * Group 1 is set only when the pass bound any texture, so shaders
+ * without samplers (shape) never see a mismatched group. */
void flushBindGroup();
+ /** @brief The lazily created shared sampler (linear/clamp bring-up default). */
+ WGPUSampler defaultSampler();
/** @brief True while inside beginRenderPass/endRenderPass. */
bool inPass() const { return pass_ != nullptr; }
@@ -191,8 +198,13 @@ private:
u32 bound_index_buffer_ = 0;
static constexpr u32 kUniformSlots = 8;
u32 uniform_slots_[kUniformSlots] = {}; ///< BufferHandle id per UBO binding slot.
+ static constexpr u32 kTextureSlots = 8;
+ u32 texture_slots_[kTextureSlots] = {}; ///< TextureHandle id per sampler unit.
+ bool any_texture_bound_ = false;
bool bind_group_dirty_ = true;
WGPUBindGroup bind_group_ = nullptr;
+ WGPUBindGroup texture_group_ = nullptr;
+ WGPUSampler sampler_ = nullptr;
u32 next_id_ = 1;
std::unordered_map<u32, BufferRec> buffers_;
diff --git a/tests/renderer/webgpu_bringup.cpp b/tests/renderer/webgpu_bringup.cpp
index c91496a81..e12e97fab 100644
--- a/tests/renderer/webgpu_bringup.cpp
+++ b/tests/renderer/webgpu_bringup.cpp
@@ -1,15 +1,18 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
- * @file WebGPU bring-up (REARCH_WGSL Phase 2 slice 2) — NOT a doctest harness.
+ * @file WebGPU bring-up (REARCH_WGSL Phase 2 slices 2+3) — NOT a doctest harness.
*
* A browser-run program: the host page acquires a GPUDevice (navigator.gpu) and
* hands it over via Module.preinitializedWebGPUDevice; this program then drives
* the REAL WebGPUDevice through the same RHI calls the engine's render path
- * makes — surface pass with a load-op clear, lazy pipeline from the Shape layout,
- * group-0 FrameConstants bind group, one indexed draw of the shape-shader WGSL
- * twin — and renders a red SDF circle on a dark blue clear. The electron runner
- * (desktop/scripts/webgpu-bringup.mjs) asserts the pixels.
+ * makes. Each frame renders BOTH engine shader twins in one pass — pipeline
+ * switch + bind-group rebuild included:
+ * - shape twin: a magenta SDF circle, top-center (slice 2)
+ * - batch twin (default variant): two quads sharing one draw, selecting
+ * different sampler slots per-vertex via texIndex — red left, green right
+ * (slice 3: texture views + shared sampler as bind group 1)
+ * The electron runner (desktop/scripts/webgpu-bringup.mjs) asserts the pixels.
*/
#include "esengine/renderer/webgpu/WebGPUDevice.hpp"
@@ -86,35 +89,121 @@ struct VSOut {
}
)";
+// WGSL twin of the batch shader's DEFAULT variant (batch.esshader): Batch layout
+// attributes 0..3 (pos, unorm8x4 color, uv, texIndex), FrameConstants at group 0,
+// and the multi-texture set as bind group 1 — 8 texture_2d at bindings 0..7 plus
+// one shared sampler at binding 8 (the WGSL spelling of u_textures[8]).
+// textureSampleLevel(…, 0) keeps sampling uniform-flow-legal inside the branch
+// chain; 2D sprites sample mip 0 (the mipped path is a phase-3 topic).
+static const char* kBatchWGSL_Vertex = R"(
+struct FrameConstants { projection : mat4x4f };
+@group(0) @binding(0) var<uniform> frame : FrameConstants;
+
+struct VSIn {
+ @location(0) position : vec2f,
+ @location(1) color : vec4f,
+ @location(2) uv : vec2f,
+ @location(3) texIndex : f32,
+};
+struct VSOut {
+ @builtin(position) pos : vec4f,
+ @location(0) color : vec4f,
+ @location(1) uv : vec2f,
+ @location(2) texIndex : f32,
+};
+
+@vertex fn vs_main(v : VSIn) -> VSOut {
+ var out : VSOut;
+ out.pos = frame.projection * vec4f(v.position, 0.0, 1.0);
+ out.color = v.color;
+ out.uv = v.uv;
+ out.texIndex = v.texIndex;
+ return out;
+}
+)";
+
+static const char* kBatchWGSL_Fragment = R"(
+@group(1) @binding(0) var t0 : texture_2d<f32>;
+@group(1) @binding(1) var t1 : texture_2d<f32>;
+@group(1) @binding(2) var t2 : texture_2d<f32>;
+@group(1) @binding(3) var t3 : texture_2d<f32>;
+@group(1) @binding(4) var t4 : texture_2d<f32>;
+@group(1) @binding(5) var t5 : texture_2d<f32>;
+@group(1) @binding(6) var t6 : texture_2d<f32>;
+@group(1) @binding(7) var t7 : texture_2d<f32>;
+@group(1) @binding(8) var samp : sampler;
+
+struct VSOut {
+ @builtin(position) pos : vec4f,
+ @location(0) color : vec4f,
+ @location(1) uv : vec2f,
+ @location(2) texIndex : f32,
+};
+
+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+ let idx = i32(v.texIndex + 0.5);
+ var c : vec4f;
+ if (idx == 0) { c = textureSampleLevel(t0, samp, v.uv, 0.0); }
+ else if (idx == 1) { c = textureSampleLevel(t1, samp, v.uv, 0.0); }
+ else if (idx == 2) { c = textureSampleLevel(t2, samp, v.uv, 0.0); }
+ else if (idx == 3) { c = textureSampleLevel(t3, samp, v.uv, 0.0); }
+ else if (idx == 4) { c = textureSampleLevel(t4, samp, v.uv, 0.0); }
+ else if (idx == 5) { c = textureSampleLevel(t5, samp, v.uv, 0.0); }
+ else if (idx == 6) { c = textureSampleLevel(t6, samp, v.uv, 0.0); }
+ else { c = textureSampleLevel(t7, samp, v.uv, 0.0); }
+ return c * v.color;
+}
+)";
+
namespace {
WebGPUDevice* g_device = nullptr;
-PipelineHandle g_pipeline{};
-BufferHandle g_vbo{}, g_ibo{}, g_ubo{};
+PipelineHandle g_shapePipeline{}, g_batchPipeline{};
+BufferHandle g_shapeVbo{}, g_batchVbo{}, g_ibo6{}, g_ibo12{}, g_ubo{};
+TextureHandle g_texRed{}, g_texGreen{};
int g_frames = 0;
-// One ShapeVertex (mirrors the engine's Shape stream, stride 48).
+// Mirrors the engine's Shape stream vertex (stride 48).
struct ShapeVertex {
f32 px, py, ux, uy;
f32 cr, cg, cb, ca;
f32 shapeType, halfW, halfH, cornerRadius;
};
+// Mirrors the engine's Batch stream vertex (stride 24).
+struct BatchVertex {
+ f32 px, py;
+ u32 color;
+ f32 ux, uy;
+ f32 texIndex;
+};
+
void renderFrame() {
RenderPassDesc pass{};
pass.clearColor = true;
- pass.clearDepth = false;
pass.clearColorValue[0] = 0.05f;
pass.clearColorValue[1] = 0.05f;
pass.clearColorValue[2] = 0.30f;
pass.clearColorValue[3] = 1.0f;
g_device->beginRenderPass(pass);
- g_device->setPipeline(g_pipeline);
+
+ // Act 1: shape twin — magenta SDF circle, top-center.
+ g_device->setPipeline(g_shapePipeline);
g_device->setUniformBuffer(0, g_ubo);
- g_device->setVertexBuffer(0, g_vbo, 0);
- g_device->setIndexBuffer(g_ibo);
+ g_device->setVertexBuffer(0, g_shapeVbo, 0);
+ g_device->setIndexBuffer(g_ibo6);
g_device->drawElements(6, GfxDataType::UnsignedShort, 0);
+
+ // Act 2: batch twin — two quads in ONE draw, per-vertex sampler selection.
+ g_device->setPipeline(g_batchPipeline);
+ g_device->setUniformBuffer(0, g_ubo);
+ g_device->bindTexture(0, g_texRed);
+ g_device->bindTexture(1, g_texGreen);
+ g_device->setVertexBuffer(0, g_batchVbo, 0);
+ g_device->setIndexBuffer(g_ibo12);
+ g_device->drawElements(12, GfxDataType::UnsignedShort, 0);
+
g_device->endRenderPass();
if (++g_frames == 3) {
@@ -123,6 +212,21 @@ void renderFrame() {
}
}
+TextureHandle makeSolidTexture(u8 r, u8 g, u8 b) {
+ u8 pixels[4 * 4 * 4];
+ for (int i = 0; i < 16; ++i) {
+ pixels[i * 4 + 0] = r;
+ pixels[i * 4 + 1] = g;
+ pixels[i * 4 + 2] = b;
+ pixels[i * 4 + 3] = 255;
+ }
+ TextureDesc td{};
+ td.width = 4;
+ td.height = 4;
+ td.format = GfxPixelFormat::RGBA8;
+ return g_device->createTexture(td, pixels);
+}
+
} // namespace
int main() {
@@ -144,40 +248,73 @@ int main() {
const f32 identity[16] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1};
g_ubo = device.createBuffer({GfxBufferUsage::Uniform, sizeof(identity), false}, identity);
- // A quad in clip space; uv spans ±1 so p = uv*halfSize inscribes the circle.
- const ShapeVertex verts[4] = {
- {-0.8f, -0.8f, -1, -1, 1, 0, 0, 1, /*circle*/ 0, 100, 100, 0},
- { 0.8f, -0.8f, 1, -1, 1, 0, 0, 1, 0, 100, 100, 0},
- { 0.8f, 0.8f, 1, 1, 1, 0, 0, 1, 0, 100, 100, 0},
- {-0.8f, 0.8f, -1, 1, 1, 0, 0, 1, 0, 100, 100, 0},
+ // --- Shape scene: small circle, top-center (clip y 0.55..0.95).
+ const ShapeVertex shapeVerts[4] = {
+ {-0.25f, 0.55f, -1, -1, 1, 0, 1, 1, /*circle*/ 0, 100, 100, 0},
+ { 0.25f, 0.55f, 1, -1, 1, 0, 1, 1, 0, 100, 100, 0},
+ { 0.25f, 0.95f, 1, 1, 1, 0, 1, 1, 0, 100, 100, 0},
+ {-0.25f, 0.95f, -1, 1, 1, 0, 1, 1, 0, 100, 100, 0},
};
- const u16 indices[6] = {0, 1, 2, 2, 3, 0};
- g_vbo = device.createBuffer({GfxBufferUsage::Vertex, sizeof(verts), false}, verts);
- g_ibo = device.createBuffer({GfxBufferUsage::Index, sizeof(indices), false}, indices);
+ const u16 quadIdx[6] = {0, 1, 2, 2, 3, 0};
+ g_shapeVbo = device.createBuffer({GfxBufferUsage::Vertex, sizeof(shapeVerts), false}, shapeVerts);
+ g_ibo6 = device.createBuffer({GfxBufferUsage::Index, sizeof(quadIdx), false}, quadIdx);
+
+ // --- Batch scene: left quad samples slot 0 (red), right quad slot 1 (green).
+ const u32 white = 0xFFFFFFFFu;
+ const BatchVertex batchVerts[8] = {
+ {-0.9f, -0.9f, white, 0, 0, 0}, {-0.1f, -0.9f, white, 1, 0, 0},
+ {-0.1f, 0.3f, white, 1, 1, 0}, {-0.9f, 0.3f, white, 0, 1, 0},
+ { 0.1f, -0.9f, white, 0, 0, 1}, { 0.9f, -0.9f, white, 1, 0, 1},
+ { 0.9f, 0.3f, white, 1, 1, 1}, { 0.1f, 0.3f, white, 0, 1, 1},
+ };
+ const u16 batchIdx[12] = {0, 1, 2, 2, 3, 0, 4, 5, 6, 6, 7, 4};
+ g_batchVbo = device.createBuffer({GfxBufferUsage::Vertex, sizeof(batchVerts), false}, batchVerts);
+ g_ibo12 = device.createBuffer({GfxBufferUsage::Index, sizeof(batchIdx), false}, batchIdx);
+
+ g_texRed = makeSolidTexture(255, 0, 0);
+ g_texGreen = makeSolidTexture(0, 255, 0);
+ if (g_texRed == TextureHandle::Invalid || g_texGreen == TextureHandle::Invalid) {
+ std::printf("BRINGUP_FAIL textures\n");
+ return 1;
+ }
- ShaderHandle program = device.createProgram(
+ // --- Programs + layouts + pipelines (the engine's streams, byte for byte).
+ ShaderHandle shapeProgram = device.createProgram(
GfxShaderSource{GfxShaderLanguage::WGSL, kShapeWGSL_Vertex, kShapeWGSL_Fragment},
nullptr, 0, nullptr, nullptr);
- if (program == ShaderHandle::Invalid) {
- std::printf("BRINGUP_FAIL program\n");
+ ShaderHandle batchProgram = device.createProgram(
+ GfxShaderSource{GfxShaderLanguage::WGSL, kBatchWGSL_Vertex, kBatchWGSL_Fragment},
+ nullptr, 0, nullptr, nullptr);
+ if (shapeProgram == ShaderHandle::Invalid || batchProgram == ShaderHandle::Invalid) {
+ std::printf("BRINGUP_FAIL programs\n");
return 1;
}
- // The engine's Shape layout, byte for byte (TransientBufferPool::setupStream).
- VertexLayoutDesc layout{};
- layout.attributeCount = 4;
- layout.strides[0] = 48;
- layout.attributes[0] = {0, 2, GfxDataType::Float, false, 0, 0};
- layout.attributes[1] = {1, 2, GfxDataType::Float, false, 8, 0};
- layout.attributes[2] = {2, 4, GfxDataType::Float, false, 16, 0};
- layout.attributes[3] = {3, 4, GfxDataType::Float, false, 32, 0};
-
- PipelineDesc pd{};
- pd.program = program;
- pd.vertexLayout = device.createVertexLayout(layout);
- pd.blend = BlendMode::Normal;
- pd.blendEnabled = true;
- g_pipeline = device.createPipeline(pd);
+ VertexLayoutDesc shapeLayout{};
+ shapeLayout.attributeCount = 4;
+ shapeLayout.strides[0] = 48;
+ shapeLayout.attributes[0] = {0, 2, GfxDataType::Float, false, 0, 0};
+ shapeLayout.attributes[1] = {1, 2, GfxDataType::Float, false, 8, 0};
+ shapeLayout.attributes[2] = {2, 4, GfxDataType::Float, false, 16, 0};
+ shapeLayout.attributes[3] = {3, 4, GfxDataType::Float, false, 32, 0};
+
+ VertexLayoutDesc batchLayout{};
+ batchLayout.attributeCount = 4;
+ batchLayout.strides[0] = 24;
+ batchLayout.attributes[0] = {0, 2, GfxDataType::Float, false, 0, 0};
+ batchLayout.attributes[1] = {1, 4, GfxDataType::UnsignedByte, true, 8, 0};
+ batchLayout.attributes[2] = {2, 2, GfxDataType::Float, false, 12, 0};
+ batchLayout.attributes[3] = {3, 1, GfxDataType::Float, false, 20, 0};
+
+ PipelineDesc shapePd{};
+ shapePd.program = shapeProgram;
+ shapePd.vertexLayout = device.createVertexLayout(shapeLayout);
+ g_shapePipeline = device.createPipeline(shapePd);
+
+ PipelineDesc batchPd{};
+ batchPd.program = batchProgram;
+ batchPd.vertexLayout = device.createVertexLayout(batchLayout);
+ g_batchPipeline = device.createPipeline(batchPd);
std::printf("BRINGUP_INIT_OK\n");
emscripten_set_main_loop(renderFrame, 0, /*simulate_infinite_loop=*/false);