@esmirnov.ai/sperm-lab 0.0.0-stage → 0.4.2

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.
@@ -0,0 +1,382 @@
1
+ import { FACTORS, getFactor } from "./factors.js";
2
+ import { DEFECT_CATALOG } from "./defects.js";
3
+ import { SLOW_SPEED_THRESHOLD } from "./constants.js";
4
+ export { SLOW_SPEED_THRESHOLD } from "./constants.js";
5
+ // These authored coefficients create visible teaching examples. They are not research effect sizes.
6
+ const profiles = {
7
+ exercise: { production: 1.08, motility: 0, vitality: 0, shape: 0, dna: 0, speed: 1 },
8
+ endurance: { production: .87, motility: -.1, vitality: 0, shape: .045, dna: 0, speed: .9 },
9
+ cycling: { production: .9, motility: -.075, vitality: 0, shape: .065, dna: 0, speed: .94 },
10
+ smoking: { production: .86, motility: -.19, vitality: 0, shape: .13, dna: .25, speed: .76 },
11
+ alcohol: { production: .74, motility: -.16, vitality: 0, shape: .11, dna: 0, speed: .84 },
12
+ stress: { production: .92, motility: -.065, vitality: 0, shape: .025, dna: 0, speed: .95 },
13
+ sleep: { production: .93, motility: -.065, vitality: 0, shape: .035, dna: 0, speed: .95 },
14
+ heat: { production: .72, motility: -.24, vitality: 0, shape: .18, dna: .21, speed: .7 },
15
+ fever: { production: .68, motility: -.22, vitality: 0, shape: .16, dna: 0, speed: .78 },
16
+ metabolic: { production: .83, motility: -.12, vitality: 0, shape: .08, dna: .1, speed: .88 },
17
+ androgens: { production: .2, motility: 0, vitality: 0, shape: 0, dna: 0, speed: 1 },
18
+ pesticides: { production: .8, motility: -.17, vitality: 0, shape: .12, dna: .19, speed: .8 },
19
+ };
20
+ function finite(value, fallback) { return typeof value === "number" && Number.isFinite(value) ? value : fallback; }
21
+ function clamp(value, min = 0, max = 1) { return Math.min(max, Math.max(min, value)); }
22
+ /** Resolve all twelve independent strengths. Unknown keys are errors; invalid numeric values become zero. */
23
+ export function resolveFactors(settings = {}) {
24
+ if (!settings || typeof settings !== "object" || Array.isArray(settings))
25
+ throw new TypeError("Factor settings must be an object.");
26
+ for (const key of Object.keys(settings))
27
+ getFactor(key);
28
+ return Object.freeze(Object.fromEntries(FACTORS.map(factor => [factor.id, clamp(finite(settings[factor.id], 0))])));
29
+ }
30
+ export function getActiveFactors(world) {
31
+ return FACTORS.filter(factor => world.factors[factor.id] > 0);
32
+ }
33
+ function composeChannels(factors, progress) {
34
+ let production = 1, motility = .79, typical = .83, intactDna = .88, speed = 1, intactMidpiece = .92;
35
+ // Independent visual pathways saturate separately. No channel is an aggregate fertility score.
36
+ // Canonical factor order makes the result independent of object property order.
37
+ for (const factor of FACTORS) {
38
+ const effect = factors[factor.id] * progress;
39
+ if (effect === 0)
40
+ continue;
41
+ const profile = profiles[factor.id];
42
+ production *= 1 + (profile.production - 1) * effect;
43
+ motility *= 1 + profile.motility / .79 * effect;
44
+ typical *= 1 - profile.shape / .83 * effect;
45
+ intactDna *= 1 - profile.dna / .88 * effect;
46
+ speed *= 1 + (profile.speed - 1) * effect;
47
+ // Only these cited oxidative examples affect the illustrated midpiece pathway.
48
+ if (factor.id === "smoking" || factor.id === "heat")
49
+ intactMidpiece *= 1 - .12 / .92 * effect;
50
+ }
51
+ return { production: clamp(production, .12, 1.08), motility: clamp(motility), shape: clamp(1 - typical), dna: clamp(1 - intactDna), speed: clamp(speed, .25, 1.08), midpiece: clamp(1 - intactMidpiece) };
52
+ }
53
+ function randomGenerator(seed) {
54
+ let state = seed >>> 0;
55
+ return () => {
56
+ state = (state + 0x6D2B79F5) >>> 0;
57
+ let mixed = Math.imul(state ^ state >>> 15, 1 | state);
58
+ mixed ^= mixed + Math.imul(mixed ^ mixed >>> 7, 61 | mixed);
59
+ return ((mixed ^ mixed >>> 14) >>> 0) / 4294967296;
60
+ };
61
+ }
62
+ /** Create a new fictional cohort. Progress is not elapsed biological time. */
63
+ export function createSimulation(options = {}) {
64
+ const seed = Math.trunc(finite(options.seed, 42)) >>> 0;
65
+ const teachingPopulation = options.teachingPopulation === true;
66
+ const minimumCount = teachingPopulation ? DEFECT_CATALOG.length : 1;
67
+ const requestedCount = Math.round(clamp(finite(options.count, 48), minimumCount, 160));
68
+ const progress = clamp(finite(options.progress, 1));
69
+ const independent = options.factors !== undefined;
70
+ const intensity = independent ? 1 : clamp(finite(options.intensity, 1));
71
+ if (!independent && options.factor !== undefined)
72
+ getFactor(options.factor);
73
+ const factors = resolveFactors(independent ? options.factors : options.factor ? { [options.factor]: intensity } : {});
74
+ const channels = composeChannels(factors, progress);
75
+ const count = Math.round(clamp(requestedCount * channels.production, minimumCount, 160));
76
+ const random = randomGenerator(seed);
77
+ const cells = [];
78
+ for (let id = 0; id < count; id++) {
79
+ const x = .04 + random() * .92;
80
+ const y = .04 + random() * .92;
81
+ const angle = random() * Math.PI * 2;
82
+ const phase = random() * Math.PI * 2;
83
+ const vitalityDraw = random();
84
+ const movementDraw = random();
85
+ const shapeDraw = random();
86
+ const dnaDraw = random();
87
+ const progressDraw = random();
88
+ const speedDraw = random();
89
+ const beatDraw = random();
90
+ const headDraw = random(), tailDraw = random(), midpieceDraw = random();
91
+ const headShapeDraw = random(), tailShapeDraw = random(), midpieceShapeDraw = random(), fragmentDraw = random();
92
+ const alive = vitalityDraw < .95;
93
+ const headCount = headDraw < .035 ? 2 : 1;
94
+ // Named developmental forms are sampled independently of lifestyle settings.
95
+ let headShape = headShapeDraw < .03 ? "small" : headShapeDraw < .06 ? "large" : headShapeDraw < .09 ? "tapered" : headShapeDraw < .12 ? "round" : "typical";
96
+ let tailShape = tailShapeDraw < .025 ? "absent" : tailShapeDraw < .055 ? "short" : tailShapeDraw < .085 ? "coiled" : tailShapeDraw < .12 ? "bent" : "typical";
97
+ if (headShape === "typical" && shapeDraw < channels.shape * .52)
98
+ headShape = "irregular";
99
+ if (tailShape === "typical" && shapeDraw >= channels.shape * .52 && shapeDraw < channels.shape)
100
+ tailShape = "irregular";
101
+ const midpieceShape = midpieceShapeDraw < .04 ? "bent" : midpieceShapeDraw < .08 ? "thick" : "typical";
102
+ const tailCount = tailShape === "absent" ? 0 : tailDraw < .01 ? 3 : tailDraw < .045 ? 2 : 1;
103
+ const motile = alive && tailCount > 0 && movementDraw < channels.motility;
104
+ const headDefect = headCount === 2 || headShape !== "typical";
105
+ const tailDefect = tailCount !== 1 || tailShape !== "typical";
106
+ const midpieceDamage = midpieceDraw < channels.midpiece;
107
+ const morphology = headDefect ? "head" : tailDefect ? "tail" : "typical";
108
+ const dnaDamage = dnaDraw < channels.dna;
109
+ const dnaFragmentation = dnaDamage ? (3 + Math.floor(fragmentDraw * 4)) : 0;
110
+ // Shape alone does not determine movement. The separate draw preserves that distinction.
111
+ const speed = motile ? (.02 + speedDraw * .05) * channels.speed : 0;
112
+ cells.push({ id, x, y, angle, phase, alive, speed, beat: motile ? 4 + beatDraw * 3 : 0,
113
+ headCount, tailCount, headShape, tailShape, midpieceShape, headDefect, tailDefect, midpieceDamage, morphology, dnaDamage, dnaFragmentation,
114
+ progressive: motile && progressDraw < (tailDefect ? .33 : .81), trail: [] });
115
+ }
116
+ const world = { cells, time: 0, seed, factors, teachingPopulation, factor: independent ? undefined : options.factor, progress, intensity, requestedCount, model: "fictional-teaching-sample", trailClock: 0 };
117
+ if (teachingPopulation)
118
+ prepareTeachingExamples(world, channels);
119
+ return world;
120
+ }
121
+ /** Make an explicitly prepared sample for a discovery challenge. Cell zero is the target. */
122
+ export function createChallengeSimulation(kind, options = {}) {
123
+ if (!["hidden-dna", "immotile-alive", "circling"].includes(kind))
124
+ throw new RangeError(`Unknown challenge: ${String(kind)}`);
125
+ const world = createSimulation(options);
126
+ const target = world.cells[0];
127
+ world.fixture = kind;
128
+ target.alive = true;
129
+ target.headCount = target.tailCount = 1;
130
+ target.headShape = target.tailShape = target.midpieceShape = "typical";
131
+ target.headDefect = target.tailDefect = target.midpieceDamage = false;
132
+ target.morphology = "typical";
133
+ target.dnaDamage = kind === "hidden-dna";
134
+ target.dnaFragmentation = kind === "hidden-dna" ? 5 : 0;
135
+ target.speed = kind === "immotile-alive" ? 0 : .052;
136
+ target.beat = kind === "immotile-alive" ? 0 : 5.5;
137
+ target.progressive = kind === "hidden-dna";
138
+ // Other cells cannot satisfy the selected challenge. The prepared target is unambiguous.
139
+ for (const cell of world.cells.slice(1)) {
140
+ if (kind === "hidden-dna") {
141
+ cell.dnaDamage = false;
142
+ cell.dnaFragmentation = 0;
143
+ }
144
+ if (kind === "immotile-alive" && cell.alive && cell.speed === 0) {
145
+ if (cell.tailCount === 0) {
146
+ cell.tailCount = 1;
147
+ cell.tailShape = "typical";
148
+ cell.tailDefect = false;
149
+ cell.morphology = cell.headDefect ? "head" : "typical";
150
+ }
151
+ cell.speed = .045;
152
+ cell.beat = 5;
153
+ cell.progressive = true;
154
+ }
155
+ if (kind === "circling" && cell.speed > 0)
156
+ cell.progressive = true;
157
+ }
158
+ return world;
159
+ }
160
+ /** Make prepared anatomy examples without assigning them to a lifestyle exposure. */
161
+ export function createDefectSimulation(options = {}) {
162
+ const world = createSimulation({ ...options, teachingPopulation: true });
163
+ world.fixture = "defect-examples";
164
+ return world;
165
+ }
166
+ function prepareTeachingExamples(world, channels) {
167
+ for (const [index, cell] of world.cells.slice(0, DEFECT_CATALOG.length).entries()) {
168
+ // Pin only the named lesson trait. Other channels remain responsive to the controls.
169
+ const example = DEFECT_CATALOG[index].id;
170
+ cell.example = example;
171
+ switch (example) {
172
+ case "double-head":
173
+ cell.headCount = 2;
174
+ break;
175
+ case "small-head":
176
+ cell.headShape = "small";
177
+ break;
178
+ case "large-head":
179
+ cell.headShape = "large";
180
+ break;
181
+ case "tapered-head":
182
+ cell.headShape = "tapered";
183
+ break;
184
+ case "round-head":
185
+ cell.headShape = "round";
186
+ break;
187
+ case "double-tail":
188
+ cell.tailCount = 2;
189
+ if (cell.tailShape === "absent")
190
+ cell.tailShape = "typical";
191
+ break;
192
+ case "triple-tail":
193
+ cell.tailCount = 3;
194
+ if (cell.tailShape === "absent")
195
+ cell.tailShape = "typical";
196
+ break;
197
+ case "bent-tail":
198
+ cell.tailShape = "bent";
199
+ if (cell.tailCount === 0)
200
+ cell.tailCount = 1;
201
+ break;
202
+ case "coiled-tail":
203
+ cell.tailShape = "coiled";
204
+ if (cell.tailCount === 0)
205
+ cell.tailCount = 1;
206
+ break;
207
+ case "short-tail":
208
+ cell.tailShape = "short";
209
+ if (cell.tailCount === 0)
210
+ cell.tailCount = 1;
211
+ break;
212
+ case "absent-tail":
213
+ cell.tailShape = "absent";
214
+ cell.tailCount = 0;
215
+ cell.speed = cell.beat = 0;
216
+ cell.progressive = false;
217
+ break;
218
+ case "bent-midpiece":
219
+ cell.midpieceShape = "bent";
220
+ break;
221
+ case "thick-midpiece":
222
+ cell.midpieceShape = "thick";
223
+ break;
224
+ case "midpiece-damage":
225
+ cell.midpieceDamage = true;
226
+ break;
227
+ case "dna-fragmentation":
228
+ cell.dnaDamage = true;
229
+ cell.dnaFragmentation = clamp(3 + Math.floor(channels.dna * 6), 3, 6);
230
+ break;
231
+ case "slow":
232
+ cell.alive = true;
233
+ if (cell.tailCount === 0) {
234
+ cell.tailCount = 1;
235
+ cell.tailShape = "typical";
236
+ }
237
+ cell.speed = .018 * channels.speed;
238
+ cell.beat = 5.5;
239
+ break;
240
+ case "immotile":
241
+ cell.alive = true;
242
+ cell.speed = cell.beat = 0;
243
+ cell.progressive = false;
244
+ break;
245
+ case "nonprogressive":
246
+ cell.alive = true;
247
+ if (cell.tailCount === 0) {
248
+ cell.tailCount = 1;
249
+ cell.tailShape = "typical";
250
+ }
251
+ cell.speed = .052 * channels.speed;
252
+ cell.beat = 5.5;
253
+ cell.progressive = false;
254
+ break;
255
+ }
256
+ cell.headDefect = cell.headCount > 1 || cell.headShape !== "typical";
257
+ cell.tailDefect = cell.tailCount !== 1 || cell.tailShape !== "typical";
258
+ cell.morphology = cell.headDefect ? "head" : cell.tailDefect ? "tail" : "typical";
259
+ }
260
+ }
261
+ /** Advance physical motion only. Sperm biology remains fixed within a cohort. */
262
+ export function stepSimulation(world, dt, flow) {
263
+ if (!Number.isFinite(dt) || dt <= 0)
264
+ return;
265
+ const step = Math.min(dt, .05);
266
+ world.time += step;
267
+ world.trailClock += step;
268
+ const keepTrail = world.trailClock >= .06;
269
+ if (keepTrail)
270
+ world.trailClock %= .06;
271
+ const validFlow = flow && [flow.x, flow.y, flow.dx, flow.dy, flow.strength].every(Number.isFinite);
272
+ for (const cell of world.cells) {
273
+ if (cell.speed > 0) {
274
+ cell.angle += (cell.progressive ? Math.sin(world.time * .8 + cell.phase) * .1 : 2.25) * step;
275
+ cell.x += Math.cos(cell.angle) * cell.speed * step;
276
+ cell.y += Math.sin(cell.angle) * cell.speed * step;
277
+ }
278
+ if (validFlow && flow) {
279
+ const distance = Math.hypot(cell.x - clamp(flow.x), cell.y - clamp(flow.y));
280
+ const weight = Math.max(0, 1 - distance / .28) ** 2 * clamp(flow.strength, 0, 3);
281
+ cell.x += clamp(flow.dx, -.4, .4) * weight * step * 8;
282
+ cell.y += clamp(flow.dy, -.4, .4) * weight * step * 8;
283
+ }
284
+ if (cell.x < .015 || cell.x > .985) {
285
+ cell.x = clamp(cell.x, .015, .985);
286
+ cell.angle = Math.PI - cell.angle;
287
+ cell.trail.length = 0;
288
+ }
289
+ if (cell.y < .015 || cell.y > .985) {
290
+ cell.y = clamp(cell.y, .015, .985);
291
+ cell.angle = -cell.angle;
292
+ cell.trail.length = 0;
293
+ }
294
+ cell.angle = ((cell.angle % (Math.PI * 2)) + Math.PI * 2) % (Math.PI * 2);
295
+ if (keepTrail) {
296
+ cell.trail.push({ x: cell.x, y: cell.y });
297
+ if (cell.trail.length > 28)
298
+ cell.trail.shift();
299
+ }
300
+ }
301
+ }
302
+ export function getMetrics(world) {
303
+ const metrics = { total: world.cells.length, motile: 0, progressive: 0, alive: 0, typical: 0, dnaDamaged: 0,
304
+ multiHead: 0, multiTail: 0, midpieceDamaged: 0, headDefects: 0, tailDefects: 0, slow: 0, immotile: 0, nonprogressive: 0 };
305
+ for (const cell of world.cells) {
306
+ if (cell.alive)
307
+ metrics.alive++;
308
+ if (cell.alive && cell.speed > 0)
309
+ metrics.motile++;
310
+ if (cell.alive && cell.speed > 0 && cell.progressive)
311
+ metrics.progressive++;
312
+ if (cell.morphology === "typical")
313
+ metrics.typical++;
314
+ if (cell.dnaDamage)
315
+ metrics.dnaDamaged++;
316
+ if (cell.headCount > 1)
317
+ metrics.multiHead++;
318
+ if (cell.tailCount > 1)
319
+ metrics.multiTail++;
320
+ if (cell.midpieceDamage)
321
+ metrics.midpieceDamaged++;
322
+ if (cell.headDefect)
323
+ metrics.headDefects++;
324
+ if (cell.tailDefect)
325
+ metrics.tailDefects++;
326
+ if (isSlow(cell))
327
+ metrics.slow++;
328
+ if (!cell.alive || cell.speed === 0)
329
+ metrics.immotile++;
330
+ if (cell.alive && cell.speed > 0 && !cell.progressive)
331
+ metrics.nonprogressive++;
332
+ }
333
+ return metrics;
334
+ }
335
+ export function isSlow(cell) {
336
+ return cell.alive && cell.speed > 0 && cell.speed < SLOW_SPEED_THRESHOLD;
337
+ }
338
+ /** Return schematic tail geometry in the same normalized plane as the cell. */
339
+ export function getTailPoints(cell, time, tailIndex = 0) {
340
+ const points = [];
341
+ if (cell.tailCount === 0 || cell.tailShape === "absent")
342
+ return points;
343
+ const t = finite(time, 0);
344
+ const indexOffset = Math.round(clamp(finite(tailIndex, 0), 0, (cell.tailCount ?? 1) - 1));
345
+ const separation = (indexOffset - ((cell.tailCount ?? 1) - 1) / 2) * .009;
346
+ const cos = Math.cos(cell.angle), sin = Math.sin(cell.angle);
347
+ for (let index = 0; index <= 20; index++) {
348
+ const fraction = index / 20;
349
+ const lengthScale = cell.tailShape === "short" ? .32 : 1;
350
+ let along = -.009 - .18 * fraction * lengthScale;
351
+ // The short proximal section stays nearly straight. Bending grows smoothly along the flagellum.
352
+ const flexible = clamp((fraction - .1) / .9);
353
+ const envelope = flexible * flexible * (3 - 2 * flexible);
354
+ const phase = t * cell.beat * 2 * Math.PI - flexible * Math.PI * 3 * lengthScale + cell.phase + indexOffset * Math.PI * 2 / (cell.tailCount ?? 1);
355
+ let wave = cell.beat > 0 ? Math.sin(phase) * .009 * envelope : .002 * envelope;
356
+ let bend = cell.tailShape === "bent" ? .065 * clamp((flexible - .35) / .65) : cell.tailDefect ? .023 * Math.sin(flexible * Math.PI) * envelope : 0;
357
+ if (cell.tailShape === "coiled" && fraction > .12) {
358
+ const sweep = (fraction - .12) / .88 * Math.PI * 2.2;
359
+ along = -.0306 - .026 * Math.sin(sweep);
360
+ bend = .026 * (1 - Math.cos(sweep));
361
+ wave *= .2;
362
+ }
363
+ const across = wave + bend + separation * (1 + fraction * 2.8) + (cell.midpieceShape === "bent" ? .006 : 0);
364
+ points.push({ x: cell.x + along * cos - across * sin, y: cell.y + along * sin + across * cos });
365
+ }
366
+ return points;
367
+ }
368
+ /** Select a nearby cell with a small, input-friendly hit target. */
369
+ export function findCell(world, x, y, radius = .045) {
370
+ if (![x, y, radius].every(Number.isFinite) || radius < 0)
371
+ return undefined;
372
+ let nearest;
373
+ let nearestDistance = radius;
374
+ for (const cell of world.cells) {
375
+ const distance = Math.hypot(cell.x - x, cell.y - y);
376
+ if (distance <= nearestDistance) {
377
+ nearest = cell;
378
+ nearestDistance = distance;
379
+ }
380
+ }
381
+ return nearest;
382
+ }
@@ -0,0 +1,116 @@
1
+ export type FactorId = "exercise" | "endurance" | "cycling" | "smoking" | "alcohol" | "stress" | "sleep" | "heat" | "fever" | "metabolic" | "androgens" | "pesticides";
2
+ export type FactorSettings = Partial<Record<FactorId, number>>;
3
+ export type ResolvedFactors = Readonly<Record<FactorId, number>>;
4
+ export type HeadShape = "typical" | "small" | "large" | "tapered" | "round" | "irregular";
5
+ export type TailShape = "typical" | "bent" | "coiled" | "short" | "absent" | "irregular";
6
+ export type MidpieceShape = "typical" | "bent" | "thick";
7
+ export type DefectId = "double-head" | "small-head" | "large-head" | "tapered-head" | "round-head" | "double-tail" | "triple-tail" | "bent-tail" | "coiled-tail" | "short-tail" | "absent-tail" | "bent-midpiece" | "thick-midpiece" | "midpiece-damage" | "dna-fragmentation" | "slow" | "immotile" | "nonprogressive";
8
+ export type Evidence = "Human association" | "Mixed evidence" | "Established mechanism";
9
+ export interface Source {
10
+ title: string;
11
+ url: string;
12
+ }
13
+ export interface Factor {
14
+ id: FactorId;
15
+ title: string;
16
+ summary: string;
17
+ mechanism: string;
18
+ timescale: string;
19
+ evidence: Evidence;
20
+ limits: string;
21
+ sources: readonly Source[];
22
+ }
23
+ export interface Defect {
24
+ id: DefectId;
25
+ title: string;
26
+ description: string;
27
+ region: "head" | "tail" | "midpiece" | "dna" | "movement";
28
+ sources: readonly Source[];
29
+ }
30
+ export interface Point {
31
+ x: number;
32
+ y: number;
33
+ }
34
+ export interface SpermCell extends Point {
35
+ id: number;
36
+ angle: number;
37
+ phase: number;
38
+ /** Model distance per second. Zero means no active movement. */
39
+ speed: number;
40
+ beat: number;
41
+ alive: boolean;
42
+ /** Developmental variants. Lifestyle settings do not change these counts. */
43
+ headCount: 1 | 2;
44
+ tailCount: 0 | 1 | 2 | 3;
45
+ headShape: HeadShape;
46
+ tailShape: TailShape;
47
+ midpieceShape: MidpieceShape;
48
+ headDefect: boolean;
49
+ tailDefect: boolean;
50
+ /** Illustrated cellular injury. This flag does not require a visibly abnormal contour. */
51
+ midpieceDamage: boolean;
52
+ /** Compatibility summary. Independent traits carry the detailed anatomy. */
53
+ morphology: "typical" | "head" | "tail";
54
+ dnaDamage: boolean;
55
+ /** Number of drawn strand pieces. This is not a measured DNA fragmentation index. */
56
+ dnaFragmentation: 0 | 3 | 4 | 5 | 6;
57
+ /** Identifies a pinned teaching example, without a lifestyle cause. */
58
+ example?: DefectId;
59
+ progressive: boolean;
60
+ trail: Point[];
61
+ }
62
+ export type ChallengeKind = "hidden-dna" | "immotile-alive" | "circling";
63
+ export type FixtureKind = ChallengeKind | "defect-examples";
64
+ export interface Simulation {
65
+ cells: SpermCell[];
66
+ time: number;
67
+ seed: number;
68
+ factors: ResolvedFactors;
69
+ /** Includes an authored catalog of common forms, without prevalence estimates. */
70
+ teachingPopulation: boolean;
71
+ /** Legacy single-factor selection. Undefined for the independent factors API. */
72
+ factor?: FactorId;
73
+ progress: number;
74
+ intensity: number;
75
+ requestedCount: number;
76
+ fixture?: FixtureKind;
77
+ /** The sample is an authored example, without clinical units. */
78
+ model: "fictional-teaching-sample";
79
+ trailClock: number;
80
+ }
81
+ export interface SimulationOptions {
82
+ seed?: number;
83
+ count?: number;
84
+ /** Independent illustrative settings. This object takes priority over factor and intensity. */
85
+ factors?: FactorSettings;
86
+ /** Keep all 18 teaching examples visible. This mode has a minimum of 18 cells. */
87
+ teachingPopulation?: boolean;
88
+ /** Legacy single-factor option. */
89
+ factor?: FactorId;
90
+ /** Position in an illustrative development sequence, without a real-time calibration. */
91
+ progress?: number;
92
+ /** Relative scenario strength, without a dose calibration. */
93
+ intensity?: number;
94
+ }
95
+ export interface Flow extends Point {
96
+ dx: number;
97
+ dy: number;
98
+ strength: number;
99
+ }
100
+ export interface Metrics {
101
+ total: number;
102
+ motile: number;
103
+ progressive: number;
104
+ alive: number;
105
+ /** Typical head and tail outline in this model, not a clinical morphology score. */
106
+ typical: number;
107
+ dnaDamaged: number;
108
+ multiHead: number;
109
+ multiTail: number;
110
+ midpieceDamaged: number;
111
+ headDefects: number;
112
+ tailDefects: number;
113
+ slow: number;
114
+ immotile: number;
115
+ nonprogressive: number;
116
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,26 @@
1
+ import { type Point, type Simulation, type SpermCell } from "../core/index.js";
2
+ export type HeadGeometry = {
3
+ center: Point;
4
+ localY: number;
5
+ rx: number;
6
+ ry: number;
7
+ contour: Point[];
8
+ asymmetric: boolean;
9
+ };
10
+ export type CellGeometry = {
11
+ anchor: Point;
12
+ scale: number;
13
+ heads: HeadGeometry[];
14
+ tails: Point[][];
15
+ midpiece: Point[];
16
+ connections: Point[][];
17
+ headRx: number;
18
+ headRy: number;
19
+ midpieceWidth: number;
20
+ };
21
+ /** CSS pixel anchor shared by the scene, hit detection, and the moving inspector. */
22
+ export declare function getCellAnchor(cell: SpermCell, width: number, height: number): Point;
23
+ /** One isotropic display scale keeps cell outlines independent of canvas aspect ratio. */
24
+ export declare function getCellGeometry(cell: SpermCell, time: number, width: number, height: number): CellGeometry;
25
+ /** Hit the visible anatomy in CSS pixels, including each tail branch. */
26
+ export declare function hitTestCell(world: Simulation, px: number, py: number, width: number, height: number, padding?: number): SpermCell | undefined;
@@ -0,0 +1,98 @@
1
+ import { getTailPoints } from "../core/index.js";
2
+ /** CSS pixel anchor shared by the scene, hit detection, and the moving inspector. */
3
+ export function getCellAnchor(cell, width, height) {
4
+ return { x: cell.x * width, y: cell.y * height };
5
+ }
6
+ function rotatePoint(x, y, angle, origin) {
7
+ const cos = Math.cos(angle), sin = Math.sin(angle);
8
+ return { x: origin.x + x * cos - y * sin, y: origin.y + x * sin + y * cos };
9
+ }
10
+ function cubic(a, b, c, d, t) {
11
+ const u = 1 - t;
12
+ return { x: u ** 3 * a.x + 3 * u * u * t * b.x + 3 * u * t * t * c.x + t ** 3 * d.x,
13
+ y: u ** 3 * a.y + 3 * u * u * t * b.y + 3 * u * t * t * c.y + t ** 3 * d.y };
14
+ }
15
+ function headContour(rx, ry, asymmetric) {
16
+ const start = { x: -rx * .95, y: 0 };
17
+ const curves = [
18
+ [start, { x: -rx * .9, y: -ry * .63 }, { x: -rx * .25, y: -ry * (asymmetric ? 1.2 : 1) }, { x: rx * .35, y: -ry * .95 }],
19
+ [{ x: rx * .35, y: -ry * .95 }, { x: rx * 1.05, y: -ry * .9 }, { x: rx * 1.08, y: ry * .9 }, { x: rx * .35, y: ry * .95 }],
20
+ [{ x: rx * .35, y: ry * .95 }, { x: -rx * .25, y: ry * (asymmetric ? .78 : 1) }, { x: -rx * .9, y: ry * .63 }, start],
21
+ ];
22
+ return curves.flatMap(curve => Array.from({ length: 13 }, (_, index) => cubic(curve[0], curve[1], curve[2], curve[3], index / 12)));
23
+ }
24
+ /** One isotropic display scale keeps cell outlines independent of canvas aspect ratio. */
25
+ export function getCellGeometry(cell, time, width, height) {
26
+ const anchor = getCellAnchor(cell, width, height);
27
+ const scale = Math.max(.9, Math.min(1.1, Math.min(width, height) / 440));
28
+ const shape = cell.headShape;
29
+ const headRx = (shape === "small" ? 9 : shape === "large" ? 15.5 : shape === "tapered" ? 14.4 : shape === "round" ? 9.7 : 11.5) * scale;
30
+ const headRy = (shape === "small" ? 5.5 : shape === "large" ? 9.6 : shape === "tapered" ? 4.8 : shape === "round" ? 9.4 : 7.6) * scale;
31
+ const transform = (point) => rotatePoint(point.x, point.y, cell.angle, anchor);
32
+ const heads = Array.from({ length: cell.headCount }, (_, index) => {
33
+ const localY = cell.headCount === 2 ? (index === 0 ? -headRy * 1.22 : headRy * 1.22) : 0;
34
+ const asymmetric = cell.headShape === "irregular";
35
+ return { center: transform({ x: 0, y: localY }), localY, rx: headRx, ry: headRy, asymmetric,
36
+ contour: headContour(headRx, headRy, asymmetric).map(point => transform({ x: point.x, y: point.y + localY })) };
37
+ });
38
+ const zoom = 900 * scale;
39
+ const tails = Array.from({ length: cell.tailCount }, (_, index) => getTailPoints(cell, time, index).map(point => ({
40
+ x: anchor.x + (point.x - cell.x) * zoom, y: anchor.y + (point.y - cell.y) * zoom,
41
+ })));
42
+ const midpieceStart = -headRx * .85;
43
+ const midpiece = cell.tailCount > 0 ? Array.from({ length: 13 }, (_, index) => {
44
+ const t = index / 12;
45
+ const x = midpieceStart - 18 * scale * t;
46
+ const y = cell.midpieceShape === "bent" ? 2 * (1 - t) * t * -4.5 * scale + t * t * 4 * scale : 0;
47
+ return transform({ x, y });
48
+ }) : [];
49
+ const connections = cell.headCount === 2 ? heads.map(head => [transform({ x: -headRx * 1.35, y: 0 }), transform({ x: -headRx * .8, y: head.localY })]) : [];
50
+ return { anchor, scale, heads, tails, midpiece, connections, headRx, headRy,
51
+ midpieceWidth: (cell.midpieceShape === "thick" ? 4.1 : cell.midpieceDamage ? 3 : 2.3) * scale };
52
+ }
53
+ function segmentDistance(point, a, b) {
54
+ const dx = b.x - a.x, dy = b.y - a.y;
55
+ const length = dx * dx + dy * dy;
56
+ const t = length ? Math.max(0, Math.min(1, ((point.x - a.x) * dx + (point.y - a.y) * dy) / length)) : 0;
57
+ return Math.hypot(point.x - a.x - t * dx, point.y - a.y - t * dy);
58
+ }
59
+ function pathDistance(point, path) {
60
+ let distance = Infinity;
61
+ for (let index = 1; index < path.length; index++)
62
+ distance = Math.min(distance, segmentDistance(point, path[index - 1], path[index]));
63
+ return distance;
64
+ }
65
+ function inPolygon(point, polygon) {
66
+ let inside = false;
67
+ for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
68
+ const a = polygon[i], b = polygon[j];
69
+ if ((a.y > point.y) !== (b.y > point.y) && point.x < (b.x - a.x) * (point.y - a.y) / (b.y - a.y) + a.x)
70
+ inside = !inside;
71
+ }
72
+ return inside;
73
+ }
74
+ /** Hit the visible anatomy in CSS pixels, including each tail branch. */
75
+ export function hitTestCell(world, px, py, width, height, padding = 6) {
76
+ if (![px, py, width, height, padding].every(Number.isFinite) || width <= 0 || height <= 0 || padding < 0 || px < 0 || px > width || py < 0 || py > height)
77
+ return undefined;
78
+ const point = { x: px, y: py };
79
+ let nearest, bestDistance = padding;
80
+ for (const cell of [...world.cells].reverse()) {
81
+ const geometry = getCellGeometry(cell, world.time, width, height);
82
+ let distance = Infinity;
83
+ for (const head of geometry.heads)
84
+ distance = Math.min(distance, inPolygon(point, head.contour) ? 0 : Math.max(0, pathDistance(point, head.contour) - .7));
85
+ distance = Math.min(distance, Math.max(0, pathDistance(point, geometry.midpiece) - geometry.midpieceWidth / 2));
86
+ for (const connection of geometry.connections)
87
+ distance = Math.min(distance, Math.max(0, pathDistance(point, connection) - .8));
88
+ for (const tail of geometry.tails)
89
+ distance = Math.min(distance, Math.max(0, pathDistance(point, tail) - 1.05 * geometry.scale));
90
+ if (distance === 0)
91
+ return cell;
92
+ if (distance <= bestDistance && (!nearest || distance < bestDistance)) {
93
+ nearest = cell;
94
+ bestDistance = distance;
95
+ }
96
+ }
97
+ return nearest;
98
+ }
@@ -0,0 +1 @@
1
+ export { SpermLab, type SpermLabProps, type SpermLabMetrics } from "./sperm-lab.js";
@@ -0,0 +1,2 @@
1
+ "use client";
2
+ export { SpermLab } from "./sperm-lab.js";
@@ -0,0 +1,16 @@
1
+ import type { Simulation } from "../core/index.js";
2
+ export { getCellAnchor, getCellGeometry, hitTestCell } from "./geometry.js";
3
+ export type SpermPalette = {
4
+ ink: string;
5
+ sage: string;
6
+ clay: string;
7
+ accent: string;
8
+ paper?: string;
9
+ damage?: string;
10
+ };
11
+ export type SpermDisplay = {
12
+ trails: boolean;
13
+ dna: boolean;
14
+ selected: number | null;
15
+ };
16
+ export declare function paintSimulation(context: CanvasRenderingContext2D, world: Simulation, width: number, height: number, palette: SpermPalette, display: SpermDisplay): void;