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: Add Mut() query wrapper and playable ad bundling

esengineb96a9af0bdba
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 478589456..2c06bbcf9 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -8,6 +8,7 @@ set(CMAKE_CXX_EXTENSIONS OFF)
option(ES_BUILD_WEB "Build for Web/Emscripten" OFF)
option(ES_BUILD_WXGAME "Build for WeChat MiniGame" OFF)
option(ES_BUILD_TESTS "Build tests" ON)
+option(ES_BUILD_SINGLE_FILE "Build single-file SDK (WASM inlined)" OFF)
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
include(ESEngineConfig)
@@ -28,10 +29,6 @@ set(ESENGINE_SOURCES
src/esengine/core/Log.cpp
src/esengine/app/App.cpp
src/esengine/resource/ResourceManager.cpp
- src/esengine/resource/ShaderParser.cpp
- src/esengine/resource/LoaderJobQueue.cpp
- src/esengine/resource/HotReloadManager.cpp
- src/esengine/resource/loaders/ShaderLoader.cpp
src/esengine/renderer/RenderContext.cpp
src/esengine/renderer/Renderer.cpp
src/esengine/renderer/Shader.cpp
@@ -39,7 +36,6 @@ set(ESENGINE_SOURCES
src/esengine/renderer/Texture.cpp
src/esengine/renderer/Framebuffer.cpp
src/esengine/renderer/RenderPipeline.cpp
- src/esengine/renderer/stb_image_impl.cpp
src/esengine/platform/input/Input.cpp
src/esengine/platform/PathResolver.cpp
)
@@ -101,6 +97,11 @@ else()
src/esengine/platform/native/NativePlatform.cpp
src/esengine/platform/native/NativeFileSystem.cpp
src/esengine/platform/FileDialog.cpp
+ src/esengine/renderer/stb_image_impl.cpp
+ src/esengine/resource/ShaderParser.cpp
+ src/esengine/resource/LoaderJobQueue.cpp
+ src/esengine/resource/HotReloadManager.cpp
+ src/esengine/resource/loaders/ShaderLoader.cpp
)
list(APPEND ESENGINE_HEADERS
src/esengine/platform/native/NativePlatform.hpp
@@ -194,6 +195,87 @@ if(ES_BUILD_WEB OR ES_BUILD_WXGAME)
"${CMAKE_SOURCE_DIR}/bindings/esengine.d.ts"
"${CMAKE_BINARY_DIR}/sdk/esengine.d.ts"
)
+
+ # Single-file SDK (WASM inlined as Base64, for playable ads)
+ if(ES_BUILD_SINGLE_FILE)
+ add_executable(esengine_single src/esengine/bindings/WebSDKEntry.cpp)
+ target_link_libraries(esengine_single PRIVATE -Wl,--whole-archive esengine -Wl,--no-whole-archive)
+ es_apply_single_file_settings(esengine_single)
+
+ set_target_properties(esengine_single PROPERTIES
+ OUTPUT_NAME "esengine.single"
+ RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/sdk"
+ )
+
+ # Generate playable ad HTML template
+ file(WRITE "${CMAKE_BINARY_DIR}/sdk/playable.html.in" [=[
+<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="UTF-8">
+<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
+<meta name="ad.size" content="width=320,height=480">
+<title>Playable</title>
+<style>
+*{margin:0;padding:0;box-sizing:border-box}
+html,body{width:100%;height:100%;overflow:hidden;background:#1a1a1a}
+#canvas{display:block;width:100%;height:100%;touch-action:none}
+</style>
+</head>
+<body>
+<canvas id="canvas"></canvas>
+<script>
+// ESEngine Single-File SDK will be inlined here
+// SDK_PLACEHOLDER
+</script>
+<script>
+(function(){
+ function resizeCanvas(){
+ var c=document.getElementById('canvas');
+ var dpr=window.devicePixelRatio||1;
+ c.width=window.innerWidth*dpr;
+ c.height=window.innerHeight*dpr;
+ }
+ window.addEventListener('resize',resizeCanvas);
+ resizeCanvas();
+
+ ESEngineModule({
+ canvas:document.getElementById('canvas'),
+ print:function(t){console.log(t)},
+ printErr:function(t){console.error(t)}
+ }).then(function(Module){
+ var Registry=new Module.Registry();
+ Module.initRenderer();
+
+ // Create camera
+ var cam=Registry.create();
+ Registry.addCamera(cam,{projectionType:1,fov:60,orthoSize:400,nearPlane:0.1,farPlane:1000,aspectRatio:1,isActive:true,priority:0});
+ Registry.addLocalTransform(cam,{position:{x:0,y:0,z:10},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}});
+
+ // Create sprite
+ var spr=Registry.create();
+ Registry.addSprite(spr,{texture:0,color:{x:1,y:0.5,z:0.2,w:1},size:{x:100,y:100},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:false,flipY:false});
+ Registry.addLocalTransform(spr,{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}});
+
+ var start=performance.now();
+ function loop(){
+ var t=(performance.now()-start)/1000;
+ var tr=Registry.getLocalTransform(spr);
+ tr.position.x=Math.sin(t)*100;
+ tr.position.y=Math.cos(t)*100;
+ var vp=window.innerWidth*(window.devicePixelRatio||1);
+ var vh=window.innerHeight*(window.devicePixelRatio||1);
+ Module.renderFrame(Registry,vp,vh);
+ requestAnimationFrame(loop);
+ }
+ loop();
+ });
+})();
+</script>
+</body>
+</html>
+]=])
+ endif()
endif()
if(ES_BUILD_TESTS)
@@ -201,6 +283,11 @@ if(ES_BUILD_TESTS)
add_subdirectory(tests)
endif()
+# Bundler tool (native only)
+if(NOT ES_BUILD_WEB AND NOT ES_BUILD_WXGAME)
+ add_subdirectory(tools/bundler)
+endif()
+
install(TARGETS esengine
EXPORT ESEngineTargets
LIBRARY DESTINATION lib
diff --git a/cmake/Emscripten.cmake b/cmake/Emscripten.cmake
index eb53c0cf0..428e16300 100644
--- a/cmake/Emscripten.cmake
+++ b/cmake/Emscripten.cmake
@@ -166,6 +166,7 @@ set(ES_EMSCRIPTEN_SDK_LINK_FLAGS
)
# Single-file SDK link flags (WASM inlined as Base64, for playable ads)
+# Uses IIFE pattern instead of ES6 modules for maximum compatibility
set(ES_EMSCRIPTEN_SINGLE_FILE_FLAGS
--bind
-sWASM=1
@@ -174,11 +175,12 @@ set(ES_EMSCRIPTEN_SINGLE_FILE_FLAGS
-sFULL_ES3=1
-sALLOW_MEMORY_GROWTH=1
-sNO_EXIT_RUNTIME=1
+ -sENVIRONMENT=web
-sMODULARIZE=1
"-sEXPORT_NAME='ESEngineModule'"
"-sEXPORTED_FUNCTIONS=['_malloc','_free']"
"-sEXPORTED_RUNTIME_METHODS=['ccall','cwrap','HEAPF32','HEAPU8','HEAPU32']"
- -O3
+ -Oz
-flto
--closure=1
)
diff --git a/scripts/build-web-single.bat b/scripts/build-web-single.bat
new file mode 100644
index 000000000..b70f0a4e6
--- /dev/null
+++ b/scripts/build-web-single.bat
@@ -0,0 +1,38 @@
+@echo off
+setlocal
+
+cd /d "%~dp0\.."
+
+set BUILD_DIR=build-web-single
+
+if not exist "%BUILD_DIR%" mkdir "%BUILD_DIR%"
+cd "%BUILD_DIR%"
+
+call emcmake cmake .. -DES_BUILD_WEB=ON -DES_BUILD_TESTS=OFF -DES_BUILD_SINGLE_FILE=ON -DCMAKE_BUILD_TYPE=Release
+if errorlevel 1 goto :error
+
+call emmake make esengine_single -j4
+if errorlevel 1 goto :error
+
+echo.
+echo Single-file SDK built:
+dir sdk\esengine.single.js
+
+echo.
+echo Bundling playable HTML...
+node "%~dp0\..\tools\bundle-playable.js" --wasm sdk\esengine.single.js --game "%~dp0\..\sdk\examples\playground\build\playable\game.js" --output sdk\playable.html
+if errorlevel 1 goto :error
+
+echo.
+echo Final output:
+dir sdk\playable.html
+goto :end
+
+:error
+echo Build failed!
+pause
+exit /b 1
+
+:end
+endlocal
+pause
diff --git a/sdk/examples/playground/package.json b/sdk/examples/playground/package.json
index f5103939e..3fe1ee4a6 100644
--- a/sdk/examples/playground/package.json
+++ b/sdk/examples/playground/package.json
@@ -4,7 +4,8 @@
"type": "module",
"scripts": {
"build": "npx esbuild src/main.ts --bundle --format=esm --outfile=build/scripts/main.js --sourcemap",
- "dev": "npx esbuild src/main.ts --bundle --format=esm --outfile=build/scripts/main.js --sourcemap --watch"
+ "dev": "npx esbuild src/main.ts --bundle --format=esm --outfile=build/scripts/main.js --sourcemap --watch",
+ "build:playable": "npx esbuild src/main.ts --bundle --format=iife --global-name=Game --outfile=build/playable/game.js --minify"
},
"dependencies": {
"esengine": "file:../.."
diff --git a/sdk/examples/playground/src/main.ts b/sdk/examples/playground/src/main.ts
index a006d95bb..dbe22958e 100644
--- a/sdk/examples/playground/src/main.ts
+++ b/sdk/examples/playground/src/main.ts
@@ -18,6 +18,7 @@ import {
Res,
Time,
Query,
+ Mut,
type Entity
} from 'esengine';
@@ -80,13 +81,18 @@ export async function main(Module: ESEngineModule): Promise<void> {
));
// Add update system - runs every frame
+ // Use Mut() to mark components that will be modified (auto-commits on iteration end)
app.addSystemToSchedule(Schedule.Update, defineSystem(
- [Res(Time), Query(LocalTransform, Sprite)],
+ [Res(Time), Query(Mut(LocalTransform), Sprite)],
(time, query) => {
for (const [entity, transform, sprite] of query) {
// Move the sprite in a circle
- transform.position.x = Math.sin(time.elapsed) * 100;
- transform.position.y = Math.cos(time.elapsed) * 100;
+ // Set the whole position object (nested properties are copies)
+ transform.position = {
+ x: Math.sin(time.elapsed) * 100,
+ y: Math.cos(time.elapsed) * 100,
+ z: 0
+ };
}
}
));
diff --git a/sdk/rollup.config.js b/sdk/rollup.config.js
index f47a4f8a8..c95c27d5a 100644
--- a/sdk/rollup.config.js
+++ b/sdk/rollup.config.js
@@ -4,9 +4,6 @@ import dts from 'rollup-plugin-dts';
const modules = {
'index': 'src/index.ts',
'wasm': 'src/wasm.ts',
- // TODO: Fix imports in scene and assets modules
- // 'scene/index': 'src/scene/index.ts',
- // 'assets/index': 'src/assets/index.ts',
};
const esmBuilds = Object.entries(modules).map(([name, input]) => ({
@@ -36,4 +33,24 @@ const dtsBuilds = Object.entries(modules).map(([name, input]) => ({
plugins: [dts()],
}));
-export default [...esmBuilds, ...dtsBuilds];
+// IIFE build for playable ads (no ES6 modules, single global)
+const iifeBuild = {
+ input: 'src/index.ts',
+ output: {
+ file: 'dist/esengine.iife.js',
+ format: 'iife',
+ name: 'ES',
+ sourcemap: false,
+ },
+ plugins: [
+ typescript({
+ tsconfig: './tsconfig.json',
+ declaration: false,
+ }),
+ ],
+ treeshake: {
+ moduleSideEffects: false,
+ },
+};
+
+export default [...esmBuilds, ...dtsBuilds, iifeBuild];
diff --git a/sdk/src/index.ts b/sdk/src/index.ts
index de3bc5fb4..763ae83a6 100644
--- a/sdk/src/index.ts
+++ b/sdk/src/index.ts
@@ -76,9 +76,11 @@ export {
export {
Query,
+ Mut,
QueryInstance,
type QueryDescriptor,
type QueryResult,
+ type MutWrapper,
} from './query';
// =============================================================================
diff --git a/sdk/src/query.ts b/sdk/src/query.ts
index 7aa27ea17..3e1990f5b 100644
--- a/sdk/src/query.ts
+++ b/sdk/src/query.ts
@@ -1,31 +1,60 @@
/**
* @file query.ts
- * @brief Component query system
+ * @brief Component query system with mutable component support
*/
import { Entity } from './types';
-import { AnyComponentDef, ComponentData } from './component';
+import { AnyComponentDef, ComponentData, isBuiltinComponent } from './component';
import type { World } from './world';
+// =============================================================================
+// Mutable Component Wrapper
+// =============================================================================
+
+export interface MutWrapper<T extends AnyComponentDef> {
+ readonly _type: 'mut';
+ readonly _component: T;
+}
+
+export function Mut<T extends AnyComponentDef>(component: T): MutWrapper<T> {
+ return { _type: 'mut', _component: component };
+}
+
+export function isMutWrapper(value: unknown): value is MutWrapper<AnyComponentDef> {
+ return typeof value === 'object' && value !== null && (value as any)._type === 'mut';
+}
+
+type UnwrapMut<T> = T extends MutWrapper<infer C> ? C : T;
+type QueryArg = AnyComponentDef | MutWrapper<AnyComponentDef>;
+
// =============================================================================
// Query Descriptor
// =============================================================================
-export interface QueryDescriptor<C extends readonly AnyComponentDef[]> {
+export interface QueryDescriptor<C extends readonly QueryArg[]> {
readonly _type: 'query';
readonly _components: C;
+ readonly _mutIndices: number[];
readonly _with: AnyComponentDef[];
readonly _without: AnyComponentDef[];
}
-function createQueryDescriptor<C extends readonly AnyComponentDef[]>(
+function createQueryDescriptor<C extends readonly QueryArg[]>(
components: C,
withFilters: AnyComponentDef[] = [],
withoutFilters: AnyComponentDef[] = []
): QueryDescriptor<C> {
+ const mutIndices: number[] = [];
+ components.forEach((comp, i) => {
+ if (isMutWrapper(comp)) {
+ mutIndices.push(i);
+ }
+ });
+
return {
_type: 'query',
_components: components,
+ _mutIndices: mutIndices,
_with: withFilters,
_without: withoutFilters
};
@@ -35,7 +64,7 @@ function createQueryDescriptor<C extends readonly AnyComponentDef[]>(
// Query Factory
// =============================================================================
-export function Query<C extends AnyComponentDef[]>(...components: C): QueryDescriptor<C> {
+export function Query<C extends QueryArg[]>(...components: C): QueryDescriptor<C> {
return createQueryDescriptor(components);
}
@@ -43,11 +72,12 @@ export function Query<C extends AnyComponentDef[]>(...components: C): QueryDescr
// Query Result Type
// =============================================================================
-type ComponentsData<C extends readonly AnyComponentDef[]> = {
- [K in keyof C]: ComponentData<C[K]>;
+type UnwrapQueryArg<T> = T extends MutWrapper<infer C> ? C : T;
+type ComponentsData<C extends readonly QueryArg[]> = {
+ [K in keyof C]: ComponentData<UnwrapQueryArg<C[K]>>;
};
-export type QueryResult<C extends readonly AnyComponentDef[]> = [
+export type QueryResult<C extends readonly QueryArg[]> = [
Entity,
...ComponentsData<C>
];
@@ -56,37 +86,84 @@ export type QueryResult<C extends readonly AnyComponentDef[]> = [
// Query Instance (Runtime)
// =============================================================================
-export class QueryInstance<C extends readonly AnyComponentDef[]> implements Iterable<QueryResult<C>> {
+interface PendingMutation {
+ entity: Entity;
+ component: AnyComponentDef;
+ data: unknown;
+}
+
+export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<QueryResult<C>> {
private readonly world_: World;
private readonly descriptor_: QueryDescriptor<C>;
+ private pendingMutations_: PendingMutation[] = [];
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_ = [];
+ }
+
*[Symbol.iterator](): Iterator<QueryResult<C>> {
- const { _components, _with, _without } = this.descriptor_;
+ const { _components, _mutIndices, _with, _without } = this.descriptor_;
- const allRequired = [..._components, ..._with];
+ const actualComponents = _components.map(c => this.getActualComponent(c));
+ const allRequired = [...actualComponents, ..._with];
const entities = this.world_.getEntitiesWithComponents(allRequired);
- for (const entity of entities) {
- let excluded = false;
- for (const comp of _without) {
- if (this.world_.has(entity, comp)) {
- excluded = true;
- break;
- }
- }
-
- if (excluded) continue;
+ let prevEntity: Entity | null = null;
+ let prevMutData: Array<{ component: AnyComponentDef; data: unknown }> = [];
- const components = _components.map(comp =>
- this.world_.get(entity, comp)
- ) as ComponentsData<C>;
+ try {
+ for (const entity of entities) {
+ // Commit previous entity's mutations before moving to next
+ if (prevEntity !== null) {
+ for (const mut of prevMutData) {
+ this.world_.insert(prevEntity, mut.component, mut.data);
+ }
+ }
+ prevMutData = [];
+
+ let excluded = false;
+ for (const comp of _without) {
+ if (this.world_.has(entity, comp)) {
+ excluded = true;
+ break;
+ }
+ }
+ 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]
+ });
+ }
+ prevEntity = entity;
- yield [entity, ...components] as QueryResult<C>;
+ yield [entity, ...components] as QueryResult<C>;
+ }
+ } finally {
+ // Commit last entity's mutations
+ if (prevEntity !== null) {
+ for (const mut of prevMutData) {
+ this.world_.insert(prevEntity, mut.component, mut.data);
+ }
+ }
}
}
diff --git a/sdk/src/system.ts b/sdk/src/system.ts
index 2252d4617..fcb685a5a 100644
--- a/sdk/src/system.ts
+++ b/sdk/src/system.ts
@@ -4,7 +4,7 @@
*/
import { AnyComponentDef } from './component';
-import { QueryDescriptor, QueryInstance } from './query';
+import { QueryDescriptor, QueryInstance, MutWrapper } from './query';
import { ResDescriptor, ResMutDescriptor, ResMutInstance, ResourceStorage } from './resource';
import { CommandsDescriptor, CommandsInstance } from './commands';
import type { World } from './world';
@@ -29,8 +29,10 @@ export enum Schedule {
// System Parameter Types
// =============================================================================
+type QueryArg = AnyComponentDef | MutWrapper<AnyComponentDef>;
+
export type SystemParam =
- | QueryDescriptor<readonly AnyComponentDef[]>
+ | QueryDescriptor<readonly QueryArg[]>
| ResDescriptor<unknown>
| ResMutDescriptor<unknown>
| CommandsDescriptor;
diff --git a/src/esengine/renderer/Renderer.cpp b/src/esengine/renderer/Renderer.cpp
index aee5aeecc..6e527a886 100644
--- a/src/esengine/renderer/Renderer.cpp
+++ b/src/esengine/renderer/Renderer.cpp
@@ -328,9 +328,11 @@ void BatchRenderer2D::init() {
auto ibo = IndexBuffer::create(indices.data(), MAX_INDICES);
data_->vao->setIndexBuffer(Shared<IndexBuffer>(std::move(ibo)));
+#ifndef ES_PLATFORM_WEB
data_->shader_handle = resource_manager_.loadEngineShader("batch");
+#endif
if (!data_->shader_handle.isValid()) {
- ES_LOG_INFO("Using embedded batch shader for Web platform");
+ ES_LOG_INFO("Using embedded batch shader");
data_->shader_handle = resource_manager_.createShader(
ShaderSources::BATCH_VERTEX,
ShaderSources::BATCH_FRAGMENT
diff --git a/src/esengine/renderer/stb_image_impl.cpp b/src/esengine/renderer/stb_image_impl.cpp
index efa484ddb..b21469897 100644
--- a/src/esengine/renderer/stb_image_impl.cpp
+++ b/src/esengine/renderer/stb_image_impl.cpp
@@ -1,9 +1,13 @@
// STB Image implementation file
-// This file compiles stb_image as a separate translation unit
+// PNG, JPEG, BMP support via stb_image
+// WebP uses browser's native decoding API
#define STB_IMAGE_IMPLEMENTATION
#define STBI_ONLY_PNG
#define STBI_ONLY_JPEG
#define STBI_ONLY_BMP
+#define STBI_NO_STDIO
+#define STBI_NO_LINEAR
+#define STBI_NO_HDR
#include <stb_image.h>
diff --git a/src/esengine/resource/ResourceManager.cpp b/src/esengine/resource/ResourceManager.cpp
index 2086b4386..528090944 100644
--- a/src/esengine/resource/ResourceManager.cpp
+++ b/src/esengine/resource/ResourceManager.cpp
@@ -10,7 +10,9 @@
*/
#include "ResourceManager.hpp"
+#ifndef ES_PLATFORM_WEB
#include "loaders/ShaderLoader.hpp"
+#endif
#include "../core/Log.hpp"
#include "../platform/PathResolver.hpp"
#include "../renderer/Shader.hpp"
@@ -84,6 +86,7 @@ ShaderHandle ResourceManager::loadShader(const std::string& vertPath, const std:
return shaders_.add(std::move(shader), cacheKey);
}
+#ifndef ES_PLATFORM_WEB
ShaderHandle ResourceManager::loadShaderFile(const std::string& path, const std::string& platform) {
auto cached = shaders_.findByPath(path);
if (cached.isValid()) {
@@ -125,6 +128,7 @@ ShaderHandle ResourceManager::loadEngineShader(const std::string& name, const st
stats_.cacheMisses++;
return shaders_.add(std::move(result.resource), cacheKey);
}
+#endif
Shader* ResourceManager::getShader(ShaderHandle handle) {
return shaders_.get(handle);
diff --git a/src/esengine/resource/ResourceManager.hpp b/src/esengine/resource/ResourceManager.hpp
index 47606ceed..d10a6c3dc 100644
--- a/src/esengine/resource/ResourceManager.hpp
+++ b/src/esengine/resource/ResourceManager.hpp
@@ -125,6 +125,7 @@ public:
*/
ShaderHandle loadShader(const std::string& vertPath, const std::string& fragPath);
+#ifndef ES_PLATFORM_WEB
/**
* @brief Loads a shader from .esshader file (with caching)
* @param path Path to the .esshader file (relative to project)
@@ -140,6 +141,7 @@ public:
* @return Handle to the shader, or invalid handle on failure
*/
ShaderHandle loadEngineShader(const std::string& name, const std::string& platform = "");
+#endif
/**
* @brief Gets a shader by handle
diff --git a/tools/bundle-playable.js b/tools/bundle-playable.js
new file mode 100644
index 000000000..86a441244
--- /dev/null
+++ b/tools/bundle-playable.js
@@ -0,0 +1,139 @@
+#!/usr/bin/env node
+/**
+ * Bundle ESEngine game into a single HTML file for playable ads.
+ *
+ * Usage:
+ * node tools/bundle-playable.js --wasm build-web-single/sdk/esengine.single.js \
+ * --game sdk/examples/playground/build/playable/game.js \
+ * --output playable.html
+ */
+
+const fs = require('fs');
+const path = require('path');
+
+const HTML_TEMPLATE = `<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="UTF-8">
+<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
+<meta name="ad.size" content="width=320,height=480">
+<title>Playable</title>
+<style>
+*{margin:0;padding:0;box-sizing:border-box}
+html,body{width:100%;height:100%;overflow:hidden;background:#000}
+#canvas{display:block;width:100%;height:100%;touch-action:none}
+</style>
+</head>
+<body>
+<canvas id="canvas"></canvas>
+<script>
+{{WASM_SDK}}
+</script>
+<script>
+{{GAME_CODE}}
+</script>
+<script>
+(function(){
+ function resize(){
+ var c=document.getElementById('canvas');
+ var dpr=window.devicePixelRatio||1;
+ c.width=window.innerWidth*dpr;
+ c.height=window.innerHeight*dpr;
+ }
+ window.addEventListener('resize',resize);
+ resize();
+
+ ESEngineModule({
+ canvas:document.getElementById('canvas'),
+ print:function(t){console.log(t)},
+ printErr:function(t){console.error(t)}
+ }).then(function(Module){
+ if(typeof Game!=='undefined'&&typeof Game.main==='function'){
+ Game.main(Module);
+ }else{
+ console.error('Game.main not found');
+ }
+ }).catch(function(e){
+ if(e!=='unwind'&&(!e.message||!e.message.includes('unwind'))){
+ console.error('Failed:',e);
+ }
+ });
+})();
+</script>
+</body>
+</html>`;
+
+function parseArgs(args) {
+ const result = { wasm: null, game: null, output: 'playable.html' };
+ for (let i = 0; i < args.length; i++) {
+ if (args[i] === '--wasm' && args[i + 1]) {
+ result.wasm = args[++i];
+ } else if (args[i] === '--game' && args[i + 1]) {
+ result.game = args[++i];
+ } else if (args[i] === '--output' && args[i + 1]) {
+ result.output = args[++i];
+ } else if (args[i] === '--help' || args[i] === '-h') {
+ console.log(`
+Bundle ESEngine game into single HTML for playable ads.
+
+Usage:
+ node bundle-playable.js --wasm <sdk.js> --game <game.js> [--output <out.html>]
+
+Options:
+ --wasm Path to esengine.single.js (WASM SDK with inlined binary)
+ --game Path to game.js (IIFE bundle with SDK runtime)
+ --output Output HTML file (default: playable.html)
+
+Example:
+ node tools/bundle-playable.js \\
+ --wasm build-web-single/sdk/esengine.single.js \\
+ --game sdk/examples/playground/build/playable/game.js \\
+ --output playable.html
+`);
+ process.exit(0);
+ }
+ }
+ return result;
+}
+
+function main() {
+ const args = parseArgs(process.argv.slice(2));
+
+ if (!args.wasm) {
+ console.error('Error: --wasm is required');
+ process.exit(1);
+ }
+ if (!args.game) {
+ console.error('Error: --game is required');
+ process.exit(1);
+ }
+
+ if (!fs.existsSync(args.wasm)) {
+ console.error(`Error: WASM SDK not found: ${args.wasm}`);
+ process.exit(1);
+ }
+ if (!fs.existsSync(args.game)) {
+ console.error(`Error: Game JS not found: ${args.game}`);
+ process.exit(1);
+ }
+
+ const wasmSdk = fs.readFileSync(args.wasm, 'utf-8');
+ const gameCode = fs.readFileSync(args.game, 'utf-8');
+
+ const html = HTML_TEMPLATE
+ .replace('{{WASM_SDK}}', wasmSdk)
+ .replace('{{GAME_CODE}}', gameCode);
+
+ // Ensure output directory exists
+ const outDir = path.dirname(args.output);
+ if (outDir && !fs.existsSync(outDir)) {
+ fs.mkdirSync(outDir, { recursive: true });
+ }
+
+ fs.writeFileSync(args.output, html, 'utf-8');
+
+ const sizeKb = (fs.statSync(args.output).size / 1024).toFixed(1);
+ console.log(`Created: ${args.output} (${sizeKb} KB)`);
+}
+
+main();