-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathengine.ts
More file actions
336 lines (321 loc) · 9.68 KB
/
engine.ts
File metadata and controls
336 lines (321 loc) · 9.68 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
import {
IEngine,
IParticle,
GetParticlesInRadiusOptions,
GetParticlesInRadiusResult,
} from "./interfaces";
import { Module } from "./module";
import { WebGPUEngine } from "./runtimes/webgpu/engine";
import { CPUEngine } from "./runtimes/cpu/engine";
export type EngineOptions = {
canvas: HTMLCanvasElement;
forces: Module<string, any>[];
render: Module<string, any>[];
runtime: "cpu" | "webgpu" | "auto";
constrainIterations?: number;
clearColor?: { r: number; g: number; b: number; a: number };
cellSize?: number;
maxParticles?: number;
workgroupSize?: number;
maxNeighbors?: number;
};
export class Engine implements IEngine {
private engine: IEngine;
private actualRuntime: "cpu" | "webgpu"; // The actual runtime being used
private preferredRuntime: "cpu" | "webgpu" | "auto"; // The requested runtime (can be 'auto')
private originalOptions: EngineOptions; // Store original options for fallback
constructor(options: EngineOptions) {
this.preferredRuntime = options.runtime;
this.originalOptions = { ...options }; // Store original options for fallback
// Determine actual runtime to use
let targetRuntime: "cpu" | "webgpu" | "auto";
if (options.runtime === "auto") {
// Synchronous check - we'll handle WebGPU availability in initialize()
targetRuntime = "webgpu"; // Default to WebGPU for auto, fallback to CPU if it fails
} else {
targetRuntime = options.runtime;
}
this.actualRuntime = targetRuntime;
if (targetRuntime === "webgpu") {
this.engine = new WebGPUEngine(options);
} else {
this.engine = new CPUEngine(options);
}
}
// Delegate all methods to the concrete engine implementation
async initialize(): Promise<void> {
try {
await this.engine.initialize();
} catch (error) {
// Handle fallback for auto mode or WebGPU failures
if (this.preferredRuntime === "auto" && this.actualRuntime === "webgpu") {
console.warn(
"WebGPU initialization failed, falling back to CPU runtime:",
error
);
// Destroy the failed WebGPU engine
try {
await this.engine.destroy();
} catch (destroyError) {
console.warn("Error destroying failed WebGPU engine:", destroyError);
}
// Create CPU engine with same options
this.actualRuntime = "cpu";
const fallbackOptions = {
...this.originalOptions,
runtime: "cpu",
};
this.engine = new CPUEngine(fallbackOptions);
// Initialize the CPU engine
await this.engine.initialize();
} else {
throw error; // Re-throw if not auto mode or already CPU
}
}
// Log runtime selection for auto mode
if (this.preferredRuntime === "auto") {
if (this.actualRuntime === "cpu") {
console.warn(
"Auto runtime selection: Using CPU (WebGPU not available or failed)"
);
}
}
}
// Get the actual runtime being used (cpu or webgpu)
getActualRuntime(): "cpu" | "webgpu" {
return this.actualRuntime;
}
play(): void {
this.engine.play();
}
pause(): void {
this.engine.pause();
}
stop(): void {
this.engine.stop();
}
destroy(): Promise<void> {
return this.engine.destroy();
}
isPlaying(): boolean {
return this.engine.isPlaying();
}
toggle(): void {
this.engine.toggle();
}
getSize(): { width: number; height: number } {
return this.engine.getSize();
}
setSize(width: number, height: number): void {
this.engine.setSize(width, height);
}
setCamera(x: number, y: number): void {
this.engine.setCamera(x, y);
}
getCamera(): { x: number; y: number } {
return this.engine.getCamera();
}
setZoom(z: number): void {
this.engine.setZoom(z);
}
getZoom(): number {
return this.engine.getZoom();
}
// Oscillator API passthroughs
addOscillator(params: {
moduleName: string;
inputName: string;
min: number;
max: number;
speedHz: number;
options?: any;
}): string {
return this.engine.addOscillator(params);
}
removeOscillator(moduleName: string, inputName: string): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(this.engine as any).removeOscillator(moduleName, inputName);
}
updateOscillatorSpeed(
moduleName: string,
inputName: string,
speedHz: number
): void {
this.engine.updateOscillatorSpeed(moduleName, inputName, speedHz);
}
updateOscillatorBounds(
moduleName: string,
inputName: string,
min: number,
max: number
): void {
this.engine.updateOscillatorBounds(moduleName, inputName, min, max);
}
hasOscillator(moduleName: string, inputName: string): boolean {
return this.engine.hasOscillator(moduleName, inputName);
}
getOscillator(moduleName: string, inputName: string) {
return this.engine.getOscillator(moduleName, inputName);
}
clearOscillators(): void {
this.engine.clearOscillators();
}
clearModuleOscillators(moduleName: string): void {
this.engine.clearModuleOscillators(moduleName);
}
addOscillatorListener(
moduleName: string,
inputName: string,
handler: (value: number) => void
): void {
this.engine.addOscillatorListener(moduleName, inputName, handler);
}
removeOscillatorListener(
moduleName: string,
inputName: string,
handler: (value: number) => void
): void {
this.engine.removeOscillatorListener(moduleName, inputName, handler);
}
setOscillatorState(
moduleName: string,
inputName: string,
lastValue: number,
lastDirection: -1 | 0 | 1
): boolean {
return this.engine.setOscillatorState(
moduleName,
inputName,
lastValue,
lastDirection
);
}
getOscillatorsElapsedSeconds(): number {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return (this.engine as any).getOscillatorsElapsedSeconds();
}
setOscillatorsElapsedSeconds(seconds: number): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(this.engine as any).setOscillatorsElapsedSeconds(seconds);
}
setParticles(p: IParticle[]): void {
this.engine.setParticles(p);
}
addParticle(p: IParticle): number {
return this.engine.addParticle(p);
}
setParticle(index: number, p: IParticle): void {
this.engine.setParticle(index, p);
}
setParticleMass(index: number, mass: number): void {
this.engine.setParticleMass(index, mass);
}
getParticles(): Promise<IParticle[]> {
return this.engine.getParticles();
}
getParticle(index: number): Promise<IParticle> {
return this.engine.getParticle(index);
}
getParticlesInRadius(
center: { x: number; y: number },
radius: number,
opts?: GetParticlesInRadiusOptions
): Promise<GetParticlesInRadiusResult> {
return this.engine.getParticlesInRadius(center, radius, opts);
}
// Helpers for pinning/unpinning
async pinParticles(indexes: number[]): Promise<void> {
const particles = await this.getParticles();
for (const idx of indexes) {
if (particles[idx]) particles[idx].mass = -1;
}
this.setParticles(particles);
}
async unpinParticles(indexes: number[]): Promise<void> {
const particles = await this.getParticles();
for (const idx of indexes) {
if (particles[idx]) {
const size = particles[idx].size;
// Derive mass from size deterministically (simple proportional mapping)
particles[idx].mass = Math.max(0.1, size);
}
}
this.setParticles(particles);
}
async unpinAll(): Promise<void> {
const particles = await this.getParticles();
for (let i = 0; i < particles.length; i++) {
if (particles[i].mass < 0) {
const size = particles[i].size;
particles[i].mass = Math.max(0.1, size);
}
}
this.setParticles(particles);
}
clear(): void {
this.engine.clear();
}
getCount(): number {
return this.engine.getCount();
}
getFPS(): number {
return this.engine.getFPS();
}
export(): Record<string, Record<string, number>> {
return this.engine.export();
}
import(settings: Record<string, Record<string, number>>): void {
this.engine.import(settings);
}
// Configuration getters and setters
getClearColor(): { r: number; g: number; b: number; a: number } {
return this.engine.getClearColor();
}
setClearColor(color: { r: number; g: number; b: number; a: number }): void {
this.engine.setClearColor(color);
}
getCellSize(): number {
return this.engine.getCellSize();
}
setCellSize(size: number): void {
this.engine.setCellSize(size);
}
getConstrainIterations(): number {
return this.engine.getConstrainIterations();
}
setConstrainIterations(iterations: number): void {
this.engine.setConstrainIterations(iterations);
}
getMaxNeighbors(): number {
return this.engine.getMaxNeighbors();
}
setMaxNeighbors(size: number): void {
this.engine.setMaxNeighbors(size);
}
getMaxParticles(): number | null {
return this.engine.getMaxParticles();
}
setMaxParticles(value: number | null): void {
this.engine.setMaxParticles(value);
}
getModule(name: string): Module | undefined {
return this.engine.getModule(name);
}
// Check if a module is supported by the current runtime
isSupported(module: Module): boolean {
try {
if (this.actualRuntime === "webgpu") {
// For WebGPU, check if the module has a webgpu() method that doesn't throw
module.webgpu();
return true;
} else {
// For CPU, check if the module has a cpu() method that doesn't throw
module.cpu();
return true;
}
} catch (error) {
// If the method throws "Not implemented" or any other error, the module is not supported
return false;
}
}
}