@n3rdw1z4rd/core 0.18.5 → 0.19.1

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 (109) hide show
  1. package/README.md +72 -10
  2. package/dist/astar.d.ts +44 -0
  3. package/dist/astar.js +118 -0
  4. package/dist/canvas-renderer.d.ts +157 -0
  5. package/dist/canvas-renderer.js +207 -0
  6. package/dist/clock.d.ts +69 -0
  7. package/dist/clock.js +108 -0
  8. package/dist/color-palette.d.ts +25 -0
  9. package/dist/color-palette.js +112 -0
  10. package/dist/color.d.ts +90 -0
  11. package/dist/color.js +224 -0
  12. package/dist/css/main.css +1 -3
  13. package/dist/disposable.d.ts +27 -0
  14. package/dist/disposable.js +32 -0
  15. package/dist/dungeon-generator.d.ts +142 -0
  16. package/dist/dungeon-generator.js +288 -0
  17. package/dist/ecs.d.ts +87 -0
  18. package/dist/ecs.js +101 -0
  19. package/dist/emitter.d.ts +40 -0
  20. package/dist/emitter.js +54 -0
  21. package/dist/event-queue.d.ts +29 -0
  22. package/dist/event-queue.js +40 -0
  23. package/dist/index.cjs +3820 -0
  24. package/dist/index.d.cts +2657 -0
  25. package/dist/index.d.ts +35 -873
  26. package/dist/index.js +34 -3981
  27. package/dist/input/action-map.d.ts +79 -0
  28. package/dist/input/action-map.js +131 -0
  29. package/dist/input/bindings.d.ts +273 -0
  30. package/dist/input/bindings.js +250 -0
  31. package/dist/input/gestures.d.ts +108 -0
  32. package/dist/input/gestures.js +159 -0
  33. package/dist/input/index.d.ts +5 -0
  34. package/dist/input/index.js +5 -0
  35. package/dist/input/input.d.ts +297 -0
  36. package/dist/input/input.js +695 -0
  37. package/dist/log.d.ts +8 -0
  38. package/dist/log.js +9 -0
  39. package/dist/map2d.d.ts +83 -0
  40. package/dist/map2d.js +120 -0
  41. package/dist/map3d-CHDJiq5T.d.cts +236 -0
  42. package/dist/map3d.d.ts +94 -0
  43. package/dist/map3d.js +148 -0
  44. package/dist/math.d.ts +176 -0
  45. package/dist/math.js +206 -0
  46. package/dist/misc.d.ts +46 -0
  47. package/dist/misc.js +71 -0
  48. package/dist/observable.d.ts +43 -0
  49. package/dist/observable.js +53 -0
  50. package/dist/particle-renderer.d.ts +47 -0
  51. package/dist/particle-renderer.js +82 -0
  52. package/dist/particle-system-2d.d.ts +60 -0
  53. package/dist/particle-system-2d.js +147 -0
  54. package/dist/random.d.ts +46 -0
  55. package/dist/random.js +74 -0
  56. package/dist/rectangle.d.ts +44 -0
  57. package/dist/rectangle.js +69 -0
  58. package/dist/rng.d.ts +72 -0
  59. package/dist/rng.js +152 -0
  60. package/dist/signal.d.ts +34 -0
  61. package/dist/signal.js +41 -0
  62. package/dist/spatial-partition-2d.d.ts +42 -0
  63. package/dist/spatial-partition-2d.js +52 -0
  64. package/dist/spatial-partition-3d-Ba-VBveM.cjs +1324 -0
  65. package/dist/spatial-partition-3d.d.ts +44 -0
  66. package/dist/spatial-partition-3d.js +57 -0
  67. package/dist/three/asteroid-mesh.d.ts +41 -0
  68. package/dist/three/asteroid-mesh.js +44 -0
  69. package/dist/three/camera-rig.d.ts +140 -0
  70. package/dist/three/camera-rig.js +197 -0
  71. package/dist/three/cube-sphere-geometry.d.ts +55 -0
  72. package/dist/three/cube-sphere-geometry.js +239 -0
  73. package/dist/three/ecs.d.ts +75 -0
  74. package/dist/three/ecs.js +64 -0
  75. package/dist/three/index.d.ts +12 -0
  76. package/dist/three/index.js +12 -0
  77. package/dist/three/particle-system-3d.d.ts +53 -0
  78. package/dist/three/particle-system-3d.js +224 -0
  79. package/dist/three/renderer.d.ts +38 -0
  80. package/dist/three/renderer.js +57 -0
  81. package/dist/three/starfield.d.ts +23 -0
  82. package/dist/three/starfield.js +64 -0
  83. package/dist/three/texture-atlas.d.ts +76 -0
  84. package/dist/three/texture-atlas.js +84 -0
  85. package/dist/three/texture-utils.d.ts +31 -0
  86. package/dist/three/texture-utils.js +44 -0
  87. package/dist/three/voxel-geometry.d.ts +72 -0
  88. package/dist/three/voxel-geometry.js +231 -0
  89. package/dist/three/voxel-mesh.d.ts +67 -0
  90. package/dist/three/voxel-mesh.js +71 -0
  91. package/dist/three.cjs +1307 -0
  92. package/dist/three.d.cts +655 -0
  93. package/dist/tilemap.d.ts +17 -0
  94. package/dist/tilemap.js +26 -0
  95. package/dist/types.d.ts +34 -0
  96. package/dist/types.js +0 -0
  97. package/dist/vector.d.ts +78 -0
  98. package/dist/vector.js +169 -0
  99. package/dist/webgl-renderer.d.ts +89 -0
  100. package/dist/webgl-renderer.js +140 -0
  101. package/dist/webgl.d.ts +357 -0
  102. package/dist/webgl.js +628 -0
  103. package/dist/worker-interface.d.ts +30 -0
  104. package/dist/worker-interface.js +39 -0
  105. package/package.json +55 -13
  106. package/dist/css/index.ts +0 -1
  107. package/dist/index.css +0 -104
  108. package/dist/index.d.mts +0 -873
  109. package/dist/index.mjs +0 -3977
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @n3rdw1z4rd/core
2
2
 
