Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -244,3 +244,6 @@ references/
packages/old-core/
playwright-report/
test-results/

# Copies made by pnpm examples
.examples/
2 changes: 1 addition & 1 deletion .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ pnpm-workspace.yaml

packages/
modules/
example/
utils/
releases/
.nanoforge/
.examples/

.turbo/
node_modules/
Expand Down
11 changes: 4 additions & 7 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ Nanoforge Engine is Nanoforge's game engine for the web browser. It is a monorep

## Project Structure

A pnpm monorepo with several package folders grouped by role (`packages/*`, `modules/*`, `utils/*`), plus test apps (`e2e/game`, `e2e/game-2d`, `e2e/game-3d`) and example games (`example/*`).
A pnpm monorepo with several package folders grouped by role (`packages/*`, `modules/*`, `utils/*`), plus test apps (`e2e/game`, `e2e/game-2d`, `e2e/game-3d`). The example games live in the [examples](https://github.com/NanoForge-dev/examples) repo; `pnpm examples` copies some of them here to test them against this engine (see Main Commands).

```
Engine/
Expand All @@ -48,15 +48,11 @@ Engine/
│ ├── game-2d/ @nanoforge-dev/e2e-game-2d (private) — 2D game rendered by the graphics e2e tests
│ ├── game-3d/ @nanoforge-dev/e2e-game-3d (private) — 3D game rendered by the graphics e2e tests
│ └── graphics/ Playwright specs (<game>.spec.ts) and their reference screenshots; not a package
├── example/ # Example games (unscoped private packages)
│ ├── pong-network/ Networked Pong, used as an integration test
│ ├── pong-3d/ Networked 3D Pong (graphics-3d + network)
│ └── cube-3d/ Minimal graphics-3d scene
├── docs/
│ ├── docs/ Hand-written Mintlify pages (one folder per topic) + navigation.json
│ ├── design/ Design proposals (e.g. graphics-3d-editor-proposal.md)
│ └── typedoc/ mintlify.mjs, the typedoc plugin; the API reference is generated into docs/references (gitignored)
└── scripts/ nightly.sh, the nightly test runner
└── scripts/ nightly.sh, the nightly test runner; examples.ts, behind `pnpm examples`
```

Each package of `packages/*` and `modules/*` follows the same layout convention: `src/` (code), `test/` (unit tests), `package.json` with dual ESM/CJS exports (`dist/index.js` + `dist/index.cjs` + `.d.ts`/`.d.cts` types). The `utils/*` packages are a bare `index.js`, ESM only, with no build step.
Expand All @@ -75,9 +71,10 @@ From the repo root:
- `pnpm build` — builds all packages via Turborepo (`turbo run build --concurrency=5`).
- `pnpm format` — Prettier write + `turbo run format` per package.
- `pnpm lint` — Prettier check + `turbo run lint` per package (ESLint).
- `pnpm test` — `test:unit` (per package, via Turborepo) then `test:e2e` (Vitest on `e2e/**/*.test.ts`, today `e2e/game.test.ts`).
- `pnpm test` — `test:unit` (per package, via Turborepo) then `test:e2e` (Vitest on `e2e/**/*.test.ts`, today `e2e/game.test.ts` and `e2e/examples.test.ts`).
- `pnpm test:e2e:graphics` — Playwright screenshot tests (`e2e/graphics/<game>.spec.ts`), not part of `pnpm test`. Each game is built and served with `nf build && nf start -p <port>` (`game-2d` on 3101, `game-3d` on 3102). Needs Chromium (`pnpm exec playwright install chromium`); screenshots are only compared on Linux, since the references come from CI's Linux Chromium.
- `pnpm run docs` — builds the packages then runs `typedoc`, which writes the API reference of `packages/*` and `modules/*` as `.mdx` pages into `docs/references`. Use `pnpm run docs`: plain `pnpm docs` is pnpm's built-in command that opens a package's documentation in the browser.
- `pnpm examples [--from <path>] [--games <a,b> | --all]` — `scripts/examples.ts` (run by Node's type stripping, no build): copies examples (`basics|demos|games/<name>` of a local [examples](https://github.com/NanoForge-dev/examples) checkout: `--from`, else `$NANOFORGE_EXAMPLES`, else `../examples`) into the gitignored `.examples/<group>/<name>`, rewrites their dependencies on this repo's packages to `link:<absolute path>`, and runs `pnpm install` in each copy. Each copy is its own pnpm workspace (its `pnpm-workspace.yaml`), so the engine's lockfile and workspace never change. Without `--games`/`--all` it shows a checkbox (terminal only). Needs `pnpm build` first. Only direct dependencies are linked. Its logic is tested by `e2e/examples.test.ts`.
- `scripts/nightly.sh` — nightly test runner: unit tests with coverage (it only scans `packages/*`) then the Vitest e2e tests, and writes JSON and Markdown reports into `$REPORT_DIR` (default `reports/`). Needs `jq`.

Within an individual package/module (e.g. `packages/core`):
Expand Down
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,22 @@ And then create a new project :
nf new
```

Example games are in the [examples repository](https://github.com/NanoForge-dev/examples).

## Test the examples against this engine

`pnpm examples` copies example games from a local checkout of the examples repository into `.examples/<group>/<name>` (gitignored), points their engine dependencies at the packages of this repository (`link:`), and installs them. The checkout itself is only read.

```bash
pnpm build # the copies use the built packages
pnpm examples # pick the examples in a list
pnpm examples --games input-keyboard,pong-3d # or name them (or group/name)
pnpm examples --all --from ~/code/examples # every example of a given checkout
cd .examples/basics/input-keyboard && pnpm build && pnpm start
```

The checkout is `--from <path>`, else `$NANOFORGE_EXAMPLES`, else `../examples`; in a terminal, it asks when none is found. Running it again replaces the copies of the chosen examples.

## Packages

- `@nanoforge-dev/asset` ([source][asset-source]) - The built-in asset library, to read the files shipped with a game
Expand Down
2 changes: 1 addition & 1 deletion docs/docs/graphics-3d/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ description: "Render a 3D scene with @nanoforge-dev/graphics-3d, built on Three.

## Your first 3D scene in 5 minutes

The [`cube-3d` example](https://github.com/NanoForge-dev/Engine/tree/main/example/cube-3d) is this page as a complete app.
The [`graphics-3d` example](https://github.com/NanoForge-dev/examples/tree/main/basics/graphics-3d) is this page as a complete app.

### 1. Install

Expand Down
2 changes: 1 addition & 1 deletion docs/docs/network/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ await app.init(options); // starts listening
- "@node-datachannel/*"
```

Then send and receive packets: see [Client networking](./network-client) and [Server networking](./network-server). The [pong-network example](https://github.com/NanoForge-dev/Engine/tree/main/example/pong-network) is a complete game.
Then send and receive packets: see [Client networking](./network-client) and [Server networking](./network-server). The [pong-network example](https://github.com/NanoForge-dev/examples/tree/main/demos/pong-network) is a complete game.

## Environment variables

Expand Down
83 changes: 83 additions & 0 deletions e2e/examples.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import {
existsSync,
lstatSync,
mkdirSync,
mkdtempSync,
readFileSync,
rmSync,
symlinkSync,
writeFileSync,
} from "fs";
import { tmpdir } from "os";
import { dirname, join } from "path";
import { afterAll, describe, expect, it } from "vitest";

import { copyExample, listExamples, pickExamples } from "../scripts/examples";

const TMP = mkdtempSync(join(tmpdir(), "nf-examples-"));
const CHECKOUT = join(TMP, "examples");

const write = (path: string, content: unknown) => {
mkdirSync(dirname(join(CHECKOUT, path)), { recursive: true });
writeFileSync(
join(CHECKOUT, path),
typeof content === "string" ? content : JSON.stringify(content),
);
};

const deps = { "@nanoforge-dev/core": "^3.0.0", "@nanoforge-dev/cli": "^3.0.1" };
write("basics/pong/package.json", { devDependencies: deps });
write("basics/pong/apps/client/package.json", { dependencies: deps });
write("basics/pong/src/main.ts", "export {};");
for (const skipped of [
"node_modules/x/index.js",
"dist/main.js",
".nanoforge/cache",
"pnpm-lock.yaml",
])
write(`basics/pong/${skipped}`, "");
symlinkSync(join(CHECKOUT, "basics/pong/src/main.ts"), join(CHECKOUT, "basics/pong/linked.ts"));
write("demos/pong/package.json", {});
write("games/not-an-example/README.md", "");

const examples = listExamples(CHECKOUT);
const PACKAGES = new Map([["@nanoforge-dev/core", "/engine/packages/core"]]);

afterAll(() => rmSync(TMP, { recursive: true, force: true }));

describe("pnpm examples", () => {
it("lists the folders of basics, demos and games holding a package.json", () => {
expect(examples.map((example) => example.id).sort()).toEqual(["basics/pong", "demos/pong"]);
});

it("picks by group/name and refuses ambiguous or unknown names", () => {
expect(pickExamples(examples, ["demos/pong"]).map((example) => example.id)).toEqual([
"demos/pong",
]);
expect(() => pickExamples(examples, ["pong"])).toThrow(/ambiguous/);
expect(() => pickExamples(examples, ["../pong"])).toThrow(/Unknown/);
});

it("copies without installs and builds, and links the local packages", () => {
const dest = join(TMP, "copy");
mkdirSync(dest);
writeFileSync(join(dest, "stale.txt"), "");
for (const pong of pickExamples(examples, ["basics/pong"])) copyExample(pong, dest, PACKAGES);

expect(existsSync(join(dest, "stale.txt"))).toBe(false);
expect(existsSync(join(dest, "src/main.ts"))).toBe(true);
expect(lstatSync(join(dest, "linked.ts")).isSymbolicLink()).toBe(false);
for (const skipped of ["node_modules", "dist", ".nanoforge", "pnpm-lock.yaml"])
expect(existsSync(join(dest, skipped))).toBe(false);
expect(existsSync(join(dest, "pnpm-workspace.yaml"))).toBe(true);
for (const [file, field] of [
["package.json", "devDependencies"],
["apps/client/package.json", "dependencies"],
] as const)
expect(JSON.parse(readFileSync(join(dest, file), "utf8"))[field]).toEqual({
"@nanoforge-dev/core": "link:/engine/packages/core",
"@nanoforge-dev/cli": "^3.0.1",
});
expect(existsSync(join(CHECKOUT, "basics/pong/dist/main.js"))).toBe(true);
});
});
1 change: 1 addition & 0 deletions e2e/game-2d/apps/client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"@nanoforge-dev/common": "workspace:*",
"@nanoforge-dev/core": "workspace:*",
"@nanoforge-dev/ecs": "workspace:*",
"@nanoforge-dev/editor-lib": "workspace:*",
"@nanoforge-dev/graphics-2d": "workspace:*",
"@nanoforge-dev/input": "workspace:*",
"typescript": "catalog:core"
Expand Down
16 changes: 16 additions & 0 deletions e2e/game-2d/apps/client/src/components/player.component.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { type Rect } from "@nanoforge-dev/graphics-2d";

/**
* The square the arrow keys move, read by the `movePlayer` system.
*
* @component
* @side client
*/
export class Player {
name = "Player";

constructor(
/** The square drawn for the player: the system moves it. */
public shape: Rect,
) {}
}
31 changes: 9 additions & 22 deletions e2e/game-2d/apps/client/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,19 @@
import type { ClientRunOptions, Context } from "@nanoforge-dev/common";
import type { ClientRunOptions } from "@nanoforge-dev/common";
import { NanoforgeFactory } from "@nanoforge-dev/core";
import { EcsLibrary, type Registry } from "@nanoforge-dev/ecs/client";
import { EcsLibrary } from "@nanoforge-dev/ecs/client";
import { EditorLibrary } from "@nanoforge-dev/editor-lib";
import { Circle, Graphics2DLibrary, Rect } from "@nanoforge-dev/graphics-2d";
import { InputEnum, InputLibrary } from "@nanoforge-dev/input";
import { InputLibrary } from "@nanoforge-dev/input";

import { Player } from "./components/player.component";
import { movePlayer } from "./systems/move-player.system";

/** Read by the Playwright tests in `e2e/graphics`. */
export interface E2EState {
tick: number;
player: { x: number; y: number };
}

class Player {
name = "Player";

constructor(public shape: Rect) {}
}

// Fixed step per tick, not per second: screenshots and positions must not depend on frame timing.
const SPEED = 5;

export const main = async (options: ClientRunOptions): Promise<void> => {
const app = NanoforgeFactory.createClient({
tickRate: 60,
Expand All @@ -30,6 +25,7 @@ export const main = async (options: ClientRunOptions): Promise<void> => {
app.use(graphics);
app.use(ecs);
app.use(input);
app.use(new EditorLibrary());

await app.init(options);

Expand All @@ -45,16 +41,7 @@ export const main = async (options: ClientRunOptions): Promise<void> => {
const state: E2EState = { tick: 0, player: { x: square.x(), y: square.y() } };
(window as unknown as { __e2e: E2EState }).__e2e = state;

registry.addSystem((registry: Registry, ctx: Context) => {
registry.getZipper([Player]).forEach(({ Player }) => {
const dx =
(ctx.input.isKeyPressed(InputEnum.ArrowRight) ? SPEED : 0) -
(ctx.input.isKeyPressed(InputEnum.ArrowLeft) ? SPEED : 0);
Player.shape.x(Player.shape.x() + dx);
state.player = { x: Player.shape.x(), y: Player.shape.y() };
});
state.tick++;
});
registry.addSystem(movePlayer);

await app.run();
};
28 changes: 28 additions & 0 deletions e2e/game-2d/apps/client/src/systems/move-player.system.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import type { Context } from "@nanoforge-dev/common";
import { type Registry } from "@nanoforge-dev/ecs/client";
import { InputEnum } from "@nanoforge-dev/input";

import { Player } from "../components/player.component";
import type { E2EState } from "../main";

// Fixed step per tick, not per second: screenshots and positions must not depend on frame timing.
const SPEED = 5;

/**
* Moves the `Player` square horizontally while an arrow key is held, and reports its position and
* the tick count in `window.__e2e` for the Playwright tests.
*
* @system
* @side client
*/
export const movePlayer = (registry: Registry, ctx: Context) => {
const state = (window as unknown as { __e2e: E2EState }).__e2e;
registry.getZipper([Player]).forEach(({ Player }) => {
const dx =
(ctx.input.isKeyPressed(InputEnum.ArrowRight) ? SPEED : 0) -
(ctx.input.isKeyPressed(InputEnum.ArrowLeft) ? SPEED : 0);
Player.shape.x(Player.shape.x() + dx);
state.player = { x: Player.shape.x(), y: Player.shape.y() };
});
state.tick++;
};
2 changes: 1 addition & 1 deletion e2e/game-2d/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"start": "nf start"
},
"devDependencies": {
"@nanoforge-dev/cli": "^2.3.0",
"@nanoforge-dev/cli": "^3.0.1",
"@nanoforge-dev/config": "catalog:config",
"typescript": "catalog:core"
},
Expand Down
1 change: 1 addition & 0 deletions e2e/game-3d/apps/client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"@nanoforge-dev/common": "workspace:*",
"@nanoforge-dev/core": "workspace:*",
"@nanoforge-dev/ecs": "workspace:*",
"@nanoforge-dev/editor-lib": "workspace:*",
"@nanoforge-dev/graphics-3d": "workspace:*",
"@nanoforge-dev/input": "workspace:*",
"@types/three": "catalog:graphics",
Expand Down
16 changes: 16 additions & 0 deletions e2e/game-3d/apps/client/src/components/model.component.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { type Object3D } from "@nanoforge-dev/graphics-3d/three";

/**
* A Three.js object the arrow keys turn, read by the `turnModel` system.
*
* @component
* @side client
*/
export class Model {
name = "Model";

constructor(
/** The object in the scene: the system turns it around its Y axis. */
public object: Object3D,
) {}
}
32 changes: 9 additions & 23 deletions e2e/game-3d/apps/client/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { ClientRunOptions, Context } from "@nanoforge-dev/common";
import type { ClientRunOptions } from "@nanoforge-dev/common";
import { NanoforgeFactory } from "@nanoforge-dev/core";
import { EcsLibrary, type Registry } from "@nanoforge-dev/ecs/client";
import { EcsLibrary } from "@nanoforge-dev/ecs/client";
import { EditorLibrary } from "@nanoforge-dev/editor-lib";
import { type Graphics3DBackend, Graphics3DLibrary } from "@nanoforge-dev/graphics-3d";
import {
BoxGeometry,
Expand All @@ -9,9 +10,11 @@ import {
HemisphereLight,
Mesh,
MeshStandardMaterial,
type Object3D,
} from "@nanoforge-dev/graphics-3d/three";
import { InputEnum, InputLibrary } from "@nanoforge-dev/input";
import { InputLibrary } from "@nanoforge-dev/input";

import { Model } from "./components/model.component";
import { turnModel } from "./systems/turn-model.system";

/** Read by the Playwright tests in `e2e/graphics`. */
export interface E2EState {
Expand All @@ -20,15 +23,6 @@ export interface E2EState {
cube: { rotationY: number };
}

class Model {
name = "Model";

constructor(public object: Object3D) {}
}

// Fixed step per tick, not per second: screenshots and rotations must not depend on frame timing.
const TURN = 0.05;

export const main = async (options: ClientRunOptions): Promise<void> => {
const app = NanoforgeFactory.createClient({
tickRate: 60,
Expand All @@ -41,6 +35,7 @@ export const main = async (options: ClientRunOptions): Promise<void> => {
app.use(graphics);
app.use(ecs);
app.use(input);
app.use(new EditorLibrary());

await app.init(options);

Expand All @@ -67,16 +62,7 @@ export const main = async (options: ClientRunOptions): Promise<void> => {
};
(window as unknown as { __e2e: E2EState }).__e2e = state;

registry.addSystem((registry: Registry, ctx: Context) => {
registry.getZipper([Model]).forEach(({ Model }) => {
const turn =
(ctx.input.isKeyPressed(InputEnum.ArrowRight) ? TURN : 0) -
(ctx.input.isKeyPressed(InputEnum.ArrowLeft) ? TURN : 0);
Model.object.rotation.y += turn;
state.cube = { rotationY: Model.object.rotation.y };
});
state.tick++;
});
registry.addSystem(turnModel);

await app.run();
};
Loading
Loading