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
perf(render): the profiler can split the scene pass into a segment per shader, and the cost doc says what is in it
yhh3dce0eb6b565
diff --git a/docs/TERRAIN_WATER_GPU_COST.md b/docs/TERRAIN_WATER_GPU_COST.mdindex 9028a2833..3e71b6078 100644--- a/docs/TERRAIN_WATER_GPU_COST.md+++ b/docs/TERRAIN_WATER_GPU_COST.md@@ -383,3 +383,35 @@| 3 | 38.7 | 33.4 | 天空 1.0 + 1.5 | 雾 1.3 + 1.3 |画面:机位 0 与之前的截图逐像素比(排除两次运行本来就不同的部分),平均差 0.34/255,超过 24 的像素 0.05%,天际线和树缘放大看不出光晕。两个后端:GLSL 与 WGSL 都有,`sky-fog` 渲染场景在 WebGL2 与 WebGPU 上读出同样的颜色。**没有量的:**手机(半分辨率的 pass 在分块 GPU 上多一次读写),夜晚与阴天的云。++## scene pass 里面是什么(2026-10-26)++`--detail`(加上 `--passes`):剖析器打开时,scene pass 按“同一个着色器的一串绘制”切成段,每段一个计时查询(`scene/<着色器名>`,预通道是 `scene/prepass:<着色器名>`)。只在 WebGL2 上(WebGPU 的时间戳按整个 pass 挂,不能切);页面里用 `module.esGpuDetail = true` 打开,harness 的 `--detail` 做这件事。++默认机位(scene 共 9.3 ms):++| 段 | ms | 说明 |+|---|---|---|+| scene/Model | 5.4 | 所有植物(树、灌木、草、花、石头、芦苇),用的是同一个 Model 着色器 |+| scene/Terrain Layers | 3.2 | 地形四层混合 |+| scene/prepass:Model + Terrain | 0.67 | 深度预通道 |+| scene-glass/Water | 2.8 | 水面(不在 scene 里,在 scene-glass) |++重机位(机位 1,整图 28.4):Model 12.3、预通道 1.85、地形 1.9、阴影图 4.1、水 1.4。机位 3:Model 13.6、预通道 1.4、地形 2.9、阴影图 4.2、水 3.0。**植物(Model 加它的预通道和阴影)是重机位的一半以上**,地形反而是 2 到 3 ms 的固定块。++拿掉一样东西之后,各段的变化(机位 1,Model 段):++| 变化 | Model | 说明 |+|---|---|---|+| 整个树丛层(groves)拿掉 | 12.3 → 6.9 | 树本身 5.4,加预通道 1.2、阴影图 3.0:树合计约 9.6 ms,整图的三分之一 |+| 4× MSAA → 1× | 12.3 → 7.6(−4.7);机位 3 13.6 → 7.6(−6.0) | 植物的边缘像素多,多重采样把每个边缘像素着色最多 4 次 |+| 阴影不接收 | 12.3 → 10.0(−2.3);机位 3 −2.7 | 植物着色里的阴影查找 |+| 只拿掉一个配方(grove-oak、grove-birch…) | 每个只少 0.1 到 0.9 | 加起来远小于整层:拿掉一种,另一种照样盖住那些像素。所以成本是**被覆盖的像素数乘每像素的着色成本**,不是实例数 |++其他读数:+- 水 2.8 ms,**关掉阴影后降到 1.4(机位 0)和 0.18(机位 1)**:水面着色器自己在做阴影查找,是水的主要成本,不是波浪或折射。+- 地形 3.2 ms(机位 0)里阴影接收约 0.5,MSAA 约 0.5;其余是四层混合本身。+- 单个植物配方拿掉后阴影图最多少 1.1 ms(grove-oak),`undergrowth` 少 1.0:低矮植物也投影。+- 这些读数与消融一致:树的叶片卡片(镂空、阴影接收、4× MSAA 边缘像素)是 scene pass 的最大一块;没有哪一个“着色器阶段”是主要成本,是三者相乘(像素数 × 阴影查找 × 多重采样)。++没有量的:植物着色器里每个阶段(光照、阴影、风、透射)各占多少——要做就像之前量阴影接收那样,剪一个着色器重编一次;顶点阶段(三角形数 0.75M 到 2M)的成本也没有单独量。diff --git a/pipeline/src/runtime/gameHost.ts b/pipeline/src/runtime/gameHost.tsindex 68e58c2a0..09852a4f6 100644--- a/pipeline/src/runtime/gameHost.ts+++ b/pipeline/src/runtime/gameHost.ts@@ -696,7 +696,9 @@ async function boot(): Promise<void> {* The device answers a few frames late, so a value is the newest finished frame's, not the one just drawn. Engaging* the profiler is what turns the per-pass timers on.*/- gpu(): Record<string, number> {+ gpu(detail = false): Record<string, number> {+ // Per-shader segments of the scene pass: read by the engine each frame while the profiler is on.+ (module as unknown as { esGpuDetail?: boolean }).esGpuDetail = detail;module.engine_setCpuProfiling?.(true);try {return JSON.parse(module.engine_getGpuScopes?.() ?? '{}') as Record<string, number>;diff --git a/src/esengine/renderer/draw/DrawList.cpp b/src/esengine/renderer/draw/DrawList.cppindex 24be95080..bbeccd75a 100644--- a/src/esengine/renderer/draw/DrawList.cpp+++ b/src/esengine/renderer/draw/DrawList.cpp@@ -405,6 +405,7 @@ void DrawList::execute(GfxDevice& device, TransientBufferPool& buffers,const bool afterPrepass = pass == DrawPass::ColorAfterPrepass;PipelineDesc lastDesc{};PipelineHandle lastHandle = PipelineHandle::Invalid;+ const std::string* lastRun = nullptr;// The draws of this phase read the scene's colour and compose it under themselves.const bool composes = phase == Phase::SceneColorOnly;@@ -435,6 +436,12 @@ void DrawList::execute(GfxDevice& device, TransientBufferPool& buffers,if (!drawn) continue;}+ if (shader_run_sink_) {+ const std::string& run = materials.shaderLabel(cmd.material_id);+ if (&run != lastRun && (!lastRun || run != *lastRun)) shader_run_sink_(run.c_str());+ lastRun = &run;+ }+const GfxStencilMode stencil = stencilModeOf(cmd.state_flags);// Resolve the immutable pipeline. Depth/cull come from the command (resolved fromdiff --git a/src/esengine/renderer/draw/DrawList.hpp b/src/esengine/renderer/draw/DrawList.hppindex a51a75083..fbfd9e975 100644--- a/src/esengine/renderer/draw/DrawList.hpp+++ b/src/esengine/renderer/draw/DrawList.hpp@@ -13,6 +13,9 @@#include "../../math/Math.hpp"#include <algorithm>+#include <functional>+#include <string>+#include <utility>#include <unordered_map>#include <span>#include <vector>@@ -67,6 +70,10 @@ public:FrameCapture* capture = nullptr,const PerDrawBlockSet& blocks = {}, Phase phase = Phase::All, DrawPass pass = DrawPass::Color);+ /// Told, while a list executes, which shader the draws that follow use (and with nullptr that they are over): what lets a profiler time+ /// the scene a shader at a time. Empty costs nothing; a sink is installed only while someone is measuring.+ void setShaderRunSink(std::function<void(const char*)> sink) { shader_run_sink_ = std::move(sink); }+/// How many of the merged draws take part in a depth prepass; 0 means a prepass has nothing to draw.u32 depthPrepassDraws() const;@@ -214,6 +221,7 @@ public:}private:+ std::function<void(const char*)> shader_run_sink_;struct SortEntry {u64 key;u32 index;diff --git a/src/esengine/renderer/frame/RenderFrame.cpp b/src/esengine/renderer/frame/RenderFrame.cppindex 8e6115fdb..da029a026 100644--- a/src/esengine/renderer/frame/RenderFrame.cpp+++ b/src/esengine/renderer/frame/RenderFrame.cpp@@ -27,6 +27,9 @@#include <glm/gtc/type_ptr.hpp>#include <algorithm>+#ifdef __EMSCRIPTEN__+#include <emscripten.h>+#endif#include <cmath>#include <cstring>#include <limits>@@ -241,6 +244,15 @@ void RenderFrame::resize(u32 width, u32 height) {// The scene pass's body. The graph has bound the target and set the camera's// viewport; this is the draw and the constants it needs current.+bool RenderFrame::gpuDetailWanted() const {+#ifdef __EMSCRIPTEN__+ // A harness's switch, read only while the profiler is on: `module.esGpuDetail = true` from the page.+ return EM_ASM_INT({ return Module.esGpuDetail ? 1 : 0; }) != 0;+#else+ return false;+#endif+}+void RenderFrame::drawScene(DrawList::Phase phase) {// A temporal effect in the chain asks for the picture to be shifted by a different// sub-pixel amount each frame, so its history samples what a single frame cannot.@@ -296,14 +308,30 @@ void RenderFrame::drawScene(DrawList::Phase phase) {const u32 prepassDraws = depth_prepass_ && opaque ? draw_list_.depthPrepassDraws() : 0u;const bool prepass = prepassDraws > 0;if (opaque) ES_PROFILE_COUNTER("render.prepass.draws", prepassDraws);+ // With the pass timer running and detail asked for, each run of draws of one shader is its own timed segment of the pass.+ const bool detail = running_pass_timer_ && gpuDetailWanted();+ const auto sinkFor = [this](const char* prefix) {+ rg::PassTimer* timer = running_pass_timer_;+ draw_list_.setShaderRunSink([timer, prefix](const char* shader) {+ timer->segment(shader ? std::string(prefix) + shader : std::string("tail"));+ });+ };if (prepass) {ES_PROFILE_SCOPE("render.submit.prepass");+ if (detail) sinkFor("prepass:");draw_list_.execute(device_, pool_, context_.materials(), context_.getWhiteTextureId(),nullptr, context_.perDrawBlocks(), phase, DrawList::DrawPass::DepthPrepass);+ if (detail) draw_list_.setShaderRunSink(nullptr);}+ if (detail) sinkFor("");draw_list_.execute(device_, pool_, context_.materials(), context_.getWhiteTextureId(),&frame_capture_, context_.perDrawBlocks(), phase,prepass ? DrawList::DrawPass::ColorAfterPrepass : DrawList::DrawPass::Color);+ if (detail) {+ // The rest of the pass (the resolve, the state restored) is its own segment, closed by the graph.+ running_pass_timer_->segment("tail");+ draw_list_.setShaderRunSink(nullptr);+ }draw_list_.setGBufferPass(false);}@@ -839,7 +867,9 @@ void RenderFrame::end() {if (passTimer) {passTimer->beginFrame();graph_.setPassTimer(passTimer);+ running_pass_timer_ = passTimer;graph_.execute();+ running_pass_timer_ = nullptr;graph_.setPassTimer(nullptr);passTimer->endFrame();// The scope names are the passes' own, under pass/ so they cannot meet a scope of another kind.diff --git a/src/esengine/renderer/frame/RenderFrame.hpp b/src/esengine/renderer/frame/RenderFrame.hppindex d94b12f02..0ddb12d3a 100644--- a/src/esengine/renderer/frame/RenderFrame.hpp+++ b/src/esengine/renderer/frame/RenderFrame.hpp@@ -578,6 +578,9 @@ private:/// The profiler keeps a scope's name by pointer: "pass/<name>" per pass name, made once. Keyed by the timer's interned name.std::unordered_map<const char*, std::string> pass_scope_names_;f32 pass_graph_ms_ = -1.0f;+ /// The graph's timer while it runs, so the scene's draws can be told to it a shader at a time (see drawScene).+ rg::PassTimer* running_pass_timer_ = nullptr;+ bool gpuDetailWanted() const;FrameCapture frame_capture_;std::vector<u8> snapshot_pixels_;RenderTargetManager::Handle replay_rt_ = 0;diff --git a/src/esengine/renderer/graph/RenderGraph.cpp b/src/esengine/renderer/graph/RenderGraph.cppindex b74b0cb53..1521bc940 100644--- a/src/esengine/renderer/graph/RenderGraph.cpp+++ b/src/esengine/renderer/graph/RenderGraph.cpp@@ -93,9 +93,26 @@ void PassTimer::endFrame() {frames_[cur_].inflight = !frames_[cur_].slots.empty();}+void PassTimer::segment(const std::string& name) {+ if (state_ != 1 || arming_ || !open_) return;+ const std::string label = pass_ + "/" + name;+ end();+ Frame& f = frames_[cur_];+ if (f.slots.size() >= kMaxPasses) return;+ const u32 query = queryFor(cur_, static_cast<u32>(f.slots.size()));+ if (query == 0) return;+ Slot slot;+ slot.name = names_.insert(label).first->c_str();+ slot.query = query;+ f.slots.push_back(slot);+ device_.beginTimerQuery(query);+ open_ = true;+}+void PassTimer::begin(const std::string& name) {if (state_ != 1) return;end();+ pass_ = name;Frame& f = frames_[cur_];if (f.slots.size() >= kMaxPasses) return;const u32 query = queryFor(cur_, static_cast<u32>(f.slots.size()));diff --git a/src/esengine/renderer/graph/RenderGraph.hpp b/src/esengine/renderer/graph/RenderGraph.hppindex 5fad3f9eb..248427564 100644--- a/src/esengine/renderer/graph/RenderGraph.hpp+++ b/src/esengine/renderer/graph/RenderGraph.hpp@@ -171,6 +171,13 @@ public:void begin(const std::string& name);void end();+ /**+ * Splits the open pass: what has run so far is closed under the pass's own name, and the time from here is+ * `<pass>/<name>` until the next split or the pass's end. Only where a pass is bracketed (GL); where it is armed the+ * pass is one timestamp pair and this does nothing.+ */+ void segment(const std::string& name);+/** The newest frame whose every pass was read back. Empty until one has been. */const std::vector<Entry>& last() const { return last_; }f32 lastTotalMs() const { return lastTotal_; }@@ -188,7 +195,7 @@ private:bool inflight = false;};- static constexpr u32 kMaxPasses = 128;+ static constexpr u32 kMaxPasses = 512;u32 queryFor(u32 frame, u32 index);bool poll(Frame& frame);@@ -196,6 +203,7 @@ private:int state_ = 0; // 0 = unprobed, 1 = available, 2 = no timerbool arming_ = false;bool open_ = false;+ std::string pass_; // the open passFrame frames_[kFrames];std::vector<u32> queries_;std::unordered_set<std::string> names_;diff --git a/src/esengine/renderer/store/MaterialStore.cpp b/src/esengine/renderer/store/MaterialStore.cppindex b4fbb8185..3769387cb 100644--- a/src/esengine/renderer/store/MaterialStore.cpp+++ b/src/esengine/renderer/store/MaterialStore.cpp@@ -323,6 +323,7 @@ MaterialUniformLayout MaterialStore::layoutOf(const resource::ParsedShader& parslayout.usesGBuffer = parsed.usesGBuffer;layout.usesLights = parsed.usesLights;layout.highPrecision = parsed.highPrecision;+ layout.name = parsed.name;layout.vertexBounds = parsed.vertexBounds;layout.vertexHook = !parsed.vertexHook.empty();for (const auto& p : parsed.properties) {diff --git a/src/esengine/renderer/store/MaterialStore.hpp b/src/esengine/renderer/store/MaterialStore.hppindex 616a51b47..f118c7262 100644--- a/src/esengine/renderer/store/MaterialStore.hpp+++ b/src/esengine/renderer/store/MaterialStore.hpp@@ -102,6 +102,8 @@ struct MaterialUniformLayout {bool usesLights = false;/// The shader writes a measurement and wants a float target (ParsedShader::highPrecision).bool highPrecision = false;+ /// The shader's own name (`#pragma shader "<name>"`), for what a profiler calls a draw by.+ std::string name;/// What the shader's vertex hook can move a vertex by (ParsedShader::vertexBounds), and whether it/// has a hook at all — culling grows a mesh's box by the first, and the shadow pass builds a/// program of its own for the second.@@ -216,6 +218,14 @@ public:/// A program that is not a material's — the engine's own mesh shader — says it writes the record.void markGBufferProgram(u32 programId) const { gbuffer_programs_.insert(programId); }+ /// The name of the shader @p materialId draws with, or "default" for the path's own batch shader.+ const std::string& shaderLabel(u32 materialId) const {+ static const std::string fallback = "default";+ const MaterialRecord* m = find(materialId);+ const MaterialUniformLayout* layout = m ? layoutFor(m->shaderRef) : nullptr;+ return layout && !layout->name.empty() ? layout->name : fallback;+ }+/// How far @p materialId's vertex hook can move a vertex from the mesh's own bounds, in the/// mesh's local units; 0 for a material without one.float vertexBounds(u32 materialId) const {diff --git a/tools/terrain-water-cost.mjs b/tools/terrain-water-cost.mjsindex 669c24e31..6ced5be34 100644--- a/tools/terrain-water-cost.mjs+++ b/tools/terrain-water-cost.mjs@@ -40,7 +40,7 @@ const VIEW = Number(flag('view', '0'));const ONLY = flag('only', '') ? new Set(flag('only', '').split(',')) : null;const OUT = flag('out', path.join(ROOT, 'output', 'perf', 'terrain-water-cost.json'));const NO_EXPORT = argv.includes('--no-export');-const PASSES = argv.includes('--passes');+const PASSES = argv.includes('--passes') || argv.includes('--detail');const PASSES_TOP = Number(flag('passes-top', '24'));/** A folder to write each variant's last frame to, as `<id>-view<n>.png`. */const SHOTS = flag('shots', '');@@ -103,6 +103,9 @@ const VARIANTS = [// The plants, a layer at a time (what the world rules lay down), and with shadows taken off them{ id: 'plants-noshadow', label: 'plants cast no shadow', world: forParts((part) => { part.castShadows = false; }) },...['groves', 'banks', 'stones', 'cover', 'drifts', 'reeds', 'sea', 'shoals'].map((l) => ({ id: `layer-${l}-off`, label: `plant layer ${l} off`, world: noLayer(l) })),+ // One recipe at a time: what each kind of plant costs the scene (read with --detail).+ ...['shore-pines', 'willows', 'bank-grass', 'tufts', 'undergrowth', 'drift-amber', 'drift-blue', 'drift-ivory', 'grove-birch', 'grove-oak', 'lone-birch', 'lone-oak', 'pines', 'reed-strip', 'sea-amber', 'sea-blue', 'sea-ivory', 'sea-rose', 'sea-violet', 'pebble-field', 'shoal-flat', 'shoal-round', 'rocks-bank', 'rocks-crown', 'rocks-split']+ .map((r) => ({ id: `recipe-${r}-off`, label: `plant recipe ${r} off`, world: (w) => { for (const b of w.biomes) b.recipes = b.recipes.filter((x) => x.recipe !== r); } })),{ id: 'trees-no-lod2', label: 'trees without their third mesh (what the example drew before it)', world: trees((p) => { p.lod2Distance = 0; }) },{ id: 'trees-lod2-80', label: 'trees: lod1 from 60 m, lod2 from 80 m', world: trees((p) => { p.lod2Distance = 8000; }) },{ id: 'trees-lod2-70', label: 'trees: lod1 from 60 m, lod2 from 70 m', world: trees((p) => { p.lod2Distance = 7000; }) },@@ -183,7 +186,7 @@ async function measure(server, original, variant, browser) {}return -1;});- const result = await page.evaluate(async ({ frames, samples, passSamples }) => {+ const result = await page.evaluate(async ({ frames, samples, passSamples, detail }) => {const c = window.__estellaCooked;const px = new Uint8Array(4);const gl = document.querySelector('canvas').getContext('webgl2') ?? null;@@ -204,12 +207,12 @@ async function measure(server, original, variant, browser) {await c.step(frames, 1 / 60);sync();await new Promise((r) => setTimeout(r, 40));- gpuRuns.push(c.gpu?.() ?? {});+ gpuRuns.push(c.gpu?.(detail) ?? {});}const costs = c.costs();const cpu = costs.systems.reduce((a, x) => a + x.ms, 0);return { ms, gpuRuns, counters: c.render(), cpu, native: costs.native, size: [document.querySelector('canvas').width, document.querySelector('canvas').height], gl: !!gl };- }, { frames: FRAMES, samples: SAMPLES, passSamples: PASSES ? SAMPLES : 0 });+ }, { frames: FRAMES, samples: SAMPLES, passSamples: PASSES ? SAMPLES : 0, detail: argv.includes('--detail') });if (SHOTS) { await mkdir(SHOTS, { recursive: true }); await page.screenshot({ path: path.join(SHOTS, `${variant.id}-view${VIEW}.png`) }); }return { ms: median(result.ms), gpu: gpuMedians(result.gpuRuns), cpu: result.cpu, native: result.native, min: Math.min(...result.ms), max: Math.max(...result.ms), settled, counters: result.counters, size: result.size, errors };} finally {