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(engine): per-frame CPU scope profiler (ES_PROFILE_SCOPE)

esenginea0d57b734a96
diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.ts
index 9ea357ea2..c69b31577 100644
--- a/sdk/src/wasm.ts
+++ b/sdk/src/wasm.ts
@@ -290,6 +290,10 @@ export interface ESEngineModule {
renderer_getCulled(): number;
/** Last frame's GPU time (ms) via EXT_disjoint_timer_query, or -1 if unavailable. */
renderer_getGpuTimeMs?(): number;
+ /** Enable/disable per-frame CPU scope profiling (FrameProfiler). */
+ engine_setCpuProfiling?(on: boolean): void;
+ /** Last frame's CPU scopes as a JSON object {"render.submit": ms, …}. */
+ engine_getCpuScopes?(): string;
renderer_setClearColor(r: number, g: number, b: number, a: number): void;
renderer_setViewport(x: number, y: number, w: number, h: number): void;
renderer_setScissor(x: number, y: number, w: number, h: number, enable: boolean): void;
diff --git a/src/esengine/bindings/RendererBindings.cpp b/src/esengine/bindings/RendererBindings.cpp
index df58872ee..cfdac46c5 100644
--- a/src/esengine/bindings/RendererBindings.cpp
+++ b/src/esengine/bindings/RendererBindings.cpp
@@ -6,6 +6,7 @@
#include "../renderer/GfxDevice.hpp"
#include "../renderer/RenderFrame.hpp"
#include "../renderer/RenderContext.hpp"
+#include "../core/FrameProfiler.hpp"
#include "../renderer/RenderStage.hpp"
#include "../renderer/ImmediateDraw.hpp"
#include "../renderer/CustomGeometry.hpp"
@@ -418,6 +419,16 @@ f32 renderer_getGpuTimeMs() {
return g_renderFrame->stats().gpu_time_ms;
}
+// Per-frame CPU scope profiling (FrameProfiler): the editor turns it on and reads
+// the last frame's `cpp.*` scopes as a JSON object to fold into its breakdown.
+void engine_setCpuProfiling(bool on) {
+ FrameProfiler::get().setEnabled(on);
+}
+
+std::string engine_getCpuScopes() {
+ return FrameProfiler::get().lastJson();
+}
+
void renderer_setDeltaTime(f32 dt) {
ctx().state().delta_time = dt;
}
diff --git a/src/esengine/bindings/RendererBindings.hpp b/src/esengine/bindings/RendererBindings.hpp
index 50079e972..4275f10db 100644
--- a/src/esengine/bindings/RendererBindings.hpp
+++ b/src/esengine/bindings/RendererBindings.hpp
@@ -107,6 +107,8 @@ u32 renderer_getText();
u32 renderer_getMeshes();
u32 renderer_getCulled();
f32 renderer_getGpuTimeMs();
+void engine_setCpuProfiling(bool on);
+std::string engine_getCpuScopes();
void renderer_setDeltaTime(f32 dt);
void renderer_setClearColor(f32 r, f32 g, f32 b, f32 a);
void renderer_setViewport(i32 x, i32 y, i32 w, i32 h);
diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cpp
index d27f460fb..31cc5aab0 100644
--- a/src/esengine/bindings/WebSDKEntry.cpp
+++ b/src/esengine/bindings/WebSDKEntry.cpp
@@ -519,6 +519,8 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {
emscripten::function("renderer_getMeshes", &esengine::renderer_getMeshes);
emscripten::function("renderer_getCulled", &esengine::renderer_getCulled);
emscripten::function("renderer_getGpuTimeMs", &esengine::renderer_getGpuTimeMs);
+ emscripten::function("engine_setCpuProfiling", &esengine::engine_setCpuProfiling);
+ emscripten::function("engine_getCpuScopes", &esengine::engine_getCpuScopes);
emscripten::function("renderer_setDeltaTime", &esengine::renderer_setDeltaTime);
emscripten::function("renderer_setClearColor", &esengine::renderer_setClearColor);
emscripten::function("renderer_setViewport", &esengine::renderer_setViewport);
diff --git a/src/esengine/core/FrameProfiler.hpp b/src/esengine/core/FrameProfiler.hpp
new file mode 100644
index 000000000..1e4983288
--- /dev/null
+++ b/src/esengine/core/FrameProfiler.hpp
@@ -0,0 +1,115 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+#pragma once
+/**
+ * @file FrameProfiler.hpp
+ * @brief Per-frame CPU scope timing for the editor profiler (C++ side).
+ *
+ * `ES_PROFILE_SCOPE("render.submit")` times its block and accumulates the ms into
+ * a per-frame table — the C++ counterpart of the editor's TS `PerfMonitor.measure`
+ * and the analog of UE's SCOPE_CYCLE_COUNTER / TRACE_CPUPROFILER_EVENT_SCOPE. Both
+ * feed ONE per-frame breakdown: the TS layer reads these scopes over a binding and
+ * shows them as `cpp.*` rows alongside its own zones, so a spike inside the engine
+ * (culling vs draw submission vs a physics step) is named, not a black box.
+ *
+ * `commit()` snapshots the frame (called once at the end of the render) into a
+ * stable buffer the binding reads. Header-only + near-free when disabled (the
+ * scope short-circuits), so it can live on in the editor with no measurable cost.
+ */
+#include <vector>
+#include <string>
+#include <cstring>
+#include <cstdio>
+#ifdef __EMSCRIPTEN__
+#include <emscripten.h>
+#endif
+
+namespace esengine {
+
+/** High-resolution wall clock (ms). performance.now() under emscripten. */
+inline double es_profile_now_ms() {
+#ifdef __EMSCRIPTEN__
+ return emscripten_get_now();
+#else
+ return 0.0; // the editor profiler is web-only; native builds don't time scopes
+#endif
+}
+
+/**
+ * Frame-scoped CPU scope collector (singleton). Accumulates inclusive time per
+ * named scope for the frame in progress, then `commit()` swaps it to `last_` —
+ * the last COMPLETE frame the binding serializes. Scope names are string literals
+ * (stable for the program's life), so entries store the pointer and dedupe by
+ * strcmp (a handful of scopes per frame — negligible).
+ */
+class FrameProfiler {
+public:
+ static FrameProfiler& get() {
+ static FrameProfiler instance;
+ return instance;
+ }
+
+ void setEnabled(bool e) { enabled_ = e; }
+ bool enabled() const { return enabled_; }
+
+ void add(const char* name, double ms) {
+ for (auto& e : cur_) {
+ if (std::strcmp(e.name, name) == 0) { e.ms += ms; return; }
+ }
+ cur_.push_back({name, ms});
+ }
+
+ /** Close the frame: the accumulated scopes become the readable snapshot. */
+ void commit() {
+ last_.swap(cur_);
+ cur_.clear();
+ }
+
+ /** The last complete frame's scopes as a JSON object {"name": ms, …}. */
+ std::string lastJson() const {
+ std::string s = "{";
+ for (std::size_t i = 0; i < last_.size(); ++i) {
+ if (i) s += ',';
+ char buf[32];
+ std::snprintf(buf, sizeof(buf), "%.4f", last_[i].ms);
+ s += '"';
+ s += last_[i].name;
+ s += "\":";
+ s += buf;
+ }
+ s += '}';
+ return s;
+ }
+
+private:
+ struct Entry { const char* name; double ms; };
+ std::vector<Entry> cur_;
+ std::vector<Entry> last_;
+ bool enabled_ = false;
+};
+
+/** RAII scope: times its block into the FrameProfiler when profiling is enabled. */
+class ScopeTimer {
+public:
+ explicit ScopeTimer(const char* name)
+ : name_(name),
+ active_(FrameProfiler::get().enabled()),
+ start_(active_ ? es_profile_now_ms() : 0.0) {}
+ ~ScopeTimer() {
+ if (active_) FrameProfiler::get().add(name_, es_profile_now_ms() - start_);
+ }
+ ScopeTimer(const ScopeTimer&) = delete;
+ ScopeTimer& operator=(const ScopeTimer&) = delete;
+
+private:
+ const char* name_;
+ bool active_;
+ double start_;
+};
+
+#define ES_PROFILE_CONCAT_(a, b) a##b
+#define ES_PROFILE_CONCAT(a, b) ES_PROFILE_CONCAT_(a, b)
+/** Time the enclosing block as a named CPU scope (a `cpp.<name>` profiler row). */
+#define ES_PROFILE_SCOPE(name) ::esengine::ScopeTimer ES_PROFILE_CONCAT(es_scope_, __LINE__)(name)
+
+} // namespace esengine
diff --git a/src/esengine/renderer/RenderFrame.cpp b/src/esengine/renderer/RenderFrame.cpp
index 17031098c..b84d59528 100644
--- a/src/esengine/renderer/RenderFrame.cpp
+++ b/src/esengine/renderer/RenderFrame.cpp
@@ -9,6 +9,7 @@
#include "../ecs/components/ShadowCaster2D.hpp"
#include "../resource/ShaderParser.hpp"
#include "../core/Log.hpp"
+#include "../core/FrameProfiler.hpp"
#include "OpenGLHeaders.hpp"
#ifdef __EMSCRIPTEN__
#include <emscripten/html5.h>
@@ -248,17 +249,23 @@ void RenderFrame::flush() {
// finalize() sorts + coalesces and rewrites per-vertex texIndex into the staging, so it
// must run before upload() ships that staging to the GPU.
- draw_list_.finalize(pool_);
- pool_.upload();
+ {
+ ES_PROFILE_SCOPE("render.finalize");
+ draw_list_.finalize(pool_);
+ pool_.upload();
+ }
context_.updateFrameConstants(view_projection_);
context_.lights().uploadAndBind();
// GPU time for the scene draw: read back prior frames, then bracket this one.
gpu_timer_.poll();
- gpu_timer_.begin();
- draw_list_.execute(device_, pool_, context_.materials(), &frame_capture_);
- gpu_timer_.end();
+ {
+ ES_PROFILE_SCOPE("render.submit"); // CPU cost of issuing the draw calls
+ gpu_timer_.begin();
+ draw_list_.execute(device_, pool_, context_.materials(), &frame_capture_);
+ gpu_timer_.end();
+ }
stats_.gpu_time_ms = gpu_timer_.lastMs();
stats_.draw_calls = draw_list_.mergedDrawCallCount();
@@ -301,6 +308,7 @@ void RenderFrame::end() {
if (usePostProcess) {
#ifdef ES_ENABLE_POSTPROCESS
+ ES_PROFILE_SCOPE("render.postprocess");
post_process_->end();
#endif
} else if (current_target_ != RenderTargetManager::INVALID_HANDLE) {
@@ -313,6 +321,10 @@ void RenderFrame::end() {
frame_capture_.endCapture();
in_frame_ = false;
flushed_ = false;
+
+ // Render is the last C++ work in a frame; physics/animation/… scopes ran
+ // earlier this frame and are already accumulated. Snapshot them all now.
+ FrameProfiler::get().commit();
}
void RenderFrame::replayToDrawCall(i32 stopAtDrawCall) {
@@ -547,6 +559,7 @@ void RenderFrame::collectLights(ecs::Registry& registry) {
}
void RenderFrame::collectAll(ecs::Registry& registry, u32 skipFlags) {
+ ES_PROFILE_SCOPE("render.collect"); // cull + build the draw list from the ECS
buildClipState();
collectLights(registry);