-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathengine.ts
More file actions
684 lines (612 loc) · 20.6 KB
/
engine.ts
File metadata and controls
684 lines (612 loc) · 20.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
import {
AbstractEngine,
GetParticlesInRadiusOptions,
GetParticlesInRadiusResult,
IParticle,
ParticleQuery,
} from "../../interfaces";
import {
Module,
ModuleRole,
CanvasComposition,
CPURenderDescriptor,
CPUForceDescriptor,
} from "../../module";
import { SpatialGrid } from "./spatial-grid";
import { Particle } from "../../particle";
import { Vector } from "../../vector";
export class CPUEngine extends AbstractEngine {
private particles: Particle[] = [];
private canvas: HTMLCanvasElement;
private grid: SpatialGrid;
private animationId: number | null = null;
private particleIdToIndex: Map<number, number> = new Map();
constructor(options: {
canvas: HTMLCanvasElement;
forces: Module[];
render: Module[];
constrainIterations?: number;
clearColor?: { r: number; g: number; b: number; a: number };
cellSize?: number;
}) {
super(options);
this.canvas = options.canvas;
this.grid = new SpatialGrid({
width: this.canvas.width,
height: this.canvas.height,
cellSize: this.cellSize,
});
}
initialize(): Promise<void> {
return Promise.resolve();
}
// Implement abstract methods for animation loop
protected startAnimationLoop(): void {
if (this.animationId) {
cancelAnimationFrame(this.animationId);
this.animationId = null;
}
this.animate();
}
protected stopAnimationLoop(): void {
if (this.animationId) {
cancelAnimationFrame(this.animationId);
this.animationId = null;
}
}
/**
* Resets animation timing to prevent large deltaTime spikes.
* Useful when starting after engine restoration or long pauses.
*/
public resetTiming(): void {
this.lastTime = performance.now();
}
/**
* Resets the simulation to its initial state.
*
* This method:
* - Pauses the simulation
* - Clears all particles
* - Resets timing and FPS data
* - Clears force-specific caches
*/
public reset(): void {
this.pause();
// Ensure animation frame is properly cancelled
if (this.animationId) {
cancelAnimationFrame(this.animationId);
this.animationId = null;
}
this.particles = [];
this.lastTime = 0;
// Clear FPS tracking data
this.fpsEstimate = 60;
}
clear(): void {
this.particles = [];
this.grid.clear();
this.fpsEstimate = 60;
// Reset maxSize tracking
this.resetMaxSize();
this.particleIdToIndex.clear();
}
getCount(): number {
const actualCount = this.particles.length;
if (this.maxParticles === null) {
return actualCount;
}
return Math.min(actualCount, this.maxParticles);
}
protected getEffectiveCount(): number {
return this.getCount();
}
// Override setSize to also update spatial grid
setSize(width: number, height: number): void {
this.view.setSize(width, height);
this.grid.setSize(width, height);
}
setParticles(particle: IParticle[]): void {
this.particles = particle.map((p) => new Particle(p));
// Update maxSize tracking
this.resetMaxSize();
for (const p of particle) {
this.updateMaxSize(p.size);
}
this.particleIdToIndex.clear();
}
addParticle(particle: IParticle): number {
const index = this.particles.length;
this.particles.push(new Particle(particle));
// Update maxSize tracking
this.updateMaxSize(particle.size);
const created = this.particles[index];
if (created) this.particleIdToIndex.set(created.id, index);
return index;
}
setParticle(index: number, p: IParticle): void {
if (index < 0) return;
if (index >= this.particles.length) return;
this.particles[index] = new Particle(p);
// Best-effort maxSize tracking (monotonic)
this.updateMaxSize(p.size);
}
setParticleMass(index: number, mass: number): void {
if (index < 0) return;
if (index >= this.particles.length) return;
this.particles[index].mass = mass;
}
getParticles(): Promise<IParticle[]> {
return Promise.resolve(this.particles.map((p) => p.toJSON()));
}
getParticle(index: number): Promise<IParticle> {
return Promise.resolve(this.particles[index]);
}
async getParticlesInRadius(
center: { x: number; y: number },
radius: number,
opts?: GetParticlesInRadiusOptions
): Promise<GetParticlesInRadiusResult> {
const maxResults = Math.max(1, Math.floor(opts?.maxResults ?? 20000));
// Expand search radius to ensure we can find large particles whose discs
// intersect the query circle: dist <= radius + p.size.
const searchRadius = Math.max(0, radius) + this.getMaxSize();
// Use the existing spatial grid (built during the last simulation tick).
// Snapshot semantics: this is "as of last grid build" which is good enough
// for tool usage and avoids global scans.
const neighbors = this.grid.getParticles(
new Vector(center.x, center.y),
searchRadius,
// Ask for up to maxResults+1 so we can mark truncated more reliably.
maxResults + 1
);
const out: ParticleQuery[] = [];
const r = Math.max(0, radius);
for (const p of neighbors) {
if (p.mass === 0) continue;
const index = this.particleIdToIndex.get(p.id);
if (index === undefined) continue;
const dx = p.position.x - center.x;
const dy = p.position.y - center.y;
const rr = r + p.size;
if (dx * dx + dy * dy <= rr * rr) {
out.push({
index,
position: { x: p.position.x, y: p.position.y },
size: p.size,
mass: p.mass,
});
if (out.length >= maxResults + 1) break;
}
}
const truncated = out.length > maxResults;
return { particles: truncated ? out.slice(0, maxResults) : out, truncated };
}
destroy(): Promise<void> {
this.pause();
this.particles = [];
this.grid.clear();
this.particleIdToIndex.clear();
return Promise.resolve();
}
// Handle configuration changes
protected onClearColorChanged(): void {
// Clear color changes don't require any immediate system updates
// The new color will be used in the next render pass
}
protected onCellSizeChanged(): void {
// Rebuild spatial grid with new cell size
this.grid.setCellSize(this.cellSize);
}
protected onConstrainIterationsChanged(): void {
// Constrain iterations changes don't require any immediate system updates
// The new value will be used in the next simulation pass
}
protected onMaxNeighborsChanged(): void {
// No additional state to update on CPU when max neighbors changes
}
protected onMaxParticlesChanged(): void {
// No additional state to update on CPU when max particles changes
}
private animate = (): void => {
const dt = this.getTimeDelta();
this.updateFPS(dt);
if (this.playing) {
// Update engine-owned oscillators before module updates
this.updateOscillators(dt);
this.update(dt);
}
this.render();
this.animationId = requestAnimationFrame(this.animate);
};
private getNeighbors(position: { x: number; y: number }, radius: number) {
return this.grid.getParticles(
new Vector(position.x, position.y),
radius,
this.getMaxNeighbors()
);
}
private getImageData(
x: number,
y: number,
width: number,
height: number
): ImageData | null {
try {
const context = this.canvas.getContext("2d")!;
// Clamp to canvas bounds
const clampedX = Math.max(0, Math.min(x, this.canvas.width));
const clampedY = Math.max(0, Math.min(y, this.canvas.height));
const clampedWidth = Math.max(
0,
Math.min(width, this.canvas.width - clampedX)
);
const clampedHeight = Math.max(
0,
Math.min(height, this.canvas.height - clampedY)
);
if (clampedWidth <= 0 || clampedHeight <= 0) {
return null;
}
return context.getImageData(
clampedX,
clampedY,
clampedWidth,
clampedHeight
);
} catch (error) {
return null;
}
}
private update(dt: number): void {
const effectiveCount = this.getEffectiveCount();
// Update spatial grid with current particle positions and camera
this.grid.setCamera(
this.view.getCamera().x,
this.view.getCamera().y,
this.view.getZoom()
);
this.grid.clear();
this.particleIdToIndex.clear();
for (let i = 0; i < effectiveCount; i++) {
this.grid.insert(this.particles[i]);
this.particleIdToIndex.set(this.particles[i].id, i);
}
// Global state for modules that need it
const globalState: Record<number, Record<string, number>> = {};
// Position tracking for correct pass
const positionState: Map<
number,
{ prev: { x: number; y: number }; post: { x: number; y: number } }
> = new Map();
// Get neighbors function
const getNeighbors = (position: { x: number; y: number }, radius: number) =>
this.getNeighbors(position, radius);
// Image data access function
const getImageData = (
x: number,
y: number,
width: number,
height: number
) => this.getImageData(x, y, width, height);
// First pass: state computation for all modules
for (const module of this.modules) {
try {
// Skip disabled modules
if (!module.isEnabled()) continue;
if (module.role === ModuleRole.Force) {
const force = module.cpu() as CPUForceDescriptor;
if (force.state) {
const input: Record<string, number | number[]> = {};
for (const key of Object.keys(module.inputs)) {
const value = module.read()[key];
input[key] = value ?? 0;
}
// Always add enabled
input.enabled = module.isEnabled() ? 1 : 0;
for (let pi = 0; pi < effectiveCount; pi++) {
const particle = this.particles[pi];
if (particle.mass <= 0) continue;
const setState = (name: string, value: number) => {
if (!globalState[particle.id]) {
globalState[particle.id] = {};
}
globalState[particle.id][name] = value;
};
force.state({
particle: particle,
dt,
getNeighbors,
input,
setState,
view: this.view,
index: pi,
particles: this.particles,
getImageData,
});
}
}
}
} catch (error) {}
}
// Second pass: apply forces for all modules
for (const module of this.modules) {
try {
// Skip disabled modules
if (!module.isEnabled()) continue;
if (module.role === ModuleRole.Force) {
const force = module.cpu() as CPUForceDescriptor;
if (force.apply) {
const input: Record<string, number | number[]> = {};
for (const key of Object.keys(module.inputs)) {
const value = module.read()[key];
input[key] = value ?? 0;
}
// Always add enabled
input.enabled = module.isEnabled() ? 1 : 0;
for (let pi = 0; pi < effectiveCount; pi++) {
const particle = this.particles[pi];
if (particle.mass <= 0) continue;
const getState = (name: string, pid?: number) => {
return globalState[pid ?? particle.id]?.[name] ?? 0;
};
force.apply({
particle: particle,
dt,
maxSize: this.getMaxSize(),
getNeighbors,
input,
getState,
view: this.view,
index: pi,
particles: this.particles,
getImageData,
});
}
}
}
} catch (error) {}
}
// Third pass: integration (once per particle)
for (let i = 0; i < effectiveCount; i++) {
const particle = this.particles[i];
if (particle.mass <= 0) continue;
// Capture position before integration
const prevPos = { x: particle.position.x, y: particle.position.y };
particle.velocity.add(particle.acceleration.clone().multiply(dt));
particle.position.add(particle.velocity.clone().multiply(dt));
particle.acceleration.zero();
// Capture position after integration
const postPos = { x: particle.position.x, y: particle.position.y };
positionState.set(particle.id, { prev: prevPos, post: postPos });
}
// Fourth pass: constraints for all modules (multiple iterations)
const iterations = Math.max(1, this.constrainIterations);
for (let iter = 0; iter < iterations; iter++) {
for (const module of this.modules) {
try {
// Skip disabled modules
if (!module.isEnabled()) continue;
if (module.role === ModuleRole.Force) {
const force = module.cpu() as CPUForceDescriptor;
if (force.constrain) {
const input: Record<string, number | number[]> = {};
for (const key of Object.keys(module.inputs)) {
const value = module.read()[key];
input[key] = value ?? 0;
}
// Always add enabled
input.enabled = module.isEnabled() ? 1 : 0;
for (let pi = 0; pi < effectiveCount; pi++) {
const particle = this.particles[pi];
if (particle.mass <= 0) continue;
const getState = (name: string, pid?: number) => {
return globalState[pid ?? particle.id]?.[name] ?? 0;
};
force.constrain({
particle: particle,
getNeighbors,
dt: dt,
maxSize: this.getMaxSize(),
input,
getState,
view: this.view,
index: pi,
particles: this.particles,
getImageData,
});
}
}
}
} catch (error) {}
}
}
// Fifth pass: corrections for all modules
for (const module of this.modules) {
try {
// Skip disabled modules
if (!module.isEnabled()) continue;
if (module.role === ModuleRole.Force) {
const force = module.cpu() as CPUForceDescriptor;
if (force.correct) {
const input: Record<string, number | number[]> = {};
for (const key of Object.keys(module.inputs)) {
const value = module.read()[key];
input[key] = value ?? 0;
}
// Always add enabled
input.enabled = module.isEnabled() ? 1 : 0;
for (let index = 0; index < effectiveCount; index++) {
const particle = this.particles[index];
if (particle.mass <= 0) continue;
const getState = (name: string, pid?: number) => {
return globalState[pid ?? particle.id]?.[name] ?? 0;
};
const positions = positionState.get(particle.id);
const prevPos = positions?.prev ?? {
x: particle.position.x,
y: particle.position.y,
};
const postPos = positions?.post ?? {
x: particle.position.x,
y: particle.position.y,
};
force.correct({
particle: particle,
getNeighbors,
dt: dt,
maxSize: this.getMaxSize(),
prevPos,
postPos,
input,
getState,
view: this.view,
index,
particles: this.particles,
getImageData,
});
}
}
}
} catch (error) {}
}
}
private createRenderUtils(context: CanvasRenderingContext2D) {
return {
formatColor: (color: {
r: number;
g: number;
b: number;
a: number;
}): string => {
return `rgba(${color.r * 255}, ${color.g * 255}, ${color.b * 255}, ${
color.a
})`;
},
drawCircle: (
x: number,
y: number,
radius: number,
color: { r: number; g: number; b: number; a: number }
): void => {
context.fillStyle = `rgba(${color.r * 255}, ${color.g * 255}, ${
color.b * 255
}, ${color.a})`;
context.beginPath();
context.arc(x, y, radius, 0, Math.PI * 2);
context.fill();
},
drawRect: (
x: number,
y: number,
width: number,
height: number,
color: { r: number; g: number; b: number; a: number }
): void => {
context.fillStyle = `rgba(${color.r * 255}, ${color.g * 255}, ${
color.b * 255
}, ${color.a})`;
context.fillRect(x, y, width, height);
},
};
}
private render(): void {
const context = this.canvas.getContext("2d")!;
// Get camera and canvas info for coordinate transformation
const camera = this.view.getCamera();
const zoom = this.view.getZoom();
const size = this.view.getSize();
const centerX = size.width / 2;
const centerY = size.height / 2;
const utils = this.createRenderUtils(context);
// Check composition requirements of enabled render modules
const hasBackgroundHandler = this.modules.some((module) => {
if (!module.isEnabled() || module.role !== ModuleRole.Render)
return false;
const descriptor = module.cpu() as CPURenderDescriptor;
return descriptor.composition === CanvasComposition.HandlesBackground;
});
// Determine if there are any enabled renderers
const hasEnabledRenderer = this.modules.some(
(module) => module.isEnabled() && module.role === ModuleRole.Render
);
// Only clear canvas if no module handles background AND either some module requires clearing
// or there are no enabled renderers (to avoid leaving a stale frame on canvas)
if (!hasBackgroundHandler) {
const needsClearing = this.modules.some((module) => {
if (!module.isEnabled() || module.role !== ModuleRole.Render)
return false;
const descriptor = module.cpu() as CPURenderDescriptor;
return descriptor.composition === CanvasComposition.RequiresClear;
});
if (needsClearing || !hasEnabledRenderer) {
context.fillStyle = `rgba(${this.clearColor.r * 255}, ${
this.clearColor.g * 255
}, ${this.clearColor.b * 255}, ${this.clearColor.a})`;
context.fillRect(0, 0, context.canvas.width, context.canvas.height);
}
}
for (const module of this.modules) {
try {
// Skip disabled modules
if (!module.isEnabled()) continue;
if (module.role === ModuleRole.Render) {
const descriptor = module.cpu() as CPURenderDescriptor;
const render = descriptor;
// input
const input: Record<string, number | number[]> = {};
for (const key of Object.keys(module.inputs)) {
const value = module.read()[key];
input[key] = value ?? 0;
}
// Always add enabled
input.enabled = module.isEnabled() ? 1 : 0;
// Setup phase
render.setup?.({
context,
input,
view: this.view,
clearColor: this.clearColor,
utils,
particles: this.particles,
});
// Render each visible particle
const effectiveCount = this.getEffectiveCount();
for (let i = 0; i < effectiveCount; i++) {
const particle = this.particles[i];
if (particle.mass == 0) continue;
// Transform world position to screen position
const worldX = (particle.position.x - camera.x) * zoom;
const worldY = (particle.position.y - camera.y) * zoom;
const screenX = centerX + worldX;
const screenY = centerY + worldY;
const screenSize = particle.size * zoom;
// Skip rendering if particle is outside canvas bounds (culling)
if (
screenX + screenSize < 0 ||
screenX - screenSize > size.width ||
screenY + screenSize < 0 ||
screenY - screenSize > size.height
) {
continue;
}
render.render?.({
context,
particle,
screenX,
screenY,
screenSize,
input,
utils,
});
}
// Teardown phase
render.teardown?.({
context,
input,
utils,
});
}
} catch (error) {}
}
}
}