woofjs-engine 0.2.0 → 0.3.0

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.
Files changed (49) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +16 -106
  3. package/THIRD_PARTY_NOTICES.md +7 -0
  4. package/dist/canvas.js +4 -31
  5. package/dist/collision.js +8 -5
  6. package/dist/game.js +4 -84
  7. package/dist/index-1jykaz1m.js +142 -0
  8. package/dist/index-9mz0qg9d.js +39 -0
  9. package/dist/index-b9a70qgn.js +34 -0
  10. package/dist/index-dp75gf4w.js +57 -0
  11. package/dist/index-f63yb8zf.js +85 -0
  12. package/dist/index-gypg8d50.js +31 -0
  13. package/dist/index-pw0zq53c.js +2533 -0
  14. package/dist/index.js +134 -239
  15. package/dist/input.js +4 -33
  16. package/dist/play.js +296 -0
  17. package/dist/sound.js +4 -56
  18. package/dist/store.js +4 -30
  19. package/dist/types/canvas.d.ts +20 -2
  20. package/dist/types/collision.d.ts +62 -0
  21. package/dist/types/game.d.ts +21 -1
  22. package/dist/types/global.d.ts +4 -0
  23. package/dist/types/helpers.d.ts +92 -0
  24. package/dist/types/index.d.ts +23 -12
  25. package/dist/types/input.d.ts +4 -0
  26. package/dist/types/play.d.ts +159 -0
  27. package/dist/types/sound.d.ts +10 -3
  28. package/dist/types/sprites/custom.d.ts +9 -0
  29. package/dist/types/sprites/easing.d.ts +9 -0
  30. package/dist/types/sprites/geometry.d.ts +22 -0
  31. package/dist/types/sprites/options.d.ts +98 -0
  32. package/dist/types/sprites/render.d.ts +2 -0
  33. package/dist/types/sprites/sprite.d.ts +283 -0
  34. package/dist/types/store.d.ts +4 -0
  35. package/dist/types/ui.d.ts +65 -0
  36. package/dist/types/woof.d.ts +386 -0
  37. package/dist/types/world/audio.d.ts +118 -0
  38. package/dist/types/world/globals.d.ts +3 -0
  39. package/dist/types/world/keys.d.ts +2 -0
  40. package/dist/types/world/options.d.ts +44 -0
  41. package/dist/types/world/render.d.ts +13 -0
  42. package/dist/types/world/scheduler.d.ts +65 -0
  43. package/dist/ui.js +235 -0
  44. package/dist/woof.global.js +3577 -0
  45. package/docs/api.json +5359 -0
  46. package/docs/woof-parity.md +231 -0
  47. package/package.json +25 -8
  48. package/docs/architecture.md +0 -37
  49. package/docs/planning.md +0 -33
