@mun-ui/web 0.0.0-stage → 0.2.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 (107) hide show
  1. package/LICENSE +21 -0
  2. package/dist/accessibility.d.ts +3 -0
  3. package/dist/accessibility.d.ts.map +1 -0
  4. package/dist/accessibility.js +195 -0
  5. package/dist/accessibility.js.map +1 -0
  6. package/dist/content-transition.d.ts +23 -0
  7. package/dist/content-transition.d.ts.map +1 -0
  8. package/dist/content-transition.js +780 -0
  9. package/dist/content-transition.js.map +1 -0
  10. package/dist/continuous-corners.d.ts +3 -0
  11. package/dist/continuous-corners.d.ts.map +1 -0
  12. package/dist/continuous-corners.js +71 -0
  13. package/dist/continuous-corners.js.map +1 -0
  14. package/dist/control-styles.d.ts +7 -0
  15. package/dist/control-styles.d.ts.map +1 -0
  16. package/dist/control-styles.js +141 -0
  17. package/dist/control-styles.js.map +1 -0
  18. package/dist/controls.d.ts +4 -0
  19. package/dist/controls.d.ts.map +1 -0
  20. package/dist/controls.js +249 -0
  21. package/dist/controls.js.map +1 -0
  22. package/dist/devtools.d.ts +50 -0
  23. package/dist/devtools.d.ts.map +1 -0
  24. package/dist/devtools.js +118 -0
  25. package/dist/devtools.js.map +1 -0
  26. package/dist/dom.d.ts +12 -0
  27. package/dist/dom.d.ts.map +1 -0
  28. package/dist/dom.js +5427 -0
  29. package/dist/dom.js.map +1 -0
  30. package/dist/element-motion.d.ts +29 -0
  31. package/dist/element-motion.d.ts.map +1 -0
  32. package/dist/element-motion.js +463 -0
  33. package/dist/element-motion.js.map +1 -0
  34. package/dist/focus.d.ts +3 -0
  35. package/dist/focus.d.ts.map +1 -0
  36. package/dist/focus.js +70 -0
  37. package/dist/focus.js.map +1 -0
  38. package/dist/gpu-island.d.ts +123 -0
  39. package/dist/gpu-island.d.ts.map +1 -0
  40. package/dist/gpu-island.js +1093 -0
  41. package/dist/gpu-island.js.map +1 -0
  42. package/dist/hydration.d.ts +18 -0
  43. package/dist/hydration.d.ts.map +1 -0
  44. package/dist/hydration.js +228 -0
  45. package/dist/hydration.js.map +1 -0
  46. package/dist/index.d.ts +9 -0
  47. package/dist/index.d.ts.map +1 -0
  48. package/dist/index.js +7 -0
  49. package/dist/index.js.map +1 -0
  50. package/dist/lazy-index.d.ts +42 -0
  51. package/dist/lazy-index.d.ts.map +1 -0
  52. package/dist/lazy-index.js +136 -0
  53. package/dist/lazy-index.js.map +1 -0
  54. package/dist/motion.d.ts +49 -0
  55. package/dist/motion.d.ts.map +1 -0
  56. package/dist/motion.js +793 -0
  57. package/dist/motion.js.map +1 -0
  58. package/dist/patch-ir.d.ts +44 -0
  59. package/dist/patch-ir.d.ts.map +1 -0
  60. package/dist/patch-ir.js +221 -0
  61. package/dist/patch-ir.js.map +1 -0
  62. package/dist/path-interpolation.d.ts +29 -0
  63. package/dist/path-interpolation.d.ts.map +1 -0
  64. package/dist/path-interpolation.js +318 -0
  65. package/dist/path-interpolation.js.map +1 -0
  66. package/dist/presentation.d.ts +4 -0
  67. package/dist/presentation.d.ts.map +1 -0
  68. package/dist/presentation.js +207 -0
  69. package/dist/presentation.js.map +1 -0
  70. package/dist/props.d.ts +24 -0
  71. package/dist/props.d.ts.map +1 -0
  72. package/dist/props.js +719 -0
  73. package/dist/props.js.map +1 -0
  74. package/dist/shared.d.ts +79 -0
  75. package/dist/shared.d.ts.map +1 -0
  76. package/dist/shared.js +806 -0
  77. package/dist/shared.js.map +1 -0
  78. package/dist/ssr.d.ts +3 -0
  79. package/dist/ssr.d.ts.map +1 -0
  80. package/dist/ssr.js +280 -0
  81. package/dist/ssr.js.map +1 -0
  82. package/dist/symbols.d.ts +5 -0
  83. package/dist/symbols.d.ts.map +1 -0
  84. package/dist/symbols.js +37 -0
  85. package/dist/symbols.js.map +1 -0
  86. package/dist/text-layout.d.ts +10 -0
  87. package/dist/text-layout.d.ts.map +1 -0
  88. package/dist/text-layout.js +280 -0
  89. package/dist/text-layout.js.map +1 -0
  90. package/dist/transition.d.ts +12 -0
  91. package/dist/transition.d.ts.map +1 -0
  92. package/dist/transition.js +172 -0
  93. package/dist/transition.js.map +1 -0
  94. package/dist/ui-ir.d.ts +12 -0
  95. package/dist/ui-ir.d.ts.map +1 -0
  96. package/dist/ui-ir.js +324 -0
  97. package/dist/ui-ir.js.map +1 -0
  98. package/dist/url-policy.d.ts +2 -0
  99. package/dist/url-policy.d.ts.map +1 -0
  100. package/dist/url-policy.js +27 -0
  101. package/dist/url-policy.js.map +1 -0
  102. package/dist/visual-effects.d.ts +5 -0
  103. package/dist/visual-effects.d.ts.map +1 -0
  104. package/dist/visual-effects.js +166 -0
  105. package/dist/visual-effects.js.map +1 -0
  106. package/package.json +47 -3
  107. package/README.md +0 -3
