motlab.js 0.0.0-stage → 0.1.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 (108) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/LICENSE +21 -0
  3. package/README.md +86 -2
  4. package/docs/stability.md +53 -0
  5. package/llms.txt +794 -0
  6. package/package.json +107 -6
  7. package/src/adapters/canvas.js +68 -0
  8. package/src/adapters/lottie.js +102 -0
  9. package/src/adapters/pixi.js +62 -0
  10. package/src/adapters/rapier.js +163 -0
  11. package/src/adapters/rive.js +316 -0
  12. package/src/adapters/three.js +81 -0
  13. package/src/addons/audio.js +422 -0
  14. package/src/addons/camera.js +319 -0
  15. package/src/addons/cel.js +498 -0
  16. package/src/addons/clone.js +299 -0
  17. package/src/addons/color.js +223 -0
  18. package/src/addons/deform.js +441 -0
  19. package/src/addons/dom.js +68 -0
  20. package/src/addons/edit.js +317 -0
  21. package/src/addons/fx.js +64 -0
  22. package/src/addons/game.js +106 -0
  23. package/src/addons/input.js +209 -0
  24. package/src/addons/machine.js +240 -0
  25. package/src/addons/media.js +581 -0
  26. package/src/addons/particles.js +179 -0
  27. package/src/addons/path.js +596 -0
  28. package/src/addons/physics.js +980 -0
  29. package/src/addons/player.js +170 -0
  30. package/src/addons/rig.js +851 -0
  31. package/src/addons/text.js +133 -0
  32. package/src/addons/trace.js +456 -0
  33. package/src/core/combinators.js +129 -0
  34. package/src/core/component.js +90 -0
  35. package/src/core/dmath.js +256 -0
  36. package/src/core/ease.js +136 -0
  37. package/src/core/guard.js +139 -0
  38. package/src/core/hash.js +74 -0
  39. package/src/core/markers.js +49 -0
  40. package/src/core/math.js +43 -0
  41. package/src/core/nodes.js +328 -0
  42. package/src/core/noise.js +340 -0
  43. package/src/core/path.js +295 -0
  44. package/src/core/rand.js +135 -0
  45. package/src/core/scene.js +678 -0
  46. package/src/core/simulate.js +289 -0
  47. package/src/core/spring.js +129 -0
  48. package/src/core/timeline.js +193 -0
  49. package/src/core/track.js +258 -0
  50. package/src/core/verify.js +208 -0
  51. package/src/core/version.js +2 -0
  52. package/src/index.js +19 -0
  53. package/src/renderer/canvas2d.js +950 -0
  54. package/src/renderer/pixels.js +57 -0
  55. package/src/renderer/svg.js +589 -0
  56. package/src/renderer/text-layout.js +80 -0
  57. package/src/renderer/webgl2.js +1331 -0
  58. package/types/adapters/canvas.d.ts +46 -0
  59. package/types/adapters/lottie.d.ts +45 -0
  60. package/types/adapters/pixi.d.ts +46 -0
  61. package/types/adapters/rapier.d.ts +116 -0
  62. package/types/adapters/rive.d.ts +62 -0
  63. package/types/adapters/three.d.ts +51 -0
  64. package/types/addons/audio.d.ts +124 -0
  65. package/types/addons/camera.d.ts +134 -0
  66. package/types/addons/cel.d.ts +215 -0
  67. package/types/addons/clone.d.ts +167 -0
  68. package/types/addons/color.d.ts +73 -0
  69. package/types/addons/deform.d.ts +112 -0
  70. package/types/addons/dom.d.ts +68 -0
  71. package/types/addons/edit.d.ts +293 -0
  72. package/types/addons/fx.d.ts +65 -0
  73. package/types/addons/game.d.ts +78 -0
  74. package/types/addons/input.d.ts +56 -0
  75. package/types/addons/machine.d.ts +111 -0
  76. package/types/addons/media.d.ts +117 -0
  77. package/types/addons/particles.d.ts +110 -0
  78. package/types/addons/path.d.ts +61 -0
  79. package/types/addons/physics.d.ts +265 -0
  80. package/types/addons/player.d.ts +48 -0
  81. package/types/addons/rig.d.ts +273 -0
  82. package/types/addons/text.d.ts +63 -0
  83. package/types/addons/trace.d.ts +110 -0
  84. package/types/core/combinators.d.ts +73 -0
  85. package/types/core/component.d.ts +50 -0
  86. package/types/core/dmath.d.ts +52 -0
  87. package/types/core/ease.d.ts +50 -0
  88. package/types/core/guard.d.ts +23 -0
  89. package/types/core/hash.d.ts +6 -0
  90. package/types/core/markers.d.ts +52 -0
  91. package/types/core/math.d.ts +38 -0
  92. package/types/core/nodes.d.ts +442 -0
  93. package/types/core/noise.d.ts +65 -0
  94. package/types/core/path.d.ts +82 -0
  95. package/types/core/rand.d.ts +47 -0
  96. package/types/core/scene.d.ts +189 -0
  97. package/types/core/simulate.d.ts +169 -0
  98. package/types/core/spring.d.ts +41 -0
  99. package/types/core/timeline.d.ts +86 -0
  100. package/types/core/track.d.ts +58 -0
  101. package/types/core/verify.d.ts +42 -0
  102. package/types/core/version.d.ts +2 -0
  103. package/types/index.d.ts +18 -0
  104. package/types/renderer/canvas2d.d.ts +184 -0
  105. package/types/renderer/pixels.d.ts +28 -0
  106. package/types/renderer/svg.d.ts +19 -0
  107. package/types/renderer/text-layout.d.ts +45 -0
  108. package/types/renderer/webgl2.d.ts +71 -0