package/CHANGELOG.md ADDED
@@ -0,0 +1,13 @@
1
+ # Changelog
2
+
3
+ ## 0.3.0
4
+
5
+ WoofJS is ported: the same names and style, in JavaScript and TypeScript.
6
+
7
+ - `woofjs-engine`: projects with sprites, tasks, keyboard, mouse, touch and gamepad input, scenes, particles, camera, storage and theming.
8
+ - `woofjs-engine/play`: WoofJS globals as imports. `woof.global.js` works from a script tag.
9
+ - Sound: `amplify` (a number or `'max'`), limiter, fades, pan, speed and loop.
10
+ - `woofjs-engine/ui`: `mountGame`, `readTheme` and `watchTheme` put a game in a page and follow its theme.
11
+ - Game components for shadcn-svelte, shadcn/ui and Optimus UI, installable from the docs site.
12
+ - New documentation with tutorials and editable examples.
13
+ - The APIs of 0.2 still work.
package/README.md CHANGED
@@ -1,120 +1,30 @@
1
- # woofjs-engine
2
-
3
- A small JavaScript engine for the parts of a game loop that are easy to get subtly wrong: advancing state by elapsed time, rendering the current state, and controlling sound playback.
4
-
5
- The project takes inspiration from the approachable, component-oriented style of [WoofJS](https://github.com/stevekrouse/WoofJS) and [woofjs.com](https://woofjs.com/). This is an independent implementation; it does not claim upstream compatibility. The engine stays framework-neutral. You provide your game state and callbacks; a Node program, a browser page, or a Svelte component can decide when and where to run them.
1
+ [![Docs](https://img.shields.io/badge/docs-read-blue)](https://ratradworke.gitlab.io/woofjs-engine/) [![npm](https://img.shields.io/npm/v/woofjs-engine)](https://www.npmjs.com/package/woofjs-engine) [![pipeline](https://gitlab.com/ratradworke/woofjs-engine/badges/main/pipeline.svg)](https://gitlab.com/ratradworke/woofjs-engine/-/pipelines)
6
2
 
7
- [Documentation site](https://woofjs-engine-c23a47.gitlab.io/) · [Source and examples](https://gitlab.com/ratradworke/woofjs-engine)
8
-
9
- ## Getting started
3
+ # woofjs-engine
10
4
 
11
- Install the package in your JavaScript or TypeScript project:
5
+ A browser game engine and TypeScript port of WoofJS, for JavaScript and TypeScript. Sprites, input, timing, sound with `amplify`, scenes, and components for Svelte, React and Angular.
12
6
 
13
7
  ```sh
14
8
  npm install woofjs-engine
15
9
  ```
16
10
 
17
- The library is implemented in TypeScript and builds browser-ready ES modules plus `.d.ts` declarations with Bun. JavaScript consumers can import the package normally; TypeScript consumers receive typed APIs from the same entry points. Import the helpers:
18
-
19
11
  ```js
20
- import { createGame, createSound, createStore, createCanvas } from 'woofjs-engine';
21
- ```
22
-
23
- `createGame` takes an initial state plus an `update` callback and a `render` callback. The update callback receives elapsed time in **seconds**, so movement can be expressed in units per second rather than units per frame.
12
+ import { woof } from 'woofjs-engine';
24
13
 
25
- ```js
26
- import { createGame } from 'woofjs-engine';
27
-
28
- const game = createGame({
29
- state: { x: 0 },
30
- update(deltaSeconds, state) {
31
- state.x += 120 * deltaSeconds;
32
- },
33
- render(state) {
34
- console.log(`Player position: ${state.x.toFixed(1)}`);
35
- },
14
+ const game = woof({ width: 350, height: 300 });
15
+ const player = game.circle({ radius: 20, color: 'royalblue' });
16
+ game.onUpdate(dt => {
17
+ if (game.key('LEFT')) player.x -= 150 * dt;
18
+ if (game.key('RIGHT')) player.x += 150 * dt;
36
19
  });
37
-
38
- // step() is useful for deterministic updates, tests, and non-browser hosts.
39
- game.step(1000 / 60); // delta is supplied in milliseconds
40
- console.log(game.getState());
41
20
  ```
42
21
 
43
- For an animation loop, provide the host's frame scheduling functions and call `start()`:
44
-
45
- ```js
46
- const game = createGame({
47
- state: { x: 0 },
48
- update(deltaSeconds, state) {
49
- state.x += 120 * deltaSeconds;
50
- },
51
- render(state) {
52
- drawPlayer(state.x);
53
- },
54
- requestFrame: callback => requestAnimationFrame(callback),
55
- cancelFrame: id => cancelAnimationFrame(id),
56
- });
57
-
58
- game.start();
59
- // Later, for example when leaving the screen:
60
- game.stop();
61
- ```
62
-
63
- `step(deltaMs)` advances one frame explicitly. `start()` schedules repeated frames; `stop()` cancels them. `getState()` returns the current state. See [the architecture notes](docs/architecture.md) for lifecycle and timing details, and the [examples](examples/) for Node and Svelte usage.
64
-
65
- ## Shared state and canvases
66
-
67
- `createStore` lets multiple views share state and subscribe to changes. `createCanvas` creates an independent canvas surface, so a host can attach more than one canvas and draw each from the same store.
68
-
69
- ```js
70
- const store = createStore({ score: 0 });
71
- const unsubscribe = store.subscribe(state => console.log('score:', state.score));
72
- store.update(state => ({ ...state, score: state.score + 1 }));
73
-
74
- const surface = createCanvas({ parent: document.querySelector('#game'), width: 640, height: 360 });
75
- // Draw through surface.context; call surface.destroy() when it is no longer needed.
76
- // Call unsubscribe() when the subscriber is removed.
77
- ```
78
-
79
- See [examples/multiple-canvases.js](examples/multiple-canvases.js) for two canvases observing one store.
80
-
81
- ## Keyboard and collision
82
-
83
- Use `createKeyboard(window)` in a browser to track physical key codes. Call `destroy()` when your game or component is removed. It clears held keys on blur and does not prevent browser shortcuts or scrolling.
84
-
85
- ```js
86
- import { createKeyboard, overlaps } from 'woofjs-engine';
87
- const keyboard = createKeyboard(window);
88
- if (keyboard.isDown('ArrowRight')) player.x += 2;
89
- if (overlaps(player, target)) console.log('Collected!');
90
- // Later: keyboard.destroy();
91
- ```
92
-
93
- `overlaps` accepts rectangles with `x`, `y`, `width`, and `height`; touching edges alone do not count. Try the playable example on the [documentation site](https://woofjs-engine-c23a47.gitlab.io/#play).
94
-
95
- ## Sound
96
-
97
- Sound uses the Web Audio API supplied by the host. The engine does not fetch or decode audio files for you: pass a decoded `AudioBuffer` and an `AudioContext`.
98
-
99
- ```js
100
- const sound = createSound(decodedBuffer, audioContext, {
101
- volume: 0.7,
102
- maxGain: 4,
103
- });
104
-
105
- const playback = sound.startPlaying();
106
- playback.amplify(1.5); // clamps to the configured range [0, maxGain]
107
- // playback.amplify('max') selects maxGain; playback.stop() ends playback.
108
- ```
109
-
110
- Numeric amplification multiplies the playback's initial `volume` before clamping to `maxGain` (for example, `volume: 0.7` and `amplify(4)` gives gain `2.8` when `maxGain` is at least `2.8`). This software gain cap does not guarantee protection from clipping, loud speakers, or hearing damage; keep application and device volume appropriate.
111
-
112
- Browsers generally require audio to begin in response to a user gesture. See [examples/browser-sound.js](examples/browser-sound.js).
113
-
114
- ## Development
115
-
116
- Run `npm ci`, `npm run build`, and `npm test` from the repository root. Bun builds the JS bundles; TypeScript emits declarations. Tests import the compiled JS from `dist/`.
22
+ ## UI components
117
23
 
118
- ## Current scope and direction
24
+ | Library | Guide |
25
+ | --- | --- |
26
+ | shadcn-svelte | [Add the component](https://ratradworke.gitlab.io/woofjs-engine/#shadcn-svelte) |
27
+ | shadcn/ui | [Add the component](https://ratradworke.gitlab.io/woofjs-engine/#shadcn-ui) |
28
+ | Optimus UI | [Add the component](https://ratradworke.gitlab.io/woofjs-engine/#optimus-ui) |
119
29
 
120
- The current API is intentionally compact: deterministic stepping, a start/stop loop, shared state, canvas surfaces, and sound playback controls. The [architecture](docs/architecture.md) and [planning](docs/planning.md) documents describe the design boundaries and possible next steps without promising a release schedule. Richer UI component mappings and optional compilation remain ideas for future exploration, not capabilities promised by the current API.
30
+ [Documentation](https://ratradworke.gitlab.io/woofjs-engine/) · [npm](https://www.npmjs.com/package/woofjs-engine) · [Source](https://gitlab.com/ratradworke/woofjs-engine) · [License](LICENSE) · [Third-party notice](THIRD_PARTY_NOTICES.md)
@@ -0,0 +1,7 @@
1
+ Copyright (c) 2016 Coding Space, LLC.
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/dist/canvas.js CHANGED
@@ -1,33 +1,6 @@
1
- // src/canvas.ts
2
- function createCanvas({ document: doc = globalThis.document, parent, width = 300, height = 150, context = "2d", contextOptions } = {}) {
3
- if (!doc || typeof doc.createElement !== "function")
4
- throw new Error("A browser document is required; pass document explicitly");
5
- const element = doc.createElement("canvas");
6
- element.width = width;
7
- element.height = height;
8
- const drawingContext = element.getContext(context, contextOptions);
9
- if (!drawingContext)
10
- throw new Error(`Unable to create ${context} canvas context`);
11
- parent?.appendChild(element);
12
- let removed = false;
13
- return {
14
- element,
15
- context: drawingContext,
16
- resize(nextWidth, nextHeight) {
17
- if (removed)
18
- throw new Error("Cannot resize a removed canvas");
19
- element.width = nextWidth;
20
- element.height = nextHeight;
21
- return this;
22
- },
23
- destroy() {
24
- if (!removed) {
25
- removed = true;
26
- element.remove();
27
- }
28
- }
29
- };
30
- }
1
+ import {
2
+ createCanvas2
3
+ } from "./index-9mz0qg9d.js";
31
4
  export {
32
- createCanvas
5
+ createCanvas2 as createCanvas
33
6
  };
package/dist/collision.js CHANGED
@@ -1,7 +1,10 @@
1
- // src/collision.ts
2
- function overlaps(a, b) {
3
- return a.width > 0 && a.height > 0 && b.width > 0 && b.height > 0 && a.x < b.x + b.width && a.x + a.width > b.x && a.y < b.y + b.height && a.y + a.height > b.y;
4
- }
1
+ import {
2
+ overlaps2,
3
+ intersects2,
4
+ detectCollision2
5
+ } from "./index-1jykaz1m.js";
5
6
  export {
6
- overlaps
7
+ detectCollision2 as detectCollision,
8
+ intersects2 as intersects,
9
+ overlaps2 as overlaps
7
10
  };
package/dist/game.js CHANGED
@@ -1,86 +1,6 @@
1
- // src/game.ts
2
- function createGame({
3
- state = {},
4
- update = () => {},
5
- render = () => {},
6
- requestFrame,
7
- cancelFrame
8
- } = {}) {
9
- let running = false;
10
- let frameId = null;
11
- let previousTime = null;
12
- let frame = 0;
13
- let currentState = state;
14
- function step(deltaMs, timestamp = 0) {
15
- if (!Number.isFinite(deltaMs) || deltaMs < 0)
16
- throw new RangeError("deltaMs must be a finite, non-negative number");
17
- const deltaSeconds = deltaMs / 1000;
18
- const info = { deltaMs, timestamp, frame };
19
- update(deltaSeconds, currentState, info);
20
- render(currentState, { ...info, deltaSeconds });
21
- frame += 1;
22
- return currentState;
23
- }
24
- function getRequestFrame() {
25
- const fn = requestFrame ?? globalThis.requestAnimationFrame;
26
- if (typeof fn !== "function")
27
- throw new Error("requestAnimationFrame is unavailable; provide requestFrame");
28
- return fn;
29
- }
30
- function tick(timestamp) {
31
- if (!running)
32
- return;
33
- const delta = previousTime === null ? 0 : Math.max(0, timestamp - previousTime);
34
- previousTime = timestamp;
35
- frameId = null;
36
- try {
37
- step(delta, timestamp);
38
- if (running)
39
- frameId = getRequestFrame()(tick);
40
- } catch (error) {
41
- running = false;
42
- previousTime = null;
43
- throw error;
44
- }
45
- }
46
- const loop = {
47
- step,
48
- getState: () => currentState,
49
- setState(nextState) {
50
- currentState = nextState;
51
- return currentState;
52
- },
53
- start() {
54
- if (running)
55
- return this;
56
- const schedule = getRequestFrame();
57
- previousTime = null;
58
- running = true;
59
- try {
60
- frameId = schedule(tick);
61
- } catch (error) {
62
- running = false;
63
- throw error;
64
- }
65
- return this;
66
- },
67
- stop() {
68
- if (!running)
69
- return this;
70
- running = false;
71
- const cancel = cancelFrame ?? globalThis.cancelAnimationFrame;
72
- if (frameId !== null && typeof cancel === "function")
73
- cancel(frameId);
74
- frameId = null;
75
- previousTime = null;
76
- return this;
77
- },
78
- get running() {
79
- return running;
80
- }
81
- };
82
- return loop;
83
- }
1
+ import {
2
+ createGame2
3
+ } from "./index-f63yb8zf.js";
84
4
  export {
85
- createGame
5
+ createGame2 as createGame
86
6
  };
@@ -0,0 +1,142 @@
1
+ // src/collision.ts
2
+ function overlaps2(a, b) {
3
+ return a.width > 0 && a.height > 0 && b.width > 0 && b.height > 0 && a.x < b.x + b.width && a.x + a.width > b.x && a.y < b.y + b.height && a.y + a.height > b.y;
4
+ }
5
+ function project(c, x, y) {
6
+ if (c.kind === "polygon") {
7
+ const values = c.points.map((point) => point.x * x + point.y * y);
8
+ return [Math.min(...values), Math.max(...values)];
9
+ }
10
+ const center = c.x * x + c.y * y;
11
+ if (c.kind === "circle")
12
+ return [center - c.radius, center + c.radius];
13
+ const cos = Math.cos(c.angle);
14
+ const sin = Math.sin(c.angle);
15
+ const radius = Math.hypot(c.radiusX * (x * cos + y * sin), c.radiusY * (y * cos - x * sin));
16
+ return [center - radius, center + radius];
17
+ }
18
+ function ellipseIntersects(ellipse, other) {
19
+ const cos = Math.cos(ellipse.angle);
20
+ const sin = Math.sin(ellipse.angle);
21
+ const rx = Math.abs(ellipse.radiusX);
22
+ const ry = Math.abs(ellipse.radiusY);
23
+ if (rx === 0 || ry === 0) {
24
+ const x = rx * cos - ry * sin;
25
+ const y = rx * sin + ry * cos;
26
+ return intersects2({
27
+ kind: "polygon",
28
+ points: [
29
+ { x: ellipse.x - x, y: ellipse.y - y },
30
+ { x: ellipse.x + x, y: ellipse.y + y }
31
+ ]
32
+ }, other);
33
+ }
34
+ const transform = (x, y) => ({
35
+ x: (x * cos + y * sin) / rx,
36
+ y: (y * cos - x * sin) / ry
37
+ });
38
+ if (other.kind === "polygon") {
39
+ return intersects2({ kind: "circle", x: 0, y: 0, radius: 1 }, {
40
+ kind: "polygon",
41
+ points: other.points.map((point) => transform(point.x - ellipse.x, point.y - ellipse.y))
42
+ });
43
+ }
44
+ const center = transform(other.x - ellipse.x, other.y - ellipse.y);
45
+ const angle = other.kind === "circle" ? 0 : other.angle;
46
+ const otherX = Math.abs(other.kind === "circle" ? other.radius : other.radiusX);
47
+ const otherY = Math.abs(other.kind === "circle" ? other.radius : other.radiusY);
48
+ const u = transform(otherX * Math.cos(angle), otherX * Math.sin(angle));
49
+ const v = transform(-otherY * Math.sin(angle), otherY * Math.cos(angle));
50
+ const xx = u.x * u.x + v.x * v.x;
51
+ const xy = u.x * u.y + v.x * v.y;
52
+ const yy = u.y * u.y + v.y * v.y;
53
+ const axis = Math.atan2(2 * xy, xx - yy) / 2;
54
+ const c = Math.cos(axis);
55
+ const s = Math.sin(axis);
56
+ const major = Math.max(0, (xx + yy + Math.hypot(xx - yy, 2 * xy)) / 2);
57
+ const determinant = u.x * v.y - u.y * v.x;
58
+ const minor = major === 0 ? 0 : determinant / major * determinant;
59
+ const cx = center.x * c + center.y * s;
60
+ const cy = -center.x * s + center.y * c;
61
+ const inside = (major > 0 ? cx * cx / major : cx === 0 ? 0 : Infinity) + (minor > 0 ? cy * cy / minor : cy === 0 ? 0 : Infinity);
62
+ if (inside <= 1)
63
+ return true;
64
+ const equation = (lambda) => {
65
+ const a = major > 0 ? Math.sqrt(major) * cx / (major + lambda) : 0;
66
+ const b = minor > 0 ? Math.sqrt(minor) * cy / (minor + lambda) : 0;
67
+ return a * a + b * b;
68
+ };
69
+ let low = 0;
70
+ let high = Math.max(1, Math.sqrt(major) * Math.hypot(cx, cy));
71
+ while (equation(high) > 1)
72
+ high *= 2;
73
+ for (let i = 0;i < 100; i++) {
74
+ const mid = (low + high) / 2;
75
+ if (equation(mid) > 1)
76
+ low = mid;
77
+ else
78
+ high = mid;
79
+ }
80
+ const dx = major > 0 ? cx * high / (major + high) : cx;
81
+ const dy = minor > 0 ? cy * high / (minor + high) : cy;
82
+ return Math.hypot(dx, dy) <= 1 + 0.000000000001;
83
+ }
84
+ function intersects2(a, b) {
85
+ const bounds = (c) => {
86
+ const x = project(c, 1, 0);
87
+ const y = project(c, 0, 1);
88
+ return [x[0], x[1], y[0], y[1]];
89
+ };
90
+ const aa = bounds(a), bb = bounds(b);
91
+ if (aa[1] < bb[0] || bb[1] < aa[0] || aa[3] < bb[2] || bb[3] < aa[2])
92
+ return false;
93
+ if (a.kind === "ellipse")
94
+ return ellipseIntersects(a, b);
95
+ if (b.kind === "ellipse")
96
+ return ellipseIntersects(b, a);
97
+ if (a.kind === "circle" && b.kind === "circle")
98
+ return Math.hypot(a.x - b.x, a.y - b.y) <= a.radius + b.radius;
99
+ const axes = [];
100
+ for (const c of [a, b])
101
+ if (c.kind === "polygon")
102
+ for (let i = 0;i < c.points.length; i++) {
103
+ const p = c.points[i], q = c.points[(i + 1) % c.points.length], x = -(q.y - p.y), y = q.x - p.x, d = Math.hypot(x, y);
104
+ if (d)
105
+ axes.push({ x: x / d, y: y / d });
106
+ }
107
+ const circle = a.kind === "circle" ? a : b.kind === "circle" ? b : undefined, poly = a.kind === "polygon" ? a : b.kind === "polygon" ? b : undefined;
108
+ if (circle && poly && poly.points.length) {
109
+ const p = poly.points.reduce((best, v) => Math.hypot(v.x - circle.x, v.y - circle.y) < Math.hypot(best.x - circle.x, best.y - circle.y) ? v : best);
110
+ const x = p.x - circle.x, y = p.y - circle.y, d = Math.hypot(x, y);
111
+ if (d)
112
+ axes.push({ x: x / d, y: y / d });
113
+ }
114
+ const projection = (c, axis) => project(c, axis.x, axis.y);
115
+ return axes.every((axis) => {
116
+ const x = projection(a, axis), y = projection(b, axis);
117
+ return x[1] >= y[0] && y[1] >= x[0];
118
+ });
119
+ }
120
+ function detectCollision2(a, b) {
121
+ const normalize = (shape) => {
122
+ if ("kind" in shape)
123
+ return shape;
124
+ if ("r" in shape)
125
+ return {
126
+ kind: "circle",
127
+ x: shape.pos.x,
128
+ y: shape.pos.y,
129
+ radius: shape.r
130
+ };
131
+ return {
132
+ kind: "polygon",
133
+ points: shape.calcPoints.map((point) => ({
134
+ x: shape.pos.x + point.x,
135
+ y: shape.pos.y + point.y
136
+ }))
137
+ };
138
+ };
139
+ return intersects2(normalize(a), normalize(b));
140
+ }
141
+
142
+ export { overlaps2, intersects2, detectCollision2 };
@@ -0,0 +1,39 @@
1
+ // src/canvas.ts
2
+ function createCanvas2({
3
+ document: doc = globalThis.document,
4
+ parent,
5
+ width = 300,
6
+ height = 150,
7
+ context = "2d",
8
+ contextOptions
9
+ } = {}) {
10
+ if (!doc || typeof doc.createElement !== "function")
11
+ throw new Error("A browser document is required; pass document explicitly");
12
+ const element = doc.createElement("canvas");
13
+ element.width = width;
14
+ element.height = height;
15
+ const drawingContext = element.getContext(context, contextOptions);
16
+ if (!drawingContext)
17
+ throw new Error(`Unable to create ${context} canvas context`);
18
+ parent?.appendChild(element);
19
+ let removed = false;
20
+ return {
21
+ element,
22
+ context: drawingContext,
23
+ resize(nextWidth, nextHeight) {
24
+ if (removed)
25
+ throw new Error("Cannot resize a removed canvas");
26
+ element.width = nextWidth;
27
+ element.height = nextHeight;
28
+ return this;
29
+ },
30
+ destroy() {
31
+ if (!removed) {
32
+ removed = true;
33
+ element.remove();
34
+ }
35
+ }
36
+ };
37
+ }
38
+
39
+ export { createCanvas2 };
@@ -0,0 +1,34 @@
1
+ // src/input.ts
2
+ function createKeyboard2(target = globalThis.window) {
3
+ if (!target || typeof target.addEventListener !== "function")
4
+ throw new Error("A keyboard event target is required");
5
+ const pressed = new Set;
6
+ const down = (event) => {
7
+ const code = event.code;
8
+ if (code)
9
+ pressed.add(code);
10
+ };
11
+ const up = (event) => {
12
+ pressed.delete(event.code);
13
+ };
14
+ const clear = () => pressed.clear();
15
+ target.addEventListener("keydown", down);
16
+ target.addEventListener("keyup", up);
17
+ target.addEventListener("blur", clear);
18
+ let destroyed = false;
19
+ return {
20
+ isDown: (code) => pressed.has(code),
21
+ clear,
22
+ destroy() {
23
+ if (destroyed)
24
+ return;
25
+ destroyed = true;
26
+ target.removeEventListener("keydown", down);
27
+ target.removeEventListener("keyup", up);
28
+ target.removeEventListener("blur", clear);
29
+ clear();
30
+ }
31
+ };
32
+ }
33
+
34
+ export { createKeyboard2 };
@@ -0,0 +1,57 @@
1
+ // src/sound.ts
2
+ function createSound2(buffer, audioContext, { volume = 1, maxGain = 4 } = {}) {
3
+ if (!buffer)
4
+ throw new TypeError("buffer is required");
5
+ if (!audioContext || typeof audioContext.createBufferSource !== "function" || typeof audioContext.createGain !== "function") {
6
+ throw new TypeError("audioContext must provide createBufferSource() and createGain()");
7
+ }
8
+ if (!Number.isFinite(maxGain) || maxGain < 0)
9
+ throw new RangeError("maxGain must be a finite, non-negative number");
10
+ if (!Number.isFinite(volume) || volume < 0)
11
+ throw new RangeError("volume must be a finite, non-negative number");
12
+ return {
13
+ startPlaying({ loop = false, playbackRate = 1 } = {}) {
14
+ const source = audioContext.createBufferSource();
15
+ const gainNode = audioContext.createGain();
16
+ source.buffer = buffer;
17
+ source.loop = Boolean(loop);
18
+ if (source.playbackRate)
19
+ source.playbackRate.value = playbackRate;
20
+ const baseGain = clamp(volume, maxGain);
21
+ gainNode.gain.value = baseGain;
22
+ source.connect(gainNode);
23
+ gainNode.connect(audioContext.destination);
24
+ source.start();
25
+ let stopped = false;
26
+ return {
27
+ source,
28
+ amplify(multiplier) {
29
+ if (stopped)
30
+ return this;
31
+ if (multiplier === "max")
32
+ gainNode.gain.value = maxGain;
33
+ else if (typeof multiplier === "number" && Number.isFinite(multiplier)) {
34
+ gainNode.gain.value = clamp(baseGain * multiplier, maxGain);
35
+ } else
36
+ throw new TypeError("amplify expects a finite multiplier or 'max'");
37
+ return this;
38
+ },
39
+ stop() {
40
+ if (!stopped) {
41
+ stopped = true;
42
+ source.stop();
43
+ }
44
+ return this;
45
+ },
46
+ get stopped() {
47
+ return stopped;
48
+ }
49
+ };
50
+ }
51
+ };
52
+ }
53
+ function clamp(value, maximum) {
54
+ return Math.min(maximum, Math.max(0, value));
55
+ }
56
+
57
+ export { createSound2 };
@@ -0,0 +1,85 @@
1
+ // src/game.ts
2
+ function createGame2({
3
+ state = {},
4
+ update = () => {},
5
+ render = () => {},
6
+ requestFrame,
7
+ cancelFrame
8
+ } = {}) {
9
+ let running = false;
10
+ let frameId = null;
11
+ let previousTime = null;
12
+ let frame = 0;
13
+ let currentState = state;
14
+ function step(deltaMs, timestamp = 0) {
15
+ if (!Number.isFinite(deltaMs) || deltaMs < 0)
16
+ throw new RangeError("deltaMs must be a finite, non-negative number");
17
+ const deltaSeconds = deltaMs / 1000;
18
+ const info = { deltaMs, timestamp, frame };
19
+ update(deltaSeconds, currentState, info);
20
+ render(currentState, { ...info, deltaSeconds });
21
+ frame += 1;
22
+ return currentState;
23
+ }
24
+ function getRequestFrame() {
25
+ const fn = requestFrame ?? globalThis.requestAnimationFrame;
26
+ if (typeof fn !== "function")
27
+ throw new Error("requestAnimationFrame is unavailable; provide requestFrame");
28
+ return fn;
29
+ }
30
+ function tick(timestamp) {
31
+ if (!running)
32
+ return;
33
+ const delta = previousTime === null ? 0 : Math.max(0, timestamp - previousTime);
34
+ previousTime = timestamp;
35
+ frameId = null;
36
+ try {
37
+ step(delta, timestamp);
38
+ if (running)
39
+ frameId = getRequestFrame()(tick);
40
+ } catch (error) {
41
+ running = false;
42
+ previousTime = null;
43
+ throw error;
44
+ }
45
+ }
46
+ const loop = {
47
+ step,
48
+ getState: () => currentState,
49
+ setState(nextState) {
50
+ currentState = nextState;
51
+ return currentState;
52
+ },
53
+ start() {
54
+ if (running)
55
+ return this;
56
+ const schedule = getRequestFrame();
57
+ previousTime = null;
58
+ running = true;
59
+ try {
60
+ frameId = schedule(tick);
61
+ } catch (error) {
62
+ running = false;
63
+ throw error;
64
+ }
65
+ return this;
66
+ },
67
+ stop() {
68
+ if (!running)
69
+ return this;
70
+ running = false;
71
+ const cancel = cancelFrame ?? globalThis.cancelAnimationFrame;
72
+ if (frameId !== null && typeof cancel === "function")
73
+ cancel(frameId);
74
+ frameId = null;
75
+ previousTime = null;
76
+ return this;
77
+ },
78
+ get running() {
79
+ return running;
80
+ }
81
+ };
82
+ return loop;
83
+ }
84
+
85
+ export { createGame2 };