@pinkaphant/create-kolmo 0.1.4 → 0.3.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 (40) hide show
  1. package/README.md +15 -5
  2. package/bin/create-kolmo.mjs +45 -19
  3. package/package.json +2 -1
  4. package/templates/longline/README.md +14 -0
  5. package/templates/longline/index.html +15 -0
  6. package/templates/longline/package.json +38 -0
  7. package/templates/longline/src/App.tsx +48 -0
  8. package/templates/longline/src/components/Boat.tsx +97 -0
  9. package/templates/longline/src/components/CameraRig.tsx +61 -0
  10. package/templates/longline/src/components/Crates.tsx +48 -0
  11. package/templates/longline/src/components/Hud.tsx +197 -0
  12. package/templates/longline/src/components/Longline.tsx +107 -0
  13. package/templates/longline/src/components/Ocean.tsx +27 -0
  14. package/templates/longline/src/components/Radar.tsx +88 -0
  15. package/templates/longline/src/components/Referee.tsx +39 -0
  16. package/templates/longline/src/components/Scene.tsx +56 -0
  17. package/templates/longline/src/components/Sky.tsx +23 -0
  18. package/templates/longline/src/components/ocean-material.ts +143 -0
  19. package/templates/longline/src/components/round-context.ts +26 -0
  20. package/templates/longline/src/game/boat-control.ts +131 -0
  21. package/templates/longline/src/game/constants.ts +98 -0
  22. package/templates/longline/src/game/input.test.ts +83 -0
  23. package/templates/longline/src/game/input.ts +73 -0
  24. package/templates/longline/src/game/logic.test.ts +110 -0
  25. package/templates/longline/src/game/logic.ts +109 -0
  26. package/templates/longline/src/game/physics.test.ts +211 -0
  27. package/templates/longline/src/game/radar.ts +22 -0
  28. package/templates/longline/src/game/registry.ts +53 -0
  29. package/templates/longline/src/game/sea.ts +26 -0
  30. package/templates/longline/src/game/session.ts +6 -0
  31. package/templates/longline/src/game/simulation.test.ts +393 -0
  32. package/templates/longline/src/game/simulation.ts +137 -0
  33. package/templates/longline/src/game/store.test.ts +222 -0
  34. package/templates/longline/src/game/store.ts +195 -0
  35. package/templates/longline/src/game/test-world.ts +128 -0
  36. package/templates/longline/src/main.tsx +8 -0
  37. package/templates/longline/src/sfx.ts +50 -0
  38. package/templates/longline/src/styles.css +374 -0
  39. package/templates/longline/tsconfig.json +18 -0
  40. package/templates/longline/vite.config.ts +28 -0
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Every number the game is tuned with. The headless physics tests (physics.test.ts) run the same numbers against a
3
+ * real Rapier world, so a change here is checked there.
4
+ */
5
+
6
+ /** The one physics step. `<Physics timeStep>` and every `useBuoyancy` get this number; Kolmo refuses a mismatch. */
7
+ export const FIXED_DT = 1 / 60;
8
+
9
+ /** 9.8125 is exact in f32, so the engine's gravity and the solver's are the same number. */
10
+ export const GRAVITY = 9.8125;
11
+
12
+ /** The boat: a 3.6 m x 1.6 m hull at half the density of water, so it draws 0.25 m. Forward is -Z, the stern is +Z. */
13
+ export const BOAT = {
14
+ halfExtents: [0.8, 0.25, 1.8] as const,
15
+ density: 500,
16
+ /** Per-slab wave sampling: the hull sees the wave under its bow and its stern. */
17
+ slices: 4,
18
+ drag: { linear: 0.12, quadratic: 0.1, angular: 0.3 },
19
+ /** Forward push in newtons: about 7.3 m/s in calm water. */
20
+ thrust: 6000,
21
+ reverseThrust: 2400,
22
+ /** Yaw rate the helm asks for, rad/s, from standstill and at full speed. */
23
+ yawRate: 1.15,
24
+ yawRateFast: 0.65,
25
+ /** Speed at which the helm has dropped to `yawRateFast`, m/s. */
26
+ yawFastSpeed: 7,
27
+ /** How hard the steering torque chases the asked-for yaw rate, 1/s. */
28
+ yawGain: 5,
29
+ /** Roll and pitch rate the bilge keels take out of the hull, 1/s. */
30
+ tiltDamping: 4,
31
+ /** Sideways speed the keel takes out of the hull, 1/s. */
32
+ keel: 3.5,
33
+ /** Where the line is made fast, in the hull's frame. */
34
+ tow: [0, 0.15, 1.85] as const,
35
+ } as const;
36
+
37
+ /** The longline: floats on rope joints behind the stern. */
38
+ export const LINE = {
39
+ floats: 8,
40
+ /** Rope between neighbours, metres. */
41
+ spacing: 1.7,
42
+ floatRadius: 0.22,
43
+ floatDensity: 400,
44
+ } as const;
45
+
46
+ /** A drifting crate. Any part of the line within `catchRadius` of a crate's centre hauls it in. */
47
+ export const CRATE = {
48
+ halfExtents: [0.4, 0.25, 0.4] as const,
49
+ density: 350,
50
+ count: 9,
51
+ catchRadius: 1.1,
52
+ /** Points per crate before the combo. */
53
+ points: 100,
54
+ } as const;
55
+
56
+ /** The play area: a circle of this radius around the start. Past it the boat is pushed back and crates are lost. */
57
+ export const ARENA = {
58
+ radius: 80,
59
+ /** Crates enter in a band this far inside the upstream edge. */
60
+ spawnBand: 18,
61
+ /** Push back on the boat, m/s^2 per metre past the edge. */
62
+ push: 0.9,
63
+ } as const;
64
+
65
+ export const ROUND = {
66
+ seconds: 90,
67
+ /** A haul within this many seconds of the last one raises the combo. */
68
+ comboWindow: 4,
69
+ maxCombo: 5,
70
+ } as const;
71
+
72
+ export type SeaStateId = "calm" | "choppy" | "rough";
73
+
74
+ export interface SeaState {
75
+ id: SeaStateId;
76
+ label: string;
77
+ /** Longest wavelength in metres and the amplitude of that wave. */
78
+ wavelength: number;
79
+ amplitude: number;
80
+ steepness: number;
81
+ /** Current that carries the crates, m/s, along +X. */
82
+ current: number;
83
+ /** How much of the highest crests the shader whitens, 0 to 1. */
84
+ foam: number;
85
+ /** Seed of the wave spectrum. */
86
+ seed: number;
87
+ }
88
+
89
+ export const SEA_STATES: Readonly<Record<SeaStateId, SeaState>> = {
90
+ calm: { id: "calm", label: "Calm", wavelength: 26, amplitude: 0.08, steepness: 0.5, current: 0.3, foam: 0.1, seed: 11 },
91
+ choppy: { id: "choppy", label: "Choppy", wavelength: 24, amplitude: 0.17, steepness: 0.7, current: 0.55, foam: 0.5, seed: 7 },
92
+ rough: { id: "rough", label: "Rough", wavelength: 28, amplitude: 0.3, steepness: 0.7, current: 0.8, foam: 0.9, seed: 23 },
93
+ };
94
+
95
+ export const SEA_STATE_IDS: readonly SeaStateId[] = ["calm", "choppy", "rough"];
96
+
97
+ /** Heading of the swell in radians (the wave field's convention: 0 is +X). It runs with the current, so the crates ride it. */
98
+ export const SWELL_HEADING = 0.35;
@@ -0,0 +1,83 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { Helm, attachKeyboard } from "./input.js";
4
+
5
+ test("W and S are throttle, D and A are the rudder, and the arrow keys do the same", () => {
6
+ const h = new Helm();
7
+ assert.deepEqual(h.read(), { throttle: 0, steer: 0 });
8
+ h.press("KeyW");
9
+ h.press("KeyD");
10
+ assert.deepEqual(h.read(), { throttle: 1, steer: 1 });
11
+ h.release("KeyW");
12
+ h.release("KeyD");
13
+ h.press("ArrowDown");
14
+ h.press("ArrowLeft");
15
+ assert.deepEqual(h.read(), { throttle: -1, steer: -1 });
16
+ });
17
+
18
+ test("opposite keys cancel, and holding both ways of one axis through two keys does not exceed 1", () => {
19
+ const h = new Helm();
20
+ h.press("KeyW");
21
+ h.press("KeyS");
22
+ assert.equal(h.read().throttle, 0);
23
+ h.release("KeyS");
24
+ h.press("ArrowUp");
25
+ assert.equal(h.read().throttle, 1, "W and the up arrow together are still full ahead");
26
+ });
27
+
28
+ test("the on-screen buttons add to the keys, within -1 and 1, and letting go clears them", () => {
29
+ const h = new Helm();
30
+ h.setTouch(1, -1);
31
+ assert.deepEqual(h.read(), { throttle: 1, steer: -1 });
32
+ h.press("KeyW");
33
+ assert.equal(h.read().throttle, 1);
34
+ h.setTouch(0, 0);
35
+ h.release("KeyW");
36
+ assert.deepEqual(h.read(), { throttle: 0, steer: 0 });
37
+ });
38
+
39
+ test("releaseAll lets go of keys and buttons both", () => {
40
+ const h = new Helm();
41
+ h.press("KeyW");
42
+ h.press("KeyA");
43
+ h.setTouch(-1, 1);
44
+ h.releaseAll();
45
+ assert.deepEqual(h.read(), { throttle: 0, steer: 0 });
46
+ });
47
+
48
+ test("keys the helm does not use are not held", () => {
49
+ const h = new Helm();
50
+ h.press("KeyQ");
51
+ h.press("Space");
52
+ assert.deepEqual(h.read(), { throttle: 0, steer: 0 });
53
+ });
54
+
55
+ test("read fills the object it is given, so a caller can reuse one", () => {
56
+ const h = new Helm();
57
+ const out = { throttle: 9, steer: 9 };
58
+ h.press("KeyS");
59
+ assert.equal(h.read(out), out);
60
+ assert.deepEqual(out, { throttle: -1, steer: 0 });
61
+ });
62
+
63
+ test("attachKeyboard follows key events, swallows the ones it uses, loses them on blur and unhooks cleanly", () => {
64
+ const target = new EventTarget();
65
+ const h = new Helm();
66
+ const off = attachKeyboard(h, target as unknown as Window);
67
+ const key = (type: string, code: string) => {
68
+ const e = Object.assign(new Event(type, { cancelable: true }), { code });
69
+ target.dispatchEvent(e);
70
+ return e;
71
+ };
72
+ assert.equal(key("keydown", "KeyW").defaultPrevented, true, "the page must not scroll");
73
+ assert.equal(key("keydown", "KeyD").defaultPrevented, true);
74
+ assert.deepEqual(h.read(), { throttle: 1, steer: 1 });
75
+ assert.equal(key("keydown", "KeyP").defaultPrevented, false, "other keys are left alone");
76
+ key("keyup", "KeyD");
77
+ assert.equal(h.read().steer, 0);
78
+ target.dispatchEvent(new Event("blur"));
79
+ assert.deepEqual(h.read(), { throttle: 0, steer: 0 }, "a key-up lost to another window");
80
+ off();
81
+ key("keydown", "KeyW");
82
+ assert.equal(h.read().throttle, 0, "no longer listening");
83
+ });
@@ -0,0 +1,73 @@
1
+ import type { DriveInput } from "./boat-control.js";
2
+
3
+ const AHEAD = new Set(["KeyW", "ArrowUp"]);
4
+ const ASTERN = new Set(["KeyS", "ArrowDown"]);
5
+ const STARBOARD = new Set(["KeyD", "ArrowRight"]);
6
+ const PORT = new Set(["KeyA", "ArrowLeft"]);
7
+
8
+ /** Which of the helm's controls are held, from the keyboard and from the on-screen buttons. */
9
+ export class Helm {
10
+ private readonly keys = new Set<string>();
11
+ private touchThrottle = 0;
12
+ private touchSteer = 0;
13
+
14
+ press(code: string): void {
15
+ this.keys.add(code);
16
+ }
17
+
18
+ release(code: string): void {
19
+ this.keys.delete(code);
20
+ }
21
+
22
+ /** On-screen controls: -1, 0 or +1 on each axis. */
23
+ setTouch(throttle: number, steer: number): void {
24
+ this.touchThrottle = throttle;
25
+ this.touchSteer = steer;
26
+ }
27
+
28
+ /** Lets go of everything, e.g. when the window loses focus and the browser will never send the key-up. */
29
+ releaseAll(): void {
30
+ this.keys.clear();
31
+ this.touchThrottle = 0;
32
+ this.touchSteer = 0;
33
+ }
34
+
35
+ private axis(positive: ReadonlySet<string>, negative: ReadonlySet<string>): number {
36
+ let v = 0;
37
+ for (const k of this.keys) {
38
+ if (positive.has(k)) v += 1;
39
+ else if (negative.has(k)) v -= 1;
40
+ }
41
+ return v;
42
+ }
43
+
44
+ read(out: DriveInput = { throttle: 0, steer: 0 }): DriveInput {
45
+ const clamp = (v: number): number => (v < -1 ? -1 : v > 1 ? 1 : v);
46
+ out.throttle = clamp(this.axis(AHEAD, ASTERN) + this.touchThrottle);
47
+ out.steer = clamp(this.axis(STARBOARD, PORT) + this.touchSteer);
48
+ return out;
49
+ }
50
+ }
51
+
52
+ /** Hooks a helm up to the window's keyboard events. Returns the function that unhooks it. */
53
+ export function attachKeyboard(helm: Helm, target: Window = window): () => void {
54
+ const handled = new Set([...AHEAD, ...ASTERN, ...STARBOARD, ...PORT]);
55
+ const down = (e: KeyboardEvent): void => {
56
+ if (!handled.has(e.code)) return;
57
+ e.preventDefault();
58
+ helm.press(e.code);
59
+ };
60
+ const up = (e: KeyboardEvent): void => {
61
+ if (!handled.has(e.code)) return;
62
+ helm.release(e.code);
63
+ };
64
+ const blur = (): void => helm.releaseAll();
65
+ target.addEventListener("keydown", down);
66
+ target.addEventListener("keyup", up);
67
+ target.addEventListener("blur", blur);
68
+ return () => {
69
+ target.removeEventListener("keydown", down);
70
+ target.removeEventListener("keyup", up);
71
+ target.removeEventListener("blur", blur);
72
+ };
73
+ }
@@ -0,0 +1,110 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { ARENA, CRATE, ROUND } from "./constants.js";
4
+ import { LOSS_MARGIN, boundaryAcceleration, cratesOnLine, distanceToSegment, isLost, mulberry32, nextCombo, scatter, upstreamSpawn } from "./logic.js";
5
+
6
+ const near = (a: number, b: number, eps = 1e-9, what = "") => assert.ok(Math.abs(a - b) <= eps, `${what} ${a} vs ${b}`);
7
+
8
+ test("mulberry32 repeats for a seed, differs between seeds and stays in [0, 1)", () => {
9
+ const a = mulberry32(5);
10
+ const b = mulberry32(5);
11
+ const c = mulberry32(6);
12
+ const xs = Array.from({ length: 50 }, () => a());
13
+ assert.deepEqual(xs, Array.from({ length: 50 }, () => b()));
14
+ assert.notDeepEqual(xs, Array.from({ length: 50 }, () => c()));
15
+ for (const x of xs) assert.ok(x >= 0 && x < 1);
16
+ });
17
+
18
+ test("distanceToSegment: on the segment, beside it, past either end, and for a segment that is a point", () => {
19
+ near(distanceToSegment(2, 0, 0, 0, 4, 0), 0);
20
+ near(distanceToSegment(2, 3, 0, 0, 4, 0), 3);
21
+ near(distanceToSegment(-3, 4, 0, 0, 4, 0), 5);
22
+ near(distanceToSegment(7, 4, 0, 0, 4, 0), 5);
23
+ near(distanceToSegment(3, 4, 0, 0, 0, 0), 5);
24
+ // a slanted segment: the distance from (0, 2) to the line y = x is sqrt(2)
25
+ near(distanceToSegment(0, 2, -5, -5, 5, 5), Math.SQRT2);
26
+ });
27
+
28
+ test("cratesOnLine finds exactly the crates within the radius of any span, and nothing for a line of one point", () => {
29
+ // an L: (0,0) -> (10,0) -> (10,10)
30
+ const line = [0, 0, 10, 0, 10, 10];
31
+ const crates = [
32
+ 5, 0.5, // on the first span
33
+ 10.4, 6, // beside the second span
34
+ 4, 4, // inside the corner, 4 m from both spans
35
+ -1.0, 0, // just past the start, 1 m from its end
36
+ 12.5, 12.5, // beyond the far end
37
+ ];
38
+ const out: number[] = [];
39
+ const n = cratesOnLine(line, 3, crates, 5, 1.1, out);
40
+ assert.equal(n, 3);
41
+ assert.deepEqual(out.slice(0, n), [0, 1, 3]);
42
+ assert.equal(cratesOnLine([0, 0], 1, crates, 5, 1.1, out), 0, "one point is not a line");
43
+ assert.equal(cratesOnLine(line, 3, crates, 0, 1.1, out), 0, "no crates");
44
+ });
45
+
46
+ test("a crate right at the radius is hauled and one past it is not", () => {
47
+ const line = [0, 0, 10, 0];
48
+ const out: number[] = [];
49
+ assert.equal(cratesOnLine(line, 2, [5, CRATE.catchRadius], 1, CRATE.catchRadius, out), 1);
50
+ assert.equal(cratesOnLine(line, 2, [5, CRATE.catchRadius + 1e-6], 1, CRATE.catchRadius, out), 0);
51
+ });
52
+
53
+ test("the combo starts at 1, grows inside the window, stops at the cap and starts again after a gap", () => {
54
+ assert.equal(nextCombo(0, Infinity), 1);
55
+ assert.equal(nextCombo(1, 2), 2);
56
+ assert.equal(nextCombo(2, ROUND.comboWindow), 3, "exactly the window still counts");
57
+ assert.equal(nextCombo(ROUND.maxCombo, 1), ROUND.maxCombo);
58
+ assert.equal(nextCombo(3, ROUND.comboWindow + 0.01), 1);
59
+ assert.equal(nextCombo(3, Infinity), 1);
60
+ });
61
+
62
+ test("boundaryAcceleration is zero inside the radius and pushes toward the centre in proportion to the overshoot", () => {
63
+ const out = { x: 9, z: 9 };
64
+ boundaryAcceleration(30, 40, 50, 0.9, out);
65
+ assert.deepEqual(out, { x: 0, z: 0 }, "exactly on the edge is inside");
66
+ boundaryAcceleration(60, 80, 50, 0.9, out);
67
+ // 100 m out, 50 over: a = 45 toward the centre, along (-0.6, -0.8)
68
+ near(out.x, -0.6 * 45, 1e-9, "x");
69
+ near(out.z, -0.8 * 45, 1e-9, "z");
70
+ boundaryAcceleration(-70, 0, 50, 1, out);
71
+ near(out.x, 20, 1e-9, "x from the west");
72
+ near(Math.abs(out.z), 0, 1e-12, "z");
73
+ });
74
+
75
+ test("a crate is lost only past the edge plus the margin", () => {
76
+ assert.equal(isLost(ARENA.radius, 0, ARENA.radius), false);
77
+ assert.equal(isLost(ARENA.radius + LOSS_MARGIN, 0, ARENA.radius), false);
78
+ assert.equal(isLost(ARENA.radius + LOSS_MARGIN + 0.01, 0, ARENA.radius), true);
79
+ assert.equal(isLost(0, -(ARENA.radius + LOSS_MARGIN + 1), ARENA.radius), true);
80
+ });
81
+
82
+ test("upstreamSpawn always lands inside the arena, on the side the current comes from", () => {
83
+ const rand = mulberry32(99);
84
+ const p = { x: 0, z: 0 };
85
+ for (let i = 0; i < 500; i++) {
86
+ upstreamSpawn(rand, ARENA.radius, ARENA.spawnBand, p);
87
+ const d = Math.hypot(p.x, p.z);
88
+ assert.ok(d <= ARENA.radius - 3 + 1e-9 && d >= ARENA.radius - 3 - ARENA.spawnBand - 1e-9, `distance ${d}`);
89
+ assert.ok(p.x < 0, `x ${p.x}: upstream is -X`);
90
+ }
91
+ });
92
+
93
+ test("scatter gives the count inside the ring, apart from each other, and the same for a seed", () => {
94
+ const pts = scatter(mulberry32(3), 9, 14, 56, 12);
95
+ assert.equal(pts.length, 9);
96
+ for (const p of pts) {
97
+ const d = Math.hypot(p.x, p.z);
98
+ assert.ok(d >= 14 - 1e-9 && d <= 56 + 1e-9, `ring ${d}`);
99
+ }
100
+ for (let i = 0; i < pts.length; i++) {
101
+ for (let j = i + 1; j < pts.length; j++) assert.ok(Math.hypot(pts[i]!.x - pts[j]!.x, pts[i]!.z - pts[j]!.z) >= 12 - 1e-9, "apart");
102
+ }
103
+ assert.deepEqual(scatter(mulberry32(3), 9, 14, 56, 12), pts);
104
+ assert.notDeepEqual(scatter(mulberry32(4), 9, 14, 56, 12), pts);
105
+ });
106
+
107
+ test("scatter relaxes the separation when the ring is too crowded for it, and still returns", () => {
108
+ const pts = scatter(mulberry32(1), 30, 5, 10, 50);
109
+ assert.equal(pts.length, 30);
110
+ });
@@ -0,0 +1,109 @@
1
+ import { ROUND } from "./constants.js";
2
+
3
+ /** Small deterministic generator (mulberry32): the same seed always gives the same crates. */
4
+ export function mulberry32(seed: number): () => number {
5
+ let a = seed >>> 0;
6
+ return () => {
7
+ a = (a + 0x6d2b79f5) >>> 0;
8
+ let t = a;
9
+ t = Math.imul(t ^ (t >>> 15), t | 1);
10
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
11
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
12
+ };
13
+ }
14
+
15
+ /** Distance on the water plane from the point (px, pz) to the segment (ax, az)-(bx, bz). */
16
+ export function distanceToSegment(px: number, pz: number, ax: number, az: number, bx: number, bz: number): number {
17
+ const dx = bx - ax;
18
+ const dz = bz - az;
19
+ const len2 = dx * dx + dz * dz;
20
+ let t = len2 > 0 ? ((px - ax) * dx + (pz - az) * dz) / len2 : 0;
21
+ t = t < 0 ? 0 : t > 1 ? 1 : t;
22
+ return Math.hypot(px - (ax + dx * t), pz - (az + dz * t));
23
+ }
24
+
25
+ /**
26
+ * The crates a line passes within `radius` of. The line is `lineCount` points as (x, z) pairs and the crates are
27
+ * `crateCount` (x, z) pairs. Writes the indices of the hauled crates into `out` and returns how many.
28
+ */
29
+ export function cratesOnLine(
30
+ line: ArrayLike<number>,
31
+ lineCount: number,
32
+ crates: ArrayLike<number>,
33
+ crateCount: number,
34
+ radius: number,
35
+ out: number[],
36
+ ): number {
37
+ let found = 0;
38
+ for (let c = 0; c < crateCount; c++) {
39
+ const px = crates[c * 2]!;
40
+ const pz = crates[c * 2 + 1]!;
41
+ for (let i = 0; i + 1 < lineCount; i++) {
42
+ if (distanceToSegment(px, pz, line[i * 2]!, line[i * 2 + 1]!, line[i * 2 + 2]!, line[i * 2 + 3]!) <= radius) {
43
+ out[found++] = c;
44
+ break;
45
+ }
46
+ }
47
+ }
48
+ return found;
49
+ }
50
+
51
+ /** The combo after a haul: it grows while hauls come within the window of each other and starts again at 1 after a gap. */
52
+ export function nextCombo(combo: number, secondsSinceLastHaul: number): number {
53
+ if (combo <= 0 || secondsSinceLastHaul > ROUND.comboWindow) return 1;
54
+ return Math.min(combo + 1, ROUND.maxCombo);
55
+ }
56
+
57
+ /** Acceleration that pushes a body back into the arena, on the water plane, written into `out`. Zero inside the radius. */
58
+ export function boundaryAcceleration(x: number, z: number, radius: number, push: number, out: { x: number; z: number }): void {
59
+ const d = Math.hypot(x, z);
60
+ if (d <= radius) {
61
+ out.x = 0;
62
+ out.z = 0;
63
+ return;
64
+ }
65
+ const a = push * (d - radius);
66
+ out.x = (-x / d) * a;
67
+ out.z = (-z / d) * a;
68
+ }
69
+
70
+ /** A crate that has drifted this far past the arena's edge is lost to the current. */
71
+ export const LOSS_MARGIN = 6;
72
+
73
+ export function isLost(x: number, z: number, radius: number): boolean {
74
+ return Math.hypot(x, z) > radius + LOSS_MARGIN;
75
+ }
76
+
77
+ /**
78
+ * Where a new crate comes in: on the upstream arc of the arena, the side the current runs from (the current runs
79
+ * along +X, so that is the -X side), inside the edge by up to `band` metres.
80
+ */
81
+ export function upstreamSpawn(rand: () => number, radius: number, band: number, out: { x: number; z: number }): void {
82
+ const angle = Math.PI + (rand() * 2 - 1) * 1.1;
83
+ const r = radius - 3 - rand() * band;
84
+ out.x = Math.cos(angle) * r;
85
+ out.z = Math.sin(angle) * r;
86
+ }
87
+
88
+ /**
89
+ * `count` points in the ring rMin..rMax around the origin, at least `minSeparation` apart. Rejection sampling with a
90
+ * fixed budget: if the ring is too crowded for it, the separation relaxes instead of the call failing.
91
+ */
92
+ export function scatter(rand: () => number, count: number, rMin: number, rMax: number, minSeparation: number): Array<{ x: number; z: number }> {
93
+ const points: Array<{ x: number; z: number }> = [];
94
+ let separation = minSeparation;
95
+ let tries = 0;
96
+ while (points.length < count) {
97
+ const angle = rand() * Math.PI * 2;
98
+ const r = Math.sqrt(rMin * rMin + rand() * (rMax * rMax - rMin * rMin));
99
+ const p = { x: Math.cos(angle) * r, z: Math.sin(angle) * r };
100
+ if (points.every((q) => Math.hypot(q.x - p.x, q.z - p.z) >= separation)) {
101
+ points.push(p);
102
+ tries = 0;
103
+ } else if (++tries > 200) {
104
+ separation *= 0.9;
105
+ tries = 0;
106
+ }
107
+ }
108
+ return points;
109
+ }