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.

refactor: redesign PlayableBuilder with explicit asset loading

esengine5ce0f55fcf40
diff --git a/cmake/Emscripten.cmake b/cmake/Emscripten.cmake
index d3a1e208b..32b190154 100644
--- a/cmake/Emscripten.cmake
+++ b/cmake/Emscripten.cmake
@@ -191,11 +191,11 @@ set(ES_EMSCRIPTEN_SINGLE_FILE_FLAGS
-sENVIRONMENT=web
-sMODULARIZE=1
"-sEXPORT_NAME='ESEngineModule'"
+ -sFORCE_FILESYSTEM=1
"-sEXPORTED_FUNCTIONS=['_malloc','_free']"
- "-sEXPORTED_RUNTIME_METHODS=['ccall','cwrap','HEAPF32','HEAPU8','HEAPU32']"
+ "-sEXPORTED_RUNTIME_METHODS=['ccall','cwrap','HEAPF32','HEAPU8','HEAPU32','FS']"
-Oz
-flto
- --closure=1
)
function(es_apply_sdk_settings TARGET_NAME)
diff --git a/desktop/src-tauri/src/preview_template.html b/desktop/src-tauri/src/preview_template.html
index 7226a9e1b..f7188b6fb 100644
--- a/desktop/src-tauri/src/preview_template.html
+++ b/desktop/src-tauri/src/preview_template.html
@@ -85,7 +85,7 @@
try {
await import('/.esengine/preview/user-scripts.js');
} catch (e) {
- // No user scripts
+ console.warn('User scripts load skipped:', e);
}
updateLoading('Loading scene...');
diff --git a/editor/src/Editor.ts b/editor/src/Editor.ts
index 0fe1d29f1..ece27d091 100644
--- a/editor/src/Editor.ts
+++ b/editor/src/Editor.ts
@@ -4,6 +4,7 @@
*/
import type { App, Entity } from 'esengine';
+import * as esengine from 'esengine';
import {
Draw, Geometry, Material, BlendMode, DataType, ShaderSources,
PostProcess, Renderer, RenderStage,
@@ -344,6 +345,7 @@ export class Editor {
private setupEditorGlobals(): void {
this.baseAPI_ = {
+ ...esengine,
registerPanel,
registerMenuItem,
registerMenu,
@@ -570,6 +572,9 @@ export class Editor {
}
try {
+ if (this.scriptLoader_) {
+ await this.scriptLoader_.compile();
+ }
const compiledScript = this.scriptLoader_?.getCompiledCode() ?? undefined;
await this.previewService_.startPreview(this.store_.scene, compiledScript);
} catch (err) {
diff --git a/editor/src/builder/PlayableBuilder.ts b/editor/src/builder/PlayableBuilder.ts
index 0d76bd466..cb5e3133f 100644
--- a/editor/src/builder/PlayableBuilder.ts
+++ b/editor/src/builder/PlayableBuilder.ts
@@ -15,7 +15,7 @@ import type { BuildResult, BuildContext } from './BuildService';
import { BuildProgressReporter } from './BuildProgress';
import { BuildCache, type BuildCacheData } from './BuildCache';
import { getEditorContext } from '../context/EditorContext';
-import { findTsFiles } from '../scripting/ScriptLoader';
+import { findTsFiles, EDITOR_ONLY_DIRS } from '../scripting/ScriptLoader';
// =============================================================================
// Types
@@ -74,6 +74,9 @@ const MIME_TYPES: Record<string, string> = {
gif: 'image/gif',
webp: 'image/webp',
svg: 'image/svg+xml',
+ atlas: 'text/plain',
+ json: 'application/json',
+ skel: 'application/octet-stream',
};
// =============================================================================
@@ -102,38 +105,173 @@ html,body{width:100%;height:100%;overflow:hidden;background:#000}
{{GAME_CODE}}
</script>
<script>
-var __STARTUP_SCENE__={{SCENE_DATA}};
-(function(){
- var c=document.getElementById('canvas');
- function resize(){
- var dpr=window.devicePixelRatio||1;
- c.width=window.innerWidth*dpr;
- c.height=window.innerHeight*dpr;
+var __PA__={{ASSETS_MAP}};
+var __SCENE__={{SCENE_DATA}};
+
+function loadImagePixels(dataUrl){
+ return new Promise(function(resolve,reject){
+ var img=new Image();
+ img.onload=function(){
+ var cv=document.createElement('canvas');
+ cv.width=img.width;cv.height=img.height;
+ var ctx=cv.getContext('2d');
+ ctx.drawImage(img,0,0);
+ var id=ctx.getImageData(0,0,img.width,img.height);
+ resolve({width:img.width,height:img.height,pixels:new Uint8Array(id.data.buffer)});
+ };
+ img.onerror=reject;
+ img.src=dataUrl;
+ });
+}
+
+function createTextureFromPixels(mod,r){
+ var rm=mod.getResourceManager();
+ var ptr=mod._malloc(r.pixels.length);
+ mod.HEAPU8.set(r.pixels,ptr);
+ var h=rm.createTexture(r.width,r.height,ptr,r.pixels.length,1);
+ mod._free(ptr);
+ return h;
+}
+
+function decodeText(dataUrl){return atob(dataUrl.split(',')[1])}
+
+function decodeBinary(dataUrl){
+ var b=atob(dataUrl.split(',')[1]);
+ var a=new Uint8Array(b.length);
+ for(var i=0;i<b.length;i++)a[i]=b.charCodeAt(i);
+ return a;
+}
+
+function ensureFSDir(mod,path){
+ var parts=path.split('/');var cur='';
+ for(var i=0;i<parts.length-1;i++){
+ cur+=(cur?'/':'')+parts[i];
+ try{mod.FS.mkdir(cur)}catch(e){}
}
- window.addEventListener('resize',resize);
- resize();
+}
- ESEngineModule({
- canvas:c,
- print:function(t){console.log(t)},
- printErr:function(t){console.error(t)}
- }).then(function(Module){
- var es=window.esengine;
- if(!es||!es.createWebApp){
- console.error('esengine not found');
- return;
+function parseAtlasTextures(content){
+ var textures=[];var lines=content.split('\\n');
+ for(var i=0;i<lines.length;i++){
+ var line=lines[i].trim();
+ if(line&&line.indexOf(':')===-1&&(/\\.png$/i.test(line)||/\\.jpg$/i.test(line)))
+ textures.push(line);
+ }
+ return textures;
+}
+
+async function loadSceneTextures(mod,scene){
+ var cache={};
+ for(var i=0;i<scene.entities.length;i++){
+ var ent=scene.entities[i];
+ for(var j=0;j<ent.components.length;j++){
+ var comp=ent.components[j];
+ if(comp.type==='Sprite'&&comp.data.texture&&typeof comp.data.texture==='string'){
+ var tp=comp.data.texture;
+ if(!cache[tp]){
+ var d=__PA__[tp];
+ if(d){
+ try{cache[tp]=createTextureFromPixels(mod,await loadImagePixels(d))}
+ catch(e){console.warn('Failed to load texture:',tp,e);cache[tp]=0}
+ }else{cache[tp]=0}
+ }
+ }
}
- var app=es.createWebApp(Module);
- es.flushPendingSystems(app);
- var assetServer=new es.AssetServer(Module);
- es.loadSceneWithAssets(app.world,__STARTUP_SCENE__,{assetServer:assetServer}).then(function(){
- app.run();
- });
- }).catch(function(e){
- if(e!=='unwind'&&(!e.message||!e.message.includes('unwind'))){
- console.error('Failed:',e);
+ }
+ return cache;
+}
+
+async function loadSpineAssets(mod,scene){
+ var rm=mod.getResourceManager();
+ for(var i=0;i<scene.entities.length;i++){
+ var ent=scene.entities[i];
+ for(var j=0;j<ent.components.length;j++){
+ var comp=ent.components[j];
+ if(comp.type!=='SpineAnimation'||!comp.data)continue;
+ var skelPath=comp.data.skeletonPath,atlasPath=comp.data.atlasPath;
+ if(!skelPath||!atlasPath)continue;
+ var atlasData=__PA__[atlasPath];
+ if(atlasData){
+ var atlasContent=decodeText(atlasData);
+ ensureFSDir(mod,atlasPath);
+ mod.FS.writeFile(atlasPath,atlasContent);
+ var texNames=parseAtlasTextures(atlasContent);
+ var atlasDir=atlasPath.substring(0,atlasPath.lastIndexOf('/'));
+ for(var k=0;k<texNames.length;k++){
+ var texPath=atlasDir+'/'+texNames[k];
+ var texData=__PA__[texPath];
+ if(texData){
+ try{
+ var h=createTextureFromPixels(mod,await loadImagePixels(texData));
+ rm.registerTextureWithPath(h,texPath);
+ }catch(e){console.warn('Failed to load spine texture:',texPath,e)}
+ }
+ }
+ }
+ var skelData=__PA__[skelPath];
+ if(skelData){
+ ensureFSDir(mod,skelPath);
+ if(skelPath.endsWith('.skel'))mod.FS.writeFile(skelPath,decodeBinary(skelData));
+ else mod.FS.writeFile(skelPath,decodeText(skelData));
+ }
}
- });
+ }
+}
+
+function updateSpriteTextures(world,scene,cache,entityMap){
+ var es=window.esengine;
+ for(var i=0;i<scene.entities.length;i++){
+ var ed=scene.entities[i];
+ var entity=entityMap.get(ed.id);
+ if(entity===undefined)continue;
+ for(var j=0;j<ed.components.length;j++){
+ var comp=ed.components[j];
+ if(comp.type==='Sprite'&&comp.data.texture&&typeof comp.data.texture==='string'){
+ var sprite=world.get(entity,es.Sprite);
+ if(sprite){sprite.texture=cache[comp.data.texture]||0;world.insert(entity,es.Sprite,sprite)}
+ }
+ }
+ }
+}
+
+function applyTextureMetadata(mod,scene,cache){
+ if(!scene.textureMetadata)return;
+ var rm=mod.getResourceManager();
+ for(var tp in scene.textureMetadata){
+ var h=cache[tp];
+ if(h&&h>0){
+ var m=scene.textureMetadata[tp];
+ if(m&&m.sliceBorder){
+ var b=m.sliceBorder;
+ rm.setTextureMetadata(h,b.left,b.right,b.top,b.bottom);
+ }
+ }
+ }
+}
+
+(async function(){
+ var c=document.getElementById('canvas');
+ function resize(){var dpr=window.devicePixelRatio||1;c.width=window.innerWidth*dpr;c.height=window.innerHeight*dpr}
+ window.addEventListener('resize',resize);
+ resize();
+
+ var Module=await ESEngineModule({canvas:c,print:function(t){console.log(t)},printErr:function(t){console.error(t)}});
+ var es=window.esengine;
+ if(!es||!es.createWebApp){console.error('esengine not found');return}
+
+ var app=es.createWebApp(Module);
+ es.flushPendingSystems(app);
+
+ var textureCache=await loadSceneTextures(Module,__SCENE__);
+ applyTextureMetadata(Module,__SCENE__,textureCache);
+ await loadSpineAssets(Module,__SCENE__);
+ var entityMap=es.loadSceneData(app.world,__SCENE__);
+ updateSpriteTextures(app.world,__SCENE__,textureCache,entityMap);
+
+ var screenAspect=c.width/c.height;
+ es.updateCameraAspectRatio(app.world,screenAspect);
+
+ app.run();
})();
</script>
</body>
@@ -223,20 +361,16 @@ export class PlayableBuilder {
}
this.progress_.log('info', `Scene loaded: ${scenePath}`);
- // 4. Collect and inline assets
+ // 4. Collect assets
this.progress_.setPhase('processing_assets');
this.progress_.setCurrentTask('Collecting assets...', 0);
const assets = await this.collectAssets();
this.progress_.log('info', `Collected ${assets.size} assets`);
- this.progress_.setCurrentTask('Inlining assets...', 50);
- const gameCodeWithAssets = this.inlineAssets(gameCode, assets);
- const sceneDataWithAssets = this.inlineAssets(sceneContent, assets);
-
// 5. Assemble HTML
this.progress_.setPhase('assembling');
this.progress_.setCurrentTask('Assembling HTML...', 0);
- const html = this.assembleHTML(wasmSdk, gameCodeWithAssets, sceneDataWithAssets);
+ const html = this.assembleHTML(wasmSdk, gameCode, sceneContent, assets);
this.progress_.log('info', `HTML assembled: ${html.length} bytes`);
// 6. Write output
@@ -279,7 +413,7 @@ export class PlayableBuilder {
if (!await this.fs_!.exists(srcPath)) {
return [];
}
- return findTsFiles(this.fs_!, srcPath);
+ return findTsFiles(this.fs_!, srcPath, EDITOR_ONLY_DIRS);
}
// =========================================================================
@@ -317,7 +451,7 @@ export class PlayableBuilder {
return this.createMinimalGameCode();
}
- const scripts = await findTsFiles(this.fs_!, scriptsPath);
+ const scripts = await findTsFiles(this.fs_!, scriptsPath, EDITOR_ONLY_DIRS);
if (scripts.length === 0) {
return this.createMinimalGameCode();
@@ -336,7 +470,9 @@ ${imports}
console.log('[PlayableBuilder] Compiling scripts...');
const settings = this.context_.config.playableSettings!;
- const defines: Record<string, string> = {};
+ const defines: Record<string, string> = {
+ 'process.env.EDITOR': 'false',
+ };
for (const def of this.context_.config.defines) {
defines[`process.env.${def}`] = 'true';
}
@@ -466,10 +602,10 @@ ${imports}
private async collectAssets(): Promise<Map<string, string>> {
const assets = new Map<string, string>();
- const texturesPath = joinPath(this.projectDir_, 'assets/textures');
+ const assetsPath = joinPath(this.projectDir_, 'assets');
- if (await this.fs_!.exists(texturesPath)) {
- await this.collectAssetsRecursive(texturesPath, '', assets);
+ if (await this.fs_!.exists(assetsPath)) {
+ await this.collectAssetsRecursive(assetsPath, 'assets', assets);
}
return assets;
@@ -504,29 +640,15 @@ ${imports}
}
}
- private inlineAssets(code: string, assets: Map<string, string>): string {
- let result = code;
-
- for (const [relativePath, dataUrl] of assets) {
- const pathVariants = [
- `assets/textures/${relativePath}`,
- `assets/${relativePath}`,
- relativePath,
- ];
-
- for (const pathVariant of pathVariants) {
- result = result.split(`'${pathVariant}'`).join(`'${dataUrl}'`);
- result = result.split(`"${pathVariant}"`).join(`"${dataUrl}"`);
- }
+ private assembleHTML(wasmSdk: string, gameCode: string, sceneData: string, assets: Map<string, string>): string {
+ const entries: string[] = [];
+ for (const [path, dataUrl] of assets) {
+ entries.push(`"${path}":"${dataUrl}"`);
}
-
- return result;
- }
-
- private assembleHTML(wasmSdk: string, gameCode: string, sceneData: string): string {
return HTML_TEMPLATE
.replace('{{WASM_SDK}}', wasmSdk)
.replace('{{GAME_CODE}}', gameCode)
+ .replace('{{ASSETS_MAP}}', `{${entries.join(',')}}`)
.replace('{{SCENE_DATA}}', sceneData);
}
diff --git a/editor/src/builder/WeChatBuilder.ts b/editor/src/builder/WeChatBuilder.ts
index 97827677f..cd0d67a2e 100644
--- a/editor/src/builder/WeChatBuilder.ts
+++ b/editor/src/builder/WeChatBuilder.ts
@@ -8,7 +8,7 @@ import type { BuildResult, BuildContext } from './BuildService';
import { BuildProgressReporter } from './BuildProgress';
import { BuildCache } from './BuildCache';
import { getEditorContext } from '../context/EditorContext';
-import { findTsFiles } from '../scripting/ScriptLoader';
+import { findTsFiles, EDITOR_ONLY_DIRS } from '../scripting/ScriptLoader';
// =============================================================================
// Types
@@ -221,7 +221,7 @@ export class WeChatBuilder {
let userCode = '';
if (await this.fs_!.exists(scriptsPath)) {
- const scripts = await findTsFiles(this.fs_!, scriptsPath);
+ const scripts = await findTsFiles(this.fs_!, scriptsPath, EDITOR_ONLY_DIRS);
if (scripts.length > 0) {
userCode = await this.compileScripts(scripts);
@@ -234,6 +234,7 @@ export class WeChatBuilder {
const gameJs = `
var ESEngineModule = require('./esengine.js');
var SDK = require('./sdk.js');
+globalThis.__esengine_sdk = SDK;
function createTextureFromPixels(module, result) {
var rm = module.getResourceManager();
@@ -388,7 +389,9 @@ function applyTextureMetadata(module, sceneData, textureCache) {
private async compileScripts(scripts: string[]): Promise<string> {
const entryContent = scripts.map(p => `import "${p}";`).join('\n');
- const defines: Record<string, string> = {};
+ const defines: Record<string, string> = {
+ 'process.env.EDITOR': 'false',
+ };
for (const def of this.context_.config.defines) {
defines[`process.env.${def}`] = 'true';
}
@@ -459,6 +462,16 @@ function applyTextureMetadata(module, sceneData, textureCache) {
return {
name: 'virtual-fs',
setup(build) {
+ build.onResolve({ filter: /^esengine(\/wasm)?$/ }, (args) => ({
+ path: args.path,
+ namespace: 'sdk-shim',
+ }));
+
+ build.onLoad({ filter: /.*/, namespace: 'sdk-shim' }, () => ({
+ contents: 'module.exports = globalThis.__esengine_sdk;',
+ loader: 'js',
+ }));
+
build.onResolve({ filter: /.*/ }, async (args) => {
if (args.kind === 'entry-point') {
return { path: args.path, namespace: 'virtual' };
@@ -472,18 +485,11 @@ function applyTextureMetadata(module, sceneData, textureCache) {
const baseDir = args.importer ? getDir(args.importer) : args.resolveDir;
resolvedPath = joinPath(baseDir, args.path);
} else {
- // Bare module specifier
- if (args.path === 'esengine') {
- resolvedPath = joinPath(projectDir, '.esengine/sdk/index.js');
- } else if (args.path === 'esengine/wasm') {
- resolvedPath = joinPath(projectDir, '.esengine/sdk/wasm.js');
+ const pkgEntry = await resolvePackageEntry(args.path);
+ if (pkgEntry) {
+ resolvedPath = pkgEntry;
} else {
- const pkgEntry = await resolvePackageEntry(args.path);
- if (pkgEntry) {
- resolvedPath = pkgEntry;
- } else {
- throw new Error(`Module not found: ${args.path}. Please install it with npm.`);
- }
+ throw new Error(`Module not found: ${args.path}. Please install it with npm.`);
}
}
diff --git a/editor/src/extension/ExtensionLoader.ts b/editor/src/extension/ExtensionLoader.ts
index 166525b0c..0d36577a9 100644
--- a/editor/src/extension/ExtensionLoader.ts
+++ b/editor/src/extension/ExtensionLoader.ts
@@ -4,7 +4,8 @@
*/
import * as esbuild from 'esbuild-wasm/esm/browser';
-import { editorShimPlugin, virtualFsPlugin } from '../scripting/esbuildPlugins';
+import { editorShimPlugin, esengineShimPlugin, virtualFsPlugin } from '../scripting/esbuildPlugins';
+import { findTsFiles } from '../scripting/ScriptLoader';
import type { NativeFS, CompileError } from '../scripting/types';
import { getEditorContext } from '../context/EditorContext';
import { ExtensionContext } from './ExtensionContext';
@@ -81,22 +82,10 @@ export class ExtensionLoader {
const fs = getNativeFS();
if (!fs) return [];
+ const srcPath = joinPath(this.projectDir_, 'src');
try {
- const editorDirs = await this.findEditorDirs(fs, this.projectDir_);
- const results: string[] = [];
-
- for (const dir of editorDirs) {
- if (!await fs.exists(dir)) continue;
- const entries = await fs.listDirectoryDetailed(dir);
- for (const e of entries) {
- if (!e.isDirectory && e.name.endsWith('.ts')) {
- results.push(joinPath(dir, e.name));
- }
- }
- }
-
- this.lastEditorDir_ = editorDirs[0] ?? null;
- return results;
+ if (!await fs.exists(srcPath)) return [];
+ return await findTsFiles(fs, srcPath);
} catch (err) {
console.error('ExtensionLoader: Failed to discover extensions:', err);
return [];
@@ -124,7 +113,7 @@ export class ExtensionLoader {
stdin: {
contents: entryContent,
loader: 'ts',
- resolveDir: this.lastEditorDir_ ?? this.projectDir_,
+ resolveDir: joinPath(this.projectDir_, 'src'),
},
bundle: true,
format: 'esm',
@@ -132,9 +121,12 @@ export class ExtensionLoader {
sourcemap: true,
platform: 'browser',
target: 'es2020',
- external: ['esengine'],
+ define: {
+ 'process.env.EDITOR': 'true',
+ },
plugins: [
editorShimPlugin(),
+ esengineShimPlugin(),
virtualFsPlugin({ fs, projectDir: this.projectDir_ }),
],
});
@@ -231,14 +223,14 @@ export class ExtensionLoader {
this.unwatch();
+ const srcPath = joinPath(this.projectDir_, 'src');
this.unwatchFn_ = await fs.watchDirectory(
- this.projectDir_,
+ srcPath,
(event) => {
- const hasEditorTs = event.paths.some(p => {
- const normalized = normalizePath(p);
- return /\/editor\/[^/]+\.ts$/.test(normalized);
- });
- if (!hasEditorTs) return;
+ const hasTsChange = event.paths.some(p =>
+ normalizePath(p).endsWith('.ts')
+ );
+ if (!hasTsChange) return;
if (this.recompileTimer_ !== null) {
clearTimeout(this.recompileTimer_);
@@ -272,31 +264,6 @@ export class ExtensionLoader {
// Private Methods
// =========================================================================
- private static readonly IGNORED_DIRS = new Set([
- 'node_modules', '.git', '.esengine', 'dist', 'build', '.next', '.cache',
- 'assets', 'public', 'vendor',
- ]);
-
- private async findEditorDirs(fs: NativeFS, dir: string): Promise<string[]> {
- const results: string[] = [];
- const entries = await fs.listDirectoryDetailed(dir);
-
- for (const e of entries) {
- if (!e.isDirectory) continue;
- if (ExtensionLoader.IGNORED_DIRS.has(e.name)) continue;
-
- const fullPath = joinPath(dir, e.name);
- if (e.name === 'editor') {
- results.push(fullPath);
- } else {
- const nested = await this.findEditorDirs(fs, fullPath);
- results.push(...nested);
- }
- }
-
- return results;
- }
-
private disposeCurrentUrl(): void {
if (this.currentBlobUrl_) {
URL.revokeObjectURL(this.currentBlobUrl_);
@@ -313,7 +280,6 @@ export class ExtensionLoader {
private baseAPI_: Record<string, unknown>;
private initialized_ = false;
private isReloading_ = false;
- private lastEditorDir_: string | null = null;
private lastCompiled_: string | null = null;
private lastSourcemap_: string | null = null;
private currentBlobUrl_: string | null = null;
diff --git a/editor/src/index.ts b/editor/src/index.ts
index 509a78d70..a06a52b2a 100644
--- a/editor/src/index.ts
+++ b/editor/src/index.ts
@@ -332,7 +332,7 @@ export {
} from './extension';
// =============================================================================
-// SDK Re-exports (for @esengine/editor shim)
+// SDK Re-exports
// =============================================================================
export {
diff --git a/editor/src/scripting/ScriptLoader.ts b/editor/src/scripting/ScriptLoader.ts
index 0746eb6bb..ed296ac85 100644
--- a/editor/src/scripting/ScriptLoader.ts
+++ b/editor/src/scripting/ScriptLoader.ts
@@ -80,7 +80,7 @@ export class ScriptLoader {
try {
if (!await fs.exists(srcPath)) return [];
- return await findTsFiles(fs, srcPath);
+ return await findTsFiles(fs, srcPath, EDITOR_ONLY_DIRS);
} catch (err) {
console.error('ScriptLoader: Failed to discover scripts:', err);
return [];
@@ -251,19 +251,25 @@ export class ScriptLoader {
// Script Discovery
// =============================================================================
-const IGNORED_SCRIPT_DIRS = new Set(['editor', 'node_modules', 'dist', 'build']);
+const IGNORED_SCRIPT_DIRS = new Set(['node_modules', 'dist', 'build']);
+const EDITOR_ONLY_DIRS = new Set(['editor']);
interface DirListable {
listDirectoryDetailed(path: string): Promise<{ name: string; isDirectory: boolean }[]>;
}
-async function findTsFiles(fs: DirListable, dir: string): Promise<string[]> {
+async function findTsFiles(
+ fs: DirListable,
+ dir: string,
+ excludeDirs?: Set<string>,
+): Promise<string[]> {
const results: string[] = [];
const entries = await fs.listDirectoryDetailed(dir);
for (const e of entries) {
if (e.isDirectory) {
- if (!IGNORED_SCRIPT_DIRS.has(e.name) && !e.name.startsWith('.')) {
- results.push(...await findTsFiles(fs, joinPath(dir, e.name)));
+ if (!IGNORED_SCRIPT_DIRS.has(e.name) && !e.name.startsWith('.')
+ && !(excludeDirs?.has(e.name))) {
+ results.push(...await findTsFiles(fs, joinPath(dir, e.name), excludeDirs));
}
} else if (e.name.endsWith('.ts')) {
results.push(joinPath(dir, e.name));
@@ -272,7 +278,7 @@ async function findTsFiles(fs: DirListable, dir: string): Promise<string[]> {
return results;
}
-export { findTsFiles, IGNORED_SCRIPT_DIRS };
+export { findTsFiles, IGNORED_SCRIPT_DIRS, EDITOR_ONLY_DIRS };
// =============================================================================
// Component Extraction
diff --git a/editor/src/scripting/esbuildPlugins.ts b/editor/src/scripting/esbuildPlugins.ts
index 4af2c0a40..506165125 100644
--- a/editor/src/scripting/esbuildPlugins.ts
+++ b/editor/src/scripting/esbuildPlugins.ts
@@ -45,36 +45,58 @@ function resolvePath(from: string, to: string): string {
}
// =============================================================================
-// Editor Shim Plugin
+// Shim Code Generation
// =============================================================================
-const EDITOR_SHIM_EXPORTS = [
- 'registerPanel', 'registerMenuItem', 'registerMenu',
- 'registerGizmo', 'registerStatusbarItem', 'registerPropertyEditor',
- 'registerComponentSchema', 'registerBoundsProvider',
- 'icons', 'showToast', 'showSuccessToast', 'showErrorToast',
- 'showContextMenu', 'showConfirmDialog', 'showInputDialog',
- 'getEditorInstance', 'getEditorStore',
- 'Draw', 'Geometry', 'Material', 'BlendMode', 'DataType', 'ShaderSources',
- 'PostProcess', 'Renderer', 'RenderStage',
- 'registerDrawCallback', 'unregisterDrawCallback',
- 'onDispose',
-] as const;
-
-const EDITOR_SHIM_CODE = EDITOR_SHIM_EXPORTS.map(
- name => `export const ${name} = window.__ESENGINE_EDITOR__.${name};`
-).join('\n');
+const JS_RESERVED = new Set([
+ 'break', 'case', 'catch', 'continue', 'debugger', 'default', 'delete',
+ 'do', 'else', 'finally', 'for', 'function', 'if', 'in', 'instanceof',
+ 'new', 'return', 'switch', 'this', 'throw', 'try', 'typeof', 'var',
+ 'void', 'while', 'with', 'class', 'const', 'enum', 'export', 'extends',
+ 'import', 'super', 'implements', 'interface', 'let', 'package', 'private',
+ 'protected', 'public', 'static', 'yield',
+]);
+
+function generateShimCode(): string {
+ const api = (window as any).__ESENGINE_EDITOR__ || {};
+ return Object.keys(api)
+ .filter(key => /^[a-zA-Z_$]/.test(key) && !JS_RESERVED.has(key))
+ .map(key => `export var ${key} = window.__ESENGINE_EDITOR__["${key}"];`)
+ .join('\n');
+}
+
+// =============================================================================
+// Editor Shim Plugin
+// =============================================================================
export function editorShimPlugin(): esbuild.Plugin {
return {
name: 'editor-shim',
setup(build) {
- build.onResolve({ filter: /^@esengine\/editor$/ }, () => {
- return { path: '@esengine/editor', namespace: 'editor-shim' };
- });
- build.onLoad({ filter: /.*/, namespace: 'editor-shim' }, () => {
- return { contents: EDITOR_SHIM_CODE, loader: 'js' };
- });
+ build.onResolve({ filter: /^@esengine\/editor$/ }, () => ({
+ path: '@esengine/editor', namespace: 'editor-shim',
+ }));
+ build.onLoad({ filter: /.*/, namespace: 'editor-shim' }, () => ({
+ contents: generateShimCode(), loader: 'js',
+ }));
+ },
+ };
+}
+
+// =============================================================================
+// ESEngine Shim Plugin
+// =============================================================================
+
+export function esengineShimPlugin(): esbuild.Plugin {
+ return {
+ name: 'esengine-shim',
+ setup(build) {
+ build.onResolve({ filter: /^esengine$/ }, () => ({
+ path: 'esengine', namespace: 'esengine-shim',
+ }));
+ build.onLoad({ filter: /.*/, namespace: 'esengine-shim' }, () => ({
+ contents: generateShimCode(), loader: 'js',
+ }));
},
};
}
@@ -108,12 +130,8 @@ export function virtualFsPlugin(options: VirtualFsPluginOptions): esbuild.Plugin
build.onResolve({ filter: /^[^./]/ }, async (args) => {
if (/^[A-Za-z]:/.test(args.path)) return undefined;
- // Handle esengine SDK from editor
- if (args.path === 'esengine') {
- return { path: joinPath(projectDir, '.esengine/sdk/index.js'), namespace: NS };
- }
- if (args.path === 'esengine/wasm') {
- return { path: joinPath(projectDir, '.esengine/sdk/wasm.js'), namespace: NS };
+ if (args.path === 'esengine' || args.path === 'esengine/wasm') {
+ return { path: args.path, external: true };
}
const pkgName = args.path.startsWith('@')
diff --git a/sdk/src/app.ts b/sdk/src/app.ts
index 1df959dac..c111df924 100644
--- a/sdk/src/app.ts
+++ b/sdk/src/app.ts
@@ -316,7 +316,7 @@ function computeViewProjection(registry: CppRegistry, width: number, height: num
if (camera.projectionType === 1) {
const halfH = camera.orthoSize;
const halfW = halfH * aspect;
- projection = ortho(-halfW, halfW, -halfH, halfH, camera.nearPlane, camera.farPlane);
+ projection = ortho(-halfW, halfW, -halfH, halfH, -camera.farPlane, camera.farPlane);
} else {
projection = perspective(
camera.fov * Math.PI / 180,