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.

perf: optimize SDK hot paths, resource cleanup, and platform compatibility

esengineb11dbd4f6643
diff --git a/sdk/src/asset/AssetServer.ts b/sdk/src/asset/AssetServer.ts
index 4932c6c4b..5f7f6bfd7 100644
--- a/sdk/src/asset/AssetServer.ts
+++ b/sdk/src/asset/AssetServer.ts
@@ -155,6 +155,21 @@ export class AssetServer {
this.jsonCache_.clear();
this.textCache_.clear();
this.binaryCache_.clear();
+ this.loadedSpines_.clear();
+ this.cleanupVirtualFS();
+ }
+
+ private cleanupVirtualFS(): void {
+ const fs = this.module_.FS;
+ if (!fs) return;
+ for (const path of this.virtualFSPaths_) {
+ try {
+ fs.unlink(path);
+ } catch {
+ // File may already be removed
+ }
+ }
+ this.virtualFSPaths_.clear();
}
setTextureMetadata(handle: TextureHandle, border: SliceBorder): void {
diff --git a/sdk/src/component.ts b/sdk/src/component.ts
index e6d8ed6f2..181aa7198 100644
--- a/sdk/src/component.ts
+++ b/sdk/src/component.ts
@@ -34,7 +34,7 @@ function createComponentDef<T extends object>(
_default: defaults,
_builtin: false as const,
create(data?: Partial<T>): T {
- return { ...defaults, ...data };
+ return data ? { ...defaults, ...data } : { ...defaults };
}
};
}
diff --git a/sdk/src/material.ts b/sdk/src/material.ts
index 635c2f985..72da2a8b7 100644
--- a/sdk/src/material.ts
+++ b/sdk/src/material.ts
@@ -338,7 +338,7 @@ let materialCallbackRegistered = false;
let uniformBuffer: number = 0;
const UNIFORM_BUFFER_SIZE = 4096;
const encodedNameCache = new Map<string, Uint8Array>();
-const encoder = new TextEncoder();
+let encoder: TextEncoder | null = null;
function ensureUniformBuffer(): number {
if (uniformBuffer === 0 && module) {
@@ -362,6 +362,7 @@ function serializeUniforms(uniforms: Map<string, UniformValue>): { ptr: number;
let nameBytes = encodedNameCache.get(name);
if (!nameBytes) {
+ if (!encoder) encoder = new TextEncoder();
nameBytes = encoder.encode(name);
encodedNameCache.set(name, nameBytes);
}
diff --git a/sdk/src/platform/web.ts b/sdk/src/platform/web.ts
index c3294d25f..4c3b6ffa1 100644
--- a/sdk/src/platform/web.ts
+++ b/sdk/src/platform/web.ts
@@ -17,6 +17,7 @@ import type {
class WebPlatformAdapter implements PlatformAdapter {
readonly name = 'web' as const;
+ private inputCleanup_: (() => void) | null = null;
async fetch(url: string, options?: PlatformRequestOptions): Promise<PlatformResponse> {
const response = await globalThis.fetch(url, {
@@ -106,45 +107,76 @@ class WebPlatformAdapter implements PlatformAdapter {
}
bindInputEvents(callbacks: InputEventCallbacks, target?: unknown): void {
- const el = (target as HTMLElement) ?? document.querySelector('canvas') ?? document.body;
+ if (this.inputCleanup_) {
+ this.inputCleanup_();
+ this.inputCleanup_ = null;
+ }
- document.addEventListener('keydown', (e) => callbacks.onKeyDown(e.code));
- document.addEventListener('keyup', (e) => callbacks.onKeyUp(e.code));
+ const el = (target as HTMLElement) ?? document.querySelector('canvas') ?? document.body;
- el.addEventListener('mousemove', (e) => {
+ const onKeyDown = (e: Event) => callbacks.onKeyDown((e as KeyboardEvent).code);
+ const onKeyUp = (e: Event) => callbacks.onKeyUp((e as KeyboardEvent).code);
+ const onMouseMove = (e: Event) => {
const me = e as MouseEvent;
callbacks.onPointerMove(me.offsetX, me.offsetY);
- });
- el.addEventListener('mousedown', (e) => {
+ };
+ const onMouseDown = (e: Event) => {
const me = e as MouseEvent;
callbacks.onPointerDown(me.button, me.offsetX, me.offsetY);
- });
- el.addEventListener('mouseup', (e) => {
+ };
+ const onMouseUp = (e: Event) => {
callbacks.onPointerUp((e as MouseEvent).button);
- });
-
- el.addEventListener('touchstart', (e) => {
+ };
+ const onTouchStart = (e: Event) => {
const touch = (e as TouchEvent).touches[0];
if (touch) {
const rect = (el as HTMLElement).getBoundingClientRect();
callbacks.onPointerDown(0, touch.clientX - rect.left, touch.clientY - rect.top);
}
- });
- el.addEventListener('touchmove', (e) => {
+ };
+ const onTouchMove = (e: Event) => {
const touch = (e as TouchEvent).touches[0];
if (touch) {
const rect = (el as HTMLElement).getBoundingClientRect();
callbacks.onPointerMove(touch.clientX - rect.left, touch.clientY - rect.top);
}
- });
- el.addEventListener('touchend', () => {
+ };
+ const onTouchEnd = () => {
callbacks.onPointerUp(0);
- });
-
- el.addEventListener('wheel', (e) => {
+ };
+ const onWheel = (e: Event) => {
const we = e as WheelEvent;
callbacks.onWheel(we.deltaX, we.deltaY);
- });
+ };
+
+ document.addEventListener('keydown', onKeyDown);
+ document.addEventListener('keyup', onKeyUp);
+ el.addEventListener('mousemove', onMouseMove);
+ el.addEventListener('mousedown', onMouseDown);
+ el.addEventListener('mouseup', onMouseUp);
+ el.addEventListener('touchstart', onTouchStart);
+ el.addEventListener('touchmove', onTouchMove);
+ el.addEventListener('touchend', onTouchEnd);
+ el.addEventListener('wheel', onWheel);
+
+ this.inputCleanup_ = () => {
+ document.removeEventListener('keydown', onKeyDown);
+ document.removeEventListener('keyup', onKeyUp);
+ el.removeEventListener('mousemove', onMouseMove);
+ el.removeEventListener('mousedown', onMouseDown);
+ el.removeEventListener('mouseup', onMouseUp);
+ el.removeEventListener('touchstart', onTouchStart);
+ el.removeEventListener('touchmove', onTouchMove);
+ el.removeEventListener('touchend', onTouchEnd);
+ el.removeEventListener('wheel', onWheel);
+ };
+ }
+
+ unbindInputEvents(): void {
+ if (this.inputCleanup_) {
+ this.inputCleanup_();
+ this.inputCleanup_ = null;
+ }
}
}
diff --git a/sdk/src/platform/wechat/index.ts b/sdk/src/platform/wechat/index.ts
index 25e50dfb0..6f0e2de22 100644
--- a/sdk/src/platform/wechat/index.ts
+++ b/sdk/src/platform/wechat/index.ts
@@ -99,6 +99,7 @@ export function initWeChatPlatform(): void {
if (initialized) return;
initialized = true;
+ polyfillPerformance();
polyfillFetch();
polyfillWebAssembly();
polyfillTextEncoder();
@@ -106,6 +107,18 @@ export function initWeChatPlatform(): void {
console.log('[ESEngine] WeChat platform initialized');
}
+function polyfillPerformance(): void {
+ const g = globalThis as any;
+ if (typeof g.performance === 'undefined') {
+ const start = Date.now();
+ g.performance = {
+ now(): number {
+ return Date.now() - start;
+ }
+ };
+ }
+}
+
function polyfillTextEncoder(): void {
const g = globalThis as any;
if (typeof g.TextEncoder === 'undefined') {
diff --git a/sdk/src/query.ts b/sdk/src/query.ts
index 3e1990f5b..358c09267 100644
--- a/sdk/src/query.ts
+++ b/sdk/src/query.ts
@@ -95,72 +95,73 @@ interface PendingMutation {
export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<QueryResult<C>> {
private readonly world_: World;
private readonly descriptor_: QueryDescriptor<C>;
- private pendingMutations_: PendingMutation[] = [];
+ private readonly actualComponents_: AnyComponentDef[];
+ private readonly allRequired_: AnyComponentDef[];
constructor(world: World, descriptor: QueryDescriptor<C>) {
this.world_ = world;
this.descriptor_ = descriptor;
- }
-
- private getActualComponent(arg: QueryArg): AnyComponentDef {
- return isMutWrapper(arg) ? arg._component : arg;
- }
-
- private commitPending(): void {
- for (const mutation of this.pendingMutations_) {
- this.world_.insert(mutation.entity, mutation.component, mutation.data);
- }
- this.pendingMutations_ = [];
+ this.actualComponents_ = descriptor._components.map(c =>
+ isMutWrapper(c) ? c._component : c
+ );
+ this.allRequired_ = this.actualComponents_.concat(descriptor._with);
}
*[Symbol.iterator](): Iterator<QueryResult<C>> {
- const { _components, _mutIndices, _with, _without } = this.descriptor_;
-
- const actualComponents = _components.map(c => this.getActualComponent(c));
- const allRequired = [...actualComponents, ..._with];
- const entities = this.world_.getEntitiesWithComponents(allRequired);
+ const { _mutIndices, _without } = this.descriptor_;
+ const actualComponents = this.actualComponents_;
+ const entities = this.world_.getEntitiesWithComponents(this.allRequired_);
+ const compCount = actualComponents.length;
+ const hasMut = _mutIndices.length > 0;
+ const hasWithout = _without.length > 0;
let prevEntity: Entity | null = null;
let prevMutData: Array<{ component: AnyComponentDef; data: unknown }> = [];
try {
for (const entity of entities) {
- // Commit previous entity's mutations before moving to next
- if (prevEntity !== null) {
- for (const mut of prevMutData) {
+ if (prevEntity !== null && hasMut) {
+ for (let i = 0; i < prevMutData.length; i++) {
+ const mut = prevMutData[i];
this.world_.insert(prevEntity, mut.component, mut.data);
}
+ prevMutData.length = 0;
}
- prevMutData = [];
- let excluded = false;
- for (const comp of _without) {
- if (this.world_.has(entity, comp)) {
- excluded = true;
- break;
+ if (hasWithout) {
+ let excluded = false;
+ for (let i = 0; i < _without.length; i++) {
+ if (this.world_.has(entity, _without[i])) {
+ excluded = true;
+ break;
+ }
}
+ if (excluded) continue;
+ }
+
+ const result = new Array(compCount + 1);
+ result[0] = entity;
+ for (let i = 0; i < compCount; i++) {
+ result[i + 1] = this.world_.get(entity, actualComponents[i]);
}
- if (excluded) continue;
-
- const components = actualComponents.map(comp =>
- this.world_.get(entity, comp)
- ) as ComponentsData<C>;
-
- // Track mutable components for write-back
- for (const idx of _mutIndices) {
- prevMutData.push({
- component: actualComponents[idx],
- data: components[idx]
- });
+
+ if (hasMut) {
+ for (let i = 0; i < _mutIndices.length; i++) {
+ const idx = _mutIndices[i];
+ prevMutData.push({
+ component: actualComponents[idx],
+ data: result[idx + 1]
+ });
+ }
+ prevEntity = entity;
}
- prevEntity = entity;
- yield [entity, ...components] as QueryResult<C>;
+ yield result as QueryResult<C>;
}
} finally {
- // Commit last entity's mutations
- if (prevEntity !== null) {
- for (const mut of prevMutData) {
+ if (prevEntity !== null && hasMut) {
+ for (let i = 0; i < prevMutData.length; i++) {
+ const mut = prevMutData[i];
this.world_.insert(prevEntity, mut.component, mut.data);
}
}
diff --git a/sdk/src/renderPipeline.ts b/sdk/src/renderPipeline.ts
index fc59a2696..377917d47 100644
--- a/sdk/src/renderPipeline.ts
+++ b/sdk/src/renderPipeline.ts
@@ -29,6 +29,8 @@ export type SpineRendererFn = (registry: { _cpp: CppRegistry }, elapsed: number)
export class RenderPipeline {
private spineRenderer_: SpineRendererFn | null = null;
+ private lastWidth_ = 0;
+ private lastHeight_ = 0;
setSpineRenderer(fn: SpineRendererFn | null): void {
this.spineRenderer_ = fn;
@@ -37,10 +39,13 @@ export class RenderPipeline {
render(params: RenderParams): void {
const { registry, viewProjection, width, height, elapsed } = params;
- Renderer.resize(width, height);
-
- if (PostProcess.isInitialized() && PostProcess.getPassCount() > 0 && !PostProcess.isBypassed()) {
- PostProcess.resize(width, height);
+ if (width !== this.lastWidth_ || height !== this.lastHeight_) {
+ Renderer.resize(width, height);
+ if (PostProcess.isInitialized() && PostProcess.getPassCount() > 0) {
+ PostProcess.resize(width, height);
+ }
+ this.lastWidth_ = width;
+ this.lastHeight_ = height;
}
Renderer.setViewport(0, 0, width, height);
diff --git a/sdk/src/world.ts b/sdk/src/world.ts
index f40de661e..725d28e1d 100644
--- a/sdk/src/world.ts
+++ b/sdk/src/world.ts
@@ -222,9 +222,24 @@ export class World {
return this.getAllEntities();
}
+ let smallestPool: Map<Entity, unknown> | null = null;
+ let smallestSize = Infinity;
+
+ for (const comp of components) {
+ if (!isBuiltinComponent(comp)) {
+ const storage = this.tsStorage_.get(comp._id);
+ const size = storage ? storage.size : 0;
+ if (size < smallestSize) {
+ smallestSize = size;
+ smallestPool = storage ?? null;
+ }
+ }
+ }
+
const entities: Entity[] = [];
+ const candidates = smallestPool ? smallestPool.keys() : this.entities_;
- for (const entity of this.entities_) {
+ for (const entity of candidates) {
let hasAll = true;
for (const comp of components) {
if (!this.has(entity, comp)) {
diff --git a/src/esengine/bindings/PhysicsModuleEntry.cpp b/src/esengine/bindings/PhysicsModuleEntry.cpp
index b50d52ade..bf77f5a25 100644
--- a/src/esengine/bindings/PhysicsModuleEntry.cpp
+++ b/src/esengine/bindings/PhysicsModuleEntry.cpp
@@ -14,6 +14,7 @@
#include <unordered_map>
#include <vector>
+#include <algorithm>
#include <cstdint>
#include <cstring>
@@ -28,6 +29,7 @@ static float g_accumulator = 0.0f;
static std::unordered_map<uint32_t, b2BodyId> g_entityToBody;
static std::unordered_map<uint32_t, b2ShapeId> g_entityToShape;
+static std::vector<uint32_t> g_dynamicBodyEntities;
// [entityId_bits, x, y, angle, ...]
static std::vector<float> g_dynamicTransformBuffer;
@@ -91,6 +93,7 @@ void physics_shutdown() {
g_entityToBody.clear();
g_entityToShape.clear();
+ g_dynamicBodyEntities.clear();
g_dynamicTransformBuffer.clear();
g_collisionEnterBuffer.clear();
g_collisionExitBuffer.clear();
@@ -130,6 +133,9 @@ void physics_createBody(uint32_t entityId, int bodyType, float x, float y, float
b2BodyId bodyId = b2CreateBody(g_worldId, &bodyDef);
b2Body_SetUserData(bodyId, reinterpret_cast<void*>(static_cast<uintptr_t>(entityId)));
g_entityToBody[entityId] = bodyId;
+ if (bodyDef.type == b2_dynamicBody) {
+ g_dynamicBodyEntities.push_back(entityId);
+ }
}
EMSCRIPTEN_KEEPALIVE
@@ -142,6 +148,11 @@ void physics_destroyBody(uint32_t entityId) {
}
g_entityToBody.erase(it);
g_entityToShape.erase(entityId);
+ auto dit = std::find(g_dynamicBodyEntities.begin(), g_dynamicBodyEntities.end(), entityId);
+ if (dit != g_dynamicBodyEntities.end()) {
+ *dit = g_dynamicBodyEntities.back();
+ g_dynamicBodyEntities.pop_back();
+ }
}
EMSCRIPTEN_KEEPALIVE
@@ -245,26 +256,19 @@ void physics_setBodyTransform(uint32_t entityId, float x, float y, float angle)
EMSCRIPTEN_KEEPALIVE
int physics_getDynamicBodyCount() {
- int count = 0;
- for (auto& [entityId, bodyId] : g_entityToBody) {
- if (!b2Body_IsValid(bodyId)) continue;
- if (b2Body_GetType(bodyId) == b2_dynamicBody) {
- ++count;
- }
- }
- return count;
+ return static_cast<int>(g_dynamicBodyEntities.size());
}
EMSCRIPTEN_KEEPALIVE
uintptr_t physics_getDynamicBodyTransforms() {
g_dynamicTransformBuffer.clear();
- for (auto& [entityId, bodyId] : g_entityToBody) {
- if (!b2Body_IsValid(bodyId)) continue;
- if (b2Body_GetType(bodyId) != b2_dynamicBody) continue;
+ for (uint32_t entityId : g_dynamicBodyEntities) {
+ auto it = g_entityToBody.find(entityId);
+ if (it == g_entityToBody.end() || !b2Body_IsValid(it->second)) continue;
- b2Vec2 pos = b2Body_GetPosition(bodyId);
- float angle = b2Rot_GetAngle(b2Body_GetRotation(bodyId));
+ b2Vec2 pos = b2Body_GetPosition(it->second);
+ float angle = b2Rot_GetAngle(b2Body_GetRotation(it->second));
pushEntityBits(g_dynamicTransformBuffer, entityId);
g_dynamicTransformBuffer.push_back(pos.x);
@@ -512,7 +516,17 @@ void physics_updateBodyProperties(uint32_t entityId, int bodyType,
case 1: type = b2_kinematicBody; break;
default: type = b2_dynamicBody; break;
}
+ b2BodyType oldType = b2Body_GetType(it->second);
b2Body_SetType(it->second, type);
+ if (oldType != type) {
+ auto dit = std::find(g_dynamicBodyEntities.begin(), g_dynamicBodyEntities.end(), entityId);
+ if (type == b2_dynamicBody && dit == g_dynamicBodyEntities.end()) {
+ g_dynamicBodyEntities.push_back(entityId);
+ } else if (type != b2_dynamicBody && dit != g_dynamicBodyEntities.end()) {
+ *dit = g_dynamicBodyEntities.back();
+ g_dynamicBodyEntities.pop_back();
+ }
+ }
b2Body_SetGravityScale(it->second, gravityScale);
b2Body_SetLinearDamping(it->second, linearDamping);
b2Body_SetAngularDamping(it->second, angularDamping);
diff --git a/src/esengine/ecs/TransformSystem.hpp b/src/esengine/ecs/TransformSystem.hpp
index 68ff9c631..5e9783ac4 100644
--- a/src/esengine/ecs/TransformSystem.hpp
+++ b/src/esengine/ecs/TransformSystem.hpp
@@ -156,10 +156,11 @@ inline void setParent(Registry& registry, Entity child, Entity newParent) {
Entity oldParent = registry.get<Parent>(child).entity;
if (registry.valid(oldParent) && registry.has<Children>(oldParent)) {
auto& oldChildren = registry.get<Children>(oldParent);
- auto it = std::find(oldChildren.entities.begin(),
- oldChildren.entities.end(), child);
- if (it != oldChildren.entities.end()) {
- oldChildren.entities.erase(it);
+ auto& vec = oldChildren.entities;
+ auto it = std::find(vec.begin(), vec.end(), child);
+ if (it != vec.end()) {
+ *it = vec.back();
+ vec.pop_back();
}
}
@@ -256,10 +257,11 @@ inline void destroyWithChildren(Registry& registry, Entity entity) {
Entity parent = registry.get<Parent>(entity).entity;
if (registry.valid(parent) && registry.has<Children>(parent)) {
auto& parentChildren = registry.get<Children>(parent);
- auto it = std::find(parentChildren.entities.begin(),
- parentChildren.entities.end(), entity);
- if (it != parentChildren.entities.end()) {
- parentChildren.entities.erase(it);
+ auto& vec = parentChildren.entities;
+ auto it = std::find(vec.begin(), vec.end(), entity);
+ if (it != vec.end()) {
+ *it = vec.back();
+ vec.pop_back();
}
}
}
diff --git a/src/esengine/renderer/PostProcessPipeline.cpp b/src/esengine/renderer/PostProcessPipeline.cpp
index 828a83ac7..97c784ffd 100644
--- a/src/esengine/renderer/PostProcessPipeline.cpp
+++ b/src/esengine/renderer/PostProcessPipeline.cpp
@@ -72,19 +72,6 @@ void PostProcessPipeline::init(u32 width, u32 height) {
width_ = width;
height_ = height;
- FramebufferSpec spec;
- spec.width = width;
- spec.height = height;
- spec.depthStencil = false;
-
- fboA_ = Framebuffer::create(spec);
- fboB_ = Framebuffer::create(spec);
-
- if (!fboA_ || !fboB_) {
- ES_LOG_ERROR("PostProcessPipeline: Failed to create framebuffers");
- return;
- }
-
f32 quadVertices[] = {
// position texCoord
-1.0f, -1.0f, 0.0f, 0.0f,
@@ -119,6 +106,25 @@ void PostProcessPipeline::init(u32 width, u32 height) {
ES_LOG_INFO("PostProcessPipeline initialized ({}x{})", width, height);
}
+void PostProcessPipeline::ensureFBOs() {
+ if (fbosCreated_) return;
+
+ FramebufferSpec spec;
+ spec.width = width_;
+ spec.height = height_;
+ spec.depthStencil = false;
+
+ fboA_ = Framebuffer::create(spec);
+ fboB_ = Framebuffer::create(spec);
+
+ if (!fboA_ || !fboB_) {
+ ES_LOG_ERROR("PostProcessPipeline: Failed to create framebuffers");
+ return;
+ }
+
+ fbosCreated_ = true;
+}
+
void PostProcessPipeline::shutdown() {
if (!initialized_) return;
@@ -126,6 +132,7 @@ void PostProcessPipeline::shutdown() {
screenQuadVAO_.reset();
fboA_.reset();
fboB_.reset();
+ fbosCreated_ = false;
if (blitShader_.isValid()) {
resourceManager_.releaseShader(blitShader_);
@@ -141,8 +148,10 @@ void PostProcessPipeline::resize(u32 width, u32 height) {
width_ = width;
height_ = height;
- if (fboA_) fboA_->resize(width, height);
- if (fboB_) fboB_->resize(width, height);
+ if (fbosCreated_) {
+ if (fboA_) fboA_->resize(width, height);
+ if (fboB_) fboB_->resize(width, height);
+ }
}
u32 PostProcessPipeline::addPass(const std::string& name, resource::ShaderHandle shader) {
@@ -220,6 +229,9 @@ PostProcessPass* PostProcessPipeline::findPass(const std::string& name) {
void PostProcessPipeline::begin() {
if (!initialized_ || inFrame_ || bypass_) return;
+ ensureFBOs();
+ if (!fbosCreated_) return;
+
fboA_->bind();
RenderCommand::setViewport(0, 0, width_, height_);
RenderCommand::clear();
diff --git a/src/esengine/renderer/PostProcessPipeline.hpp b/src/esengine/renderer/PostProcessPipeline.hpp
index be9db0faa..4e7c0e0e3 100644
--- a/src/esengine/renderer/PostProcessPipeline.hpp
+++ b/src/esengine/renderer/PostProcessPipeline.hpp
@@ -157,6 +157,7 @@ public:
private:
PostProcessPass* findPass(const std::string& name);
+ void ensureFBOs();
void renderPass(const PostProcessPass& pass, u32 inputTexture);
void blitToScreen(u32 texture);
@@ -172,6 +173,7 @@ private:
u32 width_ = 0;
u32 height_ = 0;
bool initialized_ = false;
+ bool fbosCreated_ = false;
bool inFrame_ = false;
bool bypass_ = false;
u32 currentFBO_ = 0;