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: Improve WeChat MiniGame build with image loading and Chinese filename support

esengine63d7ac26510f
diff --git a/desktop/public/sdk/cjs/esengine.js b/desktop/public/sdk/cjs/esengine.js
index 9659f91db..946594281 100644
--- a/desktop/public/sdk/cjs/esengine.js
+++ b/desktop/public/sdk/cjs/esengine.js
@@ -1525,6 +1525,16 @@ function loadSceneData(world, sceneData) {
loadComponent(world, entity, compData);
}
}
+ // Set parent-child relationships
+ for (const entityData of sceneData.entities) {
+ if (entityData.parent !== null) {
+ const entity = entityMap.get(entityData.id);
+ const parentEntity = entityMap.get(entityData.parent);
+ if (entity !== undefined && parentEntity !== undefined) {
+ world.setParent(entity, parentEntity);
+ }
+ }
+ }
return entityMap;
}
async function loadSceneWithAssets(world, sceneData, options) {
@@ -1600,6 +1610,16 @@ function loadComponent(world, entity, compData) {
console.warn(`Unknown component type: ${compData.type}`);
}
}
+function updateCameraAspectRatio(world, aspectRatio) {
+ const cameraEntities = world.getEntitiesWithComponents([Camera]);
+ for (const entity of cameraEntities) {
+ const camera = world.get(entity, Camera);
+ if (camera) {
+ camera.aspectRatio = aspectRatio;
+ world.insert(entity, Camera, camera);
+ }
+ }
+}
/**
* @file PreviewPlugin.ts
@@ -1745,6 +1765,7 @@ exports.platformReadFile = platformReadFile;
exports.platformReadTextFile = platformReadTextFile;
exports.quat = quat;
exports.textPlugin = textPlugin;
+exports.updateCameraAspectRatio = updateCameraAspectRatio;
exports.vec2 = vec2;
exports.vec3 = vec3;
exports.vec4 = vec4;
diff --git a/desktop/public/sdk/cjs/esengine.wechat.js b/desktop/public/sdk/cjs/esengine.wechat.js
index 55e17c573..608ad6a65 100644
--- a/desktop/public/sdk/cjs/esengine.wechat.js
+++ b/desktop/public/sdk/cjs/esengine.wechat.js
@@ -334,6 +334,84 @@ function wxWriteFile(path, data) {
});
}
+/**
+ * @file image.ts
+ * @brief WeChat MiniGame image loading utilities
+ */
+/// <reference types="minigame-api-typings" />
+// =============================================================================
+// Canvas Management
+// =============================================================================
+let offscreenCanvas = null;
+let offscreenCtx = null;
+function getOffscreenCanvas(width, height) {
+ if (!offscreenCanvas) {
+ offscreenCanvas = wx.createCanvas();
+ offscreenCanvas.width = width;
+ offscreenCanvas.height = height;
+ offscreenCtx = offscreenCanvas.getContext('2d');
+ }
+ if (offscreenCanvas.width < width || offscreenCanvas.height < height) {
+ offscreenCanvas.width = Math.max(offscreenCanvas.width, width);
+ offscreenCanvas.height = Math.max(offscreenCanvas.height, height);
+ }
+ return { canvas: offscreenCanvas, ctx: offscreenCtx };
+}
+// =============================================================================
+// Image Loading
+// =============================================================================
+/**
+ * Load an image from a file path
+ * @param path - File path relative to game root
+ */
+function wxLoadImage(path) {
+ return new Promise((resolve, reject) => {
+ const img = wx.createImage();
+ img.onload = () => resolve(img);
+ img.onerror = (err) => reject(new Error(`Failed to load image: ${path}, ${err}`));
+ img.src = path;
+ });
+}
+/**
+ * Extract pixel data from an image
+ * @param img - Loaded image object
+ * @param flipY - Whether to flip the image vertically (default: true for OpenGL)
+ */
+function wxGetImagePixels(img, flipY = true) {
+ const { width, height } = img;
+ const { ctx } = getOffscreenCanvas(width, height);
+ ctx.clearRect(0, 0, width, height);
+ ctx.drawImage(img, 0, 0);
+ const imageData = ctx.getImageData(0, 0, width, height);
+ const pixels = new Uint8Array(imageData.data.buffer);
+ if (flipY) {
+ return { width, height, pixels: flipVertically(pixels, width, height) };
+ }
+ return { width, height, pixels };
+}
+/**
+ * Load image and get pixel data in one call
+ * @param path - File path relative to game root
+ * @param flipY - Whether to flip the image vertically (default: true for OpenGL)
+ */
+async function wxLoadImagePixels(path, flipY = true) {
+ const img = await wxLoadImage(path);
+ return wxGetImagePixels(img, flipY);
+}
+// =============================================================================
+// Utility Functions
+// =============================================================================
+function flipVertically(pixels, width, height) {
+ const rowSize = width * 4;
+ const flipped = new Uint8Array(pixels.length);
+ for (let y = 0; y < height; y++) {
+ const srcOffset = y * rowSize;
+ const dstOffset = (height - 1 - y) * rowSize;
+ flipped.set(pixels.subarray(srcOffset, srcOffset + rowSize), dstOffset);
+ }
+ return flipped;
+}
+
/**
* @file index.ts
* @brief WeChat MiniGame platform adapter
@@ -1767,6 +1845,16 @@ function loadSceneData(world, sceneData) {
loadComponent(world, entity, compData);
}
}
+ // Set parent-child relationships
+ for (const entityData of sceneData.entities) {
+ if (entityData.parent !== null) {
+ const entity = entityMap.get(entityData.id);
+ const parentEntity = entityMap.get(entityData.parent);
+ if (entity !== undefined && parentEntity !== undefined) {
+ world.setParent(entity, parentEntity);
+ }
+ }
+ }
return entityMap;
}
async function loadSceneWithAssets(world, sceneData, options) {
@@ -1842,6 +1930,16 @@ function loadComponent(world, entity, compData) {
console.warn(`Unknown component type: ${compData.type}`);
}
}
+function updateCameraAspectRatio(world, aspectRatio) {
+ const cameraEntities = world.getEntitiesWithComponents([Camera]);
+ for (const entity of cameraEntities) {
+ const camera = world.get(entity, Camera);
+ if (camera) {
+ camera.aspectRatio = aspectRatio;
+ world.insert(entity, Camera, camera);
+ }
+ }
+}
/**
* @file PreviewPlugin.ts
@@ -1988,11 +2086,15 @@ exports.platformReadFile = platformReadFile;
exports.platformReadTextFile = platformReadTextFile;
exports.quat = quat;
exports.textPlugin = textPlugin;
+exports.updateCameraAspectRatio = updateCameraAspectRatio;
exports.vec2 = vec2;
exports.vec3 = vec3;
exports.vec4 = vec4;
exports.wxFileExists = wxFileExists;
exports.wxFileExistsSync = wxFileExistsSync;
+exports.wxGetImagePixels = wxGetImagePixels;
+exports.wxLoadImage = wxLoadImage;
+exports.wxLoadImagePixels = wxLoadImagePixels;
exports.wxReadFile = wxReadFile;
exports.wxReadTextFile = wxReadTextFile;
exports.wxWriteFile = wxWriteFile;
diff --git a/desktop/public/sdk/esm/esengine.js b/desktop/public/sdk/esm/esengine.js
index b435b47ed..ef6e8abbc 100644
--- a/desktop/public/sdk/esm/esengine.js
+++ b/desktop/public/sdk/esm/esengine.js
@@ -1523,6 +1523,16 @@ function loadSceneData(world, sceneData) {
loadComponent(world, entity, compData);
}
}
+ // Set parent-child relationships
+ for (const entityData of sceneData.entities) {
+ if (entityData.parent !== null) {
+ const entity = entityMap.get(entityData.id);
+ const parentEntity = entityMap.get(entityData.parent);
+ if (entity !== undefined && parentEntity !== undefined) {
+ world.setParent(entity, parentEntity);
+ }
+ }
+ }
return entityMap;
}
async function loadSceneWithAssets(world, sceneData, options) {
@@ -1598,6 +1608,16 @@ function loadComponent(world, entity, compData) {
console.warn(`Unknown component type: ${compData.type}`);
}
}
+function updateCameraAspectRatio(world, aspectRatio) {
+ const cameraEntities = world.getEntitiesWithComponents([Camera]);
+ for (const entity of cameraEntities) {
+ const camera = world.get(entity, Camera);
+ if (camera) {
+ camera.aspectRatio = aspectRatio;
+ world.insert(entity, Camera, camera);
+ }
+ }
+}
/**
* @file PreviewPlugin.ts
@@ -1690,4 +1710,4 @@ class PreviewPlugin {
// Initialize Web platform
setPlatform(webAdapter);
-export { App, AssetPlugin, AssetServer, Assets, Camera, Canvas, Children, Commands, CommandsInstance, EntityCommands, INVALID_ENTITY, INVALID_TEXTURE, Input, LocalTransform, Mut, Parent, PreviewPlugin, Query, QueryInstance, Res, ResMut, Schedule, Sprite, SystemRunner, Text, TextAlign, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, UIRect, Velocity, World, WorldTransform, assetPlugin, color, createWebApp, defineComponent, defineResource, defineSystem, defineTag, getPlatform, getPlatformType, isBuiltinComponent, isPlatformInitialized, isWeChat, isWeb, loadSceneData, loadSceneWithAssets, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, quat, textPlugin, vec2, vec3, vec4 };
+export { App, AssetPlugin, AssetServer, Assets, Camera, Canvas, Children, Commands, CommandsInstance, EntityCommands, INVALID_ENTITY, INVALID_TEXTURE, Input, LocalTransform, Mut, Parent, PreviewPlugin, Query, QueryInstance, Res, ResMut, Schedule, Sprite, SystemRunner, Text, TextAlign, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, UIRect, Velocity, World, WorldTransform, assetPlugin, color, createWebApp, defineComponent, defineResource, defineSystem, defineTag, getPlatform, getPlatformType, isBuiltinComponent, isPlatformInitialized, isWeChat, isWeb, loadSceneData, loadSceneWithAssets, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, quat, textPlugin, updateCameraAspectRatio, vec2, vec3, vec4 };
diff --git a/desktop/public/sdk/iife/esengine.js b/desktop/public/sdk/iife/esengine.js
index 28f225a15..89ae86c62 100644
--- a/desktop/public/sdk/iife/esengine.js
+++ b/desktop/public/sdk/iife/esengine.js
@@ -1526,6 +1526,16 @@ var ES = (function (exports) {
loadComponent(world, entity, compData);
}
}
+ // Set parent-child relationships
+ for (const entityData of sceneData.entities) {
+ if (entityData.parent !== null) {
+ const entity = entityMap.get(entityData.id);
+ const parentEntity = entityMap.get(entityData.parent);
+ if (entity !== undefined && parentEntity !== undefined) {
+ world.setParent(entity, parentEntity);
+ }
+ }
+ }
return entityMap;
}
async function loadSceneWithAssets(world, sceneData, options) {
@@ -1601,6 +1611,16 @@ var ES = (function (exports) {
console.warn(`Unknown component type: ${compData.type}`);
}
}
+ function updateCameraAspectRatio(world, aspectRatio) {
+ const cameraEntities = world.getEntitiesWithComponents([Camera]);
+ for (const entity of cameraEntities) {
+ const camera = world.get(entity, Camera);
+ if (camera) {
+ camera.aspectRatio = aspectRatio;
+ world.insert(entity, Camera, camera);
+ }
+ }
+ }
/**
* @file PreviewPlugin.ts
@@ -1746,6 +1766,7 @@ var ES = (function (exports) {
exports.platformReadTextFile = platformReadTextFile;
exports.quat = quat;
exports.textPlugin = textPlugin;
+ exports.updateCameraAspectRatio = updateCameraAspectRatio;
exports.vec2 = vec2;
exports.vec3 = vec3;
exports.vec4 = vec4;
diff --git a/editor/src/builder/BuildSettingsDialog.ts b/editor/src/builder/BuildSettingsDialog.ts
index c6edf7a9e..5c38269ce 100644
--- a/editor/src/builder/BuildSettingsDialog.ts
+++ b/editor/src/builder/BuildSettingsDialog.ts
@@ -439,10 +439,13 @@ export class BuildSettingsDialog {
if (config) {
const editor = (window as any).__esengine_editor;
const scenePath = editor?.currentScenePath;
- if (scenePath && !config.scenes.includes(scenePath)) {
- config.scenes.push(scenePath);
- saveBuildSettings(this.settings_);
- this.render();
+ if (scenePath) {
+ const relativePath = this.toRelativePath(scenePath);
+ if (!config.scenes.includes(relativePath)) {
+ config.scenes.push(relativePath);
+ saveBuildSettings(this.settings_);
+ this.render();
+ }
}
}
break;
@@ -705,6 +708,21 @@ export class BuildSettingsDialog {
return parts[parts.length - 1] || path;
}
+ private toRelativePath(absolutePath: string): string {
+ const normalized = absolutePath.replace(/\\/g, '/');
+ const projectDir = this.getProjectDir();
+ if (normalized.startsWith(projectDir)) {
+ return normalized.substring(projectDir.length + 1);
+ }
+ return normalized;
+ }
+
+ private getProjectDir(): string {
+ const normalized = this.options_.projectPath.replace(/\\/g, '/');
+ const lastSlash = normalized.lastIndexOf('/');
+ return lastSlash > 0 ? normalized.substring(0, lastSlash) : normalized;
+ }
+
private async openOutputFolder(outputPath: string): Promise<void> {
try {
// Get directory from output path
diff --git a/editor/src/builder/WeChatBuilder.ts b/editor/src/builder/WeChatBuilder.ts
index 689f394b6..170d75826 100644
--- a/editor/src/builder/WeChatBuilder.ts
+++ b/editor/src/builder/WeChatBuilder.ts
@@ -47,6 +47,10 @@ function getFileExtension(path: string): string {
return lastDot > 0 ? path.substring(lastDot + 1).toLowerCase() : '';
}
+function isAbsolutePath(path: string): boolean {
+ return path.startsWith('/') || /^[a-zA-Z]:/.test(path);
+}
+
// =============================================================================
// WeChatBuilder
// =============================================================================
@@ -210,10 +214,75 @@ export class WeChatBuilder {
const firstSceneName = firstScene ? firstScene.replace(/.*\//, '').replace('.esscene', '') : '';
const gameJs = `
-// ESEngine WeChat Mini Game Entry
var ESEngineModule = require('./esengine.js');
var SDK = require('./sdk.js');
+function createTextureFromPixels(module, result) {
+ var rm = module.getResourceManager();
+ var ptr = module._malloc(result.pixels.length);
+ module.HEAPU8.set(result.pixels, ptr);
+ var handle = rm.createTexture(result.width, result.height, ptr, result.pixels.length, 1);
+ module._free(ptr);
+ return handle;
+}
+
+async function loadSceneTextures(module, sceneData) {
+ var textureCache = {};
+ for (var i = 0; i < sceneData.entities.length; i++) {
+ var entity = sceneData.entities[i];
+ for (var j = 0; j < entity.components.length; j++) {
+ var comp = entity.components[j];
+ if (comp.type === 'Sprite' && comp.data.texture && typeof comp.data.texture === 'string') {
+ var texturePath = comp.data.texture;
+ if (!textureCache[texturePath]) {
+ try {
+ var result = await SDK.wxLoadImagePixels(texturePath);
+ textureCache[texturePath] = createTextureFromPixels(module, result);
+ } catch (err) {
+ console.warn('Failed to load texture:', texturePath, err);
+ textureCache[texturePath] = 0;
+ }
+ }
+ }
+ }
+ }
+ return textureCache;
+}
+
+function updateSpriteTextures(world, sceneData, textureCache, entityMap) {
+ for (var i = 0; i < sceneData.entities.length; i++) {
+ var entityData = sceneData.entities[i];
+ var entity = entityMap.get(entityData.id);
+ if (entity === undefined) continue;
+ for (var j = 0; j < entityData.components.length; j++) {
+ var comp = entityData.components[j];
+ if (comp.type === 'Sprite' && comp.data.texture && typeof comp.data.texture === 'string') {
+ var handle = textureCache[comp.data.texture] || 0;
+ var sprite = world.get(entity, SDK.Sprite);
+ if (sprite) {
+ sprite.texture = handle;
+ world.insert(entity, SDK.Sprite, sprite);
+ }
+ }
+ }
+ }
+}
+
+function applyTextureMetadata(module, sceneData, textureCache) {
+ if (!sceneData.textureMetadata) return;
+ var rm = module.getResourceManager();
+ for (var texturePath in sceneData.textureMetadata) {
+ var handle = textureCache[texturePath];
+ if (handle && handle > 0) {
+ var metadata = sceneData.textureMetadata[texturePath];
+ if (metadata && metadata.sliceBorder) {
+ var border = metadata.sliceBorder;
+ rm.setTextureMetadata(handle, border.left, border.right, border.top, border.bottom);
+ }
+ }
+ }
+}
+
(async function() {
var canvas = wx.createCanvas();
var info = wx.getSystemInfoSync();
@@ -230,7 +299,6 @@ var SDK = require('./sdk.js');
}
});
- // Create WebGL context in JS and register with Emscripten
var gl = canvas.getContext('webgl2') || canvas.getContext('webgl');
if (!gl) {
console.error('[ESEngine] Failed to create WebGL context');
@@ -249,24 +317,26 @@ var SDK = require('./sdk.js');
}
});
- // Load scene
${firstSceneName ? `
try {
var sceneJson = wx.getFileSystemManager().readFileSync('scenes/${firstSceneName}.json', 'utf-8');
var sceneData = JSON.parse(sceneJson);
- SDK.loadSceneData(app.world, sceneData);
- console.log('[ESEngine] Scene loaded: ${firstSceneName}');
+
+ var textureCache = await loadSceneTextures(module, sceneData);
+ applyTextureMetadata(module, sceneData, textureCache);
+ var entityMap = SDK.loadSceneData(app.world, sceneData);
+ updateSpriteTextures(app.world, sceneData, textureCache, entityMap);
+
+ var screenAspect = canvas.width / canvas.height;
+ SDK.updateCameraAspectRatio(app.world, screenAspect);
} catch (err) {
console.error('[ESEngine] Failed to load scene:', err);
}
- ` : '// No scene configured'}
+ ` : ''}
- // User scripts
${userCode}
- // Start game loop
app.run();
- console.log('[ESEngine] Game started');
})();
`;
@@ -344,25 +414,40 @@ var SDK = require('./sdk.js');
const fs = this.fs_!;
const projectDir = this.projectDir_;
- const isAbsolutePath = (p: string): boolean => {
- return p.startsWith('/') || /^[a-zA-Z]:/.test(p);
- };
-
const getDir = (filePath: string): string => {
const normalized = normalizePath(filePath);
const lastSlash = normalized.lastIndexOf('/');
return lastSlash > 0 ? normalized.substring(0, lastSlash) : normalized;
};
+ const resolvePackageEntry = async (pkgName: string): Promise<string | null> => {
+ const pkgJsonPath = joinPath(projectDir, 'node_modules', pkgName, 'package.json');
+ const pkgContent = await fs.readFile(pkgJsonPath);
+ if (!pkgContent) return null;
+
+ try {
+ const pkg = JSON.parse(pkgContent);
+ let entry = pkg.main || 'index.js';
+ if (pkg.exports) {
+ const root = pkg.exports['.'];
+ if (typeof root === 'string') {
+ entry = root;
+ } else if (root?.import) {
+ entry = root.import;
+ } else if (root?.default) {
+ entry = root.default;
+ }
+ }
+ return joinPath(projectDir, 'node_modules', pkgName, entry);
+ } catch {
+ return joinPath(projectDir, 'node_modules', pkgName, 'index.js');
+ }
+ };
+
return {
name: 'virtual-fs',
setup(build) {
- // Mark esengine as external for WeChat (will use require)
- build.onResolve({ filter: /^esengine$/ }, () => {
- return { path: 'esengine', external: true };
- });
-
- build.onResolve({ filter: /.*/ }, (args) => {
+ build.onResolve({ filter: /.*/ }, async (args) => {
if (args.kind === 'entry-point') {
return { path: args.path, namespace: 'virtual' };
}
@@ -375,11 +460,26 @@ var SDK = require('./sdk.js');
const baseDir = args.importer ? getDir(args.importer) : args.resolveDir;
resolvedPath = joinPath(baseDir, args.path);
} else {
- resolvedPath = joinPath(projectDir, 'node_modules', args.path);
+ // Bare module specifier - resolve from node_modules
+ const pkgEntry = await resolvePackageEntry(args.path);
+ if (pkgEntry) {
+ resolvedPath = pkgEntry;
+ } else {
+ resolvedPath = joinPath(projectDir, 'node_modules', args.path);
+ }
}
+ // Add extension if missing
if (!resolvedPath.endsWith('.ts') && !resolvedPath.endsWith('.js')) {
- resolvedPath += '.ts';
+ if (await fs.exists(resolvedPath + '.ts')) {
+ resolvedPath += '.ts';
+ } else if (await fs.exists(resolvedPath + '.js')) {
+ resolvedPath += '.js';
+ } else if (await fs.exists(joinPath(resolvedPath, 'index.ts'))) {
+ resolvedPath = joinPath(resolvedPath, 'index.ts');
+ } else if (await fs.exists(joinPath(resolvedPath, 'index.js'))) {
+ resolvedPath = joinPath(resolvedPath, 'index.js');
+ }
}
return { path: resolvedPath, namespace: 'virtual' };
@@ -402,18 +502,57 @@ var SDK = require('./sdk.js');
await this.fs_!.createDirectory(scenesDir);
for (const scenePath of this.context_.config.scenes) {
- const fullPath = scenePath.startsWith('/')
- ? scenePath
+ const fullPath = isAbsolutePath(scenePath)
+ ? normalizePath(scenePath)
: joinPath(this.projectDir_, scenePath);
const content = await this.fs_!.readFile(fullPath);
if (content) {
const name = scenePath.replace(/.*\//, '').replace('.esscene', '');
- await this.fs_!.writeFile(joinPath(scenesDir, `${name}.json`), content);
+ const encodedContent = this.encodeTexturePathsInScene(content);
+ await this.fs_!.writeFile(joinPath(scenesDir, `${name}.json`), encodedContent);
+ }
+ }
+ }
+
+ private encodeTexturePathsInScene(sceneJson: string): string {
+ try {
+ const scene = JSON.parse(sceneJson);
+ for (const entity of scene.entities || []) {
+ for (const comp of entity.components || []) {
+ if (comp.type === 'Sprite' && comp.data?.texture) {
+ comp.data.texture = this.encodeAssetPath(comp.data.texture);
+ }
+ }
}
+ if (scene.textureMetadata) {
+ const encodedMetadata: Record<string, unknown> = {};
+ for (const [path, metadata] of Object.entries(scene.textureMetadata)) {
+ encodedMetadata[this.encodeAssetPath(path)] = metadata;
+ }
+ scene.textureMetadata = encodedMetadata;
+ }
+ return JSON.stringify(scene, null, 2);
+ } catch {
+ return sceneJson;
}
}
+ private encodeAssetPath(path: string): string {
+ if (!path || typeof path !== 'string') return path;
+ const parts = path.split('/');
+ const encodedParts = parts.map(part => {
+ const dotIndex = part.lastIndexOf('.');
+ if (dotIndex > 0) {
+ const name = part.substring(0, dotIndex);
+ const ext = part.substring(dotIndex);
+ return encodeURIComponent(name) + ext;
+ }
+ return encodeURIComponent(part);
+ });
+ return encodedParts.join('/');
+ }
+
private async copyAssets(outputDir: string): Promise<void> {
const srcTexturesPath = joinPath(this.projectDir_, 'assets/textures');
const destTexturesPath = joinPath(outputDir, 'assets/textures');
@@ -437,7 +576,8 @@ var SDK = require('./sdk.js');
for (const entry of entries) {
const srcPath = joinPath(srcDir, entry.name);
- const destPath = joinPath(destDir, entry.name);
+ const encodedName = this.encodeFileName(entry.name);
+ const destPath = joinPath(destDir, encodedName);
if (entry.isDirectory) {
await this.copyDirectoryRecursive(srcPath, destPath);
@@ -452,4 +592,14 @@ var SDK = require('./sdk.js');
}
}
}
+
+ private encodeFileName(name: string): string {
+ const dotIndex = name.lastIndexOf('.');
+ if (dotIndex > 0) {
+ const baseName = name.substring(0, dotIndex);
+ const ext = name.substring(dotIndex);
+ return encodeURIComponent(baseName) + ext;
+ }
+ return encodeURIComponent(name);
+ }
}
diff --git a/scripts/build-wxgame.bat b/scripts/build-wxgame.bat
new file mode 100644
index 000000000..5ea0fd714
--- /dev/null
+++ b/scripts/build-wxgame.bat
@@ -0,0 +1,42 @@
+@echo off
+setlocal
+
+cd /d "%~dp0\.."
+
+set BUILD_DIR=build-wxgame
+set OUTPUT_DIR=desktop\public\wasm
+
+echo === Building ESEngine for WeChat MiniGame ===
+
+if not exist "%BUILD_DIR%" mkdir "%BUILD_DIR%"
+cd "%BUILD_DIR%"
+
+echo Configuring...
+call emcmake cmake .. -DES_BUILD_WXGAME=ON -DCMAKE_BUILD_TYPE=Release
+if errorlevel 1 goto :error
+
+echo Building...
+call cmake --build . --target esengine_wxgame -j4
+if errorlevel 1 goto :error
+
+echo.
+echo Copying to %OUTPUT_DIR%...
+if not exist "..\%OUTPUT_DIR%" mkdir "..\%OUTPUT_DIR%"
+copy /Y sdk\esengine.wxgame.js "..\%OUTPUT_DIR%\"
+copy /Y sdk\esengine.wxgame.wasm "..\%OUTPUT_DIR%\"
+
+echo.
+echo === Build complete ===
+echo Output files:
+echo - %OUTPUT_DIR%\esengine.wxgame.js
+echo - %OUTPUT_DIR%\esengine.wxgame.wasm
+goto :end
+
+:error
+echo Build failed!
+pause
+exit /b 1
+
+:end
+endlocal
+pause
diff --git a/sdk/package-lock.json b/sdk/package-lock.json
index a037110d7..df5645c0d 100644
--- a/sdk/package-lock.json
+++ b/sdk/package-lock.json
@@ -1,15 +1,16 @@
{
- "name": "@esengine/sdk",
+ "name": "esengine",
"version": "0.3.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
- "name": "@esengine/sdk",
+ "name": "esengine",
"version": "0.3.0",
"license": "MIT",
"devDependencies": {
"@rollup/plugin-typescript": "^11.1.5",
+ "minigame-api-typings": "^3.8.16",
"rimraf": "^5.0.5",
"rollup": "^4.9.0",
"rollup-plugin-dts": "^6.1.0",
@@ -736,6 +737,13 @@
"@jridgewell/sourcemap-codec": "^1.5.5"
}
},
+ "node_modules/minigame-api-typings": {
+ "version": "3.8.16",
+ "resolved": "https://registry.npmjs.org/minigame-api-typings/-/minigame-api-typings-3.8.16.tgz",
+ "integrity": "sha512-xSxV1onUDkwBRRqxAQgu+Xct1Ose74Ol2ESefE/hUpxH+7oY/eAFUvEaQB8hKL/2TZNx4RMIduEZv4Z5cAuvYg==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/minimatch": {
"version": "9.0.5",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz",
diff --git a/sdk/src/core.ts b/sdk/src/core.ts
index 49887a6b9..5cf0f03d7 100644
--- a/sdk/src/core.ts
+++ b/sdk/src/core.ts
@@ -175,6 +175,7 @@ export {
export {
loadSceneData,
loadSceneWithAssets,
+ updateCameraAspectRatio,
type SceneData,
type SceneEntityData,
type SceneComponentData,
diff --git a/sdk/src/index.wechat.ts b/sdk/src/index.wechat.ts
index a06a4c0ce..0e838abfb 100644
--- a/sdk/src/index.wechat.ts
+++ b/sdk/src/index.wechat.ts
@@ -20,4 +20,8 @@ export {
wxFileExists,
wxFileExistsSync,
wxWriteFile,
+ wxLoadImage,
+ wxGetImagePixels,
+ wxLoadImagePixels,
+ type ImageLoadResult,
} from './platform/wechat';
diff --git a/sdk/src/platform/wechat/image.ts b/sdk/src/platform/wechat/image.ts
new file mode 100644
index 000000000..5700ab2d3
--- /dev/null
+++ b/sdk/src/platform/wechat/image.ts
@@ -0,0 +1,107 @@
+/**
+ * @file image.ts
+ * @brief WeChat MiniGame image loading utilities
+ */
+
+/// <reference types="minigame-api-typings" />
+
+// =============================================================================
+// Types
+// =============================================================================
+
+export interface ImageLoadResult {
+ width: number;
+ height: number;
+ pixels: Uint8Array;
+}
+
+// =============================================================================
+// Canvas Management
+// =============================================================================
+
+let offscreenCanvas: WechatMinigame.Canvas | null = null;
+let offscreenCtx: CanvasRenderingContext2D | null = null;
+
+function getOffscreenCanvas(width: number, height: number): {
+ canvas: WechatMinigame.Canvas;
+ ctx: CanvasRenderingContext2D;
+} {
+ if (!offscreenCanvas) {
+ offscreenCanvas = wx.createCanvas();
+ offscreenCanvas.width = width;
+ offscreenCanvas.height = height;
+ offscreenCtx = offscreenCanvas.getContext('2d') as CanvasRenderingContext2D;
+ }
+
+ if (offscreenCanvas.width < width || offscreenCanvas.height < height) {
+ offscreenCanvas.width = Math.max(offscreenCanvas.width, width);
+ offscreenCanvas.height = Math.max(offscreenCanvas.height, height);
+ }
+
+ return { canvas: offscreenCanvas, ctx: offscreenCtx! };
+}
+
+// =============================================================================
+// Image Loading
+// =============================================================================
+
+/**
+ * Load an image from a file path
+ * @param path - File path relative to game root
+ */
+export function wxLoadImage(path: string): Promise<WechatMinigame.Image> {
+ return new Promise((resolve, reject) => {
+ const img = wx.createImage();
+ img.onload = () => resolve(img);
+ img.onerror = (err) => reject(new Error(`Failed to load image: ${path}, ${err}`));
+ img.src = path;
+ });
+}
+
+/**
+ * Extract pixel data from an image
+ * @param img - Loaded image object
+ * @param flipY - Whether to flip the image vertically (default: true for OpenGL)
+ */
+export function wxGetImagePixels(img: WechatMinigame.Image, flipY = true): ImageLoadResult {
+ const { width, height } = img;
+ const { ctx } = getOffscreenCanvas(width, height);
+
+ ctx.clearRect(0, 0, width, height);
+ ctx.drawImage(img as unknown as CanvasImageSource, 0, 0);
+ const imageData = ctx.getImageData(0, 0, width, height);
+ const pixels = new Uint8Array(imageData.data.buffer);
+
+ if (flipY) {
+ return { width, height, pixels: flipVertically(pixels, width, height) };
+ }
+
+ return { width, height, pixels };
+}
+
+/**
+ * Load image and get pixel data in one call
+ * @param path - File path relative to game root
+ * @param flipY - Whether to flip the image vertically (default: true for OpenGL)
+ */
+export async function wxLoadImagePixels(path: string, flipY = true): Promise<ImageLoadResult> {
+ const img = await wxLoadImage(path);
+ return wxGetImagePixels(img, flipY);
+}
+
+// =============================================================================
+// Utility Functions
+// =============================================================================
+
+function flipVertically(pixels: Uint8Array, width: number, height: number): Uint8Array {
+ const rowSize = width * 4;
+ const flipped = new Uint8Array(pixels.length);
+
+ for (let y = 0; y < height; y++) {
+ const srcOffset = y * rowSize;
+ const dstOffset = (height - 1 - y) * rowSize;
+ flipped.set(pixels.subarray(srcOffset, srcOffset + rowSize), dstOffset);
+ }
+
+ return flipped;
+}
diff --git a/sdk/src/platform/wechat/index.ts b/sdk/src/platform/wechat/index.ts
index e3123b6ba..3d6c2b2cb 100644
--- a/sdk/src/platform/wechat/index.ts
+++ b/sdk/src/platform/wechat/index.ts
@@ -79,3 +79,4 @@ export const wechatAdapter = new WeChatPlatformAdapter();
export { polyfillFetch, polyfillWebAssembly };
export { wxReadFile, wxReadTextFile, wxFileExists, wxFileExistsSync, wxWriteFile } from './fs';
+export { wxLoadImage, wxGetImagePixels, wxLoadImagePixels, type ImageLoadResult } from './image';
diff --git a/sdk/src/scene.ts b/sdk/src/scene.ts
index d195624ca..ad5d144f8 100644
--- a/sdk/src/scene.ts
+++ b/sdk/src/scene.ts
@@ -76,6 +76,17 @@ export function loadSceneData(world: World, sceneData: SceneData): Map<number, E
}
}
+ // Set parent-child relationships
+ for (const entityData of sceneData.entities) {
+ if (entityData.parent !== null) {
+ const entity = entityMap.get(entityData.id);
+ const parentEntity = entityMap.get(entityData.parent);
+ if (entity !== undefined && parentEntity !== undefined) {
+ world.setParent(entity, parentEntity);
+ }
+ }
+ }
+
return entityMap;
}
@@ -162,3 +173,15 @@ function loadComponent(world: World, entity: Entity, compData: SceneComponentDat
console.warn(`Unknown component type: ${compData.type}`);
}
}
+
+export function updateCameraAspectRatio(world: World, aspectRatio: number): void {
+ const cameraEntities = world.getEntitiesWithComponents([Camera]);
+ for (const entity of cameraEntities) {
+ const camera = world.get(entity, Camera) as CameraData;
+ if (camera) {
+ camera.aspectRatio = aspectRatio;
+ world.insert(entity, Camera, camera);
+ }
+ }
+}
+