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: update project structure and builders for src/ scripts directory

esengine232be93807eb
diff --git a/desktop/src-tauri/src/preview_template.html b/desktop/src-tauri/src/preview_template.html
index 13c8940f7..7226a9e1b 100644
--- a/desktop/src-tauri/src/preview_template.html
+++ b/desktop/src-tauri/src/preview_template.html
@@ -97,6 +97,7 @@
const app = sdk.createWebApp(Module, {
getViewportSize: getCanvasViewportSize
});
+ sdk.flushPendingSystems(app);
app.addPlugin(sdk.assetPlugin);
app.addPlugin(previewPlugin);
diff --git a/editor/src/Editor.ts b/editor/src/Editor.ts
index afba5f941..0fe1d29f1 100644
--- a/editor/src/Editor.ts
+++ b/editor/src/Editor.ts
@@ -314,12 +314,14 @@ export class Editor {
},
onCompileSuccess: () => {
console.log('Scripts compiled successfully');
+ this.store_.notifyChange();
},
});
try {
await this.scriptLoader_.initialize();
await this.scriptLoader_.compile();
+ await this.scriptLoader_.watch();
} catch (err) {
console.error('Failed to initialize scripts:', err);
}
@@ -952,6 +954,7 @@ export class Editor {
dispose(): void {
this.shortcutManager_.detach();
+ this.scriptLoader_?.dispose();
this.extensionLoader_?.dispose();
for (const instance of this.statusbarInstances_) {
instance.dispose();
diff --git a/editor/src/builder/PlayableBuilder.ts b/editor/src/builder/PlayableBuilder.ts
index 5fdb105d4..0d76bd466 100644
--- a/editor/src/builder/PlayableBuilder.ts
+++ b/editor/src/builder/PlayableBuilder.ts
@@ -15,6 +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';
// =============================================================================
// Types
@@ -123,6 +124,7 @@ var __STARTUP_SCENE__={{SCENE_DATA}};
return;
}
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();
@@ -195,7 +197,7 @@ export class PlayableBuilder {
this.progress_.setCurrentTask('Compiling scripts...', 0);
let gameCode: string;
- const scriptsPath = joinPath(this.projectDir_, 'assets/scripts');
+ const scriptsPath = joinPath(this.projectDir_, 'src');
const scriptFiles = await this.getScriptFiles(scriptsPath);
if (cachedData?.compiledScripts && this.cache_) {
@@ -273,15 +275,11 @@ export class PlayableBuilder {
}
}
- private async getScriptFiles(scriptsPath: string): Promise<string[]> {
- if (!await this.fs_!.exists(scriptsPath)) {
+ private async getScriptFiles(srcPath: string): Promise<string[]> {
+ if (!await this.fs_!.exists(srcPath)) {
return [];
}
-
- const entries = await this.fs_!.listDirectoryDetailed(scriptsPath);
- return entries
- .filter(e => !e.isDirectory && e.name.endsWith('.ts'))
- .map(e => joinPath(scriptsPath, e.name));
+ return findTsFiles(this.fs_!, srcPath);
}
// =========================================================================
@@ -313,16 +311,13 @@ export class PlayableBuilder {
}
private async compileUserScripts(): Promise<string> {
- const scriptsPath = joinPath(this.projectDir_, 'assets/scripts');
+ const scriptsPath = joinPath(this.projectDir_, 'src');
if (!await this.fs_!.exists(scriptsPath)) {
return this.createMinimalGameCode();
}
- const entries = await this.fs_!.listDirectoryDetailed(scriptsPath);
- const scripts = entries
- .filter(e => !e.isDirectory && e.name.endsWith('.ts'))
- .map(e => joinPath(scriptsPath, e.name));
+ const scripts = await findTsFiles(this.fs_!, scriptsPath);
if (scripts.length === 0) {
return this.createMinimalGameCode();
diff --git a/editor/src/builder/WeChatBuilder.ts b/editor/src/builder/WeChatBuilder.ts
index 30a4baa94..35ada528f 100644
--- a/editor/src/builder/WeChatBuilder.ts
+++ b/editor/src/builder/WeChatBuilder.ts
@@ -8,6 +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';
// =============================================================================
// Types
@@ -216,14 +217,11 @@ export class WeChatBuilder {
}
private async generateGameJs(outputDir: string): Promise<void> {
- const scriptsPath = joinPath(this.projectDir_, 'assets/scripts');
+ const scriptsPath = joinPath(this.projectDir_, 'src');
let userCode = '';
if (await this.fs_!.exists(scriptsPath)) {
- const entries = await this.fs_!.listDirectoryDetailed(scriptsPath);
- const scripts = entries
- .filter(e => !e.isDirectory && e.name.endsWith('.ts'))
- .map(e => joinPath(scriptsPath, e.name));
+ const scripts = await findTsFiles(this.fs_!, scriptsPath);
if (scripts.length > 0) {
userCode = await this.compileScripts(scripts);
@@ -356,6 +354,7 @@ function applyTextureMetadata(module, sceneData, textureCache) {
${userCode}
+ SDK.flushPendingSystems(app);
app.run();
})();
`;
@@ -408,7 +407,7 @@ function applyTextureMetadata(module, sceneData, textureCache) {
stdin: {
contents: entryContent,
loader: 'ts',
- resolveDir: joinPath(this.projectDir_, 'assets/scripts'),
+ resolveDir: joinPath(this.projectDir_, 'src'),
},
bundle: true,
format: 'iife',
diff --git a/editor/src/extension/ExtensionLoader.ts b/editor/src/extension/ExtensionLoader.ts
index 7c616779a..166525b0c 100644
--- a/editor/src/extension/ExtensionLoader.ts
+++ b/editor/src/extension/ExtensionLoader.ts
@@ -274,6 +274,7 @@ export class ExtensionLoader {
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[]> {
diff --git a/editor/src/launcher/ProjectService.ts b/editor/src/launcher/ProjectService.ts
index 77ac23e46..db373a1b9 100644
--- a/editor/src/launcher/ProjectService.ts
+++ b/editor/src/launcher/ProjectService.ts
@@ -118,7 +118,6 @@ export async function createProject(
const directories = [
projectDir,
joinPath(projectDir, 'src'),
- joinPath(projectDir, 'editor'),
joinPath(projectDir, 'assets'),
joinPath(projectDir, 'assets/scenes'),
joinPath(projectDir, 'assets/textures'),
@@ -164,9 +163,8 @@ export async function createProject(
const settingsPath = joinPath(projectDir, '.esengine/settings.json');
await fs.writeFile(settingsPath, JSON.stringify(editorSettings, null, 2));
- // Create script files
- const scriptFiles = createProjectScripts(name, template);
- for (const [filePath, content] of Object.entries(scriptFiles)) {
+ const projectFiles = createProjectFiles(name, template);
+ for (const [filePath, content] of Object.entries(projectFiles)) {
const fullPath = joinPath(projectDir, filePath);
if (!(await fs.writeFile(fullPath, content))) {
console.warn(`Failed to write script file: ${filePath}`);
@@ -268,127 +266,9 @@ export async function loadProjectConfig(
}
// =============================================================================
-// Script Templates
+// Project File Templates
// =============================================================================
-const MAIN_TS_TEMPLATE = `/**
- * ESEngine Project Entry Point
- *
- * This file is the main entry point for your game logic.
- * Press F5 in the editor to run, or use Web Preview for browser testing.
- */
-import {
- type ESEngineModule,
- App,
- createWebApp,
- defineSystem,
- Schedule,
- Commands,
- LocalTransform,
- Sprite,
- Camera,
- Canvas,
- Res,
- Time,
- Query,
- Mut,
- type Entity
-} from 'esengine';
-
-// =============================================================================
-// Main Entry Point
-// =============================================================================
-
-export async function main(Module: ESEngineModule): Promise<void> {
- console.log('ESEngine starting...');
-
- // Create the app with WASM module (handles renderer init + render loop)
- const app = createWebApp(Module);
-
- // Add startup system - runs once at beginning
- app.addSystemToSchedule(Schedule.Startup, defineSystem(
- [Commands()],
- (cmds) => {
- console.log('Startup: Creating entities...');
-
- // Create camera
- const camera = cmds.spawn()
- .insert(Camera, {
- projectionType: 1, // Orthographic
- fov: 60,
- orthoSize: 400,
- nearPlane: 0.1,
- farPlane: 1000,
- aspectRatio: 1,
- isActive: true,
- priority: 0
- })
- .insert(LocalTransform, {
- position: { x: 0, y: 0, z: 10 },
- rotation: { w: 1, x: 0, y: 0, z: 0 },
- scale: { x: 1, y: 1, z: 1 }
- })
- .id();
-
- // Create a test sprite
- const sprite = cmds.spawn()
- .insert(Sprite, {
- 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
- })
- .insert(LocalTransform, {
- position: { x: 0, y: 0, z: 0 },
- rotation: { w: 1, x: 0, y: 0, z: 0 },
- scale: { x: 1, y: 1, z: 1 }
- })
- .id();
-
- console.log(\`Created camera: \${camera}, sprite: \${sprite}\`);
- }
- ));
-
- // Add update system - runs every frame
- app.addSystemToSchedule(Schedule.Update, defineSystem(
- [Res(Time), Query(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;
- }
- }
- ));
-
- // Start the game loop
- console.log('Starting game loop...');
- app.run();
-}
-`;
-
-function createPackageJson(projectName: string): string {
- return JSON.stringify({
- name: projectName.toLowerCase().replace(/\s+/g, '-'),
- version: '0.1.0',
- type: 'module',
- scripts: {
- build: 'rollup -c',
- watch: 'rollup -c -w',
- },
- devDependencies: {
- '@rollup/plugin-node-resolve': '^15.2.3',
- '@rollup/plugin-typescript': '^11.1.6',
- rollup: '^4.18.0',
- typescript: '^5.4.5',
- },
- }, null, 2);
-}
-
const TSCONFIG_TEMPLATE = JSON.stringify({
compilerOptions: {
target: 'ES2020',
@@ -408,55 +288,25 @@ const TSCONFIG_TEMPLATE = JSON.stringify({
'@esengine/editor': ['./.esengine/editor/index.d.ts'],
},
},
- include: ['src/**/*', 'editor/**/*'],
+ include: ['src/**/*'],
exclude: ['node_modules'],
}, null, 2);
-const ROLLUP_CONFIG_TEMPLATE = `import resolve from '@rollup/plugin-node-resolve';
-import typescript from '@rollup/plugin-typescript';
-
-export default {
- input: 'src/main.ts',
- output: {
- file: 'dist/bundle.js',
- format: 'es',
- sourcemap: true
- },
- plugins: [
- resolve(),
- typescript()
- ],
- external: ['esengine']
-};
-`;
-
-const GITIGNORE_TEMPLATE = `# Dependencies
-node_modules/
-
-# Build outputs
+const GITIGNORE_TEMPLATE = `node_modules/
dist/
-
-# IDE
.vscode/
.idea/
-
-# OS
.DS_Store
Thumbs.db
-
-# Editor cache
.esengine/cache/
`;
-function createProjectScripts(
- name: string,
+function createProjectFiles(
+ _name: string,
_template: ProjectTemplate
): Record<string, string> {
return {
- 'src/main.ts': MAIN_TS_TEMPLATE,
- 'package.json': createPackageJson(name),
'tsconfig.json': TSCONFIG_TEMPLATE,
- 'rollup.config.js': ROLLUP_CONFIG_TEMPLATE,
'.gitignore': GITIGNORE_TEMPLATE,
};
}
diff --git a/editor/src/panels/ContentBrowserPanel.ts b/editor/src/panels/ContentBrowserPanel.ts
index 4ff1ded50..0a61e66a5 100644
--- a/editor/src/panels/ContentBrowserPanel.ts
+++ b/editor/src/panels/ContentBrowserPanel.ts
@@ -642,16 +642,11 @@ export class ContentBrowserPanel {
const platform = getPlatformAdapter();
const filePath = `${parentPath}/${name}`;
- const content = `import { defineSystem, Query, Mut, LocalTransform } from 'esengine';
-
-export const ${this.toClassName(name)}System = defineSystem({
- name: '${this.toClassName(name)}',
- query: Query(Mut(LocalTransform)),
- run(query) {
- for (const [transform] of query) {
- // Update logic here
- }
- },
+ const className = this.toClassName(name);
+ const content = `import { defineComponent } from 'esengine';
+
+export const ${className} = defineComponent('${className}', {
+ value: 0,
});
`;
diff --git a/editor/src/store/EditorStore.ts b/editor/src/store/EditorStore.ts
index 26bf7ed94..24b7b4a65 100644
--- a/editor/src/store/EditorStore.ts
+++ b/editor/src/store/EditorStore.ts
@@ -470,6 +470,10 @@ export class EditorStore {
// Subscription
// =========================================================================
+ notifyChange(): void {
+ this.notify();
+ }
+
subscribe(listener: EditorListener): () => void {
this.listeners_.add(listener);
return () => this.listeners_.delete(listener);