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(templates): an Online 3D starter, a networked 3D game with a dedicated server that runs the same project

yhh7de842248d0d
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 4fe3e8285..622279759 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -494,6 +494,11 @@ jobs:
ESTELLA_REQUIRE_WASM: '1'
run: node tools/check-arena-server.mjs
+ - name: Check the Online 3D template's server
+ env:
+ ESTELLA_REQUIRE_WASM: '1'
+ run: node tools/check-arena-server.mjs --project templates/online-3d --bound 1450 --speed 340
+
# Booting a packaged game needs the same real engine, and for the same
# reason it belongs here rather than in the fast lane.
- name: Check a packaged game's script failure
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3aad7d74a..e9788ef0a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,7 @@ published separately; it ships inside the editor.
### Added
+- **An Online 3D starter.** A template for a networked 3D game: a lit ground, a pawn per player predicted on its owner's screen and replicated to the others, a camera that follows your own, and a `server/` that runs the same project headless. The rules both ends agree on are one module, `src/shared/rules.ts`. `tools/check-arena-server.mjs` now takes `--project`, and runs against this template too.
- **Start a project from the command line.** `estella create <template> <dir> [--name]` makes a project from any starter or example, and `estella templates` lists them. The editor's New project gallery and the command line now share one implementation (`pipeline/src/project/scaffold.ts`), so both copy the same files and write the same `package.json` and `.gitignore`.
- **Clouds drawn from a coverage picture.** `skyAtmosphere` takes a Cloud Mask (`u_cloudMask`, with `u_cloudMaskTile` in kilometres of the cloud layer) and a second, higher one (`u_cloudMask2`): the clouds stand where the mask says and the noise only erodes them. The shadow the clouds cast and the beams of `heightFog`'s `cloudShade` read the same masks, which the fog takes from the sky. Terrain & Water uses the two the art made.
- **A Display LUT.** The `displayLut` effect reads a look off a 1024x32 lookup table by the picture as the display will show it, in the last pass, after the output transform and the transfer function: the place a look authored against the finished image belongs, and one no effect in the chain can be, since they run on scene values before the curve. It is a variant of the pass that was running, one texture read and no pass of its own, and `PostProcessStack.setDisplayLut(texture, amount)` is the same thing in code. The last pass now reads its parameters off the reflected layout as a material does, and the copies it makes share them.
diff --git a/docs/astro/src/content/docs/scripting/networking.mdx b/docs/astro/src/content/docs/scripting/networking.mdx
index 8c1fce806..6073c2944 100644
--- a/docs/astro/src/content/docs/scripting/networking.mdx
+++ b/docs/astro/src/content/docs/scripting/networking.mdx
@@ -159,6 +159,8 @@ clientNet.client?.sendInput({ move: { x: 1, y: 0 } }); // per-tick input uplin
See the **Multiplayer Arena** example for the full pattern — replication, per-tick input, and client prediction — in ~130 lines. Its `server/` directory is the dedicated-server half: the same project, headless, behind a real WebSocket.
+To start a game of your own on that pattern, create it from the **Online 3D** template (`estella create online-3d ./my-game`, or pick it in the editor's New project gallery): a lit 3D ground, a pawn per player that is predicted on its owner's screen and replicated to everyone else, a camera that follows your own, and a `server/` that runs the same code headless. The rules both ends must agree on (speed, the world's edge) sit in `src/shared/rules.ts`, apart from any system, so a server can refuse what they forbid. What it leaves to the game is written in its README: a stable player identity across reconnects, saving the world, and who sees what.
+
### Interest management — who sees what
By default every client receives every replicated entity. For bigger worlds,
diff --git a/docs/astro/src/content/docs/zh-cn/scripting/networking.mdx b/docs/astro/src/content/docs/zh-cn/scripting/networking.mdx
index 2d31a729b..c4e4cdc0d 100644
--- a/docs/astro/src/content/docs/zh-cn/scripting/networking.mdx
+++ b/docs/astro/src/content/docs/zh-cn/scripting/networking.mdx
@@ -148,6 +148,8 @@ clientNet.client?.sendInput({ move: { x: 1, y: 0 } }); // 每 tick 输入上
完整范式(复制、每 tick 输入、客户端预测)见 **Multiplayer Arena** 示例(约 130 行)。它的 `server/` 目录就是专用服务器那一半:同一个项目,无头运行,后面是一条真实的 WebSocket。
+要在这套范式上开始自己的游戏,用 **Online 3D** 模板创建(`estella create online-3d ./my-game`,或在编辑器的"新建项目"画廊里选):一块有光照的 3D 地面,每个玩家一个角色(在自己屏幕上即时预测、向其他人复制),跟随自己角色的镜头,以及用同一份代码无头运行的 `server/`。两端必须一致的规则(速度、世界边界)放在 `src/shared/rules.ts`,不在任何系统里,服务器才能拒绝它们禁止的事。模板留给游戏自己的部分写在它的 README 里:重连后保持玩家身份、保存世界、谁能看到什么。
+
### 兴趣管理——谁看见什么
默认每个客户端接收全部复制实体。世界大了以后,在服务器上装一个**兴趣策略**:
diff --git a/templates/online-3d/README.md b/templates/online-3d/README.md
new file mode 100644
index 000000000..400b3cd52
--- /dev/null
+++ b/templates/online-3d/README.md
@@ -0,0 +1,41 @@
+# Online 3D
+
+A server-authoritative multiplayer 3D world, small enough to read in one sitting: every player steers a capsule across a lit ground, the server
+decides where it is, and your own pawn answers the key the moment it goes down.
+
+## Run it
+
+Open the project in the editor, choose **2 Players (Listen Server)** (or 3 or 4) in the Play-mode menu and press **Play**. Player 1 is the authority in
+the usual Game view, and each other player gets a `Game P#` tab. WASD or the arrow keys walk the pawn; the camera follows your own.
+
+**Single Player** works too: the same systems run offline.
+
+## Where things live
+
+| File | What it holds |
+| --- | --- |
+| `src/shared/rules.ts` | The rules both ends run, with no engine in them: the speed, the world's edge, how keys become a direction. Anything a server must be able to refuse goes here. |
+| `src/net.ts` | The pawn (one archetype both ends build it from), provisioning, the movement the server applies and the client predicts, the camera. |
+| `src/main.ts` | Registers the systems on the fixed timestep. Nothing else. |
+| `server/` | The dedicated server: the same project, headless, behind a real WebSocket. |
+
+## Dedicated server
+
+The Play-mode preview runs the authority inside player 1's own process. That is the right shape for developing and the wrong one for shipping.
+
+```sh
+cd server
+npm install # ws, and esbuild to bundle with
+npm start # ws://127.0.0.1:8080, 60 Hz
+```
+
+`run.mjs` bundles `server/main.ts` with `esengine` aliased at the SDK's headless build and runs it. The SDK and the engine wasm are taken as a pair
+from what the editor staged in `.esengine/`, so open the project in the editor once, or pass `--sdk` and `--wasm`. `--port`, `--host` and `--fps`
+do what they look like. Nothing under `src/` is server-specific: the one line this process says about itself is `online.hostPlays = false`.
+
+## What a game of your own has to add
+
+- **Who a player is.** A player who reconnects arrives as a new connection and gets a new pawn: ownership is keyed on the connection, and the SDK has no
+ identity that outlives a socket. A stable id, a session token and a reconnect window belong to the game.
+- **What persists.** Nothing is saved. A world that outlives its players needs a store on the server, written from the authority's state.
+- **Who may see what.** Every client sees every pawn. `esengine/replication` has interest management for a world too big for that.
diff --git a/templates/online-3d/assets/scenes/main.esscene b/templates/online-3d/assets/scenes/main.esscene
new file mode 100644
index 000000000..720921add
--- /dev/null
+++ b/templates/online-3d/assets/scenes/main.esscene
@@ -0,0 +1,326 @@
+{
+ "version": 4,
+ "name": "Main",
+ "folders": [
+ "Lighting",
+ "World"
+ ],
+ "entities": [
+ {
+ "id": 0,
+ "name": "Camera",
+ "parent": null,
+ "children": [],
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 420,
+ "z": 900
+ },
+ "rotation": {
+ "x": -0.15643447,
+ "y": 0,
+ "z": 0,
+ "w": 0.98768834
+ }
+ }
+ },
+ {
+ "type": "Camera",
+ "data": {
+ "projectionType": 0,
+ "fov": 55,
+ "nearPlane": 10,
+ "farPlane": 5000,
+ "isActive": true,
+ "priority": 0,
+ "backgroundColor": {
+ "r": 0.09,
+ "g": 0.11,
+ "b": 0.15,
+ "a": 1
+ }
+ }
+ }
+ ],
+ "visible": true
+ },
+ {
+ "id": 1,
+ "name": "Sun",
+ "parent": null,
+ "children": [],
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 0
+ },
+ "rotation": {
+ "w": 0.83394695,
+ "x": -0.52086316,
+ "y": 0.18230211,
+ "z": 0
+ }
+ }
+ },
+ {
+ "type": "Light",
+ "data": {
+ "type": 1,
+ "intensity": 0.52,
+ "enabled": true,
+ "color": {
+ "r": 1,
+ "g": 0.96,
+ "b": 0.9,
+ "a": 1
+ }
+ }
+ }
+ ],
+ "visible": true,
+ "folder": "Lighting"
+ },
+ {
+ "id": 2,
+ "name": "Sky",
+ "parent": null,
+ "children": [],
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 0
+ }
+ }
+ },
+ {
+ "type": "Light",
+ "data": {
+ "type": 2,
+ "intensity": 0.09,
+ "enabled": true,
+ "color": {
+ "r": 0.55,
+ "g": 0.66,
+ "b": 0.85,
+ "a": 1
+ }
+ }
+ }
+ ],
+ "visible": true,
+ "folder": "Lighting"
+ },
+ {
+ "id": 3,
+ "name": "Ground",
+ "parent": null,
+ "children": [],
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 0
+ },
+ "scale": {
+ "x": 30,
+ "y": 1,
+ "z": 30
+ }
+ }
+ },
+ {
+ "type": "MeshRenderer",
+ "data": {
+ "mesh": "builtin:plane",
+ "lit": true,
+ "opaque": true,
+ "cullBackfaces": false,
+ "color": {
+ "r": 0.3,
+ "g": 0.36,
+ "b": 0.3,
+ "a": 1
+ }
+ }
+ }
+ ],
+ "visible": true,
+ "folder": "World"
+ },
+ {
+ "id": 4,
+ "name": "Tower",
+ "parent": null,
+ "children": [],
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": -600,
+ "y": 300,
+ "z": -500
+ },
+ "scale": {
+ "x": 2,
+ "y": 6,
+ "z": 2
+ }
+ }
+ },
+ {
+ "type": "MeshRenderer",
+ "data": {
+ "mesh": "builtin:cube",
+ "lit": true,
+ "opaque": true,
+ "cullBackfaces": true,
+ "color": {
+ "r": 0.72,
+ "g": 0.55,
+ "b": 0.35,
+ "a": 1
+ }
+ }
+ }
+ ],
+ "visible": true,
+ "folder": "World"
+ },
+ {
+ "id": 5,
+ "name": "Wall",
+ "parent": null,
+ "children": [],
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 500,
+ "y": 80.0,
+ "z": -700
+ },
+ "scale": {
+ "x": 8,
+ "y": 1.6,
+ "z": 0.8
+ }
+ }
+ },
+ {
+ "type": "MeshRenderer",
+ "data": {
+ "mesh": "builtin:cube",
+ "lit": true,
+ "opaque": true,
+ "cullBackfaces": true,
+ "color": {
+ "r": 0.55,
+ "g": 0.62,
+ "b": 0.7,
+ "a": 1
+ }
+ }
+ }
+ ],
+ "visible": true,
+ "folder": "World"
+ },
+ {
+ "id": 6,
+ "name": "Plinth",
+ "parent": null,
+ "children": [],
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 700,
+ "y": 40.0,
+ "z": 400
+ },
+ "scale": {
+ "x": 3,
+ "y": 0.8,
+ "z": 3
+ }
+ }
+ },
+ {
+ "type": "MeshRenderer",
+ "data": {
+ "mesh": "builtin:cube",
+ "lit": true,
+ "opaque": true,
+ "cullBackfaces": true,
+ "color": {
+ "r": 0.62,
+ "g": 0.45,
+ "b": 0.55,
+ "a": 1
+ }
+ }
+ }
+ ],
+ "visible": true,
+ "folder": "World"
+ },
+ {
+ "id": 7,
+ "name": "Steps",
+ "parent": null,
+ "children": [],
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": -700,
+ "y": 25.0,
+ "z": 600
+ },
+ "scale": {
+ "x": 4,
+ "y": 0.5,
+ "z": 2
+ }
+ }
+ },
+ {
+ "type": "MeshRenderer",
+ "data": {
+ "mesh": "builtin:cube",
+ "lit": true,
+ "opaque": true,
+ "cullBackfaces": true,
+ "color": {
+ "r": 0.5,
+ "g": 0.66,
+ "b": 0.5,
+ "a": 1
+ }
+ }
+ }
+ ],
+ "visible": true,
+ "folder": "World"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/templates/online-3d/assets/scenes/main.esscene.meta b/templates/online-3d/assets/scenes/main.esscene.meta
new file mode 100644
index 000000000..3e45ce929
--- /dev/null
+++ b/templates/online-3d/assets/scenes/main.esscene.meta
@@ -0,0 +1,8 @@
+{
+ "uuid": "a26ae95e-cbdc-4d87-8d78-f0bc2c50e596",
+ "version": "2.0",
+ "type": "scene",
+ "importer": {
+ "autoMigrate": true
+ }
+}
diff --git a/templates/online-3d/project.esproject b/templates/online-3d/project.esproject
new file mode 100644
index 000000000..60a6a1710
--- /dev/null
+++ b/templates/online-3d/project.esproject
@@ -0,0 +1,19 @@
+{
+ "formatVersion": "1",
+ "name": "Online 3D",
+ "tag": "Starter",
+ "description": "A server-authoritative multiplayer 3D world: every player walks a pawn that is predicted at once on their own screen, with a dedicated server that runs the same code headless.",
+ "version": "0.1.0",
+ "defaultScene": "assets/scenes/main.esscene",
+ "designResolution": {
+ "width": 960,
+ "height": 640
+ },
+ "spineVersion": "none",
+ "features": {
+ "rendering": {
+ "colorSpace": "linear",
+ "outputTransform": "aces"
+ }
+ }
+}
diff --git a/templates/online-3d/server/main.ts b/templates/online-3d/server/main.ts
new file mode 100644
index 000000000..8033bf2c3
--- /dev/null
+++ b/templates/online-3d/server/main.ts
@@ -0,0 +1,140 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The dedicated server for this game — the same project, no window.
+ *
+ * The editor's "2 Players (Listen Server)" preview runs the authority inside a
+ * player's own process over in-memory ports. That is the right shape for
+ * developing, and the wrong shape for shipping: it needs somebody's game to be
+ * running, and it never exercises a connection that DROPS.
+ *
+ * This entry is the shipping shape. It boots the same engine wasm with no
+ * renderer (`createHeadlessApp`), installs the project's own systems through
+ * the same door the shipped web runtime uses (`flushPendingRegistrations`), and
+ * accepts real WebSocket clients. Not one line of `src/` is server-specific —
+ * the only thing this process says about itself is `online.hostPlays = false`,
+ * because there is nobody at a keyboard here.
+ *
+ * node server/run.mjs --port 8080
+ *
+ * A browser client then connects to `ws://<host>:8080` instead of being handed
+ * a MessagePort. See the README's "Dedicated server" section.
+ */
+import { WebSocketServer, type WebSocket } from 'ws';
+import {
+ loadEsengineModule, createHeadlessApp, runHeadless,
+ flushPendingRegistrations, type ReliableOrderedTransport,
+} from 'esengine/node';
+// Replication is a subpath on every entry, the headless one included: importing
+// it is what installs the authority this process exists to run.
+import { Net } from 'esengine/replication';
+import { online } from '../src/net';
+// Side-effect import: `src/main.ts` registers the game's systems at module
+// scope, exactly as it does in the browser. The server runs the project's real
+// entry point rather than a reimplementation of it.
+import '../src/main';
+
+interface ServerOptions {
+ port: number;
+ host: string;
+ /** Directory holding the web engine build (esengine.js + esengine.wasm). */
+ wasm: string;
+ /** Simulation rate. The replication cadence follows the fixed timestep. */
+ fps: number;
+}
+
+/**
+ * One accepted `ws` connection, as the transport replication asks for: send a
+ * frame, subscribe to frames, and a claim that the link loses and reorders
+ * nothing. A WebSocket does neither, so the claim is honest here; a transport
+ * that cannot make it is refused at compile time rather than desynchronizing.
+ */
+function wsTransport(socket: WebSocket): ReliableOrderedTransport {
+ const handlers = new Set<(data: string | ArrayBuffer) => void>();
+ socket.on('message', (data: Buffer | ArrayBuffer | Buffer[], isBinary: boolean) => {
+ // Binary frames are the delta stream and must reach the channel as an
+ // ArrayBuffer; `ws` hands over a Buffer that is usually a VIEW into a
+ // larger pooled allocation, so the byte range has to be sliced out.
+ const frame = isBinary ? toArrayBuffer(data) : String(data);
+ for (const handler of [...handlers]) handler(frame);
+ });
+ return {
+ delivery: 'reliable-ordered',
+ send: (data) => socket.send(data),
+ on: (_event, handler) => {
+ handlers.add(handler);
+ return () => handlers.delete(handler);
+ },
+ };
+}
+
+function toArrayBuffer(data: Buffer | ArrayBuffer | Buffer[]): ArrayBuffer {
+ if (data instanceof ArrayBuffer) return data;
+ const buf = Array.isArray(data) ? Buffer.concat(data) : data;
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength) as ArrayBuffer;
+}
+
+export async function startServer(options: ServerOptions): Promise<() => Promise<void>> {
+ // No keyboard on this machine, so no pawn for player 0 — the one line that
+ // separates a dedicated server from the editor's listen server.
+ online.hostPlays = false;
+
+ const engineModule = await loadEsengineModule(options.wasm);
+ const app = createHeadlessApp(engineModule);
+ // Install what `src/main.ts` registered at import time. Before the loop
+ // starts, so the authority's first tick already runs the game's systems.
+ flushPendingRegistrations(app);
+
+ const server = app.getResource(Net).startServer();
+
+ const wss = new WebSocketServer({ port: options.port, host: options.host });
+ await new Promise<void>((resolve, reject) => {
+ wss.once('listening', resolve);
+ wss.once('error', reject);
+ });
+
+ wss.on('connection', (socket: WebSocket) => {
+ const id = server.attachConnection(wsTransport(socket));
+ console.log(`[server] connection ${id} attached`);
+ // Detaching is what makes the roster shrink: `clientIds` drops this id,
+ // and ProvisionPawnsSystem retires the pawn on its next fixed tick.
+ // Without it the world fills up with pawns nobody is steering.
+ const drop = () => {
+ server.detachConnection(id);
+ console.log(`[server] connection ${id} dropped`);
+ };
+ socket.on('close', drop);
+ socket.on('error', drop);
+ });
+
+ const stopLoop = runHeadless(app, { fps: options.fps });
+ const address = wss.address();
+ const port = typeof address === 'object' && address ? address.port : options.port;
+ console.log(`[server] listening on ws://${options.host}:${port} (${options.fps} Hz)`);
+
+ return async () => {
+ stopLoop();
+ await new Promise<void>((resolve) => wss.close(() => resolve()));
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Command line. `--port 0` asks the OS for a free port and prints the one it
+// got, which is how the repo's gate runs this without picking a fixed number.
+// ---------------------------------------------------------------------------
+
+function arg(name: string, fallback: string): string {
+ const i = process.argv.indexOf(`--${name}`);
+ return i >= 0 && process.argv[i + 1] ? process.argv[i + 1] : fallback;
+}
+
+const stop = await startServer({
+ port: Number(arg('port', '8080')),
+ host: arg('host', '127.0.0.1'),
+ wasm: arg('wasm', 'wasm'),
+ fps: Number(arg('fps', '60')),
+});
+
+for (const signal of ['SIGINT', 'SIGTERM'] as const) {
+ process.on(signal, () => { void stop().then(() => process.exit(0)); });
+}
diff --git a/templates/online-3d/server/package.json b/templates/online-3d/server/package.json
new file mode 100644
index 000000000..facd9042c
--- /dev/null
+++ b/templates/online-3d/server/package.json
@@ -0,0 +1,16 @@
+{
+ "name": "online-3d-server",
+ "private": true,
+ "type": "module",
+ "description": "Dedicated server for this game — the same project, headless.",
+ "scripts": {
+ "start": "node run.mjs",
+ "build": "node run.mjs --build-only"
+ },
+ "dependencies": {
+ "ws": "^8.21.0"
+ },
+ "devDependencies": {
+ "esbuild": "^0.27.0"
+ }
+}
diff --git a/templates/online-3d/server/run.mjs b/templates/online-3d/server/run.mjs
new file mode 100644
index 000000000..d1b416a5f
--- /dev/null
+++ b/templates/online-3d/server/run.mjs
@@ -0,0 +1,108 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Build-and-run for the game's dedicated server.
+ *
+ * The gameplay under `src/` is TypeScript that imports the bare specifier
+ * `esengine`, exactly like the code the browser runs. A server is the same
+ * project pointed at a different SDK build, so this does what every other
+ * Estella export already does: bundle the entry with esbuild and alias
+ * `esengine` at the SDK flavour this platform needs — here `index.node.js`,
+ * the headless one.
+ *
+ * Aliasing BOTH `esengine` and `esengine/node` to the same file is not a
+ * detail: two SDK copies would mean two component registries, and the
+ * handshake's schema check would reject the server's own clients.
+ *
+ * node server/run.mjs [--port 8080] [--host 127.0.0.1] [--fps 60]
+ * [--sdk <dir>] [--wasm <dir>] [--build-only]
+ *
+ * `--sdk` and `--wasm` default to what the editor stages inside the project
+ * (`.esengine/sdk`, `.esengine/play/wasm`),
+ */
+import { spawn } from 'node:child_process';
+import { existsSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const PROJECT = path.resolve(HERE, '..');
+
+const argv = process.argv.slice(2);
+function flag(name, fallback) {
+ const i = argv.indexOf(`--${name}`);
+ return i >= 0 && argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[i + 1] : fallback;
+}
+/**
+ * SDK and wasm are resolved as a PAIR, never independently: they carry a shared
+ * ABI layout hash and the engine refuses a module built from another component
+ * schema. A fresh SDK beside a wasm an old editor session staged is the easy
+ * mistake, and it dies at boot with a hash mismatch, not anywhere useful.
+ */
+const PAIRS = [
+ // What the editor stages inside a project when it opens it.
+ { sdk: path.join(PROJECT, '.esengine', 'sdk'), wasm: path.join(PROJECT, '.esengine', 'play', 'wasm') },
+];
+const pair = PAIRS.find((c) => existsSync(path.join(c.sdk, 'index.node.js')) && existsSync(path.join(c.wasm, 'esengine.wasm')))
+ ?? PAIRS[PAIRS.length - 1];
+
+const sdkDir = path.resolve(flag('sdk', pair.sdk));
+const wasmDir = path.resolve(flag('wasm', pair.wasm));
+
+for (const [what, dir, needs] of [
+ ['SDK', sdkDir, 'index.node.js'],
+ ['engine wasm', wasmDir, 'esengine.wasm'],
+]) {
+ if (existsSync(path.join(dir, needs))) continue;
+ console.error(`game server: no ${what} at ${dir} (looked for ${needs}).`);
+ console.error(` Open the project in the editor once, or pass --${what === 'SDK' ? 'sdk' : 'wasm'} <dir>.`);
+ process.exit(2);
+}
+
+const sdkEntry = path.join(sdkDir, 'index.node.js');
+const outfile = path.join(PROJECT, '.esengine', 'cache', 'server.mjs');
+
+const { build } = await import('esbuild');
+await build({
+ entryPoints: [path.join(HERE, 'main.ts')],
+ outfile,
+ bundle: true,
+ format: 'esm',
+ platform: 'node',
+ target: 'node20',
+ sourcemap: true,
+ logLevel: 'info',
+ // `ws` is CommonJS: the bundle calls `require('events')` and an ESM output has
+ // no `require`. Building one from this module's URL is the esbuild recipe —
+ // only node builtins reach it, everything else is already inlined.
+ banner: {
+ js: "import { createRequire as __estellaCreateRequire } from 'node:module';\n"
+ + 'const require = __estellaCreateRequire(import.meta.url);',
+ },
+ // One SDK instance, whichever specifier reached it.
+ alias: {
+ esengine: sdkEntry, 'esengine/node': sdkEntry,
+ // The same shared chunks as the entry beside it — one core, or the
+ // handshake compares two copies of the schema.
+ 'esengine/replication': path.join(sdkDir, 'net', 'replication', 'index.js'),
+ },
+ // `ws` is a real dependency of the server (and only of the server): resolve it
+ // from the server's own install first, then from the engine checkout.
+ // `ws` is the server's own dependency: its own install first, then the project's, then wherever NODE_PATH says.
+ nodePaths: [path.join(HERE, 'node_modules'), path.join(PROJECT, 'node_modules'), ...(process.env.NODE_PATH?.split(path.delimiter) ?? [])]
+ .filter((p) => p && existsSync(p)),
+});
+
+if (argv.includes('--build-only')) {
+ console.log(`game server: built ${outfile}`);
+ process.exit(0);
+}
+
+// The wasm directory is resolved against the server process's cwd, so pass it
+// absolute and let the child run wherever it likes.
+const passthrough = ['port', 'host', 'fps'].flatMap((name) => {
+ const value = flag(name, null);
+ return value === null ? [] : [`--${name}`, value];
+});
+const child = spawn(process.execPath, [outfile, '--wasm', wasmDir, ...passthrough], { stdio: 'inherit' });
+child.on('exit', (code, signal) => process.exit(signal ? 1 : (code ?? 0)));
diff --git a/templates/online-3d/server/tsconfig.json b/templates/online-3d/server/tsconfig.json
new file mode 100644
index 000000000..631d37db6
--- /dev/null
+++ b/templates/online-3d/server/tsconfig.json
@@ -0,0 +1,16 @@
+{
+ "//": "The server is a separate program from the game: Node built-ins, its own deps, and the headless SDK entry. The project's root tsconfig covers src/ only, so this one holds the server half. It only ever checks — run.mjs builds with esbuild.",
+ "extends": "../tsconfig.json",
+ "compilerOptions": {
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "types": ["node"],
+ "noEmit": true,
+ "paths": {
+ "esengine": ["../.esengine/sdk/index.d.ts"],
+ "esengine/node": ["../.esengine/sdk/index.node.d.ts"],
+ "esengine/wasm": ["../.esengine/sdk/wasm.d.ts"]
+ }
+ },
+ "include": ["**/*.ts", "../src/**/*.ts"]
+}
diff --git a/templates/online-3d/src/components.ts b/templates/online-3d/src/components.ts
new file mode 100644
index 000000000..1a3cfab8d
--- /dev/null
+++ b/templates/online-3d/src/components.ts
@@ -0,0 +1,11 @@
+import { defineComponent } from 'esengine';
+
+/**
+ * A player-steered pawn. `player` is the owning connection id (0 = the host player) and is AUTHORITY-side only: provisioning matches pawns to
+ * players with it, and a ghost learns the same fact as `Replicated.owner`, which the spawn carries. `speed` comes from the `pawn` archetype on
+ * both ends, which is what lets client prediction run the same rule.
+ */
+export const Pawn = defineComponent('Pawn', {
+ player: 0,
+ speed: 340,
+});
diff --git a/templates/online-3d/src/main.ts b/templates/online-3d/src/main.ts
new file mode 100644
index 000000000..f2f89beb3
--- /dev/null
+++ b/templates/online-3d/src/main.ts
@@ -0,0 +1,13 @@
+import { addSystemToSchedule, Schedule } from 'esengine';
+import { loadPawnMeshSystem, provisionPawnsSystem, movePawnsSystem, sendInputSystem, paintPawnsSystem, followOwnPawnSystem } from './net';
+
+addSystemToSchedule(Schedule.Startup, loadPawnMeshSystem);
+
+// Netcode lives on the fixed timestep, the replication cadence: the authority provisions and simulates there and the client uplinks its input there.
+// Each system gates on the Net role, so one set of code runs as the listen server, a client, a dedicated server, or plain offline single-player.
+addSystemToSchedule(Schedule.FixedUpdate, provisionPawnsSystem);
+addSystemToSchedule(Schedule.FixedUpdate, movePawnsSystem);
+addSystemToSchedule(Schedule.FixedUpdate, sendInputSystem);
+// Presentation: the colour is derived from ownership, and the camera takes the eye to your own pawn, at the display's own rate.
+addSystemToSchedule(Schedule.FixedUpdate, paintPawnsSystem);
+addSystemToSchedule(Schedule.PostUpdate, followOwnPawnSystem);
diff --git a/templates/online-3d/src/net.ts b/templates/online-3d/src/net.ts
new file mode 100644
index 000000000..d14f6a393
--- /dev/null
+++ b/templates/online-3d/src/net.ts
@@ -0,0 +1,167 @@
+import {
+ defineSystem, Res, GetWorld, Time, Input, Transform, MeshRenderer, Camera, Assets,
+ type World, type Entity, type InputState,
+} from 'esengine';
+// Replication is a subpath: a package that imports it carries the protocol, and one that does not carries none of it.
+import { Net, Replicated, registerReplicationArchetype } from 'esengine/replication';
+import { Pawn } from './components';
+import { PAWN_HEIGHT, moveFromKeys, stepPosition, type Move } from './shared/rules';
+
+/** The player id of whoever sits at THIS machine's keyboard when it also hosts. Connection ids a server hands out start at 1. */
+const HOST_PLAYER = 0;
+
+/**
+ * The one thing a listen server and a dedicated server disagree about. The editor preview (and offline Play) hosts player 0 on the local
+ * keyboard; a dedicated server has none, sets `hostPlays = false` at startup, and owns no pawn.
+ */
+export const online = { hostPlays: true };
+
+/** The stock capsule every pawn is drawn as. A mesh is a handle, which has to be loaded; a pawn built before it is there is given it by `paintPawnsSystem`. */
+let capsuleMesh = 0;
+export const loadPawnMeshSystem = defineSystem(
+ [Res(Assets)],
+ (assets) => {
+ // A headless process (the dedicated server) draws nothing and has no renderer to load a mesh into: nothing there needs the handle.
+ assets.load<{ handle: number }>('mesh', 'builtin:capsule').then((m) => { capsuleMesh = m.handle; }, () => undefined);
+ },
+ { name: 'LoadPawnMeshSystem' },
+);
+
+const PLAYER_COLORS = [
+ { r: 0.35, g: 0.85, b: 1.0, a: 1 },
+ { r: 1.0, g: 0.55, b: 0.35, a: 1 },
+ { r: 0.55, g: 1.0, b: 0.45, a: 1 },
+ { r: 0.95, g: 0.5, b: 1.0, a: 1 },
+];
+
+function readMove(input: InputState): Move {
+ return moveFromKeys(
+ input.isKeyDown('KeyA') || input.isKeyDown('ArrowLeft'), input.isKeyDown('KeyD') || input.isKeyDown('ArrowRight'),
+ input.isKeyDown('KeyW') || input.isKeyDown('ArrowUp'), input.isKeyDown('KeyS') || input.isKeyDown('ArrowDown'),
+ );
+}
+
+/** THE movement rule, applied by the server per connection per tick and by the client as its prediction. */
+function applyMove(world: World, entity: Entity, actions: Record<string, unknown>, dt: number): void {
+ const move = actions.move as Move | undefined;
+ if (!move || (move.x === 0 && move.z === 0)) return;
+ const pawn = world.tryGet(entity, Pawn);
+ const transform = world.tryGet(entity, Transform);
+ if (!pawn || !transform) return;
+ const next = stepPosition(transform.position.x, transform.position.z, move, pawn.speed, dt);
+ transform.position.x = next.x;
+ transform.position.z = next.z;
+ world.set(entity, Transform, transform);
+}
+
+/**
+ * What a pawn IS, in one place: the authority builds one with it and so does every client, because it is registered as the ghost's construction
+ * contract. A spawn carries identity and declared state, never a dump of the server's components, so what a proxy needs to exist is said here.
+ */
+function buildPawn(world: World, entity: Entity): void {
+ world.insert(entity, MeshRenderer, { mesh: capsuleMesh, lit: true, opaque: true, cullBackfaces: true });
+ world.insert(entity, Pawn, {});
+ if (world.tryGet(entity, Transform)) world.update(entity, Transform, (d) => { (d as { scale: unknown }).scale = { x: 1.6, y: 1.6, z: 1.6 }; });
+}
+registerReplicationArchetype('pawn', buildPawn);
+
+function spawnPawn(world: World, player: number): void {
+ const e = world.spawn(`Pawn P${player + 1}`);
+ world.insert(e, Transform, { position: { x: -300 + player * 200, y: PAWN_HEIGHT, z: 300 } });
+ buildPawn(world, e);
+ world.update(e, Pawn, (d) => { (d as { player: number }).player = player; });
+ // Marking it Replicated is all it takes: it spawns on every client through the archetype, its pose streams as deltas, and `owner` routes that
+ // connection's input to it.
+ world.insert(e, Replicated, { owner: player, archetype: 'pawn' });
+}
+
+/** Colour from ownership, on whichever end is looking: the client is given `owner`, and the colour is derived from it by the same rule everywhere. */
+export const paintPawnsSystem = defineSystem(
+ [GetWorld()],
+ (world) => {
+ for (const e of world.getEntitiesWithComponents([Pawn, MeshRenderer, Replicated])) {
+ const owner = (world.tryGet(e, Replicated) as { owner: number }).owner;
+ const want = PLAYER_COLORS[owner % PLAYER_COLORS.length]!;
+ const mesh = world.tryGet(e, MeshRenderer) as { mesh: number; color: { r: number; g: number; b: number } };
+ const painted = mesh.color.r === want.r && mesh.color.g === want.g && mesh.color.b === want.b;
+ if (painted && (mesh.mesh === capsuleMesh || capsuleMesh === 0)) continue;
+ world.update(e as Entity, MeshRenderer, (d) => { (d as { color: unknown; mesh: number }).color = { ...want }; (d as { mesh: number }).mesh = capsuleMesh; });
+ }
+ },
+ { name: 'PaintPawnsSystem' },
+);
+
+/** Authority-side provisioning, both directions: a player owed a pawn gets one, and a pawn whose player left is retired. */
+export const provisionPawnsSystem = defineSystem(
+ [GetWorld(), Res(Net)],
+ (world, net) => {
+ if (net.role === 'client') return;
+ const live = new Set<number>();
+ if (online.hostPlays) live.add(HOST_PLAYER);
+ for (const id of net.server?.clientIds ?? []) live.add(id);
+
+ const have = new Set<number>();
+ for (const e of world.getEntitiesWithComponents([Pawn])) {
+ const player = (world.tryGet(e, Pawn) as { player: number }).player;
+ if (!live.has(player)) {
+ // Despawning the authority's entity is the whole retirement: replication makes it a despawn on every client that sees it.
+ world.despawn(e as Entity);
+ continue;
+ }
+ have.add(player);
+ }
+ for (const player of live) if (!have.has(player)) spawnPawn(world, player);
+ },
+ { name: 'ProvisionPawnsSystem' },
+);
+
+/** Authority-side movement: the host pawn reads the local keyboard, the others consume their connection's input queue, one command per tick. */
+export const movePawnsSystem = defineSystem(
+ [GetWorld(), Res(Net), Res(Input), Res(Time)],
+ (world, net, input, time) => {
+ if (net.role === 'client') return;
+ for (const e of world.getEntitiesWithComponents([Pawn, Replicated])) {
+ const repl = world.tryGet(e, Replicated)!;
+ const actions = repl.owner === HOST_PLAYER ? { move: readMove(input) } : (net.server?.tickInputOf(repl.owner)?.actions ?? {});
+ applyMove(world as World, e as Entity, actions, time.fixedDelta);
+ }
+ },
+ { name: 'MovePawnsSystem' },
+);
+
+/** Client-side input uplink and prediction: one command per fixed tick, an idle move included, with the same rule the server runs. */
+export const sendInputSystem = defineSystem(
+ [Res(Net), Res(Input)],
+ (net, input) => {
+ if (net.role !== 'client' || !net.client) return;
+ if (!net.client.predictionEnabled) net.client.enablePrediction({ apply: applyMove, smoothing: { halfLife: 0.08 } });
+ net.client.sendInput({ move: readMove(input) });
+ },
+ { name: 'SendInputSystem' },
+);
+
+/** The camera follows your own pawn: the one whose owner is this connection (or the host's, where this machine hosts). */
+export const followOwnPawnSystem = defineSystem(
+ [GetWorld(), Res(Net), Res(Time)],
+ (world, net, time) => {
+ const mine = net.role === 'client' ? net.client?.connectionId ?? 0 : (online.hostPlays ? HOST_PLAYER : -1);
+ if (mine < 0 || (net.role === 'client' && mine === 0)) return;
+ let target: { x: number; z: number } | null = null;
+ for (const e of world.getEntitiesWithComponents([Pawn, Replicated])) {
+ if ((world.tryGet(e, Replicated) as { owner: number }).owner !== mine) continue;
+ target = (world.tryGet(e, Transform) as { position: { x: number; z: number } }).position;
+ break;
+ }
+ if (!target) return;
+ const t = Math.min(1, 5 * time.delta);
+ for (const e of world.getEntitiesWithComponents([Camera, Transform])) {
+ const p = (world.tryGet(e, Transform) as { position: { x: number; y: number; z: number } }).position;
+ world.update(e as Entity, Transform, (d) => {
+ const pos = (d as { position: { x: number; z: number } }).position;
+ pos.x = p.x + (target!.x - p.x) * t;
+ pos.z = p.z + (target!.z + 900 - p.z) * t;
+ });
+ }
+ },
+ { name: 'FollowOwnPawnSystem' },
+);
diff --git a/templates/online-3d/src/shared/rules.ts b/templates/online-3d/src/shared/rules.ts
new file mode 100644
index 000000000..50a5952bf
--- /dev/null
+++ b/templates/online-3d/src/shared/rules.ts
@@ -0,0 +1,26 @@
+/**
+ * The rules both ends run, with nothing of the engine in them: the server applies them to each connection's input, and the client applies the
+ * same ones as its prediction, so a player's own pawn answers the key at once and the server's word rarely disagrees. Put anything a server must
+ * be able to refuse (a speed, a wall, a build rule) here and not in a system, and the two cannot drift apart.
+ */
+
+/** Half the walkable ground, in world units: the pawn is held inside it. */
+export const WORLD_HALF = 1450;
+/** The height a pawn stands at above the ground plane. */
+export const PAWN_HEIGHT = 80;
+
+export interface Move { x: number; z: number }
+
+/** The ground position one fixed step takes a pawn to: `move` is a unit direction (or zero), `speed` is units a second, held inside the world. */
+export function stepPosition(x: number, z: number, move: Move, speed: number, dt: number): { x: number; z: number } {
+ const clamp = (v: number): number => Math.min(WORLD_HALF, Math.max(-WORLD_HALF, v));
+ return { x: clamp(x + move.x * speed * dt), z: clamp(z + move.z * speed * dt) };
+}
+
+/** A direction from which keys are down: the diagonal is normalised, or two keys would be about 1.4 times faster than one. */
+export function moveFromKeys(left: boolean, right: boolean, forward: boolean, back: boolean): Move {
+ const x = (right ? 1 : 0) - (left ? 1 : 0);
+ const z = (back ? 1 : 0) - (forward ? 1 : 0);
+ const length = Math.hypot(x, z);
+ return length > 0 ? { x: x / length, z: z / length } : { x: 0, z: 0 };
+}
diff --git a/templates/online-3d/tsconfig.json b/templates/online-3d/tsconfig.json
new file mode 100644
index 000000000..20e787135
--- /dev/null
+++ b/templates/online-3d/tsconfig.json
@@ -0,0 +1,22 @@
+{
+ "compilerOptions": {
+ "target": "ES2020",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "strict": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "forceConsistentCasingInFileNames": true,
+ "declaration": false,
+ "outDir": "./dist",
+ "rootDir": ".",
+ "paths": {
+ "esengine": ["./.esengine/sdk/index.d.ts"],
+ "estella-plugin-*": ["./.esengine/packages/*"],
+ "esengine/wasm": ["./.esengine/sdk/wasm.d.ts"],
+ "esengine/replication": ["./.esengine/sdk/net/replication/index.d.ts"]
+ }
+ },
+ "include": ["src/**/*"],
+ "exclude": ["node_modules"]
+}
diff --git a/tools/check-arena-server.mjs b/tools/check-arena-server.mjs
index 81d2bf97a..00eff29e4 100644
--- a/tools/check-arena-server.mjs
+++ b/tools/check-arena-server.mjs
@@ -22,6 +22,10 @@
* 5. a client that leaves takes its pawn with it
*
* node tools/check-arena-server.mjs
+ * node tools/check-arena-server.mjs --project templates/online-3d --bound 1450 --speed 340
+ *
+ * The project is any one with a `server/` and a pawn that walks right on `KeyD`; `--bound` is the world's edge along x and `--speed` the pawn's
+ * speed, both from the project's own movement rule.
*/
import { spawn, spawnSync } from 'node:child_process';
import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
@@ -30,12 +34,17 @@ import path from 'node:path';
import { pathToFileURL, fileURLToPath } from 'node:url';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
-const PROJECT = path.join(ROOT, 'examples', 'multiplayer-arena');
+const flag = (name, fallback) => {
+ const i = process.argv.indexOf(`--${name}`);
+ return i >= 0 && process.argv[i + 1] ? process.argv[i + 1] : fallback;
+};
+const PROJECT = path.resolve(ROOT, flag('project', path.join('examples', 'multiplayer-arena')));
const SDK = path.join(ROOT, 'sdk', 'dist', 'index.node.js');
const WASM = path.join(ROOT, 'build', 'wasm', 'web');
-/** Arena bounds, from the example's own movement rule. */
-const BOUND_X = 420;
+/** The world's edge along x and the pawn's speed, from the project's own movement rule (the arena's by default). */
+const BOUND_X = Number(flag('bound', '420'));
+const SPEED = Number(flag('speed', '260'));
const STEP = 1 / 60;
// The server runs a REAL engine, so a checkout without one cannot answer this.
@@ -54,6 +63,7 @@ if (!existsSync(path.join(WASM, 'esengine.wasm'))) {
}
const work = mkdtempSync(path.join(tmpdir(), 'estella-arena-'));
+const NAME = path.basename(PROJECT);
let server = null;
function fail(message, detail) {
@@ -107,9 +117,14 @@ if (typed.status !== 0) {
fail('the server entry does not type-check against the SDK.', typed.stdout || typed.stderr);
}
+// The SDK and wasm are this checkout's own, a pair: a template's server has no engine tree beside it to fall back to.
const built = spawnSync(process.execPath, [
- path.join(PROJECT, 'server', 'run.mjs'), '--build-only',
-], { encoding: 'utf8', cwd: ROOT });
+ path.join(PROJECT, 'server', 'run.mjs'), '--build-only', '--sdk', path.dirname(SDK), '--wasm', WASM,
+], {
+ encoding: 'utf8', cwd: ROOT,
+ // `ws` is the server's own dependency; in this checkout it is installed with the SDK, which a template has no tree beside it to find.
+ env: { ...process.env, NODE_PATH: [path.join(ROOT, 'sdk', 'node_modules'), path.join(ROOT, 'node_modules')].join(path.delimiter) },
+});
if (built.status !== 0) fail('the server bundle failed to build.', built.stderr || built.stdout);
/**
@@ -258,7 +273,7 @@ if (!(movedX > startX + 20)) {
// Long enough to cross the arena and pin against the wall. The clamp is part of
// the shared movement rule, so server and prediction must agree on it exactly.
-await run([player.app, spectator.app], 3.0);
+await run([player.app, spectator.app], (BOUND_X * 2) / SPEED + 1);
input.keysDown.delete('KeyD');
const wallX = own().x;
if (Math.abs(wallX - BOUND_X) > 0.5) {
@@ -290,5 +305,5 @@ if (after.length !== 1) {
spectator.client.disconnect();
spectator.socket.close();
cleanup();
-console.log('check-arena-server: multiplayer-arena served headless over a real socket —'
- + ' no host phantom, input moved and clamped, replicated to a third party, and a leaver was retired.');
+console.log(`check-arena-server: ${NAME} served headless over a real socket — no host phantom, input moved and clamped,`
+ + ' replicated to a third party, and a leaver was retired.');
diff --git a/tools/gates.mjs b/tools/gates.mjs
index a17a0dca6..3a167858b 100644
--- a/tools/gates.mjs
+++ b/tools/gates.mjs
@@ -160,6 +160,13 @@ export const GATES = [
why: 'the server it starts runs the real engine wasm, and the fast CI lane builds none;'
+ ' the engine-coupled job runs it where the artifact is, under ESTELLA_REQUIRE_WASM',
},
+ // The starter a networked game begins from: the same facts, checked against the template itself so it cannot rot unseen.
+ {
+ id: 'online-3d-server',
+ run: 'node tools/check-arena-server.mjs --project templates/online-3d --bound 1450 --speed 340',
+ where: 'local',
+ why: 'it starts a server on the real engine wasm too; the engine-coupled job runs it',
+ },
{ id: 'cycles', run: 'node tools/check-cycles.mjs' },
{ id: 'layers', run: 'node tools/check-layers.mjs' },
// A system's parameters are what the schedule knows about it; the World
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 5ed8ac0ce..d890b545c 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -2874,6 +2874,8 @@ export const NOTED = {
{"note":"Start a project from the command line."},
"refactor(launcher): a new project is made by the pipeline's template code, shared with the command line":
{"note":"Start a project from the command line."},
+ "feat(templates): an Online 3D starter, a networked 3D game with a dedicated server that runs the same project":
+ {"note":"An Online 3D starter."},
"feat(water): two tiled, scrolling detail normal maps give the surface its sparkle":
{"note":"Sparkle on the water."},
"fix(lod): a LODGroup with only a cull size is no longer ignored":