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): drawing a frame costs the CPU a third of what it did - a draw no probe lights reads the zero block instead of staging its own, a draw binds only the texture units its program samples, the cull face is cached, vertex arrays are bound without asking the browser for their index buffer (no FULL_ES3), and device objects are found by index
yhhfda61d3f13ed
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 11eed0cac..77ae102ee 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -34,6 +34,7 @@ published separately; it ships inside the editor.### Fixed- **A playable samples its textures as their import settings say.** A single-file playable was handed no manifest, which is the only way a texture's `.meta` reaches a package, so its wrap mode, its filter, whether it is colour and its 9-slice border were all lost and every texture took the defaults. A ground or a wall whose picture repeats then drew one copy of it and smeared its last row of pixels over everything past the first tile: cliffs came out one flat colour with level stripes along the waterline, while the same scene was right in the editor and in a web export. The settings of the textures a playable inlines now ride in the page and reach the runtime the way they reach every other package.+- **Drawing a frame costs the CPU a third of what it did.** Issuing a frame's draws went through four costs the engine did not need. Every draw staged a light-probe block of its own, up to 16 KB of zeroes filled, copied and uploaded, though no probe lit it; a run no probe lights now reads the zero block. Every draw bound every texture unit its slots named, where the program it drew with read none of some (a shadow caster, most of all); a draw now binds only the units its program samples, read from the program once. The face to cull was set at every change of pipeline though it nearly never changed. And every vertex array bound asked the browser which index buffer it held, through a WebGL emulation (`FULL_ES3`) nothing in the engine used. Pipelines and other device objects are also found by index rather than searched for. On the Bistro scene at 640x360, where the CPU and not the GPU sets the pace, the renderer's CPU time a frame went from 11 to 14 ms down to 3.3 ms, the frame from 13.4 to 6.7 ms, and the WebGL calls a frame from 17,926 to 7,139; 52 pixel gates on WebGL2 and 23 on WebGPU draw what they did. `node tools/render-submit-cost.mjs` measures it: a synthetic grid in three spreads of material, or an example such as `--scene bistro`, with `--glcalls` and `--profile`.- **A cloud's shadow dims the sun, not the sky.** Sky Atmosphere's **Cloud Shadows** and a custom sky's `groundShadow` multiplied every surface in the frame by the shadow, after it was lit: ambient light, reflections, other lights and emission were dimmed with the sun, and an unlit or emissive object went dark under a cloud. Measured against a reference island lit the same way, its ground came out 25 to 35 levels darker than the reference, and lit by the sky alone it was black. Now the sky draws a cloud shadow map before the scene, into one tile of the sun's shadow atlas (16 km round the camera, `u_cloudShadowExtentKm`), and the first directional light is dimmed by it where each surface is shaded, as Unreal's atmosphere sun reads its clouds' shadow map; nothing else is. The cloud shadow criteria now light their floor by a sun and add a floor nothing lights, which must keep its colour under the clouds; they and 56 shadow and sun criteria pass on WebGL2 and WebGPU. With the atlas full (High quality's four cascades fill it) the sun gives up its farthest cascade to the map. The map holds the light left at the camera's own height, exact below the cloud layer and an estimate inside it.- **A package that ships texture recipes draws them.** An export carried its `.esimage` files and drew its ground and its walls with no texture, saying only in the console that nothing there draws recipes. The call that installs the drawer had ended up in a part of the built SDK that was not marked as having an effect, and the bundler dropped it; and a playable ad, whose entry is the whole SDK, never imported the drawer at all. Both are put right, and a check now bundles a game that imports it and looks for it.- **A cleared asset field no longer stops a game.** An empty string in an asset field of an engine component (a material cleared to nothing) was taken for a path to load, came back from the load still a string, was written back as one and asked for again, without end: a field of plants put it on every cell it grew, and the packaged game stopped answering half a minute in. An empty string is no asset now, and a path nothing resolves keeps its placeholder.diff --git a/cmake/Emscripten.cmake b/cmake/Emscripten.cmakeindex 233a7980b..88d70235f 100644--- a/cmake/Emscripten.cmake+++ b/cmake/Emscripten.cmake@@ -57,7 +57,9 @@ set(ES_EMSCRIPTEN_LINK_FLAGS--emit-tsd esengine.d.ts # Auto-generate TypeScript definitions-sWASM=1-sUSE_WEBGL2=1- -sFULL_ES3=1+ # No FULL_ES3: its client-side array emulation queried ELEMENT_ARRAY_BUFFER_BINDING with getParameter at every+ # glBindVertexArray, once a draw. Every draw here reads GPU buffers by offset (GLDevice::prepareVertexState).+ -sMAX_WEBGL_VERSION=2-sALLOW_MEMORY_GROWTH=1-sNO_EXIT_RUNTIME=1-sASSERTIONS=1@@ -81,7 +83,9 @@ set(ES_EMSCRIPTEN_MAIN_MODULE_FLAGS-sMAIN_MODULE=2-sWASM=1-sUSE_WEBGL2=1- -sFULL_ES3=1+ # No FULL_ES3: its client-side array emulation queried ELEMENT_ARRAY_BUFFER_BINDING with getParameter at every+ # glBindVertexArray, once a draw. Every draw here reads GPU buffers by offset (GLDevice::prepareVertexState).+ -sMAX_WEBGL_VERSION=2-sALLOW_MEMORY_GROWTH=1-sALLOW_TABLE_GROWTH=1-sNO_EXIT_RUNTIME=1@@ -105,7 +109,9 @@ set(ES_EMSCRIPTEN_WXGAME_MAIN_MODULE_FLAGS-sMAIN_MODULE=2-sWASM=1-sUSE_WEBGL2=1- -sFULL_ES3=1+ # No FULL_ES3: its client-side array emulation queried ELEMENT_ARRAY_BUFFER_BINDING with getParameter at every+ # glBindVertexArray, once a draw. Every draw here reads GPU buffers by offset (GLDevice::prepareVertexState).+ -sMAX_WEBGL_VERSION=2-sALLOW_MEMORY_GROWTH=1-sALLOW_TABLE_GROWTH=1-sNO_EXIT_RUNTIME=1@@ -163,7 +169,9 @@ set(ES_EMSCRIPTEN_WXGAME_SDK_FLAGS--bind-sWASM=1-sUSE_WEBGL2=1- -sFULL_ES3=1+ # No FULL_ES3: its client-side array emulation queried ELEMENT_ARRAY_BUFFER_BINDING with getParameter at every+ # glBindVertexArray, once a draw. Every draw here reads GPU buffers by offset (GLDevice::prepareVertexState).+ -sMAX_WEBGL_VERSION=2-sALLOW_MEMORY_GROWTH=1-sNO_EXIT_RUNTIME=1-sENVIRONMENT=web@@ -250,7 +258,9 @@ set(ES_EMSCRIPTEN_SDK_LINK_FLAGS# --emit-tsd esengine.d.ts # Temporarily disabled due to binding mismatch-sWASM=1-sUSE_WEBGL2=1- -sFULL_ES3=1+ # No FULL_ES3: its client-side array emulation queried ELEMENT_ARRAY_BUFFER_BINDING with getParameter at every+ # glBindVertexArray, once a draw. Every draw here reads GPU buffers by offset (GLDevice::prepareVertexState).+ -sMAX_WEBGL_VERSION=2-sALLOW_MEMORY_GROWTH=1-sALLOW_TABLE_GROWTH=1-sNO_EXIT_RUNTIME=1diff --git a/src/esengine/renderer/draw/DrawList.cpp b/src/esengine/renderer/draw/DrawList.cppindex f41bf6ee2..6fa91fd54 100644--- a/src/esengine/renderer/draw/DrawList.cpp+++ b/src/esengine/renderer/draw/DrawList.cpp@@ -337,7 +337,17 @@ void DrawList::stageBlocks(const PerDrawBlockSet& blocks) {// WHERE this draw's instances read their irradiance, not what it is: the// coefficients are in the frame's texture, one run per instance, so a// merged draw holding objects in many places still says one thing here.+ // A run no probe lights reads the zero block, which says the same thing, rather than zeroes of its own: staging+ // them filled and uploaded up to sixteen kilobytes a draw, and gave every draw a range of its own to bind.+ bool probeLit = false;if (blocks.probe) {+ const u32 runs = std::min(cmd.instance_count > 0 ? cmd.instance_count : 1u, PROBE_MAX_INSTANCES);+ for (u32 n = 0; n < runs && !probeLit; ++n) {+ const size_t at = static_cast<size_t>(cmd.probe_base) + n;+ probeLit = at < probe_slots_.size() && probe_slots_[at] != 0;+ }+ }+ if (blocks.probe && probeLit) {// Every instance of this run, in the order it draws them, capped at// what the block holds — a longer run carries no irradiance at all,// so its tail reads zeroes and takes the environment.@@ -518,6 +528,8 @@ void DrawList::execute(GfxDevice& device, TransientBufferPool& buffers,lastDesc = desc;}device.setPipeline(lastHandle);+ // The units this program samples: nothing else is bound for it. A depth program reads none, most of all.+ const u32 sampled = device.boundSamplerUnits();if (cmd.skin_count > 0 && blocks.skin) {blocks.skin->bind(SKIN_CONSTANTS_BINDING, staged.skin);@@ -545,6 +557,7 @@ void DrawList::execute(GfxDevice& device, TransientBufferPool& buffers,// put there, in any pass, the prepass too (a vertex hook reads textures). The fill is a STABLE white, so unused units cost no rebind.if (cmd.texture_count > 0) {for (u8 slot = 0; slot < MAX_CMD_TEXTURE_SLOTS; ++slot) {+ if (!((sampled >> slot) & 1u)) continue;// The top units are the frame's screen-space light masks wherever one// exists — the merge was kept off them, so what a draw holds there is// the mask, or the fill where the pass drew nothing.@@ -562,7 +575,7 @@ void DrawList::execute(GfxDevice& device, TransientBufferPool& buffers,// below the base that its shader never reads from the draw (ShaderParser::materialOverflowUnits): the material's binding is the// one this draw samples there.if (cmd.material_id != 0) {- materials.bindForDraw(cmd.material_id);+ materials.bindForDraw(cmd.material_id, sampled);}if (cmd.hasPersistentGeometry()) {diff --git a/src/esengine/renderer/rhi/GLDevice.cpp b/src/esengine/renderer/rhi/GLDevice.cppindex 263721dca..d7adc61b8 100644--- a/src/esengine/renderer/rhi/GLDevice.cpp+++ b/src/esengine/renderer/rhi/GLDevice.cpp@@ -441,6 +441,7 @@ bool GLDevice::recreateDevice() {}void GLDevice::resetStateCache() {+ sampler_units_.clear();current_pipeline_id_ = 0;current_stencil_mode_ = GfxStencilMode::Off;current_program_name_ = 0;@@ -458,6 +459,7 @@ void GLDevice::resetStateCache() {current_depth_bias_ = 0;alpha_to_coverage_ = -1;depth_equal_ = -1;+ cull_front_ = -1;surface_blend_off_ = false;current_framebuffer_ = 0;timer_query_state_ = 0;@@ -665,7 +667,10 @@ void GLDevice::setCulling(bool enabled) {}void GLDevice::setCullFace(bool front) {+ // Set at every change of pipeline that culls, and nearly always to what it was: a GL call into the browser each time.+ if (static_cast<i8>(front) == cull_front_) return;glCullFace(front ? GL_FRONT : GL_BACK);+ cull_front_ = static_cast<i8>(front);}// =============================================================================@@ -877,6 +882,7 @@ void GLDevice::backendDeleteProgram(u32 id) {pending_programs_.erase(it);}glDeleteProgram(name);+ sampler_units_.erase(name);if (current_program_name_ == name) current_program_name_ = 0;setName(program_names_, id, 0);}@@ -916,6 +922,62 @@ void GLDevice::backendSetUniform(i32 location, const GfxUniformValue& value) {namespace {+bool isSamplerType(GLenum type) {+ switch (type) {+ case GL_SAMPLER_2D: case GL_SAMPLER_3D: case GL_SAMPLER_CUBE: case GL_SAMPLER_2D_SHADOW:+ case GL_SAMPLER_2D_ARRAY: case GL_SAMPLER_2D_ARRAY_SHADOW: case GL_SAMPLER_CUBE_SHADOW:+ case GL_INT_SAMPLER_2D: case GL_INT_SAMPLER_3D: case GL_INT_SAMPLER_CUBE: case GL_INT_SAMPLER_2D_ARRAY:+ case GL_UNSIGNED_INT_SAMPLER_2D: case GL_UNSIGNED_INT_SAMPLER_3D: case GL_UNSIGNED_INT_SAMPLER_CUBE:+ case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY:+ return true;+ default:+ return false;+ }+}++} // namespace++u32 GLDevice::backendBoundSamplerUnits() {+ const u32 program = current_program_name_;+ if (program == 0) return 0xFFFFFFFFu;+ if (const auto it = sampler_units_.find(program); it != sampler_units_.end()) return it->second;+ // Read from the program as it stands, every element of a sampler array: the unit each active sampler was last set to,+ // which is what a draw has to have bound there. Once a program, not once a draw.+ u32 units = 0;+ GLint count = 0;+ glGetProgramiv(program, GL_ACTIVE_UNIFORMS, &count);+ GLint maxNameLen = 0;+ glGetProgramiv(program, GL_ACTIVE_UNIFORM_MAX_LENGTH, &maxNameLen);+ std::string nameBuf(static_cast<size_t>(std::max(maxNameLen, 64)), '\0');+ for (GLint i = 0; i < count; ++i) {+ GLsizei nameLen = 0;+ GLint size = 0;+ GLenum type = 0;+ glGetActiveUniform(program, static_cast<GLuint>(i), static_cast<GLsizei>(nameBuf.size()), &nameLen, &size, &type, nameBuf.data());+ if (!isSamplerType(type)) continue;+ std::string base(nameBuf.data(), static_cast<size_t>(nameLen));+ if (const auto bracket = base.find('['); bracket != std::string::npos) base.erase(bracket);+ for (GLint e = 0; e < std::max(size, 1); ++e) {+ const std::string element = size > 1 ? base + "[" + std::to_string(e) + "]" : base;+ const GLint location = glGetUniformLocation(program, element.c_str());+ if (location < 0) continue;+ GLint unit = 0;+ glGetUniformiv(program, location, &unit);+ if (unit >= 0 && unit < 32) units |= 1u << static_cast<u32>(unit);+ }+ }+ sampler_units_[program] = units;+ return units;+}++void GLDevice::backendIntUniformSet(u32 program) {+ if (sampler_units_.empty()) return;+ const u32 name = nameOf(program_names_, program);+ if (name) sampler_units_.erase(name);+}++namespace {+GfxUniformType fromGLUniformType(GLenum type) {switch (type) {case GL_FLOAT: return GfxUniformType::Float;diff --git a/src/esengine/renderer/rhi/GLDevice.hpp b/src/esengine/renderer/rhi/GLDevice.hppindex f5eb7e030..b74785066 100644--- a/src/esengine/renderer/rhi/GLDevice.hpp+++ b/src/esengine/renderer/rhi/GLDevice.hpp@@ -127,6 +127,8 @@ protected:i32 backendUniformLocation(u32 program, const char* name) override;i32 backendAttribLocation(u32 program, const char* name) override;void backendSetUniform(i32 nativeLocation, const GfxUniformValue& value) override;+ u32 backendBoundSamplerUnits() override;+ void backendIntUniformSet(u32 program) override;std::vector<GfxUniformInfo> backendActiveUniforms(u32 program) override;u32 backendUniformBlockIndex(u32 program, const char* name) override;void backendUniformBlockBinding(u32 program, u32 nativeBlockIndex, u32 bindingPoint) override;@@ -263,6 +265,9 @@ private:// skips the FFI-crossing GL call. 0xFF is an out-of-range BlendMode, so the// first real set always issues.u32 current_program_name_ = 0;+ /** The units each linked program samples, by GL program name; read once from the program, forgotten when an integer+ * uniform of it is set or it is deleted. */+ std::unordered_map<u32, u32> sampler_units_;BlendMode current_blend_ = static_cast<BlendMode>(0xFF);// Redundant-state caches for the two per-draw hot paths. glActiveTexture is@@ -274,6 +279,7 @@ private:i16 current_depth_bias_ = 0;i8 depth_equal_ = -1; ///< -1: unknown. 1 when the depth test passes on equal depth too.i8 alpha_to_coverage_ = -1; ///< -1: unknown, so the next pipeline sets it.+ i8 cull_front_ = -1; ///< -1: unknown. 1 when the front faces are the ones culled./// The framebuffer being drawn into carries a second colour attachment (and a third, the albedo, beside/// it), and which draw buffer set is live: 0 = colour only, 1 = colour and surface, 2 = all three,/// -1 = not yet said for this pass.diff --git a/src/esengine/renderer/rhi/GfxDevice.cpp b/src/esengine/renderer/rhi/GfxDevice.cppindex bb3f948a7..d97815bcf 100644--- a/src/esengine/renderer/rhi/GfxDevice.cpp+++ b/src/esengine/renderer/rhi/GfxDevice.cpp@@ -371,8 +371,7 @@ const VertexLayoutDesc* GfxDevice::vertexLayoutDesc(VertexLayoutHandle layout) cPipelineHandle GfxDevice::createPipeline(const PipelineDesc& desc) {if (device_status_ == GfxDeviceStatus::Dead) return PipelineHandle::Invalid;- if (const u32 existing = registry_.findPipeline(desc)) return PipelineHandle{existing};- return PipelineHandle{registry_.pipelines.insert(GfxPipelineRecord{desc})};+ return PipelineHandle{registry_.internPipeline(desc)};}const PipelineDesc* GfxDevice::pipelineDesc(PipelineHandle handle) const {@@ -737,6 +736,7 @@ void GfxDevice::setUniformValue(i32 location, const GfxUniformValue& value) {auto* record = registry_.programs.find(id);if (!record || location < 0 || static_cast<usize>(location) >= record->uniformValues.size()) return;record->uniformValues[static_cast<usize>(location)] = value;+ if (value.type == GfxUniformValue::Type::Int) backendIntUniformSet(id);if (!record->realized) return;const i32 native = nativeUniformLocation(*record, id, location);if (native >= 0) backendSetUniform(native, value);diff --git a/src/esengine/renderer/rhi/GfxDevice.hpp b/src/esengine/renderer/rhi/GfxDevice.hppindex 9a4049cd1..02655e54f 100644--- a/src/esengine/renderer/rhi/GfxDevice.hpp+++ b/src/esengine/renderer/rhi/GfxDevice.hpp@@ -619,6 +619,14 @@ public:/** @brief Gets a vertex attribute location by name (-1 if not found) */i32 getAttribLocation(ShaderHandle program, const char* name);+ /**+ * @brief The texture units the bound program samples, one bit a unit; every unit where the backend cannot say.+ *+ * @details A unit no active sampler reads can hold anything, so a draw binds only these: what a depth program, a+ * shadow caster or a material that leaves maps unset never reads is never bound for it.+ */+ u32 boundSamplerUnits() { return backendBoundSamplerUnits(); }+/** @brief Sets an integer uniform of the bound program */void setUniform1i(i32 location, i32 value);@@ -915,6 +923,10 @@ protected:virtual i32 backendUniformLocation(u32 program, const char* name) = 0;virtual i32 backendAttribLocation(u32 program, const char* name) = 0;virtual void backendSetUniform(i32 nativeLocation, const GfxUniformValue& value) = 0;+ /** The units the bound program samples; a backend that cannot say answers every unit. */+ virtual u32 backendBoundSamplerUnits() { return 0xFFFFFFFFu; }+ /** An integer uniform of @p program was set: a sampler may have moved to another unit. */+ virtual void backendIntUniformSet(u32 program) { (void)program; }virtual std::vector<GfxUniformInfo> backendActiveUniforms(u32 program) = 0;virtual u32 backendUniformBlockIndex(u32 program, const char* name) = 0;virtual void backendUniformBlockBinding(u32 program, u32 nativeBlockIndex, u32 bindingPoint) = 0;diff --git a/src/esengine/renderer/rhi/GfxResourceRegistry.hpp b/src/esengine/renderer/rhi/GfxResourceRegistry.hppindex 7a8c9b06e..98d41ef29 100644--- a/src/esengine/renderer/rhi/GfxResourceRegistry.hpp+++ b/src/esengine/renderer/rhi/GfxResourceRegistry.hpp@@ -16,7 +16,9 @@#include "./GfxEnums.hpp"#include "./PipelineState.hpp"-#include <map>+#include <deque>+#include <optional>+#include <unordered_map>#include <functional>#include <string>#include <utility>@@ -99,36 +101,96 @@ struct GfxTimerQueryRecord {bool realized = false;};-/** @brief One kind of object, by id, in creation order. */+/**+ * @brief One kind of object, by id, in creation order.+ *+ * @details Ids are handed out in order and never reused, so a record lives at the index its id names: finding one is an+ * index, not a search. A draw finds its pipeline, its layout and its textures by id every time it is issued,+ * and a tree there cost a pointer chase per level per lookup. A deque, so a record a caller holds stays where+ * it is while others are added after it, as a map's did; an erased record leaves an empty slot behind.+ */template <typename Record>class GfxRecordTable {public:u32 insert(Record record) {- const u32 id = next_++;- records_.emplace(id, std::move(record));+ const u32 id = static_cast<u32>(slots_.size()) + 1;+ slots_.emplace_back(std::move(record));+ ++live_;return id;}Record* find(u32 id) {- auto it = records_.find(id);- return it != records_.end() ? &it->second : nullptr;+ if (id == 0 || id > slots_.size()) return nullptr;+ auto& slot = slots_[id - 1];+ return slot ? &*slot : nullptr;}const Record* find(u32 id) const {- auto it = records_.find(id);- return it != records_.end() ? &it->second : nullptr;+ if (id == 0 || id > slots_.size()) return nullptr;+ const auto& slot = slots_[id - 1];+ return slot ? &*slot : nullptr;}- bool erase(u32 id) { return records_.erase(id) != 0; }-- u32 size() const { return static_cast<u32>(records_.size()); }+ bool erase(u32 id) {+ if (id == 0 || id > slots_.size() || !slots_[id - 1]) return false;+ slots_[id - 1].reset();+ --live_;+ return true;+ }- std::map<u32, Record>& all() { return records_; }- const std::map<u32, Record>& all() const { return records_; }+ u32 size() const { return live_; }++ /** Every live record as (id, record), in creation order: what a structured binding over the old map gave. */+ template <typename Slots, typename Ref>+ class View {+ public:+ class iterator {+ public:+ iterator(Slots* slots, size_t at) : slots_(slots), at_(at) { skip(); }+ // An lvalue, so `for (auto& [id, record] : table.all())` binds as it did over the map.+ std::pair<u32, Ref>& operator*() const { current_.emplace(static_cast<u32>(at_ + 1), *(*slots_)[at_]); return *current_; }+ iterator& operator++() { ++at_; skip(); return *this; }+ bool operator!=(const iterator& other) const { return at_ != other.at_; }+ bool operator==(const iterator& other) const { return at_ == other.at_; }+ private:+ void skip() { while (at_ < slots_->size() && !(*slots_)[at_]) ++at_; }+ Slots* slots_;+ size_t at_;+ mutable std::optional<std::pair<u32, Ref>> current_;+ };+ explicit View(Slots* slots) : slots_(slots) {}+ iterator begin() const { return iterator(slots_, 0); }+ iterator end() const { return iterator(slots_, slots_->size()); }+ private:+ Slots* slots_;+ };++ View<std::deque<std::optional<Record>>, Record&> all() { return View<std::deque<std::optional<Record>>, Record&>(&slots_); }+ View<const std::deque<std::optional<Record>>, const Record&> all() const {+ return View<const std::deque<std::optional<Record>>, const Record&>(&slots_);+ }private:- std::map<u32, Record> records_;- u32 next_ = 1;+ std::deque<std::optional<Record>> slots_;+ u32 live_ = 0;+};++/** A pipeline description's hash: every field, as the equality compares them. */+struct PipelineDescHash {+ size_t operator()(const PipelineDesc& d) const noexcept {+ u64 h = 1469598103934665603ull;+ const auto mix = [&h](u64 v) { h = (h ^ v) * 1099511628211ull; };+ mix(static_cast<u32>(d.program));+ mix(static_cast<u32>(d.vertexLayout));+ mix(static_cast<u32>(d.blend));+ mix(static_cast<u32>(d.stencil));+ mix(static_cast<u32>(d.topology));+ mix(static_cast<u16>(d.depthBias));+ mix((u64(d.blendEnabled) << 0) | (u64(d.depthTest) << 1) | (u64(d.depthWrite) << 2) | (u64(d.cullEnabled) << 3)+ | (u64(d.cullFront) << 4) | (u64(d.alphaToCoverage) << 5) | (u64(d.gbuffer) << 6) | (u64(d.albedo) << 7)+ | (u64(d.colorWrite) << 8) | (u64(d.depthEqual) << 9));+ return static_cast<size_t>(h);+ }};/** @brief A Sourced object that has storage again and is waiting for its contents. */@@ -151,12 +213,18 @@ public:GfxRecordTable<GfxPipelineRecord> pipelines;GfxRecordTable<GfxTimerQueryRecord> timerQueries;- /** @brief An existing pipeline with this description, or 0. */+ /** @brief An existing pipeline with this description, or 0. A hash lookup: a pipeline is asked for at every change of state. */u32 findPipeline(const PipelineDesc& desc) const {- for (const auto& [id, record] : pipelines.all()) {- if (record.desc == desc) return id;- }- return 0;+ const auto it = pipelineIndex_.find(desc);+ return it != pipelineIndex_.end() ? it->second : 0;+ }++ /** @brief The pipeline with this description, made if there is none. Pipelines are never erased, so the index only grows. */+ u32 internPipeline(const PipelineDesc& desc) {+ if (const u32 existing = findPipeline(desc)) return existing;+ const u32 id = pipelines.insert(GfxPipelineRecord{desc});+ pipelineIndex_.emplace(desc, id);+ return id;}std::vector<GfxOwedContent> owed() const {@@ -175,6 +243,9 @@ public:}return out;}++private:+ std::unordered_map<PipelineDesc, u32, PipelineDescHash> pipelineIndex_;};} // namespace esenginediff --git a/src/esengine/renderer/store/MaterialStore.cpp b/src/esengine/renderer/store/MaterialStore.cppindex 291d5ee36..78e545db7 100644--- a/src/esengine/renderer/store/MaterialStore.cpp+++ b/src/esengine/renderer/store/MaterialStore.cpp@@ -429,7 +429,7 @@ void MaterialStore::setWorldUnitsPerMeter(f32 unitsPerMeter) {}}-void MaterialStore::bindForDraw(u32 materialId) {+void MaterialStore::bindForDraw(u32 materialId, u32 samplerUnits) {if (!device_) return;auto it = materials_.find(materialId);if (it == materials_.end()) return;@@ -461,6 +461,7 @@ void MaterialStore::bindForDraw(u32 materialId) {// whatever stale texture is at the unit.if (lit != layouts_.end()) {for (const auto& slot : lit->second.textures) {+ if (slot.unit < 32 && !((samplerUnits >> slot.unit) & 1u)) continue;TextureHandle gpu = builtinDefault(slot.defaultTexture);// What stood behind this draw, where the frame took a copy of it; a material that named a texture there keeps its own.if (sceneColor_ != TextureHandle::Invalid && slot.name == "u_sceneColor") gpu = sceneColor_;diff --git a/src/esengine/renderer/store/MaterialStore.hpp b/src/esengine/renderer/store/MaterialStore.hppindex fbac4dea7..5e89cc7f4 100644--- a/src/esengine/renderer/store/MaterialStore.hpp+++ b/src/esengine/renderer/store/MaterialStore.hpp@@ -446,7 +446,8 @@ public:/// Uploads (when dirty) and binds the material's MaterialConstants UBO at binding 1./// No-op for materials whose shader declares no params (uboBytes stays empty).- void bindForDraw(u32 materialId);+ /** Binds the material's block and its textures; a texture only where @p samplerUnits says the bound program reads its unit. */+ void bindForDraw(u32 materialId, u32 samplerUnits = 0xFFFFFFFFu);/// Says what a world unit is (the project's units per metre). A param a material left at its default follows the change;/// one it set, to anything else, is the material's and stays.diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txtindex 5e3643ce7..64d825b07 100644--- a/tests/CMakeLists.txt+++ b/tests/CMakeLists.txt@@ -643,6 +643,14 @@ 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)+# The device's record tables and its pipeline index: header-only, so it links alone.+add_executable(test_record_table+ renderer/test_record_table.cpp+ ${CMAKE_SOURCE_DIR}/src/esengine/core/Log.cpp+)+target_include_directories(test_record_table PRIVATE ${CMAKE_SOURCE_DIR}/src)+add_test(NAME test_record_table COMMAND test_record_table)+# Device loss: the shared state machine (GfxDevice), driven through MockGfxDevice.# Header-only, so nothing but Log.cpp is needed to link.add_executable(test_device_lossdiff --git a/tests/renderer/test_record_table.cpp b/tests/renderer/test_record_table.cppnew file mode 100644index 000000000..edfde9dc4--- /dev/null+++ b/tests/renderer/test_record_table.cpp@@ -0,0 +1,99 @@+// The device's record tables: a record is found by its id at once, ids are never reused, a record a caller holds stays+// where it is while others are added, iteration walks the live records in creation order (as the map it replaced did),+// and a pipeline description names one pipeline however many times it is asked for.++#include "esengine/renderer/rhi/GfxResourceRegistry.hpp"++#include <cstdio>+#include <vector>++using namespace esengine;++static int g_failures = 0;+#define CHECK(cond, msg) \+ do { \+ if (!(cond)) { std::printf("FAIL: %s\n", msg); ++g_failures; } \+ else { std::printf("ok: %s\n", msg); } \+ } while (0)++struct Thing { int value = 0; };++int main() {+ {+ GfxRecordTable<Thing> table;+ const u32 a = table.insert({1});+ const u32 b = table.insert({2});+ const u32 c = table.insert({3});+ CHECK(a == 1 && b == 2 && c == 3, "ids are handed out in order from 1");+ CHECK(table.find(b) && table.find(b)->value == 2, "a record is found by its id");+ CHECK(table.find(0) == nullptr && table.find(4) == nullptr, "no id and an id not yet handed out find nothing");+ CHECK(table.size() == 3, "size counts the records");++ Thing* held = table.find(a);+ for (int i = 0; i < 5000; ++i) table.insert({100 + i});+ CHECK(held == table.find(a) && held->value == 1, "a record a caller holds stays where it is while thousands are added");++ CHECK(table.erase(b), "a record can be erased");+ CHECK(!table.erase(b), "and not twice");+ CHECK(table.find(b) == nullptr, "an erased record is not found");+ const u32 d = table.insert({4});+ CHECK(d == 5004, "an erased id is not handed out again");+ CHECK(table.size() == 5003, "size counts only the live records");++ std::vector<u32> ids;+ for (auto& [id, record] : table.all()) {+ ids.push_back(id);+ record.value += 0; // a mutable reference, as over the map+ }+ bool ordered = ids.size() == 5003;+ for (size_t i = 1; i < ids.size(); ++i) ordered = ordered && ids[i - 1] < ids[i];+ CHECK(ordered && ids.front() == 1 && ids[1] == 3, "iteration walks the live records in creation order, past the erased");++ for (auto& [id, record] : table.all()) if (id == c) record.value = 30;+ CHECK(table.find(c)->value == 30, "a record changed through iteration is changed");++ const GfxRecordTable<Thing>& constant = table;+ int sum = 0;+ for (const auto& [id, record] : constant.all()) if (id <= 3) sum += record.value;+ CHECK(sum == 31, "a const table iterates too");+ }++ {+ GfxResourceRegistry registry;+ PipelineDesc desc{};+ desc.program = ShaderHandle{7};+ desc.vertexLayout = VertexLayoutHandle{3};+ desc.depthTest = true;+ const u32 first = registry.internPipeline(desc);+ CHECK(first != 0, "a pipeline is made for a description");+ CHECK(registry.internPipeline(desc) == first, "the same description names the same pipeline");+ CHECK(registry.findPipeline(desc) == first, "and is found without making another");++ PipelineDesc other = desc;+ other.cullFront = true;+ const u32 second = registry.internPipeline(other);+ CHECK(second != first, "a description that differs in one field is another pipeline");+ other = desc;+ other.depthBias = -2;+ CHECK(registry.internPipeline(other) != first && registry.internPipeline(other) != second, "and so is one with another depth bias");+ CHECK(registry.pipelines.size() == 3, "three descriptions, three pipelines, however often asked");+ CHECK(registry.pipelines.find(first)->desc == desc, "a pipeline holds the description it was made for");++ PipelineDesc unknown = desc;+ unknown.program = ShaderHandle{99};+ CHECK(registry.findPipeline(unknown) == 0, "a description never asked for finds nothing");++ // Many pipelines, as a scene of many materials makes: each still found by its own description.+ bool all = true;+ for (u32 p = 100; p < 2100; ++p) {+ PipelineDesc many = desc;+ many.program = ShaderHandle{p};+ const u32 id = registry.internPipeline(many);+ all = all && registry.findPipeline(many) == id;+ }+ CHECK(all, "two thousand pipelines are each found by their description");+ }++ std::printf("\n%s (%d failure%s)\n", g_failures ? "FAILED" : "PASSED", g_failures, g_failures == 1 ? "" : "s");+ return g_failures ? 1 : 0;+}diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 2430cdb50..c531f9448 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -4768,4 +4768,6 @@ export const NOTED = {{"note": "A sound or a piece of music can ship as its recipe."},"fix(playable): a playable samples its textures as their .meta says - the page was handed no manifest, so no texture's wrap, filter, colour space or 9-slice border reached it and each took the defaults: a ground or a wall whose picture repeats drew one copy and smeared its edge over the rest, right in the editor and in a web export and wrong in the playable; the import settings of what is inlined ride in the page and the host hands them to the runtime":{"note": "A playable samples its textures as their import settings say."},+ "perf(render): drawing a frame costs the CPU a third of what it did - a draw no probe lights reads the zero block instead of staging its own, a draw binds only the texture units its program samples, the cull face is cached, vertex arrays are bound without asking the browser for their index buffer (no FULL_ES3), and device objects are found by index":+ {"note": "Drawing a frame costs the CPU a third of what it did."},};diff --git a/tools/render-submit-cost.mjs b/tools/render-submit-cost.mjsnew file mode 100644index 000000000..3a380faab--- /dev/null+++ b/tools/render-submit-cost.mjs@@ -0,0 +1,253 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file render-submit-cost.mjs — what the renderer's CPU costs a frame to collect and submit draws, measured headless.+ *+ * The CPU side of drawing - walking the scene into a draw list, sorting and merging it, and issuing it to the device -+ * is where an engine built on an ECS should be cheapest. This plays a scene in a headless Chromium (no window, no+ * editor), steps it by the game's own clock until it has settled, and reads the engine's own CPU scopes for the+ * frames that follow: `render.collect`, `render.submit` and the rest, with the draw counts beside them.+ *+ * node tools/render-submit-cost.mjs # the synthetic scene, every material spread+ * node tools/render-submit-cost.mjs --scene bistro # the Bistro example+ * node tools/render-submit-cost.mjs --only unique --count 8192 # one spread, more entities+ * node tools/render-submit-cost.mjs --profile --top 40 # also sample the CPU, by function+ * node tools/render-submit-cost.mjs --no-export --dir <package> # an already exported package (A/B builds)+ *+ * The synthetic scene is `--count` static entities in a grid, all in view, cycling the six closed built-in meshes, in+ * one of three material spreads: `shared` (one material, what an engine should merge), `mats64` (64 materials, a game),+ * `unique` (a material each, the worst case). A function-level profile names wasm functions only from a names build+ * (see the wasm-size notes: ESTELLA_WASM_NAMES=1 with --profiling-funcs).+ */+import { chromium } from 'playwright';+import { spawnSync } from 'node:child_process';+import { writeFile, mkdir, rm } from 'node:fs/promises';+import { randomUUID } from 'node:crypto';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { serveHost } from './lib/staticServer.mjs';++const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const argv = process.argv.slice(2);+const flag = (n, d) => {+ const i = argv.indexOf(`--${n}`);+ return i >= 0 && argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[i + 1] : d;+};+const SCENE = flag('scene', 'synthetic');+const COUNT = Number(flag('count', '4096'));+const FRAMES = Number(flag('frames', '30'));+const SAMPLES = Number(flag('samples', '5'));+const W = Number(flag('w', '1920'));+const H = Number(flag('h', '1080'));+const TOP = Number(flag('top', '30'));+const PROFILE = argv.includes('--profile');+/** Count every WebGL call per frame: the CPU work a frame hands the browser, which no GPU stall can hide. */+const GLCALLS = argv.includes('--glcalls');+const NO_EXPORT = argv.includes('--no-export');+const ONLY = flag('only', '') ? new Set(flag('only', '').split(',')) : null;+/** A png of the last measured frame, to compare two builds' pictures. */+const SHOT = flag('shot', '');+const OUT = flag('out', path.join(ROOT, 'output', 'perf', `render-submit-${SCENE}.json`));+const MESHES = ['cube', 'sphere', 'capsule', 'cylinder', 'cone', 'plane'];+const SPREADS = SCENE === 'synthetic' ? ['shared', 'mats64', 'unique'] : ['scene'];++/** What the exporter cooks an asset by: a uuid and its type, beside it. */+const meta = (file, type) => writeFile(`${file}.meta`, JSON.stringify({ uuid: randomUUID(), version: '2.0', type, importer: {} }));++/** The synthetic project: a camera over a grid of static meshes, a sun and a sky, in one material spread. */+async function writeSynthetic(dir, spread) {+ await rm(dir, { recursive: true, force: true });+ await mkdir(path.join(dir, 'assets/scenes'), { recursive: true });+ await mkdir(path.join(dir, 'assets/materials'), { recursive: true });+ await writeFile(path.join(dir, 'project.esproject'), JSON.stringify({ name: 'RenderSubmitCost', version: '1.0', defaultScene: 'assets/scenes/main.esscene' }));+ const materials = spread === 'shared' ? 1 : spread === 'mats64' ? 64 : COUNT;+ for (let m = 0; m < materials; m++) {+ await writeFile(path.join(dir, `assets/materials/m${m}.esmaterial`), JSON.stringify({+ version: '1.0', type: 'material', shader: 'builtin:model', blendMode: 0, depthTest: true, depthWrite: true, cull: 0,+ properties: { u_metallic: (m % 7) / 7, u_roughness: 0.2 + (m % 11) / 14 },+ }));+ await meta(path.join(dir, `assets/materials/m${m}.esmaterial`), 'material');+ }+ const side = Math.ceil(Math.sqrt(COUNT));+ const spacing = 140;+ const entities = [+ { id: 0, name: 'Camera', parent: null, children: [], visible: true, components: [+ { type: 'Transform', data: { position: { x: 0, y: side * spacing * 0.75, z: side * spacing * 0.75 }, rotation: { x: -0.3826834, y: 0, z: 0, w: 0.9238795 } } },+ { type: 'Camera', data: { projectionType: 0, fov: 65, nearPlane: 10, farPlane: 100000, isActive: true } }] },+ { id: 1, name: 'Sun', parent: null, children: [], visible: true, components: [+ { type: 'Transform', data: { rotation: { x: -0.42, y: 0.38, z: 0, w: 0.82 } } },+ { type: 'Light', data: { type: 1, intensity: 0.8, enabled: true, color: { r: 1, g: 1, b: 1, a: 1 } } }] },+ { id: 2, name: 'Sky', parent: null, children: [], visible: true, components: [+ { type: 'Transform', data: {} }, { type: 'Light', data: { type: 2, intensity: 0.4, enabled: true, color: { r: 1, g: 1, b: 1, a: 1 } } }] },+ ];+ for (let i = 0; i < COUNT; i++) {+ const x = (i % side) - side / 2, z = Math.floor(i / side) - side / 2;+ const turn = (i * 0.6180339) % 1 * Math.PI;+ entities.push({ id: 10 + i, name: `E${i}`, parent: null, children: [], visible: true, components: [+ { type: 'Transform', data: { position: { x: x * spacing, y: 0, z: z * spacing }, rotation: { x: 0, y: Math.sin(turn / 2), z: 0, w: Math.cos(turn / 2) } } },+ { type: 'MeshRenderer', data: { mesh: `builtin:${MESHES[i % MESHES.length]}`, material: `assets/materials/m${i % materials}.esmaterial`, lit: true, opaque: true, cullBackfaces: true, color: { r: 1, g: 1, b: 1, a: 1 } } },+ ] });+ }+ await writeFile(path.join(dir, 'assets/scenes/main.esscene'), JSON.stringify({ version: '1.0', name: 'Main', entities }));+ await meta(path.join(dir, 'assets/scenes/main.esscene'), 'scene');+}++function exportProject(project, out) {+ const r = spawnSync(process.execPath, [path.join(ROOT, 'pipeline/bin/estella.mjs'), 'export', project, '--out', out, '--platform', 'web'], { stdio: 'inherit' });+ if (r.status !== 0) throw new Error(`export of ${project} failed`);+}++const median = (a) => { const s = [...a].sort((x, y) => x - y); return s[Math.floor(s.length / 2)]; };++async function measure(browser, dir) {+ const server = await serveHost(dir);+ const context = await browser.newContext({ viewport: { width: W, height: H }, deviceScaleFactor: 1 });+ const page = await context.newPage();+ if (GLCALLS) {+ await page.addInitScript(() => {+ const counts = (window.__glCalls = {});+ for (const proto of [WebGL2RenderingContext.prototype]) {+ for (const name of Object.getOwnPropertyNames(proto)) {+ const d = Object.getOwnPropertyDescriptor(proto, name);+ if (!d || typeof d.value !== 'function' || name === 'constructor') continue;+ const f = d.value;+ proto[name] = function (...a) { counts[name] = (counts[name] ?? 0) + 1; return f.apply(this, a); };+ }+ }+ });+ }+ const errors = [];+ page.on('pageerror', (e) => errors.push(String(e).slice(0, 200)));+ if (argv.includes('--logs')) {+ page.on('console', (m) => { if (['warning', 'error'].includes(m.type())) console.log(` [${m.type()}] ${m.text().slice(0, 300)}`); });+ page.on('pageerror', (e) => console.log(` [pageerror] ${String(e).slice(0, 300)}`));+ page.on('response', (r) => { if (r.status() >= 400) console.log(` [http ${r.status()}] ${r.url()}`); });+ }+ try {+ await page.goto(`http://127.0.0.1:${server.address().port}/?headless`, { waitUntil: 'load', timeout: 180000 });+ await page.waitForFunction(() => window.__estellaCooked?.facts, null, { timeout: Number(flag('wait', '180000')) });+ await page.evaluate(() => window.__estellaCooked.setPaused(true));+ const settled = await page.evaluate(async () => {+ const c = window.__estellaCooked;+ // Settled: nothing baking, no draw waiting on a program, something drawn, and the same draws for twenty checks running -+ // a scene whose meshes and textures are still arriving draws fewer each frame than it will.+ let last = -1, same = 0;+ for (let i = 0; i < 1200; i++) {+ await c.step(2, 1 / 60);+ const r = c.render();+ const draws = (r['batch.draws'] ?? 0) + (r['render.shadow.draws'] ?? 0);+ const busy = (c.bakes?.() ?? []).length > 0 || r['render.draws.waitingForProgram'] > 0;+ same = !busy && draws > 0 && draws === last ? same + 1 : 0;+ last = draws;+ if (same >= 20) return i;+ await new Promise((r) => setTimeout(r, 30));+ }+ return -1;+ });+ let cdp = null;+ if (PROFILE) {+ cdp = await context.newCDPSession(page);+ await cdp.send('Profiler.enable');+ await cdp.send('Profiler.setSamplingInterval', { interval: 100 });+ }+ const result = await page.evaluate(async ({ frames, samples, profile }) => {+ const c = window.__estellaCooked;+ const sync = () => c.capture().rgba[0];+ c.render(); c.costs();+ await c.step(frames, 1 / 60); sync();+ const ms = [];+ const scopes = [];+ if (profile) await new Promise((r) => setTimeout(r, 0));+ for (let s = 0; s < samples; s++) {+ const t0 = performance.now();+ await c.step(frames, 1 / 60);+ sync();+ ms.push((performance.now() - t0) / frames);+ scopes.push(c.costs().native);+ }+ let gl = null;+ if (window.__glCalls) {+ for (const k of Object.keys(window.__glCalls)) delete window.__glCalls[k];+ await c.step(frames, 1 / 60);+ gl = Object.fromEntries(Object.entries(window.__glCalls).map(([k, v]) => [k, v / frames]));+ }+ const costs = c.costs();+ return { ms, scopes, counters: c.render(), systems: costs.systems, gl };+ }, { frames: FRAMES, samples: SAMPLES, profile: PROFILE });+ let profile = null;+ if (cdp) {+ await cdp.send('Profiler.start');+ await page.evaluate(async ({ frames }) => { const c = window.__estellaCooked; for (let i = 0; i < 4; i++) await c.step(frames, 1 / 60); }, { frames: FRAMES });+ profile = (await cdp.send('Profiler.stop')).profile;+ }+ if (SHOT) { await mkdir(path.dirname(path.resolve(SHOT)), { recursive: true }); await page.locator('canvas').first().screenshot({ path: path.resolve(SHOT) }); }+ const keys = new Set(result.scopes.flatMap((s) => Object.keys(s ?? {})));+ const native = {};+ for (const k of keys) native[k] = median(result.scopes.map((s) => s?.[k] ?? 0));+ return { ms: median(result.ms), native, counters: result.counters, systems: result.systems, settled, errors, profile, gl: result.gl };+ } finally {+ await context.close();+ await new Promise((r) => server.close(r));+ }+}++/** Self time by function, from a CDP profile: what the CPU was doing, not who asked. */+function bySelf(profile) {+ const byId = new Map(profile.nodes.map((n) => [n.id, n]));+ const self = new Map();+ const dt = profile.timeDeltas;+ for (let i = 0; i < profile.samples.length; i++) {+ const n = byId.get(profile.samples[i]);+ const cf = n.callFrame;+ const key = `${cf.functionName || '(anonymous)'} ${cf.url ? path.basename(cf.url) : ''}`;+ self.set(key, (self.get(key) ?? 0) + (dt[i] ?? 0) / 1000);+ }+ const total = [...self.values()].reduce((a, b) => a + b, 0);+ return { total, rows: [...self.entries()].sort((a, b) => b[1] - a[1]) };+}++const browser = await chromium.launch({+ headless: true,+ args: ['--use-angle=d3d11', '--enable-webgl', '--ignore-gpu-blocklist', '--disable-gpu-vsync', '--disable-frame-rate-limit', '--enable-unsafe-swiftshader'],+});+const table = {};+try {+ for (const spread of SPREADS) {+ if (ONLY && !ONLY.has(spread)) continue;+ const dir = path.resolve(flag('dir', path.join(ROOT, 'output', 'perf', `submit-${SCENE}-${spread}`)));+ if (!NO_EXPORT) {+ if (SCENE === 'synthetic') {+ const project = path.join(ROOT, 'output', 'perf', `submit-project-${spread}`);+ await writeSynthetic(project, spread);+ exportProject(project, dir);+ } else {+ exportProject(path.join(ROOT, 'examples', SCENE), dir);+ }+ }+ const r = await measure(browser, dir);+ const n = r.native, c = r.counters;+ const renderCpu = (n['render.collect'] ?? 0) + (n['render.finalize'] ?? 0) + (n['render.submit'] ?? 0) + (n['render.graph'] ?? 0);+ table[spread] = { ms: r.ms, renderCpu, native: n, counters: c, settled: r.settled, errors: r.errors, gl: r.gl };+ console.log(`${spread.padEnd(8)} frame ${r.ms.toFixed(2)} ms collect ${(n['render.collect'] ?? 0).toFixed(2)} finalize ${(n['render.finalize'] ?? 0).toFixed(2)} submit ${(n['render.submit'] ?? 0).toFixed(2)} graph ${(n['render.graph'] ?? 0).toFixed(2)} -> render CPU ${renderCpu.toFixed(2)} ms draws ${c['batch.draws'] ?? '?'} (gpu ${c['render.gpu.draws'] ?? '?'}, merged ${c['batch.merged'] ?? '?'}, shadow ${c['render.shadow.draws'] ?? '?'}) tris ${((c['render.triangles'] ?? 0) / 1e6).toFixed(2)}M settled ${r.settled}${r.errors.length ? ' ERRORS ' + r.errors[0] : ''}`);+ const breaks = Object.entries(c).filter(([k]) => k.startsWith('batch.break.')).map(([k, v]) => `${k.slice(12)}=${v}`).join(' ');+ if (breaks) console.log(` merge breaks: ${breaks}`);+ const sys = (r.systems ?? []).slice().sort((a, b) => b.ms - a.ms).slice(0, 6).map((s) => `${s.name} ${s.ms.toFixed(2)}`).join(', ');+ if (sys) console.log(` top systems: ${sys}`);+ if (r.gl) {+ const rows = Object.entries(r.gl).sort((a, b) => b[1] - a[1]);+ const total = rows.reduce((t, [, v]) => t + v, 0);+ console.log(` GL calls a frame: ${total.toFixed(0)} - ` + rows.slice(0, 14).map(([k, v]) => `${k} ${v.toFixed(0)}`).join(', '));+ }+ if (r.profile) {+ const p = bySelf(r.profile);+ console.log(` profile: ${p.total.toFixed(0)} ms sampled`);+ for (const [k, v] of p.rows.slice(0, TOP)) console.log(` ${v.toFixed(1).padStart(8)} ms ${(100 * v / p.total).toFixed(1).padStart(5)}% ${k}`);+ table[spread].profile = p.rows.slice(0, 200);+ }+ }+} finally {+ await browser.close();+}+await mkdir(path.dirname(OUT), { recursive: true });+await writeFile(OUT, JSON.stringify({ scene: SCENE, count: COUNT, size: [W, H], frames: FRAMES, samples: SAMPLES, table }, null, 1));+console.log(`\nwritten ${path.relative(ROOT, OUT)}`);