You need to sign in or sign up before continuing.

@flare-engine/simulation 0.2.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Grzegorz Otto
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,71 @@
1
+ # @flare-engine/simulation
2
+
3
+ Continuous-time dynamics: n-body gravity with Plummer softening, Verlet / leapfrog integration, wave-packet ripple pools, a diffuse/decay scalar field, and Jones-model agent stigmergy.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ bun add @flare-engine/simulation
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```ts
14
+ import { createNBodySystem, leapfrogInto, createRipplePool } from '@flare-engine/simulation';
15
+
16
+ const nb = createNBodySystem(16);
17
+ nb.add(0, 0, 0, 0, 1000);
18
+ nb.add(100, 0, 0, 3.16, 1);
19
+ nb.step(0.016, 1, 2);
20
+
21
+ const rp = createRipplePool(32);
22
+ rp.emit(0, 0, 0, 20, 100, 30, 2);
23
+ const h = rp.heightAt(100, 0, 1);
24
+ ```
25
+
26
+ ### Scalar field
27
+
28
+ A coarse pheromone/heat grid backed by two ping-pong `Float32Array`s (zero alloc after construction). Separable 3×3 box-blur diffusion + multiplicative decay + bilinear sample + central-difference gradient.
29
+
30
+ ```ts
31
+ import { createScalarField } from '@flare-engine/simulation';
32
+
33
+ // 'toroidal' (default, wrapping) or 'clamp' (bounded playfield).
34
+ const field = createScalarField(800, 600, 4, 'toroidal');
35
+ field.deposit(400, 300, 1.0);
36
+ field.step(0.4, 0.97, Infinity); // diffuse + decay (no clamp)
37
+ const v = field.sample(390, 300); // bilinear read
38
+ const grad = { x: 0, y: 0 };
39
+ field.gradient(390, 300, grad); // ∇ for obstacle avoidance / chemotaxis
40
+ ```
41
+
42
+ ### Agent stigmergy
43
+
44
+ SoA agents (Jones 2010) that sense the scalar field, turn toward the brightest sensor, move, and deposit — the engine's first emergent-AI primitive. Fully deterministic via an injected `SeededRNG`.
45
+
46
+ ```ts
47
+ import { SeededRNG } from '@flare-engine/math';
48
+ import { createScalarField, createStigmergy, SENSE_DEFAULTS } from '@flare-engine/simulation';
49
+
50
+ const field = createScalarField(800, 600, 4);
51
+ const agents = createStigmergy(field, {
52
+ count: 2000,
53
+ ...SENSE_DEFAULTS,
54
+ stepSize: 2,
55
+ depositAmount: 1,
56
+ chaos: 0.05,
57
+ }, new SeededRNG(42));
58
+
59
+ // Game loop:
60
+ field.step(0.4, 0.97, 10);
61
+ agents.update();
62
+ agents.forEachAgent((x, y) => { /* draw */ });
63
+ ```
64
+
65
+ `onSense` / `onMove` hooks let callers inject chemotaxis or repulsion by closing over their own data (nutrient sources, obstacle fields) without coupling the engine to domain logic.
66
+
67
+ See [API spec](../../docs/design/api-specs.md#flare-enginesimulation).
68
+
69
+ ## License
70
+
71
+ MIT
@@ -0,0 +1,154 @@
1
+ import { SeededRNG } from '@flare-engine/math';
2
+
3
+ interface ClosestPair {
4
+ i: number;
5
+ j: number;
6
+ sep: number;
7
+ }
8
+ interface NBodySystem {
9
+ /** Backing-array capacity (max bodies). */
10
+ readonly capacity: number;
11
+ /** Live body count. */
12
+ readonly count: number;
13
+ readonly px: Float32Array;
14
+ readonly py: Float32Array;
15
+ readonly vx: Float32Array;
16
+ readonly vy: Float32Array;
17
+ readonly mass: Float32Array;
18
+ /** Generic caller tag carried per body (e.g. a planet/color id); swapped through `absorb`. */
19
+ readonly tag: Float32Array;
20
+ /** Largest mass currently present. */
21
+ maxMass(): number;
22
+ /** Add a body; returns its index, or -1 if at capacity. `tag` is an opaque per-body scalar. */
23
+ add(x: number, y: number, vx: number, vy: number, m: number, tag?: number): number;
24
+ /** One velocity-Verlet step under Plummer-softened gravity. `gr`>0 adds a relativistic 1/r⁴
25
+ * precession pull on bodies i≥1 toward body 0 (rosette orbits); `rs` is its GR length scale. */
26
+ step(dt: number, g: number, softening: number, gr?: number, rs?: number): void;
27
+ /** Total mechanical energy KE + PE (softened, incl. the optional GR term) — bounded ⇒ stable. */
28
+ totalEnergy(g: number, softening: number, gr?: number, rs?: number): number;
29
+ /** Center-of-mass position written into `out` (for keeping the system framed). */
30
+ centerOfMass(out: {
31
+ x: number;
32
+ y: number;
33
+ }): void;
34
+ /** Translate every body by (dx,dy) — used to re-center after a resize. */
35
+ translate(dx: number, dy: number): void;
36
+ /** Merge `victim` into `into` (momentum- and mass-conserving inelastic coalescence), then
37
+ * swap-remove `victim` so the array stays packed. In practice `into` is the central mass
38
+ * (index 0), which is never the moved last slot. */
39
+ absorb(into: number, victim: number): void;
40
+ /** Closest body pair + their separation (sep = Infinity with fewer than two bodies). */
41
+ closestPair(out: ClosestPair): void;
42
+ }
43
+ declare function createNBodySystem(capacity: number): NBodySystem;
44
+
45
+ /**
46
+ * AccelFn fills ax[i]/ay[i] for i in [0, count) from the current SoA position/velocity state.
47
+ * Callers own the ax/ay scratch arrays (length >= count).
48
+ */
49
+ type AccelFn = (count: number, px: Float32Array, py: Float32Array, vx: Float32Array, vy: Float32Array, ax: Float32Array, ay: Float32Array) => void;
50
+ /**
51
+ * Self-contained kick-drift-kick leapfrog (velocity-Verlet-equivalent). Advances pos/vel in place
52
+ * under accel; symplectic => bounded energy for conservative forces. ax/ay are caller scratch
53
+ * (length >= count). Evals accel TWICE per step. Zero-alloc.
54
+ */
55
+ declare function leapfrogInto(count: number, px: Float32Array, py: Float32Array, vx: Float32Array, vy: Float32Array, dt: number, accel: AccelFn, ax: Float32Array, ay: Float32Array): void;
56
+ /**
57
+ * Velocity-Verlet step reusing a cached a(t) — the nbody scheme, ONE accel eval/step. On ENTRY
58
+ * ax/ay must hold a(t) for the current positions; on RETURN they hold a(t+dt) (feed into the next
59
+ * step). axPrev/ayPrev are caller scratch (length >= count). Zero-alloc.
60
+ *
61
+ * Symplectic => bounded energy for conservative forces.
62
+ */
63
+ declare function verletStep(count: number, px: Float32Array, py: Float32Array, vx: Float32Array, vy: Float32Array, dt: number, accel: AccelFn, ax: Float32Array, ay: Float32Array, axPrev: Float32Array, ayPrev: Float32Array): void;
64
+
65
+ interface RipplePool {
66
+ readonly capacity: number;
67
+ /** Live wavefront count. */
68
+ readonly count: number;
69
+ /** Emit an expanding wavefront from (x,y) born at sim time `now`. Overwrites the oldest slot
70
+ * when full so a long run never starves. */
71
+ emit(x: number, y: number, now: number, amp: number, speed: number, wavelength: number, life: number): void;
72
+ /** Summed transverse height (px, signed) at (x,y) from all live fronts at time `now`. */
73
+ heightAt(x: number, y: number, now: number): number;
74
+ /** Retire spent wavefronts (call once/frame). */
75
+ prune(now: number): void;
76
+ /** Drop all wavefronts (e.g. on resize). */
77
+ clear(): void;
78
+ }
79
+ declare function createRipplePool(capacity: number): RipplePool;
80
+
81
+ interface ScalarField {
82
+ readonly w: number;
83
+ readonly h: number;
84
+ readonly cols: number;
85
+ readonly rows: number;
86
+ readonly cell: number;
87
+ readonly edge: 'toroidal' | 'clamp';
88
+ /** Bilinear read in px space. */
89
+ sample(x: number, y: number): number;
90
+ /** Central-difference gradient ∇ of the field at (x,y) — one cell apart, edge-aware. */
91
+ gradient(x: number, y: number, out: {
92
+ x: number;
93
+ y: number;
94
+ }): void;
95
+ /** Additive pheromone splat into the nearest cell. */
96
+ deposit(x: number, y: number, amount: number): void;
97
+ /** Multiply cells within radiusPx of (x,y) by `mul` (0..1). */
98
+ erode(x: number, y: number, radiusPx: number, mul: number): void;
99
+ /** Whole-field update: separable 3×3 box blur lerped by diffuseRate, then × decayRate.
100
+ * Each cell is clamped to maxVal (use Infinity for no clamp). */
101
+ step(diffuseRate: number, decayRate: number, maxVal: number): void;
102
+ /** Strided mean over the whole field. */
103
+ meanValue(stride: number): number;
104
+ /** Strided max over the whole field. */
105
+ maxValue(stride: number): number;
106
+ /** Mean field value in a disc around (x,y). */
107
+ localMean(x: number, y: number, radiusPx: number): number;
108
+ /** Pack the field into an RGBA byte buffer (length cols*rows*4) with a palette-binned ramp:
109
+ * low→mid→hi by value, knot reserved for the brightest cells; brightness folded into rgb
110
+ * so dim cells add nothing under additive Plus. `out` is caller-owned and reused. */
111
+ toRGBA(out: Uint8Array, norm: number, low: readonly number[], mid: readonly number[], hi: readonly number[], knot: readonly number[]): void;
112
+ resize(width: number, height: number): void;
113
+ }
114
+ declare function createScalarField(width: number, height: number, cellSize: number, edgeMode?: 'toroidal' | 'clamp'): ScalarField;
115
+
116
+ interface SenseConfig {
117
+ /** rad — angular offset of the two side sensors. */
118
+ sensorAngle: number;
119
+ /** px — how far ahead the sensors read. */
120
+ sensorDist: number;
121
+ /** rad — turn applied per step toward the brightest sensor. */
122
+ rotateAngle: number;
123
+ }
124
+ declare const SENSE_DEFAULTS: SenseConfig;
125
+ /** Read the field at one sensor: `offset` rad off the agent heading, `dist` px ahead. */
126
+ declare function senseAt(field: ScalarField, x: number, y: number, heading: number, offset: number, dist: number): number;
127
+ /** Jones turn decision from three sensor readings: −1 turn left, 0 straight, +1 turn right.
128
+ * `rand` ∈ [0,1) breaks the symmetric "both sides brighter" case. */
129
+ declare function decideTurn(left: number, center: number, right: number, rand: number): -1 | 0 | 1;
130
+ interface StigmergyConfig {
131
+ count: number;
132
+ sensorAngle: number;
133
+ sensorDist: number;
134
+ rotateAngle: number;
135
+ stepSize: number;
136
+ depositAmount: number;
137
+ chaos: number;
138
+ /** Returns an extra heading delta (rad) applied before moving. */
139
+ onSense?: (index: number, x: number, y: number, heading: number) => number;
140
+ /** Post-move notify. */
141
+ onMove?: (index: number, x: number, y: number, heading: number) => void;
142
+ }
143
+ interface AgentField {
144
+ readonly count: number;
145
+ readonly px: Float32Array;
146
+ readonly py: Float32Array;
147
+ readonly heading: Float32Array;
148
+ update(): void;
149
+ forEachAgent(cb: (x: number, y: number) => void, stride?: number): void;
150
+ resize(width: number, height: number): void;
151
+ }
152
+ declare function createStigmergy(field: ScalarField, config: StigmergyConfig, rng: SeededRNG): AgentField;
153
+
154
+ export { type AccelFn, type AgentField, type ClosestPair, type NBodySystem, type RipplePool, SENSE_DEFAULTS, type ScalarField, type SenseConfig, type StigmergyConfig, createNBodySystem, createRipplePool, createScalarField, createStigmergy, decideTurn, leapfrogInto, senseAt, verletStep };
@@ -0,0 +1,154 @@
1
+ import { SeededRNG } from '@flare-engine/math';
2
+
3
+ interface ClosestPair {
4
+ i: number;
5
+ j: number;
6
+ sep: number;
7
+ }
8
+ interface NBodySystem {
9
+ /** Backing-array capacity (max bodies). */
10
+ readonly capacity: number;
11
+ /** Live body count. */
12
+ readonly count: number;
13
+ readonly px: Float32Array;
14
+ readonly py: Float32Array;
15
+ readonly vx: Float32Array;
16
+ readonly vy: Float32Array;
17
+ readonly mass: Float32Array;
18
+ /** Generic caller tag carried per body (e.g. a planet/color id); swapped through `absorb`. */
19
+ readonly tag: Float32Array;
20
+ /** Largest mass currently present. */
21
+ maxMass(): number;
22
+ /** Add a body; returns its index, or -1 if at capacity. `tag` is an opaque per-body scalar. */
23
+ add(x: number, y: number, vx: number, vy: number, m: number, tag?: number): number;
24
+ /** One velocity-Verlet step under Plummer-softened gravity. `gr`>0 adds a relativistic 1/r⁴
25
+ * precession pull on bodies i≥1 toward body 0 (rosette orbits); `rs` is its GR length scale. */
26
+ step(dt: number, g: number, softening: number, gr?: number, rs?: number): void;
27
+ /** Total mechanical energy KE + PE (softened, incl. the optional GR term) — bounded ⇒ stable. */
28
+ totalEnergy(g: number, softening: number, gr?: number, rs?: number): number;
29
+ /** Center-of-mass position written into `out` (for keeping the system framed). */
30
+ centerOfMass(out: {
31
+ x: number;
32
+ y: number;
33
+ }): void;
34
+ /** Translate every body by (dx,dy) — used to re-center after a resize. */
35
+ translate(dx: number, dy: number): void;
36
+ /** Merge `victim` into `into` (momentum- and mass-conserving inelastic coalescence), then
37
+ * swap-remove `victim` so the array stays packed. In practice `into` is the central mass
38
+ * (index 0), which is never the moved last slot. */
39
+ absorb(into: number, victim: number): void;
40
+ /** Closest body pair + their separation (sep = Infinity with fewer than two bodies). */
41
+ closestPair(out: ClosestPair): void;
42
+ }
43
+ declare function createNBodySystem(capacity: number): NBodySystem;
44
+
45
+ /**
46
+ * AccelFn fills ax[i]/ay[i] for i in [0, count) from the current SoA position/velocity state.
47
+ * Callers own the ax/ay scratch arrays (length >= count).
48
+ */
49
+ type AccelFn = (count: number, px: Float32Array, py: Float32Array, vx: Float32Array, vy: Float32Array, ax: Float32Array, ay: Float32Array) => void;
50
+ /**
51
+ * Self-contained kick-drift-kick leapfrog (velocity-Verlet-equivalent). Advances pos/vel in place
52
+ * under accel; symplectic => bounded energy for conservative forces. ax/ay are caller scratch
53
+ * (length >= count). Evals accel TWICE per step. Zero-alloc.
54
+ */
55
+ declare function leapfrogInto(count: number, px: Float32Array, py: Float32Array, vx: Float32Array, vy: Float32Array, dt: number, accel: AccelFn, ax: Float32Array, ay: Float32Array): void;
56
+ /**
57
+ * Velocity-Verlet step reusing a cached a(t) — the nbody scheme, ONE accel eval/step. On ENTRY
58
+ * ax/ay must hold a(t) for the current positions; on RETURN they hold a(t+dt) (feed into the next
59
+ * step). axPrev/ayPrev are caller scratch (length >= count). Zero-alloc.
60
+ *
61
+ * Symplectic => bounded energy for conservative forces.
62
+ */
63
+ declare function verletStep(count: number, px: Float32Array, py: Float32Array, vx: Float32Array, vy: Float32Array, dt: number, accel: AccelFn, ax: Float32Array, ay: Float32Array, axPrev: Float32Array, ayPrev: Float32Array): void;
64
+
65
+ interface RipplePool {
66
+ readonly capacity: number;
67
+ /** Live wavefront count. */
68
+ readonly count: number;
69
+ /** Emit an expanding wavefront from (x,y) born at sim time `now`. Overwrites the oldest slot
70
+ * when full so a long run never starves. */
71
+ emit(x: number, y: number, now: number, amp: number, speed: number, wavelength: number, life: number): void;
72
+ /** Summed transverse height (px, signed) at (x,y) from all live fronts at time `now`. */
73
+ heightAt(x: number, y: number, now: number): number;
74
+ /** Retire spent wavefronts (call once/frame). */
75
+ prune(now: number): void;
76
+ /** Drop all wavefronts (e.g. on resize). */
77
+ clear(): void;
78
+ }
79
+ declare function createRipplePool(capacity: number): RipplePool;
80
+
81
+ interface ScalarField {
82
+ readonly w: number;
83
+ readonly h: number;
84
+ readonly cols: number;
85
+ readonly rows: number;
86
+ readonly cell: number;
87
+ readonly edge: 'toroidal' | 'clamp';
88
+ /** Bilinear read in px space. */
89
+ sample(x: number, y: number): number;
90
+ /** Central-difference gradient ∇ of the field at (x,y) — one cell apart, edge-aware. */
91
+ gradient(x: number, y: number, out: {
92
+ x: number;
93
+ y: number;
94
+ }): void;
95
+ /** Additive pheromone splat into the nearest cell. */
96
+ deposit(x: number, y: number, amount: number): void;
97
+ /** Multiply cells within radiusPx of (x,y) by `mul` (0..1). */
98
+ erode(x: number, y: number, radiusPx: number, mul: number): void;
99
+ /** Whole-field update: separable 3×3 box blur lerped by diffuseRate, then × decayRate.
100
+ * Each cell is clamped to maxVal (use Infinity for no clamp). */
101
+ step(diffuseRate: number, decayRate: number, maxVal: number): void;
102
+ /** Strided mean over the whole field. */
103
+ meanValue(stride: number): number;
104
+ /** Strided max over the whole field. */
105
+ maxValue(stride: number): number;
106
+ /** Mean field value in a disc around (x,y). */
107
+ localMean(x: number, y: number, radiusPx: number): number;
108
+ /** Pack the field into an RGBA byte buffer (length cols*rows*4) with a palette-binned ramp:
109
+ * low→mid→hi by value, knot reserved for the brightest cells; brightness folded into rgb
110
+ * so dim cells add nothing under additive Plus. `out` is caller-owned and reused. */
111
+ toRGBA(out: Uint8Array, norm: number, low: readonly number[], mid: readonly number[], hi: readonly number[], knot: readonly number[]): void;
112
+ resize(width: number, height: number): void;
113
+ }
114
+ declare function createScalarField(width: number, height: number, cellSize: number, edgeMode?: 'toroidal' | 'clamp'): ScalarField;
115
+
116
+ interface SenseConfig {
117
+ /** rad — angular offset of the two side sensors. */
118
+ sensorAngle: number;
119
+ /** px — how far ahead the sensors read. */
120
+ sensorDist: number;
121
+ /** rad — turn applied per step toward the brightest sensor. */
122
+ rotateAngle: number;
123
+ }
124
+ declare const SENSE_DEFAULTS: SenseConfig;
125
+ /** Read the field at one sensor: `offset` rad off the agent heading, `dist` px ahead. */
126
+ declare function senseAt(field: ScalarField, x: number, y: number, heading: number, offset: number, dist: number): number;
127
+ /** Jones turn decision from three sensor readings: −1 turn left, 0 straight, +1 turn right.
128
+ * `rand` ∈ [0,1) breaks the symmetric "both sides brighter" case. */
129
+ declare function decideTurn(left: number, center: number, right: number, rand: number): -1 | 0 | 1;
130
+ interface StigmergyConfig {
131
+ count: number;
132
+ sensorAngle: number;
133
+ sensorDist: number;
134
+ rotateAngle: number;
135
+ stepSize: number;
136
+ depositAmount: number;
137
+ chaos: number;
138
+ /** Returns an extra heading delta (rad) applied before moving. */
139
+ onSense?: (index: number, x: number, y: number, heading: number) => number;
140
+ /** Post-move notify. */
141
+ onMove?: (index: number, x: number, y: number, heading: number) => void;
142
+ }
143
+ interface AgentField {
144
+ readonly count: number;
145
+ readonly px: Float32Array;
146
+ readonly py: Float32Array;
147
+ readonly heading: Float32Array;
148
+ update(): void;
149
+ forEachAgent(cb: (x: number, y: number) => void, stride?: number): void;
150
+ resize(width: number, height: number): void;
151
+ }
152
+ declare function createStigmergy(field: ScalarField, config: StigmergyConfig, rng: SeededRNG): AgentField;
153
+
154
+ export { type AccelFn, type AgentField, type ClosestPair, type NBodySystem, type RipplePool, SENSE_DEFAULTS, type ScalarField, type SenseConfig, type StigmergyConfig, createNBodySystem, createRipplePool, createScalarField, createStigmergy, decideTurn, leapfrogInto, senseAt, verletStep };