create-dreamer-app 1.0.4 → 1.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -2
- package/index.js +36 -8
- package/package.json +4 -1
- package/template/DISCO_DREAMER_REFERENCE.md +399 -0
- package/test/cli.test.js +106 -0
package/README.md
CHANGED
|
@@ -23,6 +23,7 @@ Open the local URL printed by Vite. The development server uses port `3000` by d
|
|
|
23
23
|
- **Vite** for local development and production builds.
|
|
24
24
|
- **Source aliases** so you can import from `@/` instead of navigating relative paths.
|
|
25
25
|
- A full-page canvas with basic styles.
|
|
26
|
+
- `DISCO_DREAMER_REFERENCE.md`, a practical guide to the Disco Dreamer API.
|
|
26
27
|
|
|
27
28
|
## Make it yours
|
|
28
29
|
|
|
@@ -46,6 +47,7 @@ import { Message } from "@/components/Message";
|
|
|
46
47
|
|
|
47
48
|
```text
|
|
48
49
|
my-dreamer-app/
|
|
50
|
+
├── DISCO_DREAMER_REFERENCE.md
|
|
49
51
|
├── src/
|
|
50
52
|
│ ├── assets/
|
|
51
53
|
│ │ └── disco-dreamer.svg
|
|
@@ -75,16 +77,34 @@ Run these inside your generated project:
|
|
|
75
77
|
## CLI options
|
|
76
78
|
|
|
77
79
|
```sh
|
|
78
|
-
npx create-dreamer-app@latest [directory] [
|
|
80
|
+
npx create-dreamer-app@latest [directory] [options]
|
|
79
81
|
```
|
|
80
82
|
|
|
81
|
-
Omit the directory to choose a name interactively. The destination must be a new or empty directory.
|
|
83
|
+
Omit the directory to choose a name interactively when creating an app. The app destination must be a new or empty directory.
|
|
82
84
|
|
|
83
85
|
| Option | Description |
|
|
84
86
|
| --- | --- |
|
|
85
87
|
| `--skip-install` | Create the project without installing dependencies. |
|
|
88
|
+
| `-ro`, `--ref-only` | Copy only `DISCO_DREAMER_REFERENCE.md`, without installing dependencies. Defaults to the current directory. |
|
|
89
|
+
| `-er`, `--exclude-reference` | Create the app without `DISCO_DREAMER_REFERENCE.md`. |
|
|
86
90
|
| `-h`, `--help` | Show usage information. |
|
|
87
91
|
|
|
92
|
+
To add just the reference to an existing project, run this inside the project:
|
|
93
|
+
|
|
94
|
+
```sh
|
|
95
|
+
npx create-dreamer-app@latest --ref-only
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
You can also specify a destination, such as `npx create-dreamer-app@latest docs -ro`.
|
|
99
|
+
Reference-only mode allows existing directories but refuses to overwrite an existing reference file.
|
|
100
|
+
The `--ref-only` and `--exclude-reference` options cannot be used together.
|
|
101
|
+
|
|
102
|
+
To create an app without the reference:
|
|
103
|
+
|
|
104
|
+
```sh
|
|
105
|
+
npx create-dreamer-app@latest my-dreamer-app -er
|
|
106
|
+
```
|
|
107
|
+
|
|
88
108
|
To install dependencies yourself:
|
|
89
109
|
|
|
90
110
|
```sh
|
package/index.js
CHANGED
|
@@ -4,18 +4,26 @@ const fs = require("node:fs/promises");
|
|
|
4
4
|
const path = require("node:path");
|
|
5
5
|
const readline = require("node:readline/promises");
|
|
6
6
|
const { spawnSync } = require("node:child_process");
|
|
7
|
+
const { constants } = require("node:fs");
|
|
7
8
|
|
|
8
|
-
const
|
|
9
|
+
const referenceFile = "DISCO_DREAMER_REFERENCE.md";
|
|
10
|
+
|
|
11
|
+
const usage = `Usage: create-dreamer-app [directory] [options]
|
|
9
12
|
|
|
10
13
|
Create a Disco Dreamer app and install its dependencies.
|
|
11
14
|
If no directory is supplied, you will be prompted for one.
|
|
15
|
+
With --ref-only, the directory defaults to the current directory.
|
|
12
16
|
|
|
13
17
|
Options:
|
|
14
|
-
--skip-install
|
|
15
|
-
-
|
|
18
|
+
--skip-install Create the project without running npm install
|
|
19
|
+
-ro, --ref-only Copy only the reference, without installing dependencies
|
|
20
|
+
-er, --exclude-reference Create the project without the reference
|
|
21
|
+
-h, --help Show this help message
|
|
16
22
|
|
|
17
|
-
|
|
18
|
-
npx create-dreamer-app my-dreamer-app
|
|
23
|
+
Examples:
|
|
24
|
+
npx create-dreamer-app my-dreamer-app
|
|
25
|
+
npx create-dreamer-app --ref-only
|
|
26
|
+
npx create-dreamer-app my-dreamer-app --exclude-reference`;
|
|
19
27
|
|
|
20
28
|
async function main() {
|
|
21
29
|
const args = process.argv.slice(2);
|
|
@@ -24,12 +32,19 @@ async function main() {
|
|
|
24
32
|
return;
|
|
25
33
|
}
|
|
26
34
|
|
|
27
|
-
const
|
|
35
|
+
const options = new Set(["--skip-install", "--ref-only", "-ro", "--exclude-reference", "-er"]);
|
|
36
|
+
const unknownOption = args.find((arg) => arg.startsWith("-") && !options.has(arg));
|
|
28
37
|
if (unknownOption) throw new Error(`Unknown option: ${unknownOption}\n\n${usage}`);
|
|
29
|
-
const
|
|
38
|
+
const refOnly = args.includes("--ref-only") || args.includes("-ro");
|
|
39
|
+
const excludeReference = args.includes("--exclude-reference") || args.includes("-er");
|
|
40
|
+
if (refOnly && excludeReference) {
|
|
41
|
+
throw new Error("--ref-only (-ro) and --exclude-reference (-er) cannot be used together.");
|
|
42
|
+
}
|
|
43
|
+
const directories = args.filter((arg) => !options.has(arg));
|
|
30
44
|
if (directories.length > 1) throw new Error(`Supply only one project directory.\n\n${usage}`);
|
|
31
45
|
|
|
32
46
|
let directory = directories[0];
|
|
47
|
+
if (directory === undefined && refOnly) directory = ".";
|
|
33
48
|
if (directory === undefined) {
|
|
34
49
|
if (!process.stdin.isTTY) throw new Error(`Supply a project directory.\n\n${usage}`);
|
|
35
50
|
const prompt = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
@@ -42,6 +57,18 @@ async function main() {
|
|
|
42
57
|
if (!directory.trim()) throw new Error("The project directory cannot be empty.");
|
|
43
58
|
|
|
44
59
|
const destination = path.resolve(directory);
|
|
60
|
+
if (refOnly) {
|
|
61
|
+
await fs.mkdir(destination, { recursive: true });
|
|
62
|
+
const referencePath = path.join(destination, referenceFile);
|
|
63
|
+
try {
|
|
64
|
+
await fs.copyFile(path.join(__dirname, "template", referenceFile), referencePath, constants.COPYFILE_EXCL);
|
|
65
|
+
} catch (error) {
|
|
66
|
+
if (error.code === "EEXIST") throw new Error(`Reference already exists: ${referencePath}`);
|
|
67
|
+
throw error;
|
|
68
|
+
}
|
|
69
|
+
console.log(`Copied ${referenceFile} to ${destination}.`);
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
45
72
|
const name = path.basename(destination).toLowerCase().replace(/[^a-z0-9._-]+/g, "-");
|
|
46
73
|
if (!/^[a-z0-9][a-z0-9._-]*$/.test(name) || name.length > 214 || ["node_modules", "favicon.ico"].includes(name)) {
|
|
47
74
|
throw new Error("Choose a directory whose name starts with a letter or number and can be used as an npm package name.");
|
|
@@ -62,7 +89,8 @@ async function main() {
|
|
|
62
89
|
recursive: true,
|
|
63
90
|
force: false,
|
|
64
91
|
errorOnExist: true,
|
|
65
|
-
filter: (source) => ![".DS_Store", "node_modules", "dist"].includes(path.basename(source))
|
|
92
|
+
filter: (source) => ![".DS_Store", "node_modules", "dist"].includes(path.basename(source))
|
|
93
|
+
&& !(excludeReference && path.basename(source) === referenceFile),
|
|
66
94
|
});
|
|
67
95
|
const packagePath = path.join(destination, "package.json");
|
|
68
96
|
const manifest = JSON.parse(await fs.readFile(packagePath, "utf8"));
|
package/package.json
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "create-dreamer-app",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.5",
|
|
4
4
|
"description": "The scaffolding application for using Disco Dreamer.",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"bin": {
|
|
7
7
|
"create-dreamer-app": "index.js"
|
|
8
8
|
},
|
|
9
|
+
"scripts": {
|
|
10
|
+
"test": "node --test"
|
|
11
|
+
},
|
|
9
12
|
"engines": {
|
|
10
13
|
"node": "^20.19.0 || >=22.12.0"
|
|
11
14
|
},
|
|
@@ -0,0 +1,399 @@
|
|
|
1
|
+
# Disco Dreamer reference
|
|
2
|
+
|
|
3
|
+
A practical guide to building browser games with `discodreamer`. Examples use the public API in version 1.0.2 and TypeScript with JSX.
|
|
4
|
+
|
|
5
|
+
## How a game runs
|
|
6
|
+
|
|
7
|
+
Disco Dreamer draws a tree of game objects onto a 2D canvas. Components are functions that return game objects; hooks provide state, input, animation, and other game behavior.
|
|
8
|
+
|
|
9
|
+
Your root function runs again on every animation frame. Each frame, the engine builds the tree, solves collisions, manages sound, draws the tree, and cleans up. A state setter updates stored data immediately; it does not schedule a separate render.
|
|
10
|
+
|
|
11
|
+
- Coordinates use CSS pixels, with `(0, 0)` at the canvas's top-left, positive `x` to the right, and positive `y` downward.
|
|
12
|
+
- Child positions are relative to their parent `Scene` or `RigidBody2D`.
|
|
13
|
+
- Siblings draw in ascending `z` order; higher values appear later, on top. This is local to each parent, not a global depth order.
|
|
14
|
+
- Update times and interpolation durations are in milliseconds. Convert `dt` to seconds for movement expressed in units per second.
|
|
15
|
+
- Import components and hooks from `discodreamer`.
|
|
16
|
+
|
|
17
|
+
## First game
|
|
18
|
+
|
|
19
|
+
In a generated app, use its existing entry point and canvas. Replace the game tree or component there; keep a single `registerRoot` call.
|
|
20
|
+
|
|
21
|
+
For a custom setup, the HTML must contain a canvas with `id="c"` before registration. Give it a visible CSS size, for example:
|
|
22
|
+
|
|
23
|
+
```html
|
|
24
|
+
<canvas id="c" style="display: block; width: 800px; height: 450px;"></canvas>
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
This entry point moves a square with the arrow keys:
|
|
28
|
+
|
|
29
|
+
```tsx
|
|
30
|
+
import {
|
|
31
|
+
registerRoot,
|
|
32
|
+
Scene,
|
|
33
|
+
Rect,
|
|
34
|
+
Text,
|
|
35
|
+
gameState,
|
|
36
|
+
gameUpdate,
|
|
37
|
+
gameEvent,
|
|
38
|
+
} from "discodreamer";
|
|
39
|
+
|
|
40
|
+
function Game() {
|
|
41
|
+
const [, setPosition, getPosition] = gameState("player.position", {
|
|
42
|
+
x: 100,
|
|
43
|
+
y: 100,
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
gameUpdate((dt) => {
|
|
47
|
+
const step = 200 * dt / 1000;
|
|
48
|
+
gameEvent("key", ({ key }) => {
|
|
49
|
+
setPosition((prev) => ({
|
|
50
|
+
x: prev.x + (key === "ArrowRight" ? step : key === "ArrowLeft" ? -step : 0),
|
|
51
|
+
y: prev.y + (key === "ArrowDown" ? step : key === "ArrowUp" ? -step : 0),
|
|
52
|
+
}));
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
const position = getPosition();
|
|
57
|
+
return (
|
|
58
|
+
<Scene>
|
|
59
|
+
<Rect {...position} width={32} height={32} style={{ fill: "#ff69b4" }} />
|
|
60
|
+
<Text x={16} y={16} fontSize={20} value="Move with the arrow keys" />
|
|
61
|
+
</Scene>
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
registerRoot(Game);
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
The generated app handles the JSX factory automatically; no factory import or manual JSX configuration is needed.
|
|
69
|
+
|
|
70
|
+
Use `.tsx` files for JSX. Arrays and conditional children are supported, such as `{visible && <Rect width={20} height={20} />}`. Components can also be called directly without JSX: `Scene({ children: [Rect({ width: 20, height: 20 })] })`.
|
|
71
|
+
|
|
72
|
+
The examples below are independent excerpts; add their named imports from `discodreamer` to your game file. Asset paths such as `/player.png` are examples: supply files at URLs your app serves.
|
|
73
|
+
|
|
74
|
+
## State and keys
|
|
75
|
+
|
|
76
|
+
### `gameState(key, initialValue)`
|
|
77
|
+
|
|
78
|
+
Returns `[value, setValue, getValue, resolvedKey]`:
|
|
79
|
+
|
|
80
|
+
```ts
|
|
81
|
+
const [score, setScore, getScore] = gameState("score", 0);
|
|
82
|
+
setScore((previous) => previous + 1);
|
|
83
|
+
// score is the value read earlier in this frame.
|
|
84
|
+
// getScore() reads the latest stored value, including the increment.
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
`initialValue` initializes a new state slot; changing it on later frames does not reset existing state. Setters accept either a replacement or a function of the previous value. Replace objects rather than mutating them.
|
|
88
|
+
|
|
89
|
+
Keys identify persistent data across frames. Give each stateful hook and each body instance a stable, descriptive key. For repeated entities, include an entity ID, such as `` `enemy.${id}.health` ``.
|
|
90
|
+
|
|
91
|
+
Internally, consecutive stateful calls using the same key receive numbered slots. Their order must stay consistent. Reusing a key after a different key starts its numbering again, which can alias an earlier slot. The simplest application pattern is to use a distinct key for each hook and avoid sharing keys with component internals. Keep stateful hook calls in a consistent order each frame.
|
|
92
|
+
|
|
93
|
+
State that is no longer used is removed during frame cleanup. If an entity disappears for a frame and returns later, expect its state to initialize again.
|
|
94
|
+
|
|
95
|
+
### `createDynamicId()`
|
|
96
|
+
|
|
97
|
+
Returns a fresh string ID. Generate it when spawning an entity, store it with that entity, and reuse it across frames. Calling it on every render would give the entity a new identity every frame.
|
|
98
|
+
|
|
99
|
+
## Drawing components
|
|
100
|
+
|
|
101
|
+
### `Scene`
|
|
102
|
+
|
|
103
|
+
Groups children and adds a positional offset. Props: `x`, `y`, `z` (all default to `0`) and `children` (default `[]`).
|
|
104
|
+
|
|
105
|
+
```tsx
|
|
106
|
+
<Scene x={100} y={80}>
|
|
107
|
+
<Rect width={100} height={40} />
|
|
108
|
+
<Text y={48} fontSize={18} value="Hello!" />
|
|
109
|
+
</Scene>
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
### `Rect` and `Circ`
|
|
113
|
+
|
|
114
|
+
Both accept `x`, `y`, `z` (default `0`) and `style: { fill?, stroke? }`. Colors are canvas color strings. With no style, shapes have a white fill and black stroke. Passing a style replaces that default, so `{ stroke: "red" }` draws only a stroke.
|
|
115
|
+
|
|
116
|
+
| Component | Geometry | Origin |
|
|
117
|
+
| --- | --- | --- |
|
|
118
|
+
| `Rect` | `width`, `height`, each default `0` | Top-left corner |
|
|
119
|
+
| `Circ` | `rad`, default `0` | Center |
|
|
120
|
+
|
|
121
|
+
```tsx
|
|
122
|
+
<Scene>
|
|
123
|
+
<Rect x={20} y={20} width={100} height={60} style={{ fill: "orange" }} />
|
|
124
|
+
<Circ x={180} y={50} rad={30} style={{ stroke: "cyan" }} />
|
|
125
|
+
</Scene>
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
These shapes are visual only. Use `Bounds` inside a `RigidBody2D` for collision geometry.
|
|
129
|
+
|
|
130
|
+
### `Sprite`
|
|
131
|
+
|
|
132
|
+
Displays an image or a sprite-sheet animation. Supply exactly one of `src` or `animation`.
|
|
133
|
+
|
|
134
|
+
| Prop | Behavior |
|
|
135
|
+
| --- | --- |
|
|
136
|
+
| `src` | Image URL for a static sprite |
|
|
137
|
+
| `animation` | Result of `gameAnimation` |
|
|
138
|
+
| `x`, `y`, `z` | Position and sibling draw order; default `0` |
|
|
139
|
+
| `width`, `height` | Display size; defaults to image dimensions or animation frame size |
|
|
140
|
+
| `rotation` | Degrees around the image center; default `0` |
|
|
141
|
+
|
|
142
|
+
```tsx
|
|
143
|
+
<Sprite src="/player.png" x={100} y={80} width={64} height={64} />
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
The sprite's position is its unrotated top-left corner. Images are cached by URL, and a sprite draws nothing until its image is ready. Rotation affects drawing, not physics bounds.
|
|
147
|
+
|
|
148
|
+
### `Text`
|
|
149
|
+
|
|
150
|
+
Draws white, left-aligned, top-aligned text in a sans-serif font.
|
|
151
|
+
|
|
152
|
+
Props: required `value: string`; optional `x`, `y`, `z` (default `0`), `fontSize` (default `100`), and `width` (default `Infinity`). A finite `width` limits the canvas text draw width; it does not create wrapping lines.
|
|
153
|
+
|
|
154
|
+
```tsx
|
|
155
|
+
<Text x={16} y={16} value="Score: 10" fontSize={24} />
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
## Physics components and contact hooks
|
|
159
|
+
|
|
160
|
+
### `RigidBody2D`
|
|
161
|
+
|
|
162
|
+
A stateful moving body. Put drawing components and one or more `Bounds` inside it.
|
|
163
|
+
|
|
164
|
+
| Prop | Default | Purpose |
|
|
165
|
+
| --- | --- | --- |
|
|
166
|
+
| `key` | Required | Stable body identity; also used by contact hooks |
|
|
167
|
+
| `x`, `y`, `z` | `0` | Initial local position and draw order |
|
|
168
|
+
| `velocity` | `{ x: 0, y: 0 }` | Initial velocity in world units per second |
|
|
169
|
+
| `mass` | `1` | Kilograms; `0` creates a static body |
|
|
170
|
+
| `gravity` | `1` | Multiplier of downward acceleration, `981` units/s²; `0` disables gravity |
|
|
171
|
+
| `forces` | `[]` | Force vectors in newtons, applied each frame |
|
|
172
|
+
| `drag` | `0` | Exponential velocity damping per second |
|
|
173
|
+
| `restitution` | `1` | Bounce factor; `0` removes bounce; a pair uses the lower factor |
|
|
174
|
+
| `layer` | Unset | Layer name used by other bodies' filters |
|
|
175
|
+
| `collidesWith` | `[]` | Layers eligible for physical collision |
|
|
176
|
+
| `hitsWith` | `[]` | Layers to report overlap with, without requiring physical response |
|
|
177
|
+
| `ref` | Unset | Key returned by `gameRef` |
|
|
178
|
+
| `onChange` | Unset | Callback receiving `{ position, velocity }` |
|
|
179
|
+
| `children` | `[]` | Visuals and bounds attached to the body |
|
|
180
|
+
|
|
181
|
+
Physics treats one world unit as one centimeter. The renderer displays one unit as one CSS pixel.
|
|
182
|
+
|
|
183
|
+
Keep `x`, `y`, `velocity`, and `mass` props stable to let the simulation evolve. Changing any of these inputs resets the body's stored position, velocity, and mass to the currently supplied values. For movement that does not reset the body, use forces. `onChange` runs initially and on tracked changes; velocity comparisons use a threshold of `1` unit/s, while position changes also trigger it.
|
|
184
|
+
|
|
185
|
+
### `Bounds`
|
|
186
|
+
|
|
187
|
+
Defines collision geometry owned by its containing body. Choose either rectangle dimensions or a circle radius:
|
|
188
|
+
|
|
189
|
+
```tsx
|
|
190
|
+
// Rectangle:
|
|
191
|
+
<Bounds width={32} height={48} />;
|
|
192
|
+
// Or circle:
|
|
193
|
+
<Bounds radius={16} position={{ x: 16, y: 16 }} />;
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
Rectangle bounds use their top-left corner; circle bounds use their center. `position` is a local offset (default `{ x: 0, y: 0 }`). Optional `outline` displays the geometry for debugging; `style` controls its fill/stroke and `z` controls its visual sibling order. Bounds are invisible by default. Standalone bounds outside a body do not participate in physics.
|
|
197
|
+
|
|
198
|
+
### `gameCollision(key, handler)` and `gameHit(key, handler)`
|
|
199
|
+
|
|
200
|
+
Call these each frame with the body's public `key`. The handler receives the other body's public key once per reported body pair per frame.
|
|
201
|
+
|
|
202
|
+
- Physical collisions require both bodies to include each other's `layer` in `collidesWith`.
|
|
203
|
+
- Hits are directional: only the observing body's `hitsWith` needs to include the other body's layer.
|
|
204
|
+
- Hits alone do not separate bodies or change their velocities.
|
|
205
|
+
- Hooks read the previous frame's contact results because the current collision pass happens after tree construction. Contacts are reported repeatedly while detected; these are not enter/exit events.
|
|
206
|
+
|
|
207
|
+
```tsx
|
|
208
|
+
function PhysicsExample() {
|
|
209
|
+
gameCollision("ball", (otherKey) => {
|
|
210
|
+
if (otherKey === "floor") console.log("Ball contacted floor");
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
return (
|
|
214
|
+
<Scene>
|
|
215
|
+
<RigidBody2D key="ball" x={100} y={40}
|
|
216
|
+
layer="ball" collidesWith={["world"]} restitution={0.6}>
|
|
217
|
+
<Bounds radius={16} outline style={{ fill: "hotpink" }} />
|
|
218
|
+
</RigidBody2D>
|
|
219
|
+
<RigidBody2D key="floor" y={350} mass={0}
|
|
220
|
+
layer="world" collidesWith={["ball"]} restitution={0.6}>
|
|
221
|
+
<Bounds width={800} height={30} outline style={{ fill: "gray" }} />
|
|
222
|
+
</RigidBody2D>
|
|
223
|
+
</Scene>
|
|
224
|
+
);
|
|
225
|
+
}
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
### `gameRef<RigidBody2DSnapshot>(key)`
|
|
229
|
+
|
|
230
|
+
Reads a body's live stored state. Pass the returned `key` to the body's `ref`, and check `ready` before calling `snapshot()`:
|
|
231
|
+
|
|
232
|
+
```tsx
|
|
233
|
+
function TrackedBody() {
|
|
234
|
+
const body = gameRef<RigidBody2DSnapshot>("player.ref");
|
|
235
|
+
if (body.ready) {
|
|
236
|
+
const { position, velocity, mass } = body.snapshot();
|
|
237
|
+
// Use the snapshot for game logic or a HUD.
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
return (
|
|
241
|
+
<RigidBody2D key="player.body" ref={body.key} gravity={0}>
|
|
242
|
+
<Bounds width={32} height={32} outline />
|
|
243
|
+
</RigidBody2D>
|
|
244
|
+
);
|
|
245
|
+
}
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
Import `RigidBody2DSnapshot` with `import type`. The ref normally becomes ready on a later frame after the body attaches. A snapshot contains local position, velocity, and mass; it is a read interface, not a setter.
|
|
249
|
+
|
|
250
|
+
## Update, effect, and input hooks
|
|
251
|
+
|
|
252
|
+
### `gameUpdate(handler)`
|
|
253
|
+
|
|
254
|
+
Calls `handler(dt, frame, viewport)` immediately whenever the hook is evaluated. Used once in a component that runs every frame, it runs once per frame. `frame` starts at `0`; `dt` starts at `0` and then reflects the interval measured at the previous cleanup. `viewport` contains `{ width, height }` in CSS pixels.
|
|
255
|
+
|
|
256
|
+
```ts
|
|
257
|
+
gameUpdate((dt, frame, viewport) => {
|
|
258
|
+
// Integrate movement with dt / 1000, or run other per-frame logic.
|
|
259
|
+
});
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
### `gameEffect(key, handler, dependencies)`
|
|
263
|
+
|
|
264
|
+
Runs immediately on first use and when dependencies change. The callback receives the same arguments as `gameUpdate`. Dependencies can be strings, numbers, booleans, or values wrapped in `createComparator`.
|
|
265
|
+
|
|
266
|
+
```ts
|
|
267
|
+
gameEffect("score.log", () => {
|
|
268
|
+
console.log("Score changed", score);
|
|
269
|
+
}, [score]);
|
|
270
|
+
|
|
271
|
+
gameEffect("speed.log", () => {
|
|
272
|
+
console.log("Speed changed enough", speed);
|
|
273
|
+
}, [createComparator<number>(speed, (previous, next) => Math.abs(next - previous) >= 1)]);
|
|
274
|
+
```
|
|
275
|
+
|
|
276
|
+
Ordinary dependencies use `Object.is`. A comparator returns `true` when the effect should run; its previous value comes from the last effect run. An empty dependency array runs once for the lifetime of that state slot. Effects do not have a cleanup callback.
|
|
277
|
+
|
|
278
|
+
### `gameEvent(type, listener)`
|
|
279
|
+
|
|
280
|
+
Reads current input; call it each frame. It invokes the listener immediately for matching input, rather than installing a persistent subscription.
|
|
281
|
+
|
|
282
|
+
| Type | Listener payload | When reported |
|
|
283
|
+
| --- | --- | --- |
|
|
284
|
+
| `key` | `{ key: string }` | Each frame for each held key |
|
|
285
|
+
| `keyDown` | `{ key: string }` | New key presses; ignores browser repeat |
|
|
286
|
+
| `keyUp` | `{ key: string }` | Key releases |
|
|
287
|
+
| `touch` | `{ x, y }` | Each frame while the primary pointer is held |
|
|
288
|
+
| `touchStart` | `{ x, y }` | Primary pointer press on the canvas |
|
|
289
|
+
| `touchEnd` | `{ x, y }` | Primary pointer release or cancellation |
|
|
290
|
+
|
|
291
|
+
Key names use `KeyboardEvent.key`, for example `"ArrowLeft"`, `"a"`, or `" "` for space. Despite the `touch` names, pointer input supports mouse, touch, and pen, tracking one active pointer. Positions are relative to the canvas content area in CSS pixels.
|
|
292
|
+
|
|
293
|
+
```ts
|
|
294
|
+
gameEvent("keyDown", ({ key }) => {
|
|
295
|
+
if (key === " ") sendMessage("player.jump", null);
|
|
296
|
+
});
|
|
297
|
+
gameEvent("touchStart", ({ x, y }) => {
|
|
298
|
+
console.log("Pressed canvas at", x, y);
|
|
299
|
+
});
|
|
300
|
+
```
|
|
301
|
+
|
|
302
|
+
### `gameViewport()`
|
|
303
|
+
|
|
304
|
+
Returns the canvas's current CSS size as `{ width, height }`. Use this for responsive placement; the engine handles the canvas backing resolution for device pixel ratio.
|
|
305
|
+
|
|
306
|
+
```ts
|
|
307
|
+
const { width, height } = gameViewport();
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
## Animation and image hooks
|
|
311
|
+
|
|
312
|
+
### `gameAnimation(key, animations, config)`
|
|
313
|
+
|
|
314
|
+
Creates an animation descriptor for `Sprite`. `animations` is an ordered array of `[condition, frames, options?]`; the first true condition wins. A condition can be a boolean or a function returning a boolean. Frame numbers are zero-based, counted left to right and then top to bottom across the sheet.
|
|
315
|
+
|
|
316
|
+
Config requires `src` and `size` (the square frame size in source pixels). Optional `fps` defaults to `24`; `loop` defaults to `true`. A frame group's `{ loop }` overrides that default. Switching the selected group restarts its timing.
|
|
317
|
+
|
|
318
|
+
```tsx
|
|
319
|
+
function AnimatedPlayer({ moving }: { moving: boolean }) {
|
|
320
|
+
const animation = gameAnimation("player.animation", [
|
|
321
|
+
[moving, [4, 5, 6, 7]],
|
|
322
|
+
[true, [0, 1, 2, 3]],
|
|
323
|
+
], { src: "/player-sheet.png", size: 32, fps: 8 });
|
|
324
|
+
|
|
325
|
+
return <Sprite animation={animation} width={64} height={64} />;
|
|
326
|
+
}
|
|
327
|
+
```
|
|
328
|
+
|
|
329
|
+
Use a final `true` condition as a fallback. A non-looping group holds its final frame. Call `animation.onAnimationFinish(handler)` each frame to handle its completion transition; it is not a persistent listener. Keep the source URL unchanged for an animation key, and use a positive frame size that fits the sheet.
|
|
330
|
+
|
|
331
|
+
### `gameImage(src)`
|
|
332
|
+
|
|
333
|
+
Returns a cached `HTMLImageElement` when loaded, otherwise `null`. Useful for checking dimensions or readiness. `Sprite` and `gameAnimation` already use it internally.
|
|
334
|
+
|
|
335
|
+
```ts
|
|
336
|
+
const image = gameImage("/background.png");
|
|
337
|
+
if (image) {
|
|
338
|
+
const imageWidth = image.naturalWidth;
|
|
339
|
+
}
|
|
340
|
+
```
|
|
341
|
+
|
|
342
|
+
### `gameLerp(key, from, to, duration)`
|
|
343
|
+
|
|
344
|
+
Interpolates a number over `duration` milliseconds, returning `{ value, reset, update }`. Progress clamps at the target; a non-positive duration returns the target immediately.
|
|
345
|
+
|
|
346
|
+
```tsx
|
|
347
|
+
function SlidingPanel() {
|
|
348
|
+
const slide = gameLerp("panel.slide", -200, 20, 500);
|
|
349
|
+
gameEvent("keyDown", ({ key }) => {
|
|
350
|
+
if (key === "r") slide.reset();
|
|
351
|
+
if (key === "h") {
|
|
352
|
+
slide.update(() => ({ from: slide.value, to: -200, duration: 300 }));
|
|
353
|
+
}
|
|
354
|
+
});
|
|
355
|
+
return <Rect x={slide.value} y={50} width={180} height={100} />;
|
|
356
|
+
}
|
|
357
|
+
```
|
|
358
|
+
|
|
359
|
+
The initial arguments initialize stored interpolation data. Use `reset()` to restart that interpolation or `update(previous => ({ from?, to?, duration? }))` to change it and restart its clock. Timing uses wall-clock time. An update is reflected in the value returned on the next evaluation.
|
|
360
|
+
|
|
361
|
+
## Messages
|
|
362
|
+
|
|
363
|
+
### `sendMessage(type, value)` and `gameMessage(handler, types?)`
|
|
364
|
+
|
|
365
|
+
Send data between components without passing callbacks through the tree. Messages sent during a frame become available on the next frame, and each listener can read them. Call `gameMessage` every frame to receive them. The optional array filters by message type.
|
|
366
|
+
|
|
367
|
+
```ts
|
|
368
|
+
// In a sender:
|
|
369
|
+
sendMessage("score.add", 10);
|
|
370
|
+
|
|
371
|
+
// In a receiver, evaluated each frame:
|
|
372
|
+
gameMessage((type, value) => {
|
|
373
|
+
if (type === "score.add" && typeof value === "number") {
|
|
374
|
+
setScore((previous) => previous + value);
|
|
375
|
+
}
|
|
376
|
+
}, ["score.add"]);
|
|
377
|
+
```
|
|
378
|
+
|
|
379
|
+
Messages are cloned with `structuredClone`, so payloads must be cloneable data. Sending on every frame sends a new message every frame; use input or an effect when you want a single event.
|
|
380
|
+
|
|
381
|
+
## Sound
|
|
382
|
+
|
|
383
|
+
### `Sound`
|
|
384
|
+
|
|
385
|
+
Include a sound in the tree to play it. Props: required `key` and `src`; optional `loop` (default `false`), `volume` (default `1`), `onLoad`, and `onComplete`.
|
|
386
|
+
|
|
387
|
+
```tsx
|
|
388
|
+
<Sound key="music" src="/music.ogg" loop volume={0.4} />
|
|
389
|
+
```
|
|
390
|
+
|
|
391
|
+
A sound key must be unique across the entire tree. Keeping the same key and source preserves playback; changing volume or loop updates it. Removing the node stops playback. A completed one-shot does not restart merely because it remains in the tree: remove it for a frame and add it again, or use a new key. Changing the source also replaces playback.
|
|
392
|
+
|
|
393
|
+
`onLoad` runs once when the buffer is ready for that playback instance. `onComplete` runs once after natural playback completion, not when the node is removed. Browser audio may wait for a native pointer or keyboard gesture before becoming audible.
|
|
394
|
+
|
|
395
|
+
## Public API scope
|
|
396
|
+
|
|
397
|
+
The public components are `Scene`, `Sprite`, `Text`, `Rect`, `Circ`, `RigidBody2D`, `Bounds`, and `Sound`. The hooks described above, `DreamFactory`, `registerRoot`, `createComparator`, `createDynamicId`, and `sendMessage` are also exported.
|
|
398
|
+
|
|
399
|
+
Public type exports are `SceneProps`, `GameObject`, `Viewport`, `Vector2d`, `RigidBody2DSnapshot`, and `EventType`. Other implementation files, including `Img`, `Txt`, and the unfinished global helpers, are not public package exports.
|
package/test/cli.test.js
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
const assert = require("node:assert/strict");
|
|
2
|
+
const fs = require("node:fs/promises");
|
|
3
|
+
const os = require("node:os");
|
|
4
|
+
const path = require("node:path");
|
|
5
|
+
const { spawnSync } = require("node:child_process");
|
|
6
|
+
const { test } = require("node:test");
|
|
7
|
+
|
|
8
|
+
const cli = path.resolve(__dirname, "../index.js");
|
|
9
|
+
const reference = "DISCO_DREAMER_REFERENCE.md";
|
|
10
|
+
|
|
11
|
+
async function workspace(t) {
|
|
12
|
+
const directory = await fs.mkdtemp(path.join(os.tmpdir(), "dreamer-cli-"));
|
|
13
|
+
t.after(() => fs.rm(directory, { recursive: true, force: true }));
|
|
14
|
+
return directory;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function run(cwd, args) {
|
|
18
|
+
const result = spawnSync(process.execPath, [cli, ...args], {
|
|
19
|
+
cwd,
|
|
20
|
+
encoding: "utf8",
|
|
21
|
+
timeout: 10000,
|
|
22
|
+
});
|
|
23
|
+
assert.ifError(result.error);
|
|
24
|
+
return result;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
test("default app includes the reference and updates the package name", async (t) => {
|
|
28
|
+
const cwd = await workspace(t);
|
|
29
|
+
const result = run(cwd, ["my-app", "--skip-install"]);
|
|
30
|
+
assert.equal(result.status, 0, result.stderr);
|
|
31
|
+
assert.equal(await fs.readFile(path.join(cwd, "my-app", reference), "utf8"),
|
|
32
|
+
await fs.readFile(path.resolve(__dirname, "../template", reference), "utf8"));
|
|
33
|
+
const manifest = JSON.parse(await fs.readFile(path.join(cwd, "my-app/package.json"), "utf8"));
|
|
34
|
+
assert.equal(manifest.name, "my-app");
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
for (const flag of ["--ref-only", "-ro"]) {
|
|
38
|
+
test(`${flag} copies only the reference into the current existing project`, async (t) => {
|
|
39
|
+
const cwd = await workspace(t);
|
|
40
|
+
await fs.writeFile(path.join(cwd, "package.json"), '{"name":"existing"}\n');
|
|
41
|
+
const result = run(cwd, [flag]);
|
|
42
|
+
assert.equal(result.status, 0, result.stderr);
|
|
43
|
+
assert.deepEqual((await fs.readdir(cwd)).sort(), [reference, "package.json"]);
|
|
44
|
+
assert.equal(await fs.readFile(path.join(cwd, "package.json"), "utf8"), '{"name":"existing"}\n');
|
|
45
|
+
assert.doesNotMatch(result.stdout, /npm install|npm run dev|Installing dependencies/);
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
test(`${flag} supports a new nested destination without npm name restrictions`, async (t) => {
|
|
49
|
+
const cwd = await workspace(t);
|
|
50
|
+
const result = run(cwd, ["docs/Reference Notes", flag]);
|
|
51
|
+
assert.equal(result.status, 0, result.stderr);
|
|
52
|
+
assert.deepEqual(await fs.readdir(path.join(cwd, "docs/Reference Notes")), [reference]);
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
for (const flag of ["--exclude-reference", "-er"]) {
|
|
57
|
+
test(`${flag} excludes the reference while copying the app`, async (t) => {
|
|
58
|
+
const cwd = await workspace(t);
|
|
59
|
+
const result = run(cwd, [flag, "my-app", "--skip-install"]);
|
|
60
|
+
assert.equal(result.status, 0, result.stderr);
|
|
61
|
+
await assert.rejects(fs.access(path.join(cwd, "my-app", reference)), { code: "ENOENT" });
|
|
62
|
+
await fs.access(path.join(cwd, "my-app/package.json"));
|
|
63
|
+
await fs.access(path.join(cwd, "my-app/src/index.tsx"));
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
test("reference-only refuses to overwrite an existing reference", async (t) => {
|
|
68
|
+
const cwd = await workspace(t);
|
|
69
|
+
await fs.writeFile(path.join(cwd, reference), "custom reference");
|
|
70
|
+
const result = run(cwd, ["--ref-only"]);
|
|
71
|
+
assert.equal(result.status, 1);
|
|
72
|
+
assert.match(result.stderr, /Reference already exists/);
|
|
73
|
+
assert.equal(await fs.readFile(path.join(cwd, reference), "utf8"), "custom reference");
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
test("conflicting modes fail before creating files for all aliases", async (t) => {
|
|
77
|
+
const cwd = await workspace(t);
|
|
78
|
+
for (const refFlag of ["--ref-only", "-ro"]) {
|
|
79
|
+
for (const excludeFlag of ["--exclude-reference", "-er"]) {
|
|
80
|
+
const result = run(cwd, ["my-app", refFlag, excludeFlag]);
|
|
81
|
+
assert.equal(result.status, 1);
|
|
82
|
+
assert.match(result.stderr, /cannot be used together/);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
assert.deepEqual(await fs.readdir(cwd), []);
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
test("existing app safeguards and argument validation still apply", async (t) => {
|
|
89
|
+
const cwd = await workspace(t);
|
|
90
|
+
await fs.writeFile(path.join(cwd, "keep.txt"), "keep");
|
|
91
|
+
for (const args of [[".", "--skip-install"], [".", "-er", "--skip-install"]]) {
|
|
92
|
+
const result = run(cwd, args);
|
|
93
|
+
assert.equal(result.status, 1);
|
|
94
|
+
assert.match(result.stderr, /not an empty directory/);
|
|
95
|
+
}
|
|
96
|
+
assert.match(run(cwd, ["--unknown"]).stderr, /Unknown option/);
|
|
97
|
+
assert.match(run(cwd, ["a", "b", "-ro"]).stderr, /only one project directory/);
|
|
98
|
+
assert.deepEqual(await fs.readdir(cwd), ["keep.txt"]);
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
test("help documents both reference modes and aliases", async (t) => {
|
|
102
|
+
const result = run(await workspace(t), ["--help"]);
|
|
103
|
+
assert.equal(result.status, 0, result.stderr);
|
|
104
|
+
assert.match(result.stdout, /-ro, --ref-only/);
|
|
105
|
+
assert.match(result.stdout, /-er, --exclude-reference/);
|
|
106
|
+
});
|