@@ -0,0 +1,1093 @@
1
+ import { getRenderingQuality, prepareRenderingQuality } from "@mun-ui/animation/rendering-quality";
2
+ const WORKGROUP_SIZE = 64;
3
+ const FLOATS_PER_PARTICLE = 8;
4
+ const PARTICLE_STRIDE = FLOATS_PER_PARTICLE * Float32Array.BYTES_PER_ELEMENT;
5
+ const FLOATS_PER_CHART_POINT = 4;
6
+ const CHART_POINT_STRIDE = FLOATS_PER_CHART_POINT * Float32Array.BYTES_PER_ELEMENT;
7
+ const FRAME_PARAMETER_BYTES = 16;
8
+ const VALIDATED_ISLAND = Symbol("validated GPU Island");
9
+ const gpuGlobals = globalThis;
10
+ const BUFFER_USAGE = gpuGlobals.GPUBufferUsage ?? {
11
+ COPY_DST: 8,
12
+ STORAGE: 128,
13
+ UNIFORM: 64,
14
+ VERTEX: 32,
15
+ };
16
+ const SHADER_STAGE = gpuGlobals.GPUShaderStage ?? { COMPUTE: 4, FRAGMENT: 2, VERTEX: 1 };
17
+ const COMPUTE_SHADER = /* wgsl */ `
18
+ struct Particle {
19
+ position: vec2<f32>,
20
+ velocity: vec2<f32>,
21
+ color: vec4<f32>,
22
+ };
23
+
24
+ struct FrameParameters {
25
+ dt: f32,
26
+ count: u32,
27
+ elapsed: f32,
28
+ _padding: f32,
29
+ };
30
+
31
+ @group(0) @binding(0) var<storage, read_write> particles: array<Particle>;
32
+ @group(0) @binding(1) var<uniform> frame: FrameParameters;
33
+
34
+ @compute @workgroup_size(64)
35
+ fn computeParticles(@builtin(global_invocation_id) id: vec3<u32>) {
36
+ if (id.x >= frame.count) { return; }
37
+ var particle = particles[id.x];
38
+ var next = particle.position + particle.velocity * frame.dt;
39
+ if (abs(next.x) > 1.0) {
40
+ particle.velocity.x = -particle.velocity.x;
41
+ next.x = clamp(next.x, -1.0, 1.0);
42
+ }
43
+ if (abs(next.y) > 1.0) {
44
+ particle.velocity.y = -particle.velocity.y;
45
+ next.y = clamp(next.y, -1.0, 1.0);
46
+ }
47
+ particle.position = next;
48
+ particles[id.x] = particle;
49
+ }
50
+ `;
51
+ const RENDER_SHADER = /* wgsl */ `
52
+ struct VertexOutput {
53
+ @builtin(position) position: vec4<f32>,
54
+ @location(0) color: vec4<f32>,
55
+ };
56
+
57
+ @vertex
58
+ fn renderParticle(
59
+ @location(0) position: vec2<f32>,
60
+ @location(1) color: vec4<f32>,
61
+ ) -> VertexOutput {
62
+ var output: VertexOutput;
63
+ output.position = vec4<f32>(position, 0.0, 1.0);
64
+ output.color = color;
65
+ return output;
66
+ }
67
+
68
+ @fragment
69
+ fn shadeParticle(input: VertexOutput) -> @location(0) vec4<f32> {
70
+ return input.color;
71
+ }
72
+ `;
73
+ const CHART_COMPUTE_SHADER = /* wgsl */ `
74
+ struct ChartPoint {
75
+ source: vec2<f32>,
76
+ position: vec2<f32>,
77
+ };
78
+
79
+ struct FrameParameters {
80
+ count: u32,
81
+ elapsed: f32,
82
+ amplitude: f32,
83
+ _padding: f32,
84
+ };
85
+
86
+ @group(0) @binding(0) var<storage, read_write> points: array<ChartPoint>;
87
+ @group(0) @binding(1) var<uniform> frame: FrameParameters;
88
+
89
+ @compute @workgroup_size(64)
90
+ fn computeChartPoints(@builtin(global_invocation_id) id: vec3<u32>) {
91
+ if (id.x >= frame.count) { return; }
92
+ var point = points[id.x];
93
+ let wave = sin(frame.elapsed + point.source.x * 6.28318530718) * frame.amplitude;
94
+ point.position = vec2<f32>(point.source.x, clamp(point.source.y + wave, -1.0, 1.0));
95
+ points[id.x] = point;
96
+ }
97
+ `;
98
+ const CHART_RENDER_SHADER = /* wgsl */ `
99
+ struct VertexOutput {
100
+ @builtin(position) position: vec4<f32>,
101
+ };
102
+
103
+ @vertex
104
+ fn renderChartPoint(@location(0) position: vec2<f32>) -> VertexOutput {
105
+ var output: VertexOutput;
106
+ output.position = vec4<f32>(position, 0.0, 1.0);
107
+ return output;
108
+ }
109
+
110
+ @fragment
111
+ fn shadeChartLine() -> @location(0) vec4<f32> {
112
+ return vec4<f32>(1.0, 1.0, 1.0, 1.0);
113
+ }
114
+ `;
115
+ function record(value, label) {
116
+ if ((typeof value !== "object" && typeof value !== "function") || value === null) {
117
+ throw new TypeError(`${label} must be an object.`);
118
+ }
119
+ return value;
120
+ }
121
+ function requiredMethod(target, name, owner) {
122
+ const candidate = target[name];
123
+ if (typeof candidate !== "function")
124
+ throw new TypeError(`${owner} requires ${name}().`);
125
+ return candidate.bind(target);
126
+ }
127
+ function optionalMethod(target, name) {
128
+ const candidate = target[name];
129
+ return typeof candidate === "function" ? candidate.bind(target) : undefined;
130
+ }
131
+ function finiteLimit(limits, name) {
132
+ const value = Number(limits[name]);
133
+ if (!Number.isFinite(value) || value <= 0)
134
+ throw new TypeError(`GPUDevice.limits.${name} must be available.`);
135
+ return value;
136
+ }
137
+ function normalizedCount(value) {
138
+ if (!Number.isSafeInteger(value) || value < 1)
139
+ throw new RangeError("A GPU Island item count must be a positive safe integer.");
140
+ return value;
141
+ }
142
+ function normalizedFormat(value) {
143
+ if (typeof value !== "string" || !/^[a-z0-9-]+$/u.test(value)) {
144
+ throw new TypeError("A GPU Island requires an explicit GPU canvas format.");
145
+ }
146
+ return value;
147
+ }
148
+ function normalizedClearColor(value) {
149
+ const color = value ?? [0, 0, 0, 0];
150
+ if (color.length !== 4 || color.some(channel => !Number.isFinite(channel))) {
151
+ throw new TypeError("GPU Island clearColor must contain four finite channels.");
152
+ }
153
+ return Object.freeze({ r: color[0], g: color[1], b: color[2], a: color[3] });
154
+ }
155
+ function errorFrom(cause, prefix) {
156
+ if (cause instanceof Error)
157
+ return new Error(`${prefix}: ${cause.message}`, { cause });
158
+ return new Error(`${prefix}: ${String(cause)}`, { cause });
159
+ }
160
+ function deviceLostError(info) {
161
+ if (info && typeof info === "object") {
162
+ const message = info.message;
163
+ const reason = info.reason;
164
+ const detail = typeof message === "string" && message.length > 0 ? message : String(reason ?? "unknown reason");
165
+ return new Error(`GPU Island device lost: ${detail}`);
166
+ }
167
+ return new Error("GPU Island device lost.");
168
+ }
169
+ async function validateShaderModule(module, label) {
170
+ const getCompilationInfo = requiredMethod(module, "getCompilationInfo", `${label} shader module`);
171
+ const info = record(await getCompilationInfo(), `${label} shader compilation info`);
172
+ if (!Array.isArray(info.messages))
173
+ throw new TypeError(`${label} shader compilation info requires messages.`);
174
+ const errors = info.messages.filter(message => {
175
+ return message && typeof message === "object" && message.type === "error";
176
+ });
177
+ if (errors.length === 0)
178
+ return;
179
+ const details = errors.map(message => {
180
+ const text = message.message;
181
+ return typeof text === "string" ? text : "unknown shader error";
182
+ }).join("; ");
183
+ throw new Error(`${label} shader validation failed: ${details}`);
184
+ }
185
+ function validateInitialData(data, count) {
186
+ if (data === undefined)
187
+ return;
188
+ if (!(data instanceof Float32Array) || data.length !== count * FLOATS_PER_PARTICLE) {
189
+ throw new RangeError(`GPU Island initialData must contain exactly ${count * FLOATS_PER_PARTICLE} float values.`);
190
+ }
191
+ for (const value of data) {
192
+ if (!Number.isFinite(value))
193
+ throw new TypeError("GPU Island initialData must contain only finite values.");
194
+ }
195
+ }
196
+ function validateLineChartInitialData(data, count) {
197
+ if (data === undefined)
198
+ return;
199
+ if (!(data instanceof Float32Array) || data.length !== count * FLOATS_PER_CHART_POINT) {
200
+ throw new RangeError(`GPU LineChart initialData must contain exactly ${count * FLOATS_PER_CHART_POINT} float values.`);
201
+ }
202
+ for (const value of data) {
203
+ if (!Number.isFinite(value))
204
+ throw new TypeError("GPU LineChart initialData must contain only finite values.");
205
+ }
206
+ }
207
+ function validateCapacity(device, count) {
208
+ const byteLength = count * PARTICLE_STRIDE;
209
+ if (!Number.isSafeInteger(byteLength))
210
+ throw new RangeError("GPU Island particle storage exceeds the safe buffer size.");
211
+ const limits = record(device.limits, "GPUDevice.limits");
212
+ if (byteLength > finiteLimit(limits, "maxBufferSize"))
213
+ throw new RangeError("GPU Island particle storage exceeds maxBufferSize.");
214
+ if (byteLength > finiteLimit(limits, "maxStorageBufferBindingSize")) {
215
+ throw new RangeError("GPU Island particle storage exceeds maxStorageBufferBindingSize.");
216
+ }
217
+ const groups = Math.ceil(count / WORKGROUP_SIZE);
218
+ if (groups > finiteLimit(limits, "maxComputeWorkgroupsPerDimension")) {
219
+ throw new RangeError("GPU Island dispatch exceeds maxComputeWorkgroupsPerDimension.");
220
+ }
221
+ return byteLength;
222
+ }
223
+ function validateLineChartCapacity(device, count) {
224
+ const byteLength = count * CHART_POINT_STRIDE;
225
+ if (!Number.isSafeInteger(byteLength))
226
+ throw new RangeError("GPU LineChart storage exceeds the safe buffer size.");
227
+ const limits = record(device.limits, "GPUDevice.limits");
228
+ if (byteLength > finiteLimit(limits, "maxBufferSize"))
229
+ throw new RangeError("GPU LineChart storage exceeds maxBufferSize.");
230
+ if (byteLength > finiteLimit(limits, "maxStorageBufferBindingSize"))
231
+ throw new RangeError("GPU LineChart storage exceeds maxStorageBufferBindingSize.");
232
+ if (Math.ceil(count / WORKGROUP_SIZE) > finiteLimit(limits, "maxComputeWorkgroupsPerDimension")) {
233
+ throw new RangeError("GPU LineChart dispatch exceeds maxComputeWorkgroupsPerDimension.");
234
+ }
235
+ return byteLength;
236
+ }
237
+ function validateDeviceAndContext(deviceValue, contextValue) {
238
+ const device = record(deviceValue, "GPU Island device");
239
+ for (const method of [
240
+ "createBindGroup", "createBindGroupLayout", "createBuffer", "createCommandEncoder",
241
+ "createComputePipeline", "createPipelineLayout", "createRenderPipeline", "createShaderModule",
242
+ ])
243
+ requiredMethod(device, method, "GPU Island device");
244
+ const queue = record(device.queue, "GPUDevice.queue");
245
+ requiredMethod(queue, "submit", "GPUDevice.queue");
246
+ requiredMethod(queue, "writeBuffer", "GPUDevice.queue");
247
+ const lost = device.lost;
248
+ if (!lost || (typeof lost !== "object" && typeof lost !== "function") || typeof lost.then !== "function") {
249
+ throw new TypeError("GPU Island device requires a device-loss promise.");
250
+ }
251
+ const context = record(contextValue, "GPUCanvasContext");
252
+ requiredMethod(context, "configure", "GPUCanvasContext");
253
+ requiredMethod(context, "getCurrentTexture", "GPUCanvasContext");
254
+ return { context, device, queue, lost: lost };
255
+ }
256
+ const particlePipelineCache = new WeakMap();
257
+ const lineChartPipelineCache = new WeakMap();
258
+ async function sharedParticlePipelines(device, format) {
259
+ const key = device;
260
+ let byFormat = particlePipelineCache.get(key);
261
+ if (!byFormat) {
262
+ byFormat = new Map();
263
+ particlePipelineCache.set(key, byFormat);
264
+ }
265
+ let pending = byFormat.get(format);
266
+ if (pending)
267
+ return pending;
268
+ pending = (async () => {
269
+ const createShaderModule = requiredMethod(device, "createShaderModule", "GPU Island device");
270
+ const computeModule = record(createShaderModule({ label: "Mun particle compute shader", code: COMPUTE_SHADER }), "GPU compute shader module");
271
+ const renderModule = record(createShaderModule({ label: "Mun particle render shader", code: RENDER_SHADER }), "GPU render shader module");
272
+ await Promise.all([
273
+ validateShaderModule(computeModule, "GPU Island compute"),
274
+ validateShaderModule(renderModule, "GPU Island render"),
275
+ ]);
276
+ const computeBindGroupLayout = requiredMethod(device, "createBindGroupLayout", "GPU Island device")({
277
+ label: "Mun particle compute bindings",
278
+ entries: [
279
+ { binding: 0, visibility: SHADER_STAGE.COMPUTE, buffer: { type: "storage", minBindingSize: PARTICLE_STRIDE } },
280
+ { binding: 1, visibility: SHADER_STAGE.COMPUTE, buffer: { type: "uniform", minBindingSize: FRAME_PARAMETER_BYTES } },
281
+ ],
282
+ });
283
+ const computeLayout = requiredMethod(device, "createPipelineLayout", "GPU Island device")({
284
+ label: "Mun particle compute layout",
285
+ bindGroupLayouts: [computeBindGroupLayout],
286
+ });
287
+ const renderLayout = requiredMethod(device, "createPipelineLayout", "GPU Island device")({
288
+ label: "Mun particle render layout",
289
+ bindGroupLayouts: [],
290
+ });
291
+ const computePipeline = requiredMethod(device, "createComputePipeline", "GPU Island device")({
292
+ label: "Mun particle compute pipeline",
293
+ layout: computeLayout,
294
+ compute: { module: computeModule, entryPoint: "computeParticles" },
295
+ });
296
+ const renderPipeline = requiredMethod(device, "createRenderPipeline", "GPU Island device")({
297
+ label: "Mun particle render pipeline",
298
+ layout: renderLayout,
299
+ vertex: {
300
+ module: renderModule,
301
+ entryPoint: "renderParticle",
302
+ buffers: [{
303
+ arrayStride: PARTICLE_STRIDE,
304
+ stepMode: "vertex",
305
+ attributes: [
306
+ { shaderLocation: 0, offset: 0, format: "float32x2" },
307
+ { shaderLocation: 1, offset: 16, format: "float32x4" },
308
+ ],
309
+ }],
310
+ },
311
+ fragment: {
312
+ module: renderModule,
313
+ entryPoint: "shadeParticle",
314
+ targets: [{ format }],
315
+ },
316
+ primitive: { topology: "point-list" },
317
+ });
318
+ return Object.freeze({ computeBindGroupLayout, computePipeline, renderPipeline });
319
+ })();
320
+ byFormat.set(format, pending);
321
+ try {
322
+ return await pending;
323
+ }
324
+ catch (error) {
325
+ if (byFormat.get(format) === pending)
326
+ byFormat.delete(format);
327
+ throw error;
328
+ }
329
+ }
330
+ async function sharedLineChartPipelines(device, format) {
331
+ const key = device;
332
+ let byFormat = lineChartPipelineCache.get(key);
333
+ if (!byFormat) {
334
+ byFormat = new Map();
335
+ lineChartPipelineCache.set(key, byFormat);
336
+ }
337
+ let pending = byFormat.get(format);
338
+ if (pending)
339
+ return pending;
340
+ pending = (async () => {
341
+ const createShaderModule = requiredMethod(device, "createShaderModule", "GPU Island device");
342
+ const computeModule = record(createShaderModule({ label: "Mun chart compute shader", code: CHART_COMPUTE_SHADER }), "GPU chart compute shader module");
343
+ const renderModule = record(createShaderModule({ label: "Mun chart render shader", code: CHART_RENDER_SHADER }), "GPU chart render shader module");
344
+ await Promise.all([
345
+ validateShaderModule(computeModule, "GPU LineChart compute"),
346
+ validateShaderModule(renderModule, "GPU LineChart render"),
347
+ ]);
348
+ const computeBindGroupLayout = requiredMethod(device, "createBindGroupLayout", "GPU Island device")({
349
+ label: "Mun chart compute bindings",
350
+ entries: [
351
+ { binding: 0, visibility: SHADER_STAGE.COMPUTE, buffer: { type: "storage", minBindingSize: CHART_POINT_STRIDE } },
352
+ { binding: 1, visibility: SHADER_STAGE.COMPUTE, buffer: { type: "uniform", minBindingSize: FRAME_PARAMETER_BYTES } },
353
+ ],
354
+ });
355
+ const computeLayout = requiredMethod(device, "createPipelineLayout", "GPU Island device")({
356
+ label: "Mun chart compute layout",
357
+ bindGroupLayouts: [computeBindGroupLayout],
358
+ });
359
+ const renderLayout = requiredMethod(device, "createPipelineLayout", "GPU Island device")({
360
+ label: "Mun chart render layout",
361
+ bindGroupLayouts: [],
362
+ });
363
+ const computePipeline = requiredMethod(device, "createComputePipeline", "GPU Island device")({
364
+ label: "Mun chart compute pipeline",
365
+ layout: computeLayout,
366
+ compute: { module: computeModule, entryPoint: "computeChartPoints" },
367
+ });
368
+ const renderPipeline = requiredMethod(device, "createRenderPipeline", "GPU Island device")({
369
+ label: "Mun chart render pipeline",
370
+ layout: renderLayout,
371
+ vertex: {
372
+ module: renderModule,
373
+ entryPoint: "renderChartPoint",
374
+ buffers: [{
375
+ arrayStride: CHART_POINT_STRIDE,
376
+ stepMode: "vertex",
377
+ attributes: [{ shaderLocation: 0, offset: 8, format: "float32x2" }],
378
+ }],
379
+ },
380
+ fragment: {
381
+ module: renderModule,
382
+ entryPoint: "shadeChartLine",
383
+ targets: [{ format }],
384
+ },
385
+ primitive: { topology: "line-strip" },
386
+ });
387
+ return Object.freeze({ computeBindGroupLayout, computePipeline, renderPipeline });
388
+ })();
389
+ byFormat.set(format, pending);
390
+ try {
391
+ return await pending;
392
+ }
393
+ catch (error) {
394
+ if (byFormat.get(format) === pending)
395
+ byFormat.delete(format);
396
+ throw error;
397
+ }
398
+ }
399
+ /**
400
+ * A renderer-owned compute island. Particle storage becomes GPU-authoritative
401
+ * at creation and the exact same buffer is consumed by the compute and render
402
+ * passes. Frames only upload a 16-byte uniform; they never expose particle rows
403
+ * to JavaScript or copy GPU results into host-visible memory.
404
+ */
405
+ export class ParticleFieldGPUIsland {
406
+ kind = "gpu-island";
407
+ count;
408
+ format;
409
+ byteLength;
410
+ workgroupSize = WORKGROUP_SIZE;
411
+ resources;
412
+ clearColor;
413
+ label;
414
+ onFailure;
415
+ frameParameters = new Float32Array(FRAME_PARAMETER_BYTES / Float32Array.BYTES_PER_ELEMENT);
416
+ frameParameterWords = new Uint32Array(this.frameParameters.buffer);
417
+ state = "active";
418
+ failureValue;
419
+ elapsedSeconds = 0;
420
+ resourcesDestroyed = false;
421
+ uncapturedErrorListener;
422
+ constructor(validation, resources, options, byteLength) {
423
+ if (validation !== VALIDATED_ISLAND)
424
+ throw new TypeError("GPU Islands must be created through createParticleFieldGPUIsland().");
425
+ this.resources = resources;
426
+ this.count = options.count;
427
+ this.format = options.format;
428
+ this.byteLength = byteLength;
429
+ this.label = options.label ?? "Mun ParticleField GPU Island";
430
+ this.clearColor = normalizedClearColor(options.clearColor);
431
+ this.onFailure = options.onFailure;
432
+ this.uncapturedErrorListener = event => {
433
+ const candidate = event && typeof event === "object" ? event.error : event;
434
+ this.fail(errorFrom(candidate, "GPU Island uncaptured device error"));
435
+ };
436
+ optionalMethod(resources.device, "addEventListener")?.("uncapturederror", this.uncapturedErrorListener);
437
+ void Promise.resolve(resources.lost).then(info => this.fail(deviceLostError(info)), cause => this.fail(errorFrom(cause, "GPU Island device-loss observation failed")));
438
+ }
439
+ get status() { return this.state; }
440
+ get failure() { return this.failureValue; }
441
+ /** Encode compute followed by render and submit both as one ordered command buffer. */
442
+ renderFrame(deltaSeconds) {
443
+ this.assertActive();
444
+ if (!Number.isFinite(deltaSeconds) || deltaSeconds < 0)
445
+ throw new RangeError("GPU Island frame delta must be finite and non-negative.");
446
+ const dt = Math.min(deltaSeconds, 0.1);
447
+ this.elapsedSeconds += dt;
448
+ this.frameParameters[0] = dt;
449
+ this.frameParameterWords[1] = this.count;
450
+ this.frameParameters[2] = this.elapsedSeconds;
451
+ try {
452
+ requiredMethod(this.resources.queue, "writeBuffer", "GPUDevice.queue")(this.resources.parameterBuffer, 0, this.frameParameters);
453
+ const encoder = record(requiredMethod(this.resources.device, "createCommandEncoder", "GPU Island device")({ label: `${this.label} frame` }), "GPUCommandEncoder");
454
+ const computePass = record(requiredMethod(encoder, "beginComputePass", "GPUCommandEncoder")({
455
+ label: `${this.label} compute`,
456
+ }), "GPUComputePassEncoder");
457
+ requiredMethod(computePass, "setPipeline", "GPUComputePassEncoder")(this.resources.computePipeline);
458
+ requiredMethod(computePass, "setBindGroup", "GPUComputePassEncoder")(0, this.resources.bindGroup);
459
+ requiredMethod(computePass, "dispatchWorkgroups", "GPUComputePassEncoder")(Math.ceil(this.count / WORKGROUP_SIZE));
460
+ requiredMethod(computePass, "end", "GPUComputePassEncoder")();
461
+ const texture = record(requiredMethod(this.resources.context, "getCurrentTexture", "GPUCanvasContext")(), "GPUCanvasTexture");
462
+ const view = requiredMethod(texture, "createView", "GPUCanvasTexture")();
463
+ const renderPass = record(requiredMethod(encoder, "beginRenderPass", "GPUCommandEncoder")({
464
+ label: `${this.label} render`,
465
+ colorAttachments: [{
466
+ view,
467
+ clearValue: this.clearColor,
468
+ loadOp: "clear",
469
+ storeOp: "store",
470
+ }],
471
+ }), "GPURenderPassEncoder");
472
+ requiredMethod(renderPass, "setPipeline", "GPURenderPassEncoder")(this.resources.renderPipeline);
473
+ requiredMethod(renderPass, "setVertexBuffer", "GPURenderPassEncoder")(0, this.resources.particleBuffer);
474
+ requiredMethod(renderPass, "draw", "GPURenderPassEncoder")(this.count, 1, 0, 0);
475
+ requiredMethod(renderPass, "end", "GPURenderPassEncoder")();
476
+ const commands = requiredMethod(encoder, "finish", "GPUCommandEncoder")();
477
+ requiredMethod(this.resources.queue, "submit", "GPUDevice.queue")([commands]);
478
+ }
479
+ catch (cause) {
480
+ const failure = errorFrom(cause, "GPU Island frame failed");
481
+ this.fail(failure);
482
+ throw failure;
483
+ }
484
+ }
485
+ dispose() {
486
+ if (this.state === "disposed")
487
+ return;
488
+ this.state = "disposed";
489
+ this.destroyResources();
490
+ }
491
+ assertActive() {
492
+ if (this.state === "active")
493
+ return;
494
+ if (this.state === "failed")
495
+ throw this.failureValue ?? new Error("GPU Island failed.");
496
+ throw new Error("GPU Island is disposed.");
497
+ }
498
+ fail(error) {
499
+ if (this.state !== "active")
500
+ return;
501
+ this.state = "failed";
502
+ this.failureValue = error;
503
+ this.destroyResources();
504
+ try {
505
+ this.onFailure?.(error);
506
+ }
507
+ catch { /* reporting must not replace the device failure */ }
508
+ }
509
+ destroyResources() {
510
+ if (this.resourcesDestroyed)
511
+ return;
512
+ this.resourcesDestroyed = true;
513
+ if (this.uncapturedErrorListener) {
514
+ optionalMethod(this.resources.device, "removeEventListener")?.("uncapturederror", this.uncapturedErrorListener);
515
+ }
516
+ optionalMethod(this.resources.particleBuffer, "destroy")?.();
517
+ optionalMethod(this.resources.parameterBuffer, "destroy")?.();
518
+ }
519
+ }
520
+ /** GPU-resident chart transform + line renderer used as the second real island workload. */
521
+ export class LineChartGPUIsland {
522
+ kind = "gpu-island";
523
+ count;
524
+ format;
525
+ byteLength;
526
+ workgroupSize = WORKGROUP_SIZE;
527
+ resources;
528
+ clearColor;
529
+ label;
530
+ onFailure;
531
+ frameParameters = new Float32Array(FRAME_PARAMETER_BYTES / Float32Array.BYTES_PER_ELEMENT);
532
+ frameParameterWords = new Uint32Array(this.frameParameters.buffer);
533
+ amplitude;
534
+ state = "active";
535
+ failureValue;
536
+ elapsedSeconds = 0;
537
+ resourcesDestroyed = false;
538
+ uncapturedErrorListener;
539
+ constructor(validation, resources, options, byteLength) {
540
+ if (validation !== VALIDATED_ISLAND)
541
+ throw new TypeError("GPU Islands must be created through createLineChartGPUIsland().");
542
+ this.resources = resources;
543
+ this.count = options.count;
544
+ this.format = options.format;
545
+ this.byteLength = byteLength;
546
+ this.label = options.label ?? "Mun LineChart GPU Island";
547
+ this.clearColor = normalizedClearColor(options.clearColor);
548
+ this.onFailure = options.onFailure;
549
+ const amplitude = options.amplitude ?? 0.03;
550
+ if (!Number.isFinite(amplitude) || amplitude < 0)
551
+ throw new RangeError("GPU LineChart amplitude must be finite and non-negative.");
552
+ this.amplitude = amplitude;
553
+ this.uncapturedErrorListener = event => {
554
+ const candidate = event && typeof event === "object" ? event.error : event;
555
+ this.fail(errorFrom(candidate, "GPU LineChart uncaptured device error"));
556
+ };
557
+ optionalMethod(resources.device, "addEventListener")?.("uncapturederror", this.uncapturedErrorListener);
558
+ void Promise.resolve(resources.lost).then(info => this.fail(deviceLostError(info)), cause => this.fail(errorFrom(cause, "GPU LineChart device-loss observation failed")));
559
+ }
560
+ get status() { return this.state; }
561
+ get failure() { return this.failureValue; }
562
+ renderFrame(deltaSeconds) {
563
+ this.assertActive();
564
+ if (!Number.isFinite(deltaSeconds) || deltaSeconds < 0)
565
+ throw new RangeError("GPU LineChart frame delta must be finite and non-negative.");
566
+ this.elapsedSeconds += Math.min(deltaSeconds, 0.1);
567
+ this.frameParameterWords[0] = this.count;
568
+ this.frameParameters[1] = this.elapsedSeconds;
569
+ this.frameParameters[2] = this.amplitude;
570
+ try {
571
+ requiredMethod(this.resources.queue, "writeBuffer", "GPUDevice.queue")(this.resources.parameterBuffer, 0, this.frameParameters);
572
+ const encoder = record(requiredMethod(this.resources.device, "createCommandEncoder", "GPU Island device")({ label: `${this.label} frame` }), "GPUCommandEncoder");
573
+ const computePass = record(requiredMethod(encoder, "beginComputePass", "GPUCommandEncoder")({ label: `${this.label} compute` }), "GPUComputePassEncoder");
574
+ requiredMethod(computePass, "setPipeline", "GPUComputePassEncoder")(this.resources.computePipeline);
575
+ requiredMethod(computePass, "setBindGroup", "GPUComputePassEncoder")(0, this.resources.bindGroup);
576
+ requiredMethod(computePass, "dispatchWorkgroups", "GPUComputePassEncoder")(Math.ceil(this.count / WORKGROUP_SIZE));
577
+ requiredMethod(computePass, "end", "GPUComputePassEncoder")();
578
+ const texture = record(requiredMethod(this.resources.context, "getCurrentTexture", "GPUCanvasContext")(), "GPUCanvasTexture");
579
+ const view = requiredMethod(texture, "createView", "GPUCanvasTexture")();
580
+ const renderPass = record(requiredMethod(encoder, "beginRenderPass", "GPUCommandEncoder")({
581
+ label: `${this.label} render`,
582
+ colorAttachments: [{ view, clearValue: this.clearColor, loadOp: "clear", storeOp: "store" }],
583
+ }), "GPURenderPassEncoder");
584
+ requiredMethod(renderPass, "setPipeline", "GPURenderPassEncoder")(this.resources.renderPipeline);
585
+ requiredMethod(renderPass, "setVertexBuffer", "GPURenderPassEncoder")(0, this.resources.pointBuffer);
586
+ requiredMethod(renderPass, "draw", "GPURenderPassEncoder")(this.count, 1, 0, 0);
587
+ requiredMethod(renderPass, "end", "GPURenderPassEncoder")();
588
+ const commands = requiredMethod(encoder, "finish", "GPUCommandEncoder")();
589
+ requiredMethod(this.resources.queue, "submit", "GPUDevice.queue")([commands]);
590
+ }
591
+ catch (cause) {
592
+ const failure = errorFrom(cause, "GPU LineChart frame failed");
593
+ this.fail(failure);
594
+ throw failure;
595
+ }
596
+ }
597
+ dispose() {
598
+ if (this.state === "disposed")
599
+ return;
600
+ this.state = "disposed";
601
+ this.destroyResources();
602
+ }
603
+ assertActive() {
604
+ if (this.state === "active")
605
+ return;
606
+ if (this.state === "failed")
607
+ throw this.failureValue ?? new Error("GPU LineChart failed.");
608
+ throw new Error("GPU LineChart is disposed.");
609
+ }
610
+ fail(error) {
611
+ if (this.state !== "active")
612
+ return;
613
+ this.state = "failed";
614
+ this.failureValue = error;
615
+ this.destroyResources();
616
+ try {
617
+ this.onFailure?.(error);
618
+ }
619
+ catch { /* reporting must not replace the device failure */ }
620
+ }
621
+ destroyResources() {
622
+ if (this.resourcesDestroyed)
623
+ return;
624
+ this.resourcesDestroyed = true;
625
+ if (this.uncapturedErrorListener)
626
+ optionalMethod(this.resources.device, "removeEventListener")?.("uncapturederror", this.uncapturedErrorListener);
627
+ optionalMethod(this.resources.pointBuffer, "destroy")?.();
628
+ optionalMethod(this.resources.parameterBuffer, "destroy")?.();
629
+ }
630
+ }
631
+ export async function createLineChartGPUIsland(deviceValue, contextValue, optionsValue) {
632
+ const count = normalizedCount(optionsValue?.count);
633
+ if (count < 2)
634
+ throw new RangeError("GPU LineChart requires at least two points.");
635
+ const format = normalizedFormat(optionsValue?.format);
636
+ const options = { ...optionsValue, count, format };
637
+ validateLineChartInitialData(options.initialData, count);
638
+ const { context, device, queue, lost } = validateDeviceAndContext(deviceValue, contextValue);
639
+ const byteLength = validateLineChartCapacity(device, count);
640
+ const label = options.label ?? "Mun LineChart GPU Island";
641
+ const createBuffer = requiredMethod(device, "createBuffer", "GPU Island device");
642
+ const pointBuffer = record(createBuffer({
643
+ label: `${label} resident points`,
644
+ size: byteLength,
645
+ usage: BUFFER_USAGE.STORAGE | BUFFER_USAGE.VERTEX | BUFFER_USAGE.COPY_DST,
646
+ }), "GPU chart point buffer");
647
+ const parameterBuffer = record(createBuffer({
648
+ label: `${label} frame parameters`,
649
+ size: FRAME_PARAMETER_BYTES,
650
+ usage: BUFFER_USAGE.UNIFORM | BUFFER_USAGE.COPY_DST,
651
+ }), "GPU chart frame parameter buffer");
652
+ try {
653
+ const { computeBindGroupLayout, computePipeline, renderPipeline } = await sharedLineChartPipelines(device, format);
654
+ const bindGroup = requiredMethod(device, "createBindGroup", "GPU Island device")({
655
+ label: `${label} compute bind group`,
656
+ layout: computeBindGroupLayout,
657
+ entries: [
658
+ { binding: 0, resource: { buffer: pointBuffer, size: byteLength } },
659
+ { binding: 1, resource: { buffer: parameterBuffer, size: FRAME_PARAMETER_BYTES } },
660
+ ],
661
+ });
662
+ requiredMethod(context, "configure", "GPUCanvasContext")({ device, format, alphaMode: options.alphaMode ?? "premultiplied" });
663
+ if (options.initialData) {
664
+ requiredMethod(queue, "writeBuffer", "GPUDevice.queue")(pointBuffer, 0, options.initialData, options.initialData.byteOffset, options.initialData.byteLength);
665
+ }
666
+ return new LineChartGPUIsland(VALIDATED_ISLAND, {
667
+ bindGroup, computePipeline, context, device, lost, pointBuffer, parameterBuffer, queue, renderPipeline,
668
+ }, options, byteLength);
669
+ }
670
+ catch (cause) {
671
+ optionalMethod(pointBuffer, "destroy")?.();
672
+ optionalMethod(parameterBuffer, "destroy")?.();
673
+ throw errorFrom(cause, "GPU LineChart creation failed");
674
+ }
675
+ }
676
+ /**
677
+ * Validate and create a fixed-layout ParticleField GPU Island. Custom shaders
678
+ * are intentionally not accepted: the storage stride, shader structs, bind
679
+ * group layout, and vertex attributes are one compiler-proven contract.
680
+ */
681
+ export async function createParticleFieldGPUIsland(deviceValue, contextValue, optionsValue) {
682
+ const count = normalizedCount(optionsValue?.count);
683
+ const format = normalizedFormat(optionsValue?.format);
684
+ const options = { ...optionsValue, count, format };
685
+ validateInitialData(options.initialData, count);
686
+ const { context, device, queue, lost } = validateDeviceAndContext(deviceValue, contextValue);
687
+ const byteLength = validateCapacity(device, count);
688
+ const label = options.label ?? "Mun ParticleField GPU Island";
689
+ const createBuffer = requiredMethod(device, "createBuffer", "GPU Island device");
690
+ const particleBuffer = record(createBuffer({
691
+ label: `${label} resident particles`,
692
+ size: byteLength,
693
+ usage: BUFFER_USAGE.STORAGE | BUFFER_USAGE.VERTEX | BUFFER_USAGE.COPY_DST,
694
+ }), "GPU particle buffer");
695
+ const parameterBuffer = record(createBuffer({
696
+ label: `${label} frame parameters`,
697
+ size: FRAME_PARAMETER_BYTES,
698
+ usage: BUFFER_USAGE.UNIFORM | BUFFER_USAGE.COPY_DST,
699
+ }), "GPU frame parameter buffer");
700
+ try {
701
+ const { computeBindGroupLayout, computePipeline, renderPipeline } = await sharedParticlePipelines(device, format);
702
+ const bindGroup = requiredMethod(device, "createBindGroup", "GPU Island device")({
703
+ label: `${label} compute bind group`,
704
+ layout: computeBindGroupLayout,
705
+ entries: [
706
+ { binding: 0, resource: { buffer: particleBuffer, size: byteLength } },
707
+ { binding: 1, resource: { buffer: parameterBuffer, size: FRAME_PARAMETER_BYTES } },
708
+ ],
709
+ });
710
+ requiredMethod(context, "configure", "GPUCanvasContext")({
711
+ device,
712
+ format,
713
+ alphaMode: options.alphaMode ?? "premultiplied",
714
+ });
715
+ if (options.initialData) {
716
+ requiredMethod(queue, "writeBuffer", "GPUDevice.queue")(particleBuffer, 0, options.initialData, options.initialData.byteOffset, options.initialData.byteLength);
717
+ }
718
+ return new ParticleFieldGPUIsland(VALIDATED_ISLAND, {
719
+ bindGroup,
720
+ computePipeline,
721
+ context,
722
+ device,
723
+ lost,
724
+ particleBuffer,
725
+ parameterBuffer,
726
+ queue,
727
+ renderPipeline,
728
+ }, options, byteLength);
729
+ }
730
+ catch (cause) {
731
+ optionalMethod(particleBuffer, "destroy")?.();
732
+ optionalMethod(parameterBuffer, "destroy")?.();
733
+ throw errorFrom(cause, "GPU Island creation failed");
734
+ }
735
+ }
736
+ const mountedParticleFields = new WeakMap();
737
+ const sharedGpuDevices = new WeakMap();
738
+ /**
739
+ * A Web page should normally own one logical WebGPU device, not one device per
740
+ * GPU View. Cache the asynchronous adapter/device handshake by `navigator.gpu`
741
+ * identity and evict it on device loss so later islands can recover through a
742
+ * fresh adapter/device pair.
743
+ */
744
+ async function sharedGpuDevice(gpu) {
745
+ const key = gpu;
746
+ let pending = sharedGpuDevices.get(key);
747
+ if (pending)
748
+ return pending;
749
+ pending = (async () => {
750
+ const adapter = record(await requiredMethod(gpu, "requestAdapter", "GPU")(), "GPUAdapter");
751
+ const device = await requiredMethod(adapter, "requestDevice", "GPUAdapter")();
752
+ const preferredFormat = optionalMethod(gpu, "getPreferredCanvasFormat")?.();
753
+ const format = typeof preferredFormat === "string" ? preferredFormat : "bgra8unorm";
754
+ const deviceRecord = record(device, "GPUDevice");
755
+ const lost = deviceRecord.lost;
756
+ if (lost && (typeof lost === "object" || typeof lost === "function") && typeof lost.then === "function") {
757
+ void Promise.resolve(lost).then(() => { if (sharedGpuDevices.get(key) === pending)
758
+ sharedGpuDevices.delete(key); }, () => { if (sharedGpuDevices.get(key) === pending)
759
+ sharedGpuDevices.delete(key); });
760
+ }
761
+ return Object.freeze({ device, format });
762
+ })();
763
+ sharedGpuDevices.set(key, pending);
764
+ try {
765
+ return await pending;
766
+ }
767
+ catch (error) {
768
+ if (sharedGpuDevices.get(key) === pending)
769
+ sharedGpuDevices.delete(key);
770
+ throw error;
771
+ }
772
+ }
773
+ function seededParticleData(count, provided) {
774
+ if (provided)
775
+ return new Float32Array(provided);
776
+ const data = new Float32Array(count * FLOATS_PER_PARTICLE);
777
+ for (let index = 0; index < count; index += 1) {
778
+ const offset = index * FLOATS_PER_PARTICLE;
779
+ const phase = (index * 0.61803398875) % 1;
780
+ data[offset] = phase * 2 - 1;
781
+ data[offset + 1] = ((index * 0.41421356237) % 1) * 2 - 1;
782
+ data[offset + 2] = (((index * 17) % 31) - 15) / 150;
783
+ data[offset + 3] = (((index * 23) % 29) - 14) / 150;
784
+ data[offset + 4] = 0.35 + phase * 0.65;
785
+ data[offset + 5] = 0.45 + (1 - phase) * 0.55;
786
+ data[offset + 6] = 0.9;
787
+ data[offset + 7] = 1;
788
+ }
789
+ return data;
790
+ }
791
+ function seededLineChartData(count, provided) {
792
+ if (provided)
793
+ return new Float32Array(provided);
794
+ const data = new Float32Array(count * FLOATS_PER_CHART_POINT);
795
+ const denominator = Math.max(1, count - 1);
796
+ for (let index = 0; index < count; index += 1) {
797
+ const offset = index * FLOATS_PER_CHART_POINT;
798
+ const x = index / denominator * 2 - 1;
799
+ const y = Math.sin(index * 0.075) * 0.55 + Math.sin(index * 0.013) * 0.2;
800
+ data[offset] = x;
801
+ data[offset + 1] = y;
802
+ data[offset + 2] = x;
803
+ data[offset + 3] = y;
804
+ }
805
+ return data;
806
+ }
807
+ /**
808
+ * Drives a CPU canvas animation only while it can be seen. An offscreen,
809
+ * hidden or detached canvas stops requesting frames instead of burning a
810
+ * main-thread draw every 16ms; it resumes when it becomes visible again.
811
+ */
812
+ function runVisibleFrameLoop(canvas, owner, step) {
813
+ const document = canvas.ownerDocument;
814
+ const controller = getRenderingQuality(owner);
815
+ let stopped = false;
816
+ let frame = 0;
817
+ let intersecting = true;
818
+ let quality = "full";
819
+ let previousFrame;
820
+ let previousDraw;
821
+ const visible = () => intersecting && document.visibilityState !== "hidden" && quality !== "none";
822
+ const tick = (time) => {
823
+ frame = 0;
824
+ if (stopped || !visible())
825
+ return;
826
+ if (previousFrame !== undefined)
827
+ controller?.recordFrame(time - previousFrame);
828
+ previousFrame = time;
829
+ if (!visible())
830
+ return;
831
+ if (quality === "full" || previousDraw === undefined || time - previousDraw >= 1000 / 30 - 0.5) {
832
+ const delta = previousDraw === undefined ? 1 / 60 : Math.min(0.1, Math.max(0, (time - previousDraw) / 1000));
833
+ previousDraw = time;
834
+ step(delta);
835
+ }
836
+ if (!stopped && visible())
837
+ frame = owner.requestAnimationFrame(tick);
838
+ };
839
+ const resume = () => {
840
+ if (!visible()) {
841
+ if (frame)
842
+ owner.cancelAnimationFrame(frame);
843
+ frame = 0;
844
+ previousFrame = previousDraw = undefined;
845
+ }
846
+ else if (!stopped && frame === 0) {
847
+ previousFrame = previousDraw = undefined;
848
+ frame = owner.requestAnimationFrame(tick);
849
+ }
850
+ };
851
+ const stopQuality = controller?.subscribe(snapshot => {
852
+ if (canvas.dataset.munRenderingQuality !== snapshot.quality)
853
+ canvas.dataset.munRenderingQuality = snapshot.quality;
854
+ if (quality === snapshot.quality)
855
+ return;
856
+ quality = snapshot.quality;
857
+ resume();
858
+ });
859
+ const IntersectionObserverConstructor = owner.IntersectionObserver;
860
+ let observer;
861
+ if (typeof IntersectionObserverConstructor === "function") {
862
+ observer = new IntersectionObserverConstructor(entries => {
863
+ const entry = entries[entries.length - 1];
864
+ if (!entry)
865
+ return;
866
+ intersecting = entry.isIntersecting;
867
+ resume();
868
+ });
869
+ observer.observe(canvas);
870
+ }
871
+ document.addEventListener("visibilitychange", resume);
872
+ resume();
873
+ return () => {
874
+ stopped = true;
875
+ stopQuality?.();
876
+ observer?.disconnect();
877
+ document.removeEventListener("visibilitychange", resume);
878
+ if (frame)
879
+ owner.cancelAnimationFrame(frame);
880
+ frame = 0;
881
+ };
882
+ }
883
+ function runLineChartCanvasFallback(canvas, node, data) {
884
+ canvas.dataset.munGpuBackend = node.ir.fallback === "canvas" ? "cpu-canvas" : "static";
885
+ let context = null;
886
+ try {
887
+ context = canvas.getContext("2d");
888
+ }
889
+ catch { /* synthetic DOM or an existing WebGPU context may reject 2D */ }
890
+ if (!context)
891
+ return () => undefined;
892
+ const owner = canvas.ownerDocument.defaultView;
893
+ let elapsed = 0;
894
+ const draw = (deltaSeconds) => {
895
+ elapsed += deltaSeconds;
896
+ context.clearRect(0, 0, canvas.width, canvas.height);
897
+ context.beginPath();
898
+ for (let index = 0; index < node.ir.render.vertexCount; index += 1) {
899
+ const offset = index * FLOATS_PER_CHART_POINT;
900
+ const x = data[offset];
901
+ const y = Math.max(-1, Math.min(1, data[offset + 1] + Math.sin(elapsed + x * Math.PI * 2) * 0.03));
902
+ data[offset + 2] = x;
903
+ data[offset + 3] = y;
904
+ const px = (x + 1) * canvas.width / 2;
905
+ const py = (1 - y) * canvas.height / 2;
906
+ if (index === 0)
907
+ context.moveTo(px, py);
908
+ else
909
+ context.lineTo(px, py);
910
+ }
911
+ context.stroke();
912
+ };
913
+ draw(0);
914
+ if (node.ir.fallback !== "canvas" || typeof owner?.requestAnimationFrame !== "function")
915
+ return () => undefined;
916
+ return runVisibleFrameLoop(canvas, owner, draw);
917
+ }
918
+ function runCanvasFallback(canvas, node, data) {
919
+ if (node.ir.kind === "line-chart")
920
+ return runLineChartCanvasFallback(canvas, node, data);
921
+ canvas.dataset.munGpuBackend = node.ir.fallback === "canvas" ? "cpu-canvas" : "static";
922
+ let context = null;
923
+ try {
924
+ context = canvas.getContext("2d");
925
+ }
926
+ catch { /* synthetic DOM or a prior WebGPU context may reject 2D */ }
927
+ if (!context)
928
+ return () => undefined;
929
+ const owner = canvas.ownerDocument.defaultView;
930
+ // Particle colours never change after seeding; build each fillStyle once
931
+ // and draw every particle of one colour as a single path.
932
+ const colorBuckets = new Map();
933
+ for (let index = 0; index < node.ir.render.vertexCount; index += 1) {
934
+ const offset = index * FLOATS_PER_PARTICLE;
935
+ const color = `rgba(${Math.round(data[offset + 4] * 255)}, ${Math.round(data[offset + 5] * 255)}, ${Math.round(data[offset + 6] * 255)}, ${data[offset + 7]})`;
936
+ let bucket = colorBuckets.get(color);
937
+ if (!bucket)
938
+ colorBuckets.set(color, bucket = []);
939
+ bucket.push(offset);
940
+ }
941
+ const draw = (deltaSeconds) => {
942
+ if (deltaSeconds > 0) {
943
+ for (let index = 0; index < node.ir.render.vertexCount; index += 1) {
944
+ const offset = index * FLOATS_PER_PARTICLE;
945
+ let x = data[offset] + data[offset + 2] * deltaSeconds * 60;
946
+ let y = data[offset + 1] + data[offset + 3] * deltaSeconds * 60;
947
+ if (Math.abs(x) > 1) {
948
+ data[offset + 2] = -data[offset + 2];
949
+ x = Math.max(-1, Math.min(1, x));
950
+ }
951
+ if (Math.abs(y) > 1) {
952
+ data[offset + 3] = -data[offset + 3];
953
+ y = Math.max(-1, Math.min(1, y));
954
+ }
955
+ data[offset] = x;
956
+ data[offset + 1] = y;
957
+ }
958
+ }
959
+ context.clearRect(0, 0, canvas.width, canvas.height);
960
+ const radius = Math.max(1, Math.min(canvas.width, canvas.height) / 256);
961
+ const halfWidth = canvas.width / 2;
962
+ const halfHeight = canvas.height / 2;
963
+ for (const [color, offsets] of colorBuckets) {
964
+ context.fillStyle = color;
965
+ context.beginPath();
966
+ for (const offset of offsets) {
967
+ const x = (data[offset] + 1) * halfWidth;
968
+ const y = (1 - data[offset + 1]) * halfHeight;
969
+ context.moveTo(x + radius, y);
970
+ context.arc(x, y, radius, 0, Math.PI * 2);
971
+ }
972
+ context.fill();
973
+ }
974
+ };
975
+ draw(0);
976
+ if (node.ir.fallback !== "canvas" || typeof owner?.requestAnimationFrame !== "function")
977
+ return () => undefined;
978
+ return runVisibleFrameLoop(canvas, owner, draw);
979
+ }
980
+ /**
981
+ * Activate a graph GPU Island on a renderer-owned canvas. The returned cleanup
982
+ * owns every requestAnimationFrame and GPU resource created for this canvas.
983
+ */
984
+ export function mountParticleFieldGPUIslandCanvas(canvas, node, options = {}) {
985
+ mountedParticleFields.get(canvas)?.();
986
+ const data = node.ir.kind === "line-chart"
987
+ ? seededLineChartData(node.ir.render.vertexCount, node.options.initialData)
988
+ : seededParticleData(node.ir.render.vertexCount, node.options.initialData);
989
+ const owner = canvas.ownerDocument.defaultView;
990
+ if (options.experimentalResidentCompute !== true) {
991
+ canvas.dataset.munGpuBackend = "disabled";
992
+ const cleanup = runCanvasFallback(canvas, node, data);
993
+ const dispose = () => { cleanup(); mountedParticleFields.delete(canvas); };
994
+ mountedParticleFields.set(canvas, dispose);
995
+ return dispose;
996
+ }
997
+ // Optional CSS-compositing probe: schedule after startup without delaying GPU activation.
998
+ if (owner)
999
+ void prepareRenderingQuality(owner);
1000
+ let stopped = false;
1001
+ let stopLoop;
1002
+ let island;
1003
+ let fallbackCleanup;
1004
+ const stopFrame = () => {
1005
+ stopLoop?.();
1006
+ stopLoop = undefined;
1007
+ };
1008
+ const fallback = (reason) => {
1009
+ if (stopped || fallbackCleanup)
1010
+ return;
1011
+ stopFrame();
1012
+ island?.dispose();
1013
+ island = undefined;
1014
+ canvas.dataset.munGpuFailure = reason instanceof Error ? reason.message : String(reason);
1015
+ fallbackCleanup = runCanvasFallback(canvas, node, data);
1016
+ };
1017
+ const activate = async () => {
1018
+ const navigatorValue = owner?.navigator;
1019
+ const gpu = navigatorValue?.gpu;
1020
+ if (!gpu)
1021
+ return fallback(new Error("WebGPU is unavailable"));
1022
+ try {
1023
+ const shared = await sharedGpuDevice(gpu);
1024
+ const device = shared.device;
1025
+ const context = canvas.getContext("webgpu");
1026
+ if (!context)
1027
+ throw new Error("GPUCanvasContext is unavailable");
1028
+ const format = shared.format;
1029
+ if (stopped)
1030
+ return;
1031
+ island = node.ir.kind === "line-chart"
1032
+ ? await createLineChartGPUIsland(device, context, {
1033
+ count: node.ir.render.vertexCount,
1034
+ format,
1035
+ initialData: data,
1036
+ clearColor: node.options.clearColor,
1037
+ label: `Mun GPU LineChart ${node.ir.id}`,
1038
+ onFailure: error => fallback(error),
1039
+ })
1040
+ : await createParticleFieldGPUIsland(device, context, {
1041
+ count: node.ir.render.vertexCount,
1042
+ format,
1043
+ initialData: data,
1044
+ clearColor: node.options.clearColor,
1045
+ label: `Mun GPU Island ${node.ir.id}`,
1046
+ onFailure: error => fallback(error),
1047
+ });
1048
+ if (stopped) {
1049
+ island.dispose();
1050
+ island = undefined;
1051
+ return;
1052
+ }
1053
+ canvas.dataset.munGpuBackend = "webgpu";
1054
+ if (owner && typeof owner.requestAnimationFrame === "function") {
1055
+ const controller = getRenderingQuality(owner);
1056
+ const queue = record(record(device, "GPUDevice").queue, "GPUDevice.queue");
1057
+ stopLoop = runVisibleFrameLoop(canvas, owner, delta => {
1058
+ if (stopped || island?.status !== "active")
1059
+ return;
1060
+ try {
1061
+ island.renderFrame(delta);
1062
+ controller?.sampleGPUQueue(queue);
1063
+ }
1064
+ catch (error) {
1065
+ fallback(error);
1066
+ }
1067
+ });
1068
+ }
1069
+ else
1070
+ island.renderFrame(1 / 60);
1071
+ }
1072
+ catch (error) {
1073
+ fallback(error);
1074
+ }
1075
+ };
1076
+ queueMicrotask(() => { if (!stopped)
1077
+ void activate(); });
1078
+ const dispose = () => {
1079
+ if (stopped)
1080
+ return;
1081
+ stopped = true;
1082
+ stopFrame();
1083
+ fallbackCleanup?.();
1084
+ island?.dispose();
1085
+ mountedParticleFields.delete(canvas);
1086
+ };
1087
+ mountedParticleFields.set(canvas, dispose);
1088
+ return dispose;
1089
+ }
1090
+ export function disposeParticleFieldGPUIslandCanvas(canvas) {
1091
+ mountedParticleFields.get(canvas)?.();
1092
+ }
1093
+ //# sourceMappingURL=gpu-island.js.map