package/package.json CHANGED
@@ -1,6 +1,107 @@
1
- {
2
- "name": "motlab.js",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "motlab.js",
3
+ "version": "0.1.0",
4
+ "description": "JavaScript deterministic motion engine.",
5
+ "keywords": [
6
+ "animation",
7
+ "motion",
8
+ "deterministic",
9
+ "timeline",
10
+ "canvas",
11
+ "webgl2",
12
+ "svg",
13
+ "video",
14
+ "physics",
15
+ "rig",
16
+ "game"
17
+ ],
18
+ "homepage": "https://github.com/staryone/motlab.js#readme",
19
+ "bugs": {
20
+ "url": "https://github.com/staryone/motlab.js/issues"
21
+ },
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/staryone/motlab.js.git"
25
+ },
26
+ "license": "MIT",
27
+ "type": "module",
28
+ "engines": {
29
+ "node": ">=24.0.0"
30
+ },
31
+ "exports": {
32
+ ".": {
33
+ "types": "./types/index.d.ts",
34
+ "default": "./src/index.js"
35
+ },
36
+ "./renderer/canvas2d": {
37
+ "types": "./types/renderer/canvas2d.d.ts",
38
+ "default": "./src/renderer/canvas2d.js"
39
+ },
40
+ "./renderer/svg": {
41
+ "types": "./types/renderer/svg.d.ts",
42
+ "default": "./src/renderer/svg.js"
43
+ },
44
+ "./renderer/webgl2": {
45
+ "types": "./types/renderer/webgl2.d.ts",
46
+ "default": "./src/renderer/webgl2.js"
47
+ },
48
+ "./addons/*": {
49
+ "types": "./types/addons/*.d.ts",
50
+ "default": "./src/addons/*.js"
51
+ },
52
+ "./adapters/*": {
53
+ "types": "./types/adapters/*.d.ts",
54
+ "default": "./src/adapters/*.js"
55
+ },
56
+ "./package.json": "./package.json"
57
+ },
58
+ "sideEffects": false,
59
+ "files": [
60
+ "src",
61
+ "types",
62
+ "docs",
63
+ "llms.txt",
64
+ "CHANGELOG.md"
65
+ ],
66
+ "scripts": {
67
+ "test": "node --test \"test/*.test.js\"",
68
+ "test:browser": "node scripts/browser-test.js",
69
+ "typecheck": "tsc -p tsconfig.core.json && tsc -p tsconfig.json",
70
+ "types": "tsc -p tsconfig.types.json",
71
+ "test:types": "npm run types && tsc -p test/types/tsconfig.json",
72
+ "prepack": "npm run types"
73
+ },
74
+ "peerDependencies": {
75
+ "@dimforge/rapier2d-deterministic-compat": ">=0.19.0",
76
+ "@rive-app/canvas-advanced": "^2.0.0",
77
+ "lottie-web": "^5.10.0",
78
+ "pixi.js": "^8.0.0",
79
+ "three": ">=0.170.0"
80
+ },
81
+ "peerDependenciesMeta": {
82
+ "@dimforge/rapier2d-deterministic-compat": {
83
+ "optional": true
84
+ },
85
+ "@rive-app/canvas-advanced": {
86
+ "optional": true
87
+ },
88
+ "lottie-web": {
89
+ "optional": true
90
+ },
91
+ "pixi.js": {
92
+ "optional": true
93
+ },
94
+ "three": {
95
+ "optional": true
96
+ }
97
+ },
98
+ "devDependencies": {
99
+ "@dimforge/rapier2d-deterministic-compat": "0.21.0",
100
+ "@rive-app/canvas-advanced": "2.51.0",
101
+ "@types/three": "0.187.0",
102
+ "lottie-web": "5.13.0",
103
+ "pixi.js": "8.23.0",
104
+ "three": "0.187.0",
105
+ "typescript": "7.0.2"
106
+ }
107
+ }
@@ -0,0 +1,68 @@
1
+ // What every adapter for a canvas-drawing library needs: its picture as a layer of a motlab scene, and a motlab scene
2
+ // as a picture it can use, such as a texture.
3
+ import { draw } from '../core/nodes.js'
4
+ import { at } from '../core/math.js'
5
+ import { canvas2d } from '../renderer/canvas2d.js'
6
+ import { makeSurface } from '../renderer/pixels.js'
7
+
8
+ /**
9
+ * @template T
10
+ * @typedef {import('../core/math.js').Value<T>} Value
11
+ */
12
+ /** @typedef {import('../core/nodes.js').CommonProps} CommonProps */
13
+ /** @typedef {import('../core/nodes.js').Node} Node */
14
+ /** @typedef {import('../core/scene.js').Scene} Scene */
15
+ /** @typedef {import('../core/scene.js').DisplayItem} DisplayItem */
16
+ /** @typedef {HTMLCanvasElement | OffscreenCanvas} Surface */
17
+ /**
18
+ * A motlab renderer such as canvas2d or webgl2.
19
+ * @typedef {(canvas: Surface, options: { scale?: number }) => ((list: DisplayItem[]) => void) & {
20
+ * load: (scene: Scene) => Promise<void>, prepare: (list: DisplayItem[]) => Promise<void>, dispose?: (options?: any) => void }} RendererFactory
21
+ */
22
+
23
+ // Past this many px a side, a layer is drawn smaller and stretched, as browsers refuse larger canvases.
24
+ const MAX_SIDE = 8192
25
+
26
+ /**
27
+ * A layer drawn by another library onto a canvas of its own. render(t, width, height) draws the moment t at that size
28
+ * in px, which is the size the layer covers on screen, and returns the canvas; the layer shows it at (0, 0, w, h).
29
+ * Like a draw node, it is drawn by the Canvas 2D and WebGL2 renderers, and render must give the same picture for the
30
+ * same t.
31
+ * @param {CommonProps & { w: number, h: number, time?: Value<number>,
32
+ * render: (t: number, width: number, height: number) => CanvasImageSource }} props time is the moment to draw in
33
+ * the library's own seconds, default the node's local time.
34
+ * @returns {Node}
35
+ */
36
+ export function canvasLayer({ w, h, time, render, ...props }) {
37
+ if (!(w > 0 && h > 0)) throw new RangeError(`canvasLayer: w and h must be above 0, got ${w} and ${h}`)
38
+ if (typeof render !== 'function') throw new TypeError('canvasLayer: render(t, width, height) must draw and return a canvas')
39
+ return draw({
40
+ ...props,
41
+ draw: (ctx, t) => {
42
+ const m = ctx.getTransform()
43
+ const width = Math.min(MAX_SIDE, Math.max(1, Math.round(w * Math.hypot(m.a, m.b))))
44
+ const height = Math.min(MAX_SIDE, Math.max(1, Math.round(h * Math.hypot(m.c, m.d))))
45
+ ctx.drawImage(render(time === undefined ? t : at(time, t), width, height), 0, 0, w, h)
46
+ },
47
+ })
48
+ }
49
+
50
+ /**
51
+ * A motlab scene drawn onto a canvas of its own, for another library to use as a picture or texture. Call at(t) to
52
+ * draw a moment; for a scene with footage, `await prepare(t)` first.
53
+ * @param {Scene} scene
54
+ * @param {{ scale?: number, renderer?: RendererFactory }} [options] renderer defaults to canvas2d; pass webgl2 for
55
+ * effects drawn on the GPU.
56
+ * @returns {Promise<{ canvas: Surface, prepare: (t: number) => Promise<void>, at: (t: number) => void, dispose: () => void }>}
57
+ */
58
+ export async function sceneCanvas(scene, { scale = 1, renderer = canvas2d } = {}) {
59
+ const canvas = makeSurface(1, 1)
60
+ const drawList = renderer(canvas, { scale })
61
+ await drawList.load(scene)
62
+ return {
63
+ canvas,
64
+ prepare: t => drawList.prepare(scene.evaluate(t)),
65
+ at: t => drawList(scene.evaluate(t)),
66
+ dispose: () => drawList.dispose?.({ loseContext: true }),
67
+ }
68
+ }
@@ -0,0 +1,102 @@
1
+ // Lottie animations inside a motlab scene, drawn by lottie-web's canvas renderer. Lottie keyframes are a function of
2
+ // the frame number, so every moment is a seek: t becomes a frame and goToAndStop draws it.
3
+ import { canvasLayer } from './canvas.js'
4
+
5
+ /** @typedef {import('lottie-web').LottiePlayer} LottiePlayer */
6
+ /** @typedef {import('../core/nodes.js').CommonProps} CommonProps */
7
+ /** @typedef {import('../core/nodes.js').Node} Node */
8
+ /**
9
+ * @template T
10
+ * @typedef {import('../core/math.js').Value<T>} Value
11
+ */
12
+
13
+ /**
14
+ * The frame to show `seconds` into an animation of `total` frames at `fps`, counted from its first frame. Frames
15
+ * between whole numbers tween, as lottie-web's subframes do.
16
+ * @param {number} seconds @param {number} fps @param {number} total @param {boolean} loop
17
+ */
18
+ export function frameAt(seconds, fps, total, loop) {
19
+ const frame = Math.max(0, seconds) * fps
20
+ if (loop) return frame % total
21
+ return Math.min(frame, total - 1)
22
+ }
23
+
24
+ /**
25
+ * lottie-web's canvas renderer caches the context state it last set, such as the fill colour, and skips setting it
26
+ * again. Resizing a canvas resets that state, so the cache has to be cleared with it.
27
+ * @param {import('lottie-web').AnimationItem} anim
28
+ */
29
+ function forgetContextState(anim) {
30
+ const data = /** @type {any} */ (anim).renderer?.contextData
31
+ if (!data) return
32
+ for (const key of Object.keys(data)) if (key.startsWith('applied')) data[key] = ''
33
+ if ('currentOpacity' in data) data.currentOpacity = 1
34
+ }
35
+
36
+ /**
37
+ * Loads a Lottie animation to place in scenes. Its nodes share one player, which seeks and draws for each node in
38
+ * turn, so the same animation can show different moments at once.
39
+ * @param {LottiePlayer | { default: LottiePlayer }} lottieWeb lottie-web, from 'lottie-web' or its canvas build: the
40
+ * default export, or the whole module.
41
+ * @param {{ data: Record<string, any> }} options data is the Lottie JSON, parsed.
42
+ * @returns {Promise<{ duration: number, frameRate: number, size: [number, number],
43
+ * node: (props?: CommonProps & { w?: number, h?: number, time?: Value<number>, loop?: boolean }) => Node,
44
+ * dispose: () => void }>}
45
+ * duration is in seconds. A node is w by h px (default: the animation's size) and plays from its local time, or
46
+ * from `time`; loop repeats it, otherwise the last frame holds.
47
+ */
48
+ export async function lottie(lottieWeb, { data }) {
49
+ const player = lottieWeb && 'loadAnimation' in lottieWeb ? lottieWeb : lottieWeb?.default
50
+ if (typeof player?.loadAnimation !== 'function') throw new TypeError('lottie: pass lottie-web, as in import lottieWeb from \'lottie-web\'')
51
+ if (!data || !(data.fr > 0) || !(data.op > data.ip) || !(data.w > 0 && data.h > 0)) throw new TypeError('lottie: data must be a parsed Lottie JSON with fr, ip, op, w and h')
52
+ const fps = data.fr
53
+ const total = data.op - data.ip
54
+ /** @type {[number, number]} */
55
+ const size = [data.w, data.h]
56
+ // lottie-web expects a page, so a canvas element rather than an OffscreenCanvas.
57
+ const canvas = document.createElement('canvas')
58
+ canvas.width = data.w
59
+ canvas.height = data.h
60
+ const context = /** @type {CanvasRenderingContext2D} */ (canvas.getContext('2d'))
61
+ // The typings ask for a container element, which the canvas renderer does without when it gets a context.
62
+ const config = /** @type {import('lottie-web').AnimationConfigWithData<'canvas'>} */ (/** @type {unknown} */ ({
63
+ renderer: 'canvas', loop: false, autoplay: false, animationData: data,
64
+ rendererSettings: { context, clearCanvas: true, preserveAspectRatio: 'xMidYMid meet', dpr: 1 },
65
+ }))
66
+ const anim = player.loadAnimation(config)
67
+ // Fonts and images load in the background, and drawing is synchronous, so wait for them here.
68
+ if (!anim.isLoaded) {
69
+ await new Promise((done, reject) => {
70
+ anim.addEventListener('DOMLoaded', () => done(undefined))
71
+ anim.addEventListener('data_failed', () => reject(new Error('lottie: animation assets failed to load')))
72
+ })
73
+ }
74
+
75
+ let disposed = false
76
+ return {
77
+ duration: total / fps,
78
+ frameRate: fps,
79
+ size,
80
+ dispose() {
81
+ if (disposed) return
82
+ disposed = true
83
+ anim.destroy?.()
84
+ },
85
+ node({ w = size[0], h = size[1], loop = false, ...props } = {}) {
86
+ return canvasLayer({
87
+ ...props,
88
+ w,
89
+ h,
90
+ render(t, width, height) {
91
+ if (canvas.width !== width || canvas.height !== height) {
92
+ // Before resizing, since the resize ends by redrawing the last frame.
93
+ forgetContextState(anim)
94
+ anim.resize(width, height)
95
+ }
96
+ anim.goToAndStop(frameAt(t, fps, total, loop), true)
97
+ return canvas
98
+ },
99
+ })
100
+ },
101
+ }
102
+ }
@@ -0,0 +1,62 @@
1
+ // PixiJS and motlab.js together: a Pixi stage as a layer of a motlab scene, and a motlab scene as a Pixi texture, such
2
+ // as a cut-scene or an animated title inside a Pixi game. Pass PixiJS in rather than letting this file import it, so
3
+ // one copy is shared with your code.
4
+ import { canvasLayer, sceneCanvas } from './canvas.js'
5
+ import { withClock } from '../core/guard.js'
6
+
7
+ /** @typedef {typeof import('pixi.js')} Pixi */
8
+ /** @typedef {import('pixi.js').Renderer} Renderer */
9
+ /** @typedef {import('pixi.js').Container} Container */
10
+ /** @typedef {import('pixi.js').Texture} Texture */
11
+ /** @typedef {import('../core/nodes.js').CommonProps} CommonProps */
12
+ /** @typedef {import('../core/scene.js').Scene} Scene */
13
+ /** @typedef {import('./canvas.js').RendererFactory} RendererFactory */
14
+
15
+ /**
16
+ * A Pixi stage drawn as a layer at (0, 0, w, h), in a stage space w by h px. Each frame calls update(t), renders, and
17
+ * shows the picture, so update must set everything that moves from t alone; leave Pixi's ticker out of it. Make the
18
+ * renderer with `backgroundAlpha: 0` to see what lies under the layer, and `preference: 'webgl'`.
19
+ * @param {CommonProps & { w: number, h: number, renderer: Renderer, stage: Container, update?: (t: number) => void,
20
+ * time?: import('../core/math.js').Value<number> }} props
21
+ * @returns {import('../core/nodes.js').Node}
22
+ */
23
+ export function pixiLayer({ renderer, stage, update, ...props }) {
24
+ if (typeof renderer?.render !== 'function' || typeof renderer.resize !== 'function') throw new TypeError('pixiLayer: renderer must be a PixiJS renderer, as from autoDetectRenderer()')
25
+ if (!stage || typeof (/** @type {any} */ (stage)).addChild !== 'function') throw new TypeError('pixiLayer: stage must be a PixiJS Container')
26
+ return canvasLayer({
27
+ ...props,
28
+ render(t, width, height) {
29
+ update?.(t)
30
+ const canvas = /** @type {HTMLCanvasElement} */ (renderer.canvas)
31
+ if (canvas.width !== width || canvas.height !== height) renderer.resize(props.w, props.h, width / props.w)
32
+ // Pixi reads the clock to free GPU resources left unused for a while; that never changes the pixels.
33
+ withClock(() => renderer.render({ container: stage }))
34
+ return canvas
35
+ },
36
+ })
37
+ }
38
+
39
+ /**
40
+ * A motlab scene as a Pixi texture. Call at(t) before Pixi renders to show that moment.
41
+ * @param {Pixi} PIXI The pixi.js module.
42
+ * @param {Scene} scene
43
+ * @param {{ scale?: number, renderer?: RendererFactory }} [options] renderer defaults to canvas2d.
44
+ * @returns {Promise<{ texture: Texture, prepare: (t: number) => Promise<void>, at: (t: number) => void, dispose: () => void }>}
45
+ */
46
+ export async function pixiTexture(PIXI, scene, options) {
47
+ if (typeof PIXI?.Texture?.from !== 'function') throw new TypeError('pixiTexture: pass the pixi.js module, as in import * as PIXI from \'pixi.js\'')
48
+ const picture = await sceneCanvas(scene, options)
49
+ const texture = PIXI.Texture.from(/** @type {any} */ (picture.canvas), true)
50
+ return {
51
+ texture,
52
+ prepare: picture.prepare,
53
+ at(t) {
54
+ picture.at(t)
55
+ texture.source.update()
56
+ },
57
+ dispose() {
58
+ texture.destroy(true)
59
+ picture.dispose()
60
+ },
61
+ }
62
+ }
@@ -0,0 +1,163 @@
1
+ // Rapier as a motlab.js simulation. The world steps at a fixed rate, and Rapier's own snapshots let any time be asked
2
+ // for in any order. Use a -deterministic build of Rapier for the same result on every machine.
3
+ import { simulate } from '../core/simulate.js'
4
+ import { hash } from '../core/hash.js'
5
+ import { dmath } from '../core/dmath.js'
6
+ import { withClock } from '../core/guard.js'
7
+ import { bodyViews } from '../addons/physics.js'
8
+
9
+ /** @typedef {typeof import('@dimforge/rapier2d-deterministic-compat')} Rapier */
10
+ /** @typedef {import('@dimforge/rapier2d-deterministic-compat').World} World */
11
+ /** @typedef {import('@dimforge/rapier2d-deterministic-compat').RigidBody} RigidBody */
12
+
13
+ /**
14
+ * The followed bodies at one tick, in the order build() named them. Positions are px, angles radians.
15
+ * @typedef {object} RapierState
16
+ * @property {Float64Array} x
17
+ * @property {Float64Array} y
18
+ * @property {Float64Array} c Cosine of each body's angle.
19
+ * @property {Float64Array} s Sine of each body's angle.
20
+ * @property {Float64Array} vx px per second.
21
+ * @property {Float64Array} vy
22
+ * @property {Float64Array} w Angular velocity in radians per second.
23
+ * @property {Uint8Array | null} world Rapier's snapshot of the whole world, on the ticks simulate() keeps.
24
+ */
25
+
26
+ /**
27
+ * What before() gets ahead of each step.
28
+ * @template I
29
+ * @typedef {object} RapierStep
30
+ * @property {World} world
31
+ * @property {Readonly<Record<string, RigidBody>>} bodies The followed bodies, by name.
32
+ * @property {Rapier} RAPIER
33
+ * @property {number} tick
34
+ * @property {number} t Scene time of the tick.
35
+ * @property {I} input What spec.input gave for this tick.
36
+ */
37
+
38
+ /**
39
+ * A Rapier world as a simulation: query it at any time, in any order. Build it in px; `lengthUnit` (default 100) tells
40
+ * Rapier how many px make a metre, which scales its tolerances.
41
+ * @template [I=undefined]
42
+ * @param {Rapier} RAPIER The Rapier module after `await RAPIER.init()`.
43
+ * @param {{ build: (world: World, RAPIER: Rapier) => Record<string, RigidBody>, before?: (step: RapierStep<I>) => void,
44
+ * input?: (tick: number, t: number) => I, gravity?: readonly [number, number], lengthUnit?: number, hz?: number,
45
+ * start?: number, snapshotEvery?: number, params?: Readonly<Record<string, unknown>> }} spec
46
+ * build adds bodies and colliders, and returns the bodies to follow by name. before runs ahead of every step, to set
47
+ * kinematic targets or apply forces; it must act the same whenever a tick is stepped again. gravity defaults to
48
+ * [0, 980] px/s² and hz to 120; params, like the source of build and before, goes into the bake key.
49
+ */
50
+ export function rapier(RAPIER, { build, before, input, gravity = [0, 980], lengthUnit = 100, hz = 120, start = 0, snapshotEvery, params = {} }) {
51
+ if (typeof RAPIER?.World?.restoreSnapshot !== 'function') throw new TypeError('rapier: pass the Rapier module, after await RAPIER.init()')
52
+ if (typeof build !== 'function') throw new TypeError('rapier: build(world, RAPIER) must add the bodies and return the ones to follow, by name')
53
+ const every = snapshotEvery ?? Math.max(1, Math.round(hz / 2))
54
+
55
+ let live = new RAPIER.World({ x: gravity[0], y: gravity[1] })
56
+ let freed = false
57
+ live.timestep = 1 / hz
58
+ live.lengthUnit = lengthUnit
59
+ const made = build(live, RAPIER)
60
+ if (!made || typeof made !== 'object') throw new TypeError('rapier: build must return the bodies to follow, such as { ball, box }')
61
+ const names = Object.keys(made)
62
+ if (names.length === 0) throw new TypeError('rapier: build must return at least one body to follow')
63
+ const handles = names.map(name => {
64
+ const handle = made[name]?.handle
65
+ if (typeof handle !== 'number') throw new TypeError(`rapier: "${name}" from build is not a rigid body`)
66
+ return handle
67
+ })
68
+ const n = names.length
69
+ /** @type {Readonly<Record<string, RigidBody>>} */
70
+ let followed = Object.freeze({ ...made })
71
+ // The tick the live world is at. A step for any other tick starts from the snapshot in its state.
72
+ let liveTick = 0
73
+
74
+ /** @param {World} world @param {RapierState} st */
75
+ const read = (world, st) => {
76
+ handles.forEach((handle, i) => {
77
+ const body = world.getRigidBody(handle)
78
+ const p = body.translation()
79
+ const v = body.linvel()
80
+ const angle = body.rotation()
81
+ st.x[i] = p.x
82
+ st.y[i] = p.y
83
+ st.c[i] = dmath.cos(angle)
84
+ st.s[i] = dmath.sin(angle)
85
+ st.vx[i] = v.x
86
+ st.vy[i] = v.y
87
+ st.w[i] = body.angvel()
88
+ })
89
+ }
90
+
91
+ /** @type {RapierState} */
92
+ const first = { x: new Float64Array(n), y: new Float64Array(n), c: new Float64Array(n), s: new Float64Array(n), vx: new Float64Array(n), vy: new Float64Array(n), w: new Float64Array(n), world: null }
93
+ read(live, first)
94
+ first.world = live.takeSnapshot()
95
+
96
+ /** @param {RapierState} st @param {I} tickInput @param {number} dt @param {number} tick */
97
+ const step = (st, tickInput, dt, tick) => {
98
+ if (freed) throw new Error('rapier: this world has been disposed')
99
+ if (tick !== liveTick) {
100
+ if (!st.world) throw new Error(`rapier: no snapshot to step tick ${tick} from`)
101
+ live.free()
102
+ live = RAPIER.World.restoreSnapshot(st.world)
103
+ followed = Object.freeze(Object.fromEntries(names.map((name, i) => [name, live.getRigidBody(handles[i])])))
104
+ }
105
+ before?.({ world: live, bodies: followed, RAPIER, tick, t: start + tick * dt, input: tickInput })
106
+ // Rapier times its own stages with performance.now(); the readings never reach the result.
107
+ withClock(() => live.step())
108
+ liveTick = tick + 1
109
+ read(live, st)
110
+ st.world = liveTick % every === 0 ? live.takeSnapshot() : null
111
+ }
112
+
113
+ /** @param {RapierState} a @param {RapierState} b @param {number} k @returns {RapierState} */
114
+ const lerp = (a, b, k) => {
115
+ const out = { ...a, x: a.x.slice(), y: a.y.slice(), c: a.c.slice(), s: a.s.slice(), world: null }
116
+ for (let i = 0; i < n; i++) {
117
+ out.x[i] += (b.x[i] - a.x[i]) * k
118
+ out.y[i] += (b.y[i] - a.y[i]) * k
119
+ const c = a.c[i] + (b.c[i] - a.c[i]) * k
120
+ const s = a.s[i] + (b.s[i] - a.s[i]) * k
121
+ const len = Math.sqrt(c * c + s * s) || 1
122
+ out.c[i] = c / len
123
+ out.s[i] = s / len
124
+ }
125
+ return out
126
+ }
127
+
128
+ const sim = simulate({
129
+ init: () => first, step, lerp, input, hz, start, snapshotEvery: every,
130
+ params: { ...params, build: build.toString(), before: before?.toString() ?? null, gravity, lengthUnit, rapier: RAPIER.version() },
131
+ })
132
+
133
+ /** @param {string | number} ref */
134
+ const index = ref => {
135
+ const i = typeof ref === 'number' ? ref : names.indexOf(ref)
136
+ if (!(i >= 0 && i < n)) throw new RangeError(`rapier: no followed body "${ref}". Bodies are ${names.join(', ')}`)
137
+ return i
138
+ }
139
+
140
+ const dispose = () => {
141
+ if (freed) return
142
+ freed = true
143
+ live.free()
144
+ }
145
+
146
+ return Object.freeze({
147
+ sim,
148
+ /** The followed bodies' names, in state order. */
149
+ names: Object.freeze(names),
150
+ /** @param {number} t */
151
+ at: t => sim.at(t),
152
+ index,
153
+ ...bodyViews(sim, index),
154
+ /** Frees the underlying Rapier WASM world. */
155
+ dispose,
156
+ free: dispose,
157
+ /** A hash of the followed bodies at a tick, for checking that two machines agree. @param {number} tick */
158
+ hash: tick => {
159
+ const { world, ...bodies } = sim.tick(tick)
160
+ return hash(bodies)
161
+ },
162
+ })
163
+ }