Skip to content
44 changes: 21 additions & 23 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,11 @@ This repository contains multiple packages with separate [releases][github-relea

## Documentation

The full documentation can be found at: [https://nanoforge-dev.github.io/docs/engine](https://nanoforge-dev.github.io/docs/engine)
The full documentation can be found at: [https://docs.nanoforge.eu/docs/engine/getting-started/index](https://docs.nanoforge.eu/docs/engine/getting-started/index)

## Usage

To use Nanoforge Engine, please refer to the [CLI documentation][cli-source] !
To use Nanoforge Engine, please refer to the [CLI documentation][cli-docs] !

First, install the CLI :

Expand All @@ -37,18 +37,17 @@ nf new

## Packages

- `@nanoforge-dev/asset` ([source][asset-source]) - The built-in asset library, to read the files shipped with a game
- `@nanoforge-dev/common` ([source][common-source]) - Common interfaces and utilities used by Nanoforge Engine
- `@nanoforge-dev/core` ([source][core-source]) - A core package that contains game main loop
- `@nanoforge-dev/ecs-lib` ([source][ecs-lib-source]) - A powerful data structure for managing game entities (_do not use this in your projects_)
- `@nanoforge-dev/ecs-client` ([source][ecs-client-source]) - A wrapper of `@nanoforge-dev/ecs-lib` for client-side usage
- `@nanoforge-dev/ecs-server` ([source][ecs-server-source]) - A wrapper of `@nanoforge-dev/ecs-lib` for server-side usage
- `@nanoforge-dev/config` ([source][config-source]) - A wrapper of `class-validator` and `class-transformer` to imports validation and transformation decorators
- `@nanoforge-dev/core` ([source][core-source]) - A core package that creates the application and runs the game loop
- `@nanoforge-dev/env` ([source][env-source]) - A wrapper of `class-validator` and `class-transformer` to validate environment variables
- `@nanoforge-dev/ecs` ([source][ecs-source]) - A powerful data structure for managing game entities, for the client and the server
- `@nanoforge-dev/editor-lib` ([source][editor-source]) - The bridge between a running game and the NanoForge editor
- `@nanoforge-dev/graphics-2d` ([source][graphics-2d-source]) - A base 2D graphics library
- `@nanoforge-dev/asset-manager` ([source][asset-manager-source]) - A manager for loading assets to uniform workwith between client and server
- `@nanoforge-dev/network-client` ([source][network-client-source]) - A network lib with tcp and udp support for client-side usage
- `@nanoforge-dev/network-server` ([source][network-server-source]) - A network lib with tcp and udp support for server-side usage
- `@nanoforge-dev/input` ([source][input-source]) - An input manager for handling keyboard and mouse events
- `@nanoforge-dev/graphics-3d` ([source][graphics-3d-source]) - A 3D graphics library built on Three.js
- `@nanoforge-dev/input` ([source][input-source]) - An input manager for handling keyboard, mouse and controller events
- `@nanoforge-dev/music` ([source][music-source]) - A music player for your game
- `@nanoforge-dev/network` ([source][network-source]) - A network lib with tcp and udp support, for the client and the server
- `@nanoforge-dev/scene` ([source][scene-source]) - A scene manager, with vars shared by scenes and systems
- `@nanoforge-dev/sound` ([source][sound-source]) - A sound manager for your game

Expand All @@ -62,20 +61,19 @@ If you don't understand something in the documentation, you are experiencing pro

[contributing]: https://github.com/NanoForge-dev/Engine/blob/main/.github/CONTRIBUTING.md
[discussions]: https://github.com/NanoForge-dev/Engine/discussions
[cli-source]: https://github.com/NanoForge-dev/CLI
[cli-docs]: https://docs.nanoforge.eu/docs/cli/getting-started/quickstart
[github-releases]: https://github.com/NanoForge-dev/Engine/releases
[asset-manager-source]: https://github.com/NanoForge-dev/Engine/tree/main/packages/asset-manager
[asset-source]: https://github.com/NanoForge-dev/Engine/tree/main/packages/asset
[common-source]: https://github.com/NanoForge-dev/Engine/tree/main/packages/common
[config-source]: https://github.com/NanoForge-dev/Engine/tree/main/packages/config
[core-source]: https://github.com/NanoForge-dev/Engine/tree/main/packages/core
[ecs-client-source]: https://github.com/NanoForge-dev/Engine/tree/main/packages/ecs-client
[ecs-lib-source]: https://github.com/NanoForge-dev/Engine/tree/main/packages/ecs-lib
[ecs-server-source]: https://github.com/NanoForge-dev/Engine/tree/main/packages/ecs-server
[graphics-2d-source]: https://github.com/NanoForge-dev/Engine/tree/main/packages/graphics-2d
[input-source]: https://github.com/NanoForge-dev/Engine/tree/main/packages/input
[music-source]: https://github.com/NanoForge-dev/Engine/tree/main/packages/music
[network-client-source]: https://github.com/NanoForge-dev/Engine/tree/main/packages/network-client
[network-server-source]: https://github.com/NanoForge-dev/Engine/tree/main/packages/network-server
[env-source]: https://github.com/NanoForge-dev/Engine/tree/main/packages/env
[ecs-source]: https://github.com/NanoForge-dev/Engine/tree/main/modules/ecs
[editor-source]: https://github.com/NanoForge-dev/Engine/tree/main/modules/editor
[graphics-2d-source]: https://github.com/NanoForge-dev/Engine/tree/main/modules/graphics-2d
[graphics-3d-source]: https://github.com/NanoForge-dev/Engine/tree/main/modules/graphics-3d
[input-source]: https://github.com/NanoForge-dev/Engine/tree/main/modules/input
[music-source]: https://github.com/NanoForge-dev/Engine/tree/main/modules/music
[network-source]: https://github.com/NanoForge-dev/Engine/tree/main/modules/network
[scene-source]: https://github.com/NanoForge-dev/Engine/tree/main/modules/scene
[sound-source]: https://github.com/NanoForge-dev/Engine/tree/main/packages/sound
[sound-source]: https://github.com/NanoForge-dev/Engine/tree/main/modules/sound
[good-first-issue]: https://github.com/NanoForge-dev/Engine/contribute
File renamed without changes.
43 changes: 43 additions & 0 deletions docs/docs/assets/index.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
---
title: "Assets"
icon: "image"
description: "Load images, sounds and data files shipped with your game"
---

Assets are the files your game ships with: images, sounds, levels, configuration. Put them in your project's `assets` folder. `nf build` copies its content next to the game code, so `assets/hero.png` becomes `/hero.png`.

## Read an asset

The asset library is built into every application: you never register it. Read a file with `ctx.assets.getAsset(path)` wherever you have the context. Load each file once, not on every tick: a scene's `load` is a good place, and it can wait for the file (see [Scenes](../scene/index)).

```ts
export class Level extends Scene {
override async load(ctx: Context) {
const level = await ctx.assets.getAsset("/levels/1.json").json();

const hero = new window.Image();
hero.src = ctx.assets.getAsset("/hero.png").path;
ctx.graphics.baseLayer.add(new Image({ image: hero, x: level.x, y: level.y }));

ctx.sound.load("jump", ctx.assets.getAsset("/jump.wav").path);
}
}
```

`getAsset` returns an `NfFile`:

| Member | Gives |
| -------------------------------------------------- | ----------------------------------------------------------------------------- |
| `path` | The URL of the file. Pass it to anything that loads a URL: an image, a sound. |
| `json()` | The content parsed as JSON. |
| `text()` | The content as a string. |
| `arrayBuffer()`, `bytes()`, `blob()`, `formData()` | The content in that format. |

- Paths are normalized: `"hero.png"`, `"/hero.png"` and `"//hero.png"` find the same file.
- `getAsset` throws `NfNotFound` when no file has that path. The read methods fetch the file and throw `NfFetchException` when the fetch fails.

## In `main`

`main` has no context. There, read the URL from the run options: `options.files.get("/hero.png")` returns the same URL as `getAsset("/hero.png").path`, or `undefined` when the file is missing. [Sound and music](../audio/index) shows an example.

To change the folder name, set `dir.assets` in the app's `nanoforge.config.ts`. See [the configuration file](/docs/cli/configuration/configuration-file).
76 changes: 76 additions & 0 deletions docs/docs/audio/index.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
---
title: "Sound and music"
icon: "volume-high"
description: "Play sound effects and background music"
---

Two client libraries play audio:

| Library | Package | Context key | For |
| -------------- | ---------------------- | ----------- | ------------------------------------------------- |
| `SoundLibrary` | `@nanoforge-dev/sound` | `ctx.sound` | Sound effects. Several can play at the same time. |
| `MusicLibrary` | `@nanoforge-dev/music` | `ctx.music` | Music. Playing a track stops the one before it. |

Both have the same three methods: `load(key, url)`, `play(key)` and `mute()`.

## Load your files

Put the audio files in your project's `assets` folder, then load each one under a key after `app.init`:

```ts
const app = NanoforgeFactory.createClient();
const sound = new SoundLibrary();
const music = new MusicLibrary();
app.use(sound);
app.use(music);

await app.init(options);

// `main` has no context: read the URLs of the files in `assets/` from the run options.
const url = (path: string): string => {
const file = options.files.get(path);
if (!file) throw new Error(`Missing asset: ${path}`);
return file;
};
sound.load("jump", url("/jump.wav"));
music.load("theme", url("/theme.mp3"));
music.play("theme");

await app.run();
```

## Play

From a system, or anywhere you have the context:

```ts
if (ctx.input.isKeyPressed(InputEnum.Space)) ctx.sound.play("jump");
```

- `ctx.music.play(key)` stops the track that was playing before.
- `play` throws `NfNotFound` when no file was loaded under that key.
- Playing a sound that is already playing has no effect until it ends.

## Turn the sound on

<Warning>
Both libraries start **muted**, and `mute()` toggles the muted state: call it once to turn the
sound on. Browsers also block audio until the player has interacted with the page, so tie it to a
key press or a click.
</Warning>

A system runs on every tick, so toggle on the press, not while the key is held:

```ts
let wasPressed = false;

// Toggles sound and music once per press of M.
export const toggleSound = (_registry: Registry, ctx: Context) => {
const pressed = ctx.input.isKeyPressed(InputEnum.KeyM) ?? false;
if (pressed && !wasPressed) {
ctx.sound.mute();
ctx.music.mute();
}
wasPressed = pressed;
};
```
119 changes: 119 additions & 0 deletions docs/docs/ecs/index.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
---
title: "ECS"
icon: "boxes-stacked"
description: "Store the game state as entities and components, and update it with systems"
---

The ECS (entity component system) holds the state of your game. It comes from `@nanoforge-dev/ecs`, a registry written in C++ and compiled to WebAssembly.

- An **entity** is an id. It has no data of its own.
- A **component** is a data object attached to an entity: a position, a velocity, a health value.
- A **system** is a function called on every tick. It finds the entities that have some components and updates them.

## Register the library

Import `EcsLibrary` from the entry point of your side of the game:

```ts
import { EcsLibrary } from "@nanoforge-dev/ecs/client";

// or "@nanoforge-dev/ecs/server"

const ecs = new EcsLibrary();
app.use(ecs);
await app.init(options);

const registry = ecs.registry; // also ctx.ecs.registry in systems
```

`ecs.registry` throws before `app.init` has resolved. The types `Registry`, `Entity`, `Component` and `System` come from the same entry point.

## Components

A component is an instance of a class with a `name` field equal to its class name:

```ts
export class Position {
name = this.constructor.name;

constructor(
public x: number,
public y: number,
) {}
}
```

The registry files each component under its `name`. When you add a component it reads `name` on the instance; when you query, it reads `name` on the class you pass. The two must match.

<Warning>
Don't give a component class the name of another class in your game's bundle. When two classes
share a name, the bundler renames one (`Position2`), and the results of `getZipper` are then keyed
by that new name: destructuring `({Position})` gives `undefined`. Three.js and Konva export many
classes (`Sphere`, `Plane`, `Box3`, `Text`, `Image`, `Line`...), so prefer names that are clearly
yours, such as `Hitbox` or `PlayerSprite`.
</Warning>

An entity has at most one component of each type: adding a second `Position` replaces the first.

## Entities

```ts
const enemy = registry.spawnEntity();
registry.addComponent(enemy, new Health(3));
registry.addComponent(enemy, new Poisoned());

const health = registry.getEntityComponent(enemy, Health); // the Health instance, or undefined
registry.removeComponent(enemy, Poisoned);
registry.killEntity(enemy);
```

`killEntity` removes every component of the entity.

## Systems

A system has the type `(registry, ctx) => void`. Add it with `registry.addSystem(system)`. Systems run on every tick, in the order you added them, unless the game is paused.

`registry.getZipper([A, B])` returns one object per entity that has every listed component, keyed by component name:

```ts
export const move = (registry: Registry, ctx: Context) => {
const seconds = ctx.app.delta / 1000;
registry.getZipper([Position, Velocity]).forEach(({ Position, Velocity }) => {
Position.x += Velocity.x * seconds;
Position.y += Velocity.y * seconds;
});
};
```

The objects in the result are your component instances: changing them changes the game state.

To know which entity a result belongs to, use `getIndexedZipper`. Each object also has an `id`, which `entityFromIndex` turns back into an entity:

```ts
export const poison = (registry: Registry) => {
registry.getIndexedZipper([Health, Poisoned]).forEach(({ id, Health }) => {
Health.value -= 1;
if (Health.value <= 0) registry.killEntity(registry.entityFromIndex(id));
});
};
```

Other registry methods:

| Method | What it does |
| -------------------------- | ------------------------------------------------------------- |
| `removeSystem(index)` | Removes the system at that position in the list. |
| `clearSystems()` | Removes every system. |
| `clearEntities()` | Removes every entity and component. |
| `getComponents(Component)` | The sparse array of one component type, indexed by entity id. |
| `maxEntities()` | The number of entity ids used so far. |

To add and remove a group of entities and systems together, such as a level, use a scene: see [Scenes](../scene/index).

## Errors

An error thrown in the C++ registry reaches JavaScript as a runtime error, with less detail than a JavaScript error. For example, `entityFromIndex` throws for an id that was never spawned or was killed: check your ids before calling it.

## Editor manifests

Projects generated by `nf new` export an `EDITOR_COMPONENT_MANIFEST` next to each component and an `EDITOR_SYSTEM_MANIFEST` next to each system. The NanoForge editor reads them to show and generate your components and systems. The types are `EditorComponentManifest` and `EditorSystemManifest`. To generate a new component or system with its manifest, see the CLI [component](/docs/cli/schematics/component) and [system](/docs/cli/schematics/system) schematics.
Loading
Loading