3
- A personal, browser-facing TypeScript toolkit consolidated out of several game/graphics side projects: math and RNG with no native `Math` dependency, an event emitter (TODO: emitter replaced), two ECS flavors, procedural generation (pathfinding, Poisson-disk sampling, dungeon layout), a "particle life" simulation in 2D and 3D, and a set of Three.js helpers (camera rig, bootstrap scene, voxel meshing, texture atlases, procedural meshes).
3
+ A personal, browser-facing TypeScript toolkit consolidated out of several game/graphics side projects: math helpers and a deterministic, seedable RNG, an event emitter (TODO: emitter replaced), two ECS flavors, procedural generation (pathfinding, dungeon layout), a "particle life" simulation in 2D and 3D, raw WebGL helpers, and a set of Three.js helpers (camera rigs, voxel meshing, texture atlases, procedural meshes).
4
4
 
5
5
  Nothing here is trying to be a general-purpose framework - it's the shared plumbing that kept getting copy-pasted between projects, pulled into one place so it only has to be fixed once.
6
6
 
@@ -10,15 +10,31 @@ Nothing here is trying to be a general-purpose framework - it's the shared plumb
10
10
  npm install @n3rdw1z4rd/core
11
11
  ```
12
12
 
13
- Peer dependencies (install whichever your project actually uses):
13
+ The Three.js helpers live in their own entry point, `@n3rdw1z4rd/core/three`, and need `three` (an optional peer dependency):
14
14
 
15
15
  ```
16
- npm install three simplex-noise
16
+ npm install three
17
17
  ```
18
18
 
19
- `three` is only required if you import from `@n3rdw1z4rd/core/three` (or the top-level barrel, which re-exports it). `simplex-noise` is required for `Noise` and `AsteroidMesh`.
19
+ The package root (`@n3rdw1z4rd/core`) never imports `three`, so projects that don't use Three.js don't need it installed.
20
20
 
21
- This package ships both CJS and ESM builds plus `.d.ts` types (built with `tsup`). It targets the browser - most modules touch `window`, `document`, or `HTMLCanvasElement`.
21
+ Core has no noise implementation of its own. `AsteroidMesh` and `CubeSphereGeometry.applyFractalBrownianMotion` take a noise function, e.g. from [`simplex-noise`](https://www.npmjs.com/package/simplex-noise):
22
+
23
+ ```ts
24
+ import { createNoise3D } from "simplex-noise";
25
+ import { rng } from "@n3rdw1z4rd/core";
26
+ import { AsteroidMesh } from "@n3rdw1z4rd/core/three";
27
+
28
+ const asteroid = new AsteroidMesh({ noise3d: createNoise3D(() => rng.nextFloat()) });
29
+ ```
30
+
31
+ This package ships ESM and CJS builds plus `.d.ts` types (built with `tsdown`). The ESM build is tree-shakable: bundlers only include the modules you actually import.
32
+
33
+ ### Browser vs. Node
34
+
35
+ The data and logic modules load and run anywhere, including Node (the tests run there): math, `Random`/`Rng`, `Vector`, `Rectangle`, `Map2D`/`Map3D`/`Tilemap`, `findPath` (A*), the dungeon generator, `ECS`, the event helpers (`Emitter`, `Observable`, `Signal`, `EventQueue`, `Disposable`), `Color` and color palettes, the spatial partitions and the particle simulations.
36
+
37
+ These need a browser when used (importing them is still safe anywhere): `CanvasRenderer`, `ParticleRenderer`, `WebGlRenderer` and the WebGL helpers, `Input`, `WorkerInterface`, `Clock.start()`, `Color.fromName()` and `GetUrlParams()`, plus anything in `@n3rdw1z4rd/core/three` that renders or loads textures.
22
38
 
23
39
  ## Quick start
24
40
 
@@ -30,15 +46,61 @@ log(clamp(15, 0, 10)); // 10
30
46
 
31
47
  const clock = new Clock();
32
48
 
33
- clock.onFrame.subscribe((dt) => {
34
- // dt is seconds since last frame
49
+ clock.start((dt) => {
50
+ // dt is seconds since the last frame (capped at clock.maxDeltaTime, 0.1 by default)
51
+ // clock.fps and clock.elapsedTime are also available
35
52
  });
53
+ ```
54
+
55
+ When something else drives the loop (e.g. Three.js), advance the clock yourself:
36
56
 
37
- clock.start();
57
+ ```ts
58
+ renderer.setAnimationLoop((time) => {
59
+ const dt = clock.tick(time);
60
+ renderer.render(scene, camera);
61
+ });
38
62
  ```
39
63
 
40
- Everything (including the `three/*` modules) is re-exported from the package root, so `import { ThreeJsBoilerPlate } from "@n3rdw1z4rd/core"` works. Import from the `three` subpath if you want to make the Three.js dependency explicit in your own code:
64
+ Input works through a Godot-style action map, so game code asks about actions rather than keys or buttons:
41
65
 
42
66
  ```ts
43
- import { ThreeJsBoilerPlate } from "@n3rdw1z4rd/core/three";
67
+ import { Input, key, mouse, pad, padAxis, gesture, xr } from "@n3rdw1z4rd/core";
68
+
69
+ const input = new Input(canvas); // includes ui_accept, ui_cancel, ui_left, ... defaults
70
+
71
+ input.actions.add("jump", [key("Space"), pad("A"), gesture("tap"), xr("right", "primary")]);
72
+ input.actions.add("move_left", [key("KeyA"), padAxis("leftX", -1)]);
73
+ // ... move_right, move_forward, move_back
74
+
75
+ // once per frame, before game logic
76
+ input.update();
77
+
78
+ if (input.isActionJustPressed("jump")) player.jump();
79
+ const move = input.getVector("move_left", "move_right", "move_forward", "move_back");
80
+ ```
81
+
82
+ Keyboard, mouse and pen, touch gestures, gamepads (each its own device for local multiplayer) and WebXR controllers (`input.attachXR(session)`) all feed the same actions. `input.actions.toJSON()` / `load()` save rebinds, and `input.captureBinding()` waits for the next input for rebinding menus.
83
+
84
+ Three.js helpers come from the `three` subpath:
85
+
86
+ ```ts
87
+ import { CameraRig } from "@n3rdw1z4rd/core/three";
88
+ ```
89
+
90
+ The optional stylesheet (reset + dark defaults) is shipped as plain CSS:
91
+
92
+ ```ts
93
+ import "@n3rdw1z4rd/core/css/main.css";
94
+ ```
95
+
96
+ ## Development
97
+
98
+ ```
99
+ npm run build # tsdown -> dist/: ESM (one file per module), CJS (index + three), .d.ts / .d.cts
100
+ npm test # regression tests (run in Node)
101
+ npm test -- astar # also draws the visual A* demo in the terminal
102
+ npm test -- astar 1234 # the demo with a given seed (each run logs the seed it used)
103
+ npm run test:browser # WebGL tests in your browser: serves a test page and opens it (refresh to re-run)
104
+ npm run test:browser:headless # same tests in headless Chrome/Chromium via playwright-core (installed Chrome, or set CHROMIUM_PATH)
105
+ npm run docs # API reference (TypeDoc) -> docs/index.html; npm run docs:watch regenerates on change
44
106
  ```
@@ -0,0 +1,44 @@
1
+ import { XY } from "./types.js";
2
+ //#region src/astar.d.ts
3
+ /**
4
+ * Cost of stepping onto tile (x, y). Return `Infinity` for blocked tiles. Costs should be >= 1
5
+ * (the heuristic assumes it); use larger values for slower terrain or occupied tiles.
6
+ *
7
+ * @category Pathfinding & Procedural
8
+ */
9
+ export type StepCost = (x: number, y: number) => number;
10
+ /**
11
+ * Options for {@link findPath}.
12
+ *
13
+ * @category Pathfinding & Procedural
14
+ */
15
+ export interface PathOptions {
16
+ /** 8-way movement; a diagonal step costs SQRT2 * the tile's cost. Default false. */
17
+ diagonal?: boolean;
18
+ /** allow a diagonal step past a blocked orthogonal neighbour. Default false. */
19
+ cutCorners?: boolean;
20
+ /** stop on a tile next to the goal (the goal itself may be blocked). Default false. */
21
+ adjacent?: boolean;
22
+ /** give up after expanding this many tiles. Default 10,000. */
23
+ maxNodes?: number;
24
+ /** if the goal isn't reached, return the path to the closest tile found. Default false. */
25
+ partial?: boolean;
26
+ }
27
+ /**
28
+ * Finds a lowest-cost path on an unbounded grid with A*.
29
+ *
30
+ * The returned path excludes `start` and ends on the goal (or, with `adjacent`, on a tile next to
31
+ * it). Returns [] if `start` already satisfies the goal, or if no path is found (unless `partial`).
32
+ * The same inputs always produce the same path.
33
+ *
34
+ * ```ts
35
+ * const walls = new Set(['2,0', '2,1', '2,2']);
36
+ * const cost: StepCost = (x, y) => walls.has(`${x},${y}`) ? Infinity : 1;
37
+ *
38
+ * const path = findPath({ x: 0, y: 1 }, { x: 4, y: 1 }, cost, { diagonal: true });
39
+ * ```
40
+ *
41
+ * @category Pathfinding & Procedural
42
+ */
43
+ export declare function findPath(start: XY, goal: XY, cost: StepCost, options?: PathOptions): XY[];
44
+ //#endregion
package/dist/astar.js ADDED
@@ -0,0 +1,118 @@
1
+ import { SQRT2 } from "./math.js";
2
+ import { Heap } from "heap-js";
3
+ //#region src/astar.ts
4
+ const DEFAULT_MAX_NODES = 1e4;
5
+ const DIRECTIONS = [
6
+ [0, -1],
7
+ [1, 0],
8
+ [0, 1],
9
+ [-1, 0],
10
+ [1, -1],
11
+ [1, 1],
12
+ [-1, 1],
13
+ [-1, -1]
14
+ ];
15
+ const KEY_OFFSET = 33554432;
16
+ const KEY_BASE = 67108864;
17
+ const key = (x, y) => (x + KEY_OFFSET) * KEY_BASE + (y + KEY_OFFSET);
18
+ /**
19
+ * Finds a lowest-cost path on an unbounded grid with A*.
20
+ *
21
+ * The returned path excludes `start` and ends on the goal (or, with `adjacent`, on a tile next to
22
+ * it). Returns [] if `start` already satisfies the goal, or if no path is found (unless `partial`).
23
+ * The same inputs always produce the same path.
24
+ *
25
+ * ```ts
26
+ * const walls = new Set(['2,0', '2,1', '2,2']);
27
+ * const cost: StepCost = (x, y) => walls.has(`${x},${y}`) ? Infinity : 1;
28
+ *
29
+ * const path = findPath({ x: 0, y: 1 }, { x: 4, y: 1 }, cost, { diagonal: true });
30
+ * ```
31
+ *
32
+ * @category Pathfinding & Procedural
33
+ */
34
+ function findPath(start, goal, cost, options = {}) {
35
+ const diagonal = options.diagonal ?? false;
36
+ const cutCorners = options.cutCorners ?? false;
37
+ const adjacent = options.adjacent ?? false;
38
+ const maxNodes = options.maxNodes ?? DEFAULT_MAX_NODES;
39
+ const partial = options.partial ?? false;
40
+ const directions = diagonal ? DIRECTIONS : DIRECTIONS.slice(0, 4);
41
+ const heuristic = (x, y) => {
42
+ const dx = Math.abs(x - goal.x);
43
+ const dy = Math.abs(y - goal.y);
44
+ return diagonal ? Math.max(dx, dy) + (SQRT2 - 1) * Math.min(dx, dy) : dx + dy;
45
+ };
46
+ const isGoal = (x, y) => {
47
+ if (x === goal.x && y === goal.y) return true;
48
+ if (!adjacent) return false;
49
+ const dx = Math.abs(x - goal.x);
50
+ const dy = Math.abs(y - goal.y);
51
+ return diagonal ? Math.max(dx, dy) === 1 : dx + dy === 1;
52
+ };
53
+ const passable = (x, y) => cost(x, y) < Infinity;
54
+ if (!adjacent && !partial && !passable(goal.x, goal.y) && !(start.x === goal.x && start.y === goal.y)) return [];
55
+ let seq = 0;
56
+ const open = new Heap((a, b) => a.f - b.f || a.h - b.h || a.seq - b.seq);
57
+ const best = /* @__PURE__ */ new Map();
58
+ const closed = /* @__PURE__ */ new Set();
59
+ const startNode = {
60
+ x: start.x,
61
+ y: start.y,
62
+ g: 0,
63
+ h: heuristic(start.x, start.y),
64
+ f: 0,
65
+ seq: seq++
66
+ };
67
+ startNode.f = startNode.h;
68
+ open.push(startNode);
69
+ best.set(key(start.x, start.y), startNode);
70
+ let closest = startNode;
71
+ let expanded = 0;
72
+ while (open.length > 0 && expanded < maxNodes) {
73
+ const current = open.pop();
74
+ const currentKey = key(current.x, current.y);
75
+ if (closed.has(currentKey)) continue;
76
+ if (isGoal(current.x, current.y)) return buildPath(current);
77
+ closed.add(currentKey);
78
+ expanded++;
79
+ if (current.h < closest.h || current.h === closest.h && current.g < closest.g) closest = current;
80
+ for (let d = 0; d < directions.length; d++) {
81
+ const [dx, dy] = directions[d];
82
+ const x = current.x + dx;
83
+ const y = current.y + dy;
84
+ const k = key(x, y);
85
+ if (closed.has(k)) continue;
86
+ const stepCost = cost(x, y);
87
+ if (!(stepCost < Infinity)) continue;
88
+ const isDiagonal = dx !== 0 && dy !== 0;
89
+ if (isDiagonal && !cutCorners && (!passable(current.x + dx, current.y) || !passable(current.x, current.y + dy))) continue;
90
+ const g = current.g + (isDiagonal ? stepCost * SQRT2 : stepCost);
91
+ const known = best.get(k);
92
+ if (known && known.g <= g) continue;
93
+ const h = known?.h ?? heuristic(x, y);
94
+ const node = {
95
+ x,
96
+ y,
97
+ g,
98
+ h,
99
+ f: g + h,
100
+ seq: seq++,
101
+ parent: current
102
+ };
103
+ best.set(k, node);
104
+ open.push(node);
105
+ }
106
+ }
107
+ return partial ? buildPath(closest) : [];
108
+ }
109
+ function buildPath(end) {
110
+ const path = [];
111
+ for (let node = end; node?.parent; node = node.parent) path.push({
112
+ x: node.x,
113
+ y: node.y
114
+ });
115
+ return path.reverse();
116
+ }
117
+ //#endregion
118
+ export { findPath };
@@ -0,0 +1,157 @@
1
+ import { XY } from "./types.js";
2
+ //#region src/canvas-renderer.d.ts
3
+ /**
4
+ * Anything a 2D context accepts as a fill or stroke style: a CSS color string, a gradient or a pattern.
5
+ *
6
+ * @category Canvas 2D
7
+ */
8
+ export type CanvasColor = string | CanvasGradient | CanvasPattern;
9
+ /**
10
+ * Fill / stroke color used when {@link DrawParams.color} is not given.
11
+ *
12
+ * @category Canvas 2D
13
+ */
14
+ export declare const DEFAULT_COLOR: CanvasColor;
15
+ /**
16
+ * Side length in pixels of {@link CanvasRenderer.drawPixel} when {@link DrawParams.size} is not given.
17
+ *
18
+ * @category Canvas 2D
19
+ */
20
+ export declare const DEFAULT_PIXEL_SIZE: number;
21
+ /**
22
+ * Font size in pixels for {@link CanvasRenderer.drawText}.
23
+ *
24
+ * @category Canvas 2D
25
+ */
26
+ export declare const DEFAULT_FONT_SIZE = 14;
27
+ /**
28
+ * Font family for {@link CanvasRenderer.drawText}.
29
+ *
30
+ * @category Canvas 2D
31
+ */
32
+ export declare const DEFAULT_FONT_NAME = "monospace";
33
+ /**
34
+ * CSS font built from {@link DEFAULT_FONT_SIZE} and {@link DEFAULT_FONT_NAME} (`'14px monospace'`).
35
+ *
36
+ * @category Canvas 2D
37
+ */
38
+ export declare const DEFAULT_FONT = "14px monospace";
39
+ /**
40
+ * Default `textAlign` for {@link CanvasRenderer.drawText}.
41
+ *
42
+ * @category Canvas 2D
43
+ */
44
+ export declare const DEFAULT_TEXTALIGN = "left";
45
+ /**
46
+ * Default `textBaseline` for {@link CanvasRenderer.drawText}.
47
+ *
48
+ * @category Canvas 2D
49
+ */
50
+ export declare const DEFAULT_TEXTBASELINE = "alphabetic";
51
+ /**
52
+ * Optional style settings for the {@link CanvasRenderer} draw methods. Each method uses only the fields that apply to it.
53
+ *
54
+ * @category Canvas 2D
55
+ */
56
+ export interface DrawParams {
57
+ /** fill and stroke color, default {@link DEFAULT_COLOR} */
58
+ color?: CanvasColor;
59
+ /** shapes: fill instead of stroking the outline, default false */
60
+ filled?: boolean;
61
+ /** pixels: line width for outlines and lines (default 1), side length for drawPixel (default {@link DEFAULT_PIXEL_SIZE}), font size for drawText (default {@link DEFAULT_FONT_SIZE}) */
62
+ size?: number;
63
+ /** shapes and lines: dash pattern (see `setLineDash`), reset after drawing; default solid */
64
+ lineDash?: number[];
65
+ /** text: default {@link DEFAULT_TEXTALIGN} */
66
+ textAlign?: CanvasTextAlign;
67
+ /** text: default {@link DEFAULT_TEXTBASELINE} */
68
+ textBaseline?: CanvasTextBaseline;
69
+ /** text: a full CSS font; overrides `size` and `fontName` */
70
+ font?: string;
71
+ /** text: font family, default {@link DEFAULT_FONT_NAME} */
72
+ fontName?: string;
73
+ }
74
+ /**
75
+ * Parameters for {@link CanvasRenderer.drawSprite}: an optional source rectangle within the image (for sprite sheets). The rectangle is used only when both `sourceWidth` and `sourceHeight` are set; otherwise the whole image is drawn. The inherited style fields are ignored.
76
+ *
77
+ * @category Canvas 2D
78
+ */
79
+ export interface SpriteParams extends DrawParams {
80
+ /** pixels, default 0 */
81
+ sourceX?: number;
82
+ /** pixels, default 0 */
83
+ sourceY?: number;
84
+ /** pixels */
85
+ sourceWidth?: number;
86
+ /** pixels */
87
+ sourceHeight?: number;
88
+ }
89
+ /**
90
+ * Immediate-mode drawing of simple shapes, text and sprites on a 2D canvas. Rectangles, pixels and
91
+ * sprites are positioned by their center; circles and polygons by their center and radius.
92
+ *
93
+ * ```ts
94
+ * const renderer = new CanvasRenderer();
95
+ * document.body.appendChild(renderer.canvas);
96
+ * renderer.resize(); // to the parent's size
97
+ *
98
+ * renderer.clear();
99
+ * renderer.drawCircle(100, 100, 20, { color: 'red', filled: true });
100
+ * renderer.drawText(10, 20, 'hello', { size: 16 });
101
+ * ```
102
+ *
103
+ * @category Canvas 2D
104
+ */
105
+ export declare class CanvasRenderer {
106
+ /** the 2D context all drawing goes through */
107
+ context: CanvasRenderingContext2D;
108
+ /** the canvas being drawn on */
109
+ get canvas(): HTMLCanvasElement;
110
+ /** canvas width in pixels */
111
+ get width(): number;
112
+ /** canvas height in pixels */
113
+ get height(): number;
114
+ /** canvas center in pixels */
115
+ get center(): XY;
116
+ /**
117
+ * @param canvas defaults to a new canvas element, not attached to the page (append {@link CanvasRenderer.canvas} yourself)
118
+ */
119
+ constructor(canvas?: HTMLCanvasElement);
120
+ private _applyDefaults;
121
+ /**
122
+ * Sets the canvas size in pixels; a missing dimension defaults to the parent element's client
123
+ * size (or the current size without a parent, or while the parent has no size). Resizing clears
124
+ * the canvas and resets the context state; the renderer's default font and alignment are
125
+ * applied again. Returns whether the size changed.
126
+ */
127
+ resize(width?: number, height?: number): boolean;
128
+ /** Clears the whole canvas to transparent. */
129
+ clear(): void;
130
+ private drawPath;
131
+ /** Draws a `width` x `height` rectangle centered on (`x`, `y`): its outline, or filled with `filled`. */
132
+ drawRect(x: number, y: number, width: number, height: number, params?: DrawParams): void;
133
+ /** Draws a filled square of side `params.size` (default {@link DEFAULT_PIXEL_SIZE}) centered on (`x`, `y`). */
134
+ drawPixel(x: number, y: number, params?: DrawParams): void;
135
+ /** Draws a line segment from (`x1`, `y1`) to (`x2`, `y2`); `params.size` is the line width. */
136
+ drawLine(x1: number, y1: number, x2: number, y2: number, params?: DrawParams): void;
137
+ /** Draws a circle centered on (`x`, `y`). */
138
+ drawCircle(x: number, y: number, radius: number, params?: DrawParams): void;
139
+ /**
140
+ * Draws a regular polygon centered on (`x`, `y`) with its first vertex straight up.
141
+ *
142
+ * @param radius distance from the center to each vertex
143
+ * @param sides floored and clamped to 3..36
144
+ */
145
+ drawPolygon(x: number, y: number, radius: number, sides: number, params?: DrawParams): void;
146
+ /**
147
+ * Fills `text` at (`x`, `y`), aligned by `params.textAlign` / `params.textBaseline` (default
148
+ * left / alphabetic). The font is `params.font`, or `params.size` px `params.fontName`.
149
+ */
150
+ drawText(x: number, y: number, text: string, params?: DrawParams): void;
151
+ /**
152
+ * Draws `image` (or the `params` source rectangle of it) scaled to `width` x `height`, centered
153
+ * on (`x`, `y`).
154
+ */
155
+ drawSprite(x: number, y: number, image: CanvasImageSource, width: number, height: number, params?: SpriteParams): void;
156
+ }
157
+ //#endregion
@@ -0,0 +1,207 @@
1
+ import { PI, TAU, clamp } from "./math.js";
2
+ //#region src/canvas-renderer.ts
3
+ /**
4
+ * Fill / stroke color used when {@link DrawParams.color} is not given.
5
+ *
6
+ * @category Canvas 2D
7
+ */
8
+ const DEFAULT_COLOR = "white";
9
+ /**
10
+ * Side length in pixels of {@link CanvasRenderer.drawPixel} when {@link DrawParams.size} is not given.
11
+ *
12
+ * @category Canvas 2D
13
+ */
14
+ const DEFAULT_PIXEL_SIZE = 1;
15
+ /**
16
+ * Font size in pixels for {@link CanvasRenderer.drawText}.
17
+ *
18
+ * @category Canvas 2D
19
+ */
20
+ const DEFAULT_FONT_SIZE = 14;
21
+ /**
22
+ * Font family for {@link CanvasRenderer.drawText}.
23
+ *
24
+ * @category Canvas 2D
25
+ */
26
+ const DEFAULT_FONT_NAME = "monospace";
27
+ /**
28
+ * CSS font built from {@link DEFAULT_FONT_SIZE} and {@link DEFAULT_FONT_NAME} (`'14px monospace'`).
29
+ *
30
+ * @category Canvas 2D
31
+ */
32
+ const DEFAULT_FONT = `14px ${DEFAULT_FONT_NAME}`;
33
+ /**
34
+ * Default `textAlign` for {@link CanvasRenderer.drawText}.
35
+ *
36
+ * @category Canvas 2D
37
+ */
38
+ const DEFAULT_TEXTALIGN = "left";
39
+ /**
40
+ * Default `textBaseline` for {@link CanvasRenderer.drawText}.
41
+ *
42
+ * @category Canvas 2D
43
+ */
44
+ const DEFAULT_TEXTBASELINE = "alphabetic";
45
+ /**
46
+ * Immediate-mode drawing of simple shapes, text and sprites on a 2D canvas. Rectangles, pixels and
47
+ * sprites are positioned by their center; circles and polygons by their center and radius.
48
+ *
49
+ * ```ts
50
+ * const renderer = new CanvasRenderer();
51
+ * document.body.appendChild(renderer.canvas);
52
+ * renderer.resize(); // to the parent's size
53
+ *
54
+ * renderer.clear();
55
+ * renderer.drawCircle(100, 100, 20, { color: 'red', filled: true });
56
+ * renderer.drawText(10, 20, 'hello', { size: 16 });
57
+ * ```
58
+ *
59
+ * @category Canvas 2D
60
+ */
61
+ var CanvasRenderer = class {
62
+ /** the 2D context all drawing goes through */
63
+ context;
64
+ /** the canvas being drawn on */
65
+ get canvas() {
66
+ return this.context.canvas;
67
+ }
68
+ /** canvas width in pixels */
69
+ get width() {
70
+ return this.canvas.width;
71
+ }
72
+ /** canvas height in pixels */
73
+ get height() {
74
+ return this.canvas.height;
75
+ }
76
+ /** canvas center in pixels */
77
+ get center() {
78
+ return {
79
+ x: Math.floor(this.width / 2),
80
+ y: Math.floor(this.height / 2)
81
+ };
82
+ }
83
+ /**
84
+ * @param canvas defaults to a new canvas element, not attached to the page (append {@link CanvasRenderer.canvas} yourself)
85
+ */
86
+ constructor(canvas) {
87
+ this.context = (canvas ?? document.createElement("canvas")).getContext("2d");
88
+ this._applyDefaults();
89
+ }
90
+ _applyDefaults() {
91
+ this.context.font = DEFAULT_FONT;
92
+ this.context.textAlign = DEFAULT_TEXTALIGN;
93
+ this.context.textBaseline = DEFAULT_TEXTBASELINE;
94
+ }
95
+ /**
96
+ * Sets the canvas size in pixels; a missing dimension defaults to the parent element's client
97
+ * size (or the current size without a parent, or while the parent has no size). Resizing clears
98
+ * the canvas and resets the context state; the renderer's default font and alignment are
99
+ * applied again. Returns whether the size changed.
100
+ */
101
+ resize(width, height) {
102
+ let resized = false;
103
+ width = width ?? (this.canvas.parentElement?.clientWidth || this.width);
104
+ height = height ?? (this.canvas.parentElement?.clientHeight || this.height);
105
+ if (this.canvas.width != width || this.canvas.height != height) {
106
+ this.canvas.width = width;
107
+ this.canvas.height = height;
108
+ this._applyDefaults();
109
+ resized = true;
110
+ }
111
+ return resized;
112
+ }
113
+ /** Clears the whole canvas to transparent. */
114
+ clear() {
115
+ this.context.clearRect(0, 0, this.width, this.height);
116
+ }
117
+ drawPath(buildPath, params = {}) {
118
+ this.context.fillStyle = params.color ?? "white";
119
+ this.context.strokeStyle = params.color ?? "white";
120
+ this.context.lineWidth = params.size ?? 1;
121
+ if (params.lineDash) this.context.setLineDash(params.lineDash);
122
+ this.context.beginPath();
123
+ buildPath();
124
+ if (params.filled) this.context.fill();
125
+ else this.context.stroke();
126
+ if (params.lineDash) this.context.setLineDash([]);
127
+ }
128
+ /** Draws a `width` x `height` rectangle centered on (`x`, `y`): its outline, or filled with `filled`. */
129
+ drawRect(x, y, width, height, params = {}) {
130
+ x -= width / 2;
131
+ y -= height / 2;
132
+ this.context.fillStyle = params.color ?? "white";
133
+ this.context.strokeStyle = params.color ?? "white";
134
+ this.context.lineWidth = params.size ?? 1;
135
+ if (params.lineDash) this.context.setLineDash(params.lineDash);
136
+ if (params.filled) this.context.fillRect(x, y, width, height);
137
+ else this.context.strokeRect(x, y, width, height);
138
+ if (params.lineDash) this.context.setLineDash([]);
139
+ }
140
+ /** Draws a filled square of side `params.size` (default {@link DEFAULT_PIXEL_SIZE}) centered on (`x`, `y`). */
141
+ drawPixel(x, y, params = {}) {
142
+ const size = Math.abs(params.size ?? 1);
143
+ this.drawRect(x, y, size, size, {
144
+ ...params,
145
+ filled: true
146
+ });
147
+ }
148
+ /** Draws a line segment from (`x1`, `y1`) to (`x2`, `y2`); `params.size` is the line width. */
149
+ drawLine(x1, y1, x2, y2, params = {}) {
150
+ this.context.strokeStyle = params.color ?? "white";
151
+ this.context.lineWidth = params.size ?? 1;
152
+ if (params.lineDash) this.context.setLineDash(params.lineDash);
153
+ this.context.beginPath();
154
+ this.context.moveTo(x1, y1);
155
+ this.context.lineTo(x2, y2);
156
+ this.context.stroke();
157
+ if (params.lineDash) this.context.setLineDash([]);
158
+ }
159
+ /** Draws a circle centered on (`x`, `y`). */
160
+ drawCircle(x, y, radius, params = {}) {
161
+ this.drawPath(() => {
162
+ this.context.arc(x, y, radius, 0, TAU);
163
+ }, params);
164
+ }
165
+ /**
166
+ * Draws a regular polygon centered on (`x`, `y`) with its first vertex straight up.
167
+ *
168
+ * @param radius distance from the center to each vertex
169
+ * @param sides floored and clamped to 3..36
170
+ */
171
+ drawPolygon(x, y, radius, sides, params = {}) {
172
+ sides = Math.floor(clamp(sides, 3, 36));
173
+ this.drawPath(() => {
174
+ for (let i = 0; i < sides; i++) {
175
+ const angle = i / sides * TAU - PI / 2;
176
+ const px = x + Math.cos(angle) * radius;
177
+ const py = y + Math.sin(angle) * radius;
178
+ if (i === 0) this.context.moveTo(px, py);
179
+ else this.context.lineTo(px, py);
180
+ }
181
+ this.context.closePath();
182
+ }, params);
183
+ }
184
+ /**
185
+ * Fills `text` at (`x`, `y`), aligned by `params.textAlign` / `params.textBaseline` (default
186
+ * left / alphabetic). The font is `params.font`, or `params.size` px `params.fontName`.
187
+ */
188
+ drawText(x, y, text, params = {}) {
189
+ this.context.font = params.font ?? `${params.size ?? 14}px ${params.fontName ?? "monospace"}`;
190
+ this.context.textAlign = params.textAlign ?? "left";
191
+ this.context.textBaseline = params.textBaseline ?? "alphabetic";
192
+ this.context.fillStyle = params.color ?? "white";
193
+ this.context.fillText(text, x, y);
194
+ }
195
+ /**
196
+ * Draws `image` (or the `params` source rectangle of it) scaled to `width` x `height`, centered
197
+ * on (`x`, `y`).
198
+ */
199
+ drawSprite(x, y, image, width, height, params = {}) {
200
+ x -= width / 2;
201
+ y -= height / 2;
202
+ if (params.sourceWidth !== void 0 && params.sourceHeight !== void 0) this.context.drawImage(image, params.sourceX ?? 0, params.sourceY ?? 0, params.sourceWidth, params.sourceHeight, x, y, width, height);
203
+ else this.context.drawImage(image, x, y, width, height);
204
+ }
205
+ };
206
+ //#endregion
207
+ export { CanvasRenderer, DEFAULT_COLOR, DEFAULT_FONT, DEFAULT_FONT_NAME, DEFAULT_FONT_SIZE, DEFAULT_PIXEL_SIZE, DEFAULT_TEXTALIGN, DEFAULT_TEXTBASELINE };