@flare-engine/render-web 0.2.1 → 0.3.0

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.
package/dist/index.mjs CHANGED
@@ -1,413 +1,549 @@
1
- // src/loader.ts
2
- var pending = null;
3
- function loadCanvasKit(wasmUrl, onProgress) {
4
- if (pending !== null) {
5
- onProgress?.(1);
6
- return pending;
7
- }
8
- pending = init(wasmUrl, onProgress);
9
- return pending;
1
+ import { createPostFxRuntime } from "@flare-engine/postfx";
2
+ import { createFrameRenderer } from "@flare-engine/render";
3
+ //#region src/loader.ts
4
+ const DEFAULT_STALL_MS = 15e3;
5
+ const DEFAULT_DEADLINE_MS = 45e3;
6
+ let pending = null;
7
+ /**
8
+ * Load CanvasKit exactly once. Subsequent calls return the same promise.
9
+ *
10
+ * A rejected load is NOT cached — a transient failure would otherwise strand every later caller
11
+ * on the same rejection for the module's lifetime.
12
+ *
13
+ * @param wasmUrl Absolute URL or filesystem path to canvaskit.wasm.
14
+ * @param onProgress Optional callback receiving download fraction [0,1].
15
+ * @param options Stall and deadline bounds.
16
+ */
17
+ function loadCanvasKit(wasmUrl, onProgress, options = {}) {
18
+ if (pending !== null) {
19
+ onProgress?.(1);
20
+ return pending;
21
+ }
22
+ const deadlineMs = options.deadlineMs ?? DEFAULT_DEADLINE_MS;
23
+ pending = withDeadline(init(wasmUrl, onProgress, options), deadlineMs).catch((err) => {
24
+ pending = null;
25
+ throw err;
26
+ });
27
+ return pending;
10
28
  }
11
- async function init(wasmUrl, onProgress) {
12
- const mod = await import("canvaskit-wasm/bin/full/canvaskit.js");
13
- try {
14
- const wasmBinary = await fetchWithProgress(wasmUrl, onProgress);
15
- onProgress?.(1);
16
- return await mod.default({ locateFile: () => wasmUrl, wasmBinary });
17
- } catch {
18
- onProgress?.(1);
19
- return mod.default({ locateFile: () => wasmUrl });
20
- }
29
+ function withDeadline(p, ms) {
30
+ return new Promise((resolve, reject) => {
31
+ const timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`CanvasKit load exceeded ${ms}ms`)), ms);
32
+ p.then((v) => {
33
+ clearTimeout(timer);
34
+ resolve(v);
35
+ }, (e) => {
36
+ clearTimeout(timer);
37
+ reject(e);
38
+ });
39
+ });
21
40
  }
22
- async function fetchWithProgress(url, onProgress) {
23
- if (typeof fetch === "undefined") {
24
- const fs = await import("fs/promises");
25
- const buf = await fs.readFile(url);
26
- return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
27
- }
28
- const res = await fetch(url);
29
- if (!res.ok || !res.body) return new Uint8Array(await res.arrayBuffer());
30
- const total = Number(res.headers.get("Content-Length")) || 0;
31
- const reader = res.body.getReader();
32
- const chunks = [];
33
- let loaded = 0;
34
- for (; ; ) {
35
- const { done, value } = await reader.read();
36
- if (done) break;
37
- if (!value) continue;
38
- chunks.push(value);
39
- loaded += value.length;
40
- if (total > 0) onProgress?.(Math.min(1, loaded / total));
41
- }
42
- const out = new Uint8Array(loaded);
43
- let offset = 0;
44
- for (const chunk of chunks) {
45
- out.set(chunk, offset);
46
- offset += chunk.length;
47
- }
48
- return out;
41
+ async function init(wasmUrl, onProgress, options) {
42
+ const mod = await import("canvaskit-wasm/bin/full/canvaskit.js");
43
+ try {
44
+ const wasmBinary = await fetchWithProgress(wasmUrl, onProgress, options);
45
+ onProgress?.(1);
46
+ return await mod.default({
47
+ locateFile: () => wasmUrl,
48
+ wasmBinary
49
+ });
50
+ } catch {
51
+ onProgress?.(1);
52
+ return mod.default({ locateFile: () => wasmUrl });
53
+ }
49
54
  }
50
-
51
- // src/web-surface.ts
52
- var clearScratch = new Float32Array(4);
53
- function unpackArgb(out, argb) {
54
- out[0] = (argb >>> 16 & 255) / 255;
55
- out[1] = (argb >>> 8 & 255) / 255;
56
- out[2] = (argb & 255) / 255;
57
- out[3] = (argb >>> 24 & 255) / 255;
55
+ async function fetchWithProgress(url, onProgress, options) {
56
+ if (typeof fetch === "undefined") {
57
+ const buf = await (await import("node:fs/promises")).readFile(url);
58
+ return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
59
+ }
60
+ const stallMs = options.stallMs ?? DEFAULT_STALL_MS;
61
+ const controller = new AbortController();
62
+ let stall;
63
+ const armStall = () => {
64
+ if (stall) clearTimeout(stall);
65
+ stall = setTimeout(() => controller.abort(), stallMs);
66
+ };
67
+ try {
68
+ armStall();
69
+ const res = await fetch(url, { signal: controller.signal });
70
+ if (!res.ok || !res.body) return new Uint8Array(await res.arrayBuffer());
71
+ const total = Number(res.headers.get("Content-Length")) || 0;
72
+ const reader = res.body.getReader();
73
+ const chunks = [];
74
+ let loaded = 0;
75
+ for (;;) {
76
+ const { done, value } = await reader.read();
77
+ if (done) break;
78
+ if (!value) continue;
79
+ armStall();
80
+ chunks.push(value);
81
+ loaded += value.length;
82
+ onProgress?.(total > 0 ? Math.min(1, loaded / total) : .9 * (1 - Math.exp(-loaded / 3e6)));
83
+ }
84
+ const out = new Uint8Array(loaded);
85
+ let offset = 0;
86
+ for (const chunk of chunks) {
87
+ out.set(chunk, offset);
88
+ offset += chunk.length;
89
+ }
90
+ return out;
91
+ } finally {
92
+ if (stall) clearTimeout(stall);
93
+ }
58
94
  }
59
- function createWebSurface(kit, canvas) {
60
- const surface = kit.MakeWebGLCanvasSurface(canvas);
61
- if (!surface) return null;
62
- const ck = surface.getCanvas();
63
- return {
64
- save: () => ck.save(),
65
- restore: () => ck.restore(),
66
- translate: (x, y) => ck.translate(x, y),
67
- scale: (sx, sy) => ck.scale(sx, sy),
68
- // Forwarded verbatim to match the native bridge (no radians→degrees conversion).
69
- // Both RN-Skia and CanvasKit Canvas.rotate take degrees; the engine labels the
70
- // param "radians" — a pre-existing dormant mismatch tracked for a cross-backend fix.
71
- rotate: (radians, cx, cy) => ck.rotate(radians, cx, cy),
72
- clear: (color) => {
73
- unpackArgb(clearScratch, color);
74
- ck.clear(clearScratch);
75
- }
76
- };
95
+ //#endregion
96
+ //#region src/postfx-surface.ts
97
+ /**
98
+ * Create a `PostFxSurface` backed by a WebGL CanvasKit context.
99
+ *
100
+ * Returns `null` when WebGL is unavailable.
101
+ *
102
+ * @param kit Loaded CanvasKit instance.
103
+ * @param canvas Target `<canvas>` element.
104
+ * @param chain Effect chain to apply at composite time.
105
+ * Pass a new empty `EffectChain()` for a passthrough surface.
106
+ */
107
+ function createPostFxSurface(kit, canvas, chain) {
108
+ const clampDim = (v) => {
109
+ const n = Math.floor(v);
110
+ return Number.isFinite(n) && n > 0 ? n : 1;
111
+ };
112
+ let w = clampDim(canvas.width);
113
+ let h = clampDim(canvas.height);
114
+ const lastBg = /* @__PURE__ */ new Float32Array(3);
115
+ const info = () => ({
116
+ width: w,
117
+ height: h,
118
+ colorType: kit.ColorType.RGBA_8888,
119
+ alphaType: kit.AlphaType.Premul,
120
+ colorSpace: kit.ColorSpace.SRGB
121
+ });
122
+ let ctxHandle = 0;
123
+ let grContext = null;
124
+ let onscreen = null;
125
+ let scene = null;
126
+ let pong = null;
127
+ let lost = false;
128
+ const disposeGpu = () => {
129
+ scene?.delete();
130
+ pong?.delete();
131
+ onscreen?.delete();
132
+ grContext?.delete();
133
+ if (ctxHandle) kit.deleteContext(ctxHandle);
134
+ scene = null;
135
+ pong = null;
136
+ onscreen = null;
137
+ grContext = null;
138
+ ctxHandle = 0;
139
+ };
140
+ const buildGpu = () => {
141
+ ctxHandle = kit.GetWebGLContext(canvas);
142
+ if (!ctxHandle) return false;
143
+ grContext = kit.MakeWebGLContext(ctxHandle);
144
+ if (!grContext) {
145
+ kit.deleteContext(ctxHandle);
146
+ ctxHandle = 0;
147
+ return false;
148
+ }
149
+ onscreen = kit.MakeOnScreenGLSurface(grContext, w, h, kit.ColorSpace.SRGB);
150
+ scene = onscreen?.makeSurface(info()) ?? null;
151
+ pong = onscreen?.makeSurface(info()) ?? null;
152
+ if (!onscreen || !scene || !pong) {
153
+ disposeGpu();
154
+ return false;
155
+ }
156
+ return true;
157
+ };
158
+ if (!buildGpu()) {
159
+ disposeGpu();
160
+ return null;
161
+ }
162
+ const clearScene = (bgRgb) => {
163
+ lastBg[0] = bgRgb[0] ?? 0;
164
+ lastBg[1] = bgRgb[1] ?? 0;
165
+ lastBg[2] = bgRgb[2] ?? 0;
166
+ if (lost) return;
167
+ const sc = scene?.getCanvas();
168
+ if (!sc) return;
169
+ sc.clear(kit.Color4f(lastBg[0], lastBg[1], lastBg[2], 1));
170
+ scene?.flush();
171
+ };
172
+ const onContextLost = (e) => {
173
+ e.preventDefault();
174
+ lost = true;
175
+ };
176
+ const onContextRestored = () => {
177
+ disposeGpu();
178
+ lost = !buildGpu();
179
+ if (!lost) clearScene(lastBg);
180
+ };
181
+ canvas.addEventListener("webglcontextlost", onContextLost, false);
182
+ canvas.addEventListener("webglcontextrestored", onContextRestored, false);
183
+ const fade = new kit.Paint();
184
+ const fx = new kit.Paint();
185
+ fx.setBlendMode(kit.BlendMode.Src);
186
+ const scratch = /* @__PURE__ */ new Float32Array(4);
187
+ const rectScratch = /* @__PURE__ */ new Float32Array(4);
188
+ const childrenBuf = [null];
189
+ const runtime = createPostFxRuntime({ RuntimeEffect: { Make(sksl) {
190
+ const eff = kit.RuntimeEffect.Make(sksl);
191
+ if (!eff) return null;
192
+ return { makeShaderWithChildren: (uniforms, children) => eff.makeShaderWithChildren(uniforms, children ?? []) };
193
+ } } });
194
+ function blit(img) {
195
+ if (lost || !onscreen) return;
196
+ const passes = runtime.supported ? runtime.buildPass(chain, w, h) : [];
197
+ if (passes.length === 0) {
198
+ onscreen.getCanvas().drawImage(img, 0, 0);
199
+ onscreen.flush();
200
+ return;
201
+ }
202
+ let src = img;
203
+ const last = passes.length - 1;
204
+ rectScratch[0] = 0;
205
+ rectScratch[1] = 0;
206
+ rectScratch[2] = w;
207
+ rectScratch[3] = h;
208
+ for (let i = 0; i < passes.length; i++) {
209
+ const pass = passes[i];
210
+ if (!pass) continue;
211
+ const toScreen = i === last;
212
+ const target = toScreen ? onscreen : pong;
213
+ if (!target) break;
214
+ const srcShader = src.makeShaderOptions(kit.TileMode.Clamp, kit.TileMode.Clamp, kit.FilterMode.Linear, kit.MipmapMode.None);
215
+ const childCount = 1 + pass.children.length;
216
+ childrenBuf.length = childCount;
217
+ childrenBuf[0] = srcShader;
218
+ for (let c = 0; c < pass.children.length; c++) {
219
+ const childImg = pass.children[c];
220
+ if (!childImg) continue;
221
+ childrenBuf[c + 1] = childImg.makeShaderOptions(kit.TileMode.Clamp, kit.TileMode.Clamp, kit.FilterMode.Linear, kit.MipmapMode.None);
222
+ }
223
+ const shader = pass.shader.makeShaderWithChildren(pass.uniforms, childrenBuf);
224
+ fx.setShader(shader);
225
+ target.getCanvas().drawRect(rectScratch, fx);
226
+ fx.setShader(null);
227
+ shader?.delete();
228
+ for (let c = 0; c < childCount; c++) {
229
+ childrenBuf[c]?.delete();
230
+ childrenBuf[c] = null;
231
+ }
232
+ target.flush();
233
+ if (!toScreen) {
234
+ if (src !== img) src.delete();
235
+ src = target.makeImageSnapshot();
236
+ }
237
+ }
238
+ if (src !== img) src.delete();
239
+ }
240
+ return {
241
+ get width() {
242
+ return w;
243
+ },
244
+ get height() {
245
+ return h;
246
+ },
247
+ sceneCanvas: () => lost ? null : scene?.getCanvas() ?? null,
248
+ onscreenCanvas: () => lost ? null : onscreen?.getCanvas() ?? null,
249
+ clear(bgRgb) {
250
+ clearScene(bgRgb);
251
+ },
252
+ fadeTrail(bgRgb, alpha) {
253
+ const sc = scene?.getCanvas();
254
+ if (lost || !sc) return;
255
+ scratch[0] = bgRgb[0] ?? 0;
256
+ scratch[1] = bgRgb[1] ?? 0;
257
+ scratch[2] = bgRgb[2] ?? 0;
258
+ scratch[3] = alpha;
259
+ fade.setColor(scratch);
260
+ fade.setBlendMode(kit.BlendMode.SrcOver);
261
+ rectScratch[0] = 0;
262
+ rectScratch[1] = 0;
263
+ rectScratch[2] = w;
264
+ rectScratch[3] = h;
265
+ sc.drawRect(rectScratch, fade);
266
+ },
267
+ composite(globalIntensity) {
268
+ if (lost || !scene) return;
269
+ scene.flush();
270
+ chain.globalIntensity = globalIntensity;
271
+ const img = scene.makeImageSnapshot();
272
+ blit(img);
273
+ img.delete();
274
+ },
275
+ flush() {
276
+ if (!lost) onscreen?.flush();
277
+ },
278
+ resize(nextW, nextH) {
279
+ w = clampDim(nextW);
280
+ h = clampDim(nextH);
281
+ canvas.width = w;
282
+ canvas.height = h;
283
+ if (lost || !grContext) return;
284
+ scene?.delete();
285
+ pong?.delete();
286
+ onscreen?.delete();
287
+ onscreen = kit.MakeOnScreenGLSurface(grContext, w, h, kit.ColorSpace.SRGB);
288
+ scene = onscreen?.makeSurface(info()) ?? null;
289
+ pong = onscreen?.makeSurface(info()) ?? null;
290
+ if (!onscreen || !scene || !pong) {
291
+ disposeGpu();
292
+ lost = true;
293
+ }
294
+ },
295
+ isLost: () => lost,
296
+ dispose() {
297
+ canvas.removeEventListener("webglcontextlost", onContextLost, false);
298
+ canvas.removeEventListener("webglcontextrestored", onContextRestored, false);
299
+ fade.delete();
300
+ fx.delete();
301
+ runtime.reset();
302
+ disposeGpu();
303
+ }
304
+ };
77
305
  }
78
-
79
- // src/web-skia-module.ts
80
- var BLEND_SRC_OVER = 3;
81
- var BLEND_SRC_IN = 5;
306
+ //#endregion
307
+ //#region src/web-skia-module.ts
308
+ const BLEND_SRC_OVER = 3;
309
+ const BLEND_SRC_IN = 5;
82
310
  function makeAtlasBuffers() {
83
- let srcs = new Float32Array(32 * 4);
84
- let xforms = new Float32Array(32 * 4);
85
- return {
86
- get srcs() {
87
- return srcs;
88
- },
89
- get xforms() {
90
- return xforms;
91
- },
92
- ensureCapacity(n) {
93
- if (n * 4 > srcs.length) {
94
- let cap = srcs.length;
95
- while (cap < n * 4) cap *= 2;
96
- srcs = new Float32Array(cap);
97
- xforms = new Float32Array(cap);
98
- }
99
- }
100
- };
311
+ let srcs = /* @__PURE__ */ new Float32Array(128);
312
+ let xforms = /* @__PURE__ */ new Float32Array(128);
313
+ return {
314
+ get srcs() {
315
+ return srcs;
316
+ },
317
+ get xforms() {
318
+ return xforms;
319
+ },
320
+ ensureCapacity(n) {
321
+ if (n * 4 > srcs.length) {
322
+ let cap = srcs.length;
323
+ while (cap < n * 4) cap *= 2;
324
+ srcs = new Float32Array(cap);
325
+ xforms = new Float32Array(cap);
326
+ }
327
+ }
328
+ };
101
329
  }
102
330
  function rawPaint(paint) {
103
- return paint._ckPaint;
331
+ return paint._ckPaint;
104
332
  }
105
333
  function wrapCKCanvas(ck, atlasBuffers) {
106
- const imgSrcScratch = new Float32Array(4);
107
- const imgDstScratch = new Float32Array(4);
108
- return {
109
- save: () => ck.save(),
110
- restore: () => ck.restore(),
111
- translate: (x, y) => ck.translate(x, y),
112
- scale: (sx, sy) => ck.scale(sx, sy),
113
- // Forwarded verbatim to match the native bridge (no radians→degrees conversion).
114
- // Both RN-Skia and CanvasKit Canvas.rotate take degrees; the engine labels the
115
- // param "radians" — a pre-existing dormant mismatch tracked for a cross-backend fix.
116
- rotate: (radians, cx, cy) => ck.rotate(radians, cx, cy),
117
- clear: (color) => ck.clear(color),
118
- drawAtlas(image, srcRects, dstXforms, paint) {
119
- const n = srcRects.length;
120
- if (n === 0) return;
121
- atlasBuffers.ensureCapacity(n);
122
- for (let i = 0; i < n; i++) {
123
- const r = srcRects[i];
124
- const o = i * 4;
125
- atlasBuffers.srcs[o] = r.x;
126
- atlasBuffers.srcs[o + 1] = r.y;
127
- atlasBuffers.srcs[o + 2] = r.x + r.width;
128
- atlasBuffers.srcs[o + 3] = r.y + r.height;
129
- const xf = dstXforms[i];
130
- atlasBuffers.xforms[o] = xf.scos;
131
- atlasBuffers.xforms[o + 1] = xf.ssin;
132
- atlasBuffers.xforms[o + 2] = xf.tx;
133
- atlasBuffers.xforms[o + 3] = xf.ty;
134
- }
135
- ck.drawAtlas(
136
- image,
137
- atlasBuffers.srcs.subarray(0, n * 4),
138
- atlasBuffers.xforms.subarray(0, n * 4),
139
- rawPaint(paint),
140
- null,
141
- null
142
- );
143
- },
144
- drawImageRect(image, src, dst, paint) {
145
- const s = src;
146
- imgSrcScratch[0] = s.x;
147
- imgSrcScratch[1] = s.y;
148
- imgSrcScratch[2] = s.x + s.width;
149
- imgSrcScratch[3] = s.y + s.height;
150
- const d = dst;
151
- imgDstScratch[0] = d.x;
152
- imgDstScratch[1] = d.y;
153
- imgDstScratch[2] = d.x + d.width;
154
- imgDstScratch[3] = d.y + d.height;
155
- ck.drawImageRect(image, imgSrcScratch, imgDstScratch, rawPaint(paint), false);
156
- },
157
- drawRect(rect, paint) {
158
- const r = rect;
159
- imgSrcScratch[0] = r.x;
160
- imgSrcScratch[1] = r.y;
161
- imgSrcScratch[2] = r.x + r.width;
162
- imgSrcScratch[3] = r.y + r.height;
163
- ck.drawRect(imgSrcScratch, rawPaint(paint));
164
- }
165
- };
334
+ const imgSrcScratch = /* @__PURE__ */ new Float32Array(4);
335
+ const imgDstScratch = /* @__PURE__ */ new Float32Array(4);
336
+ return {
337
+ save: () => ck.save(),
338
+ restore: () => ck.restore(),
339
+ translate: (x, y) => ck.translate(x, y),
340
+ scale: (sx, sy) => ck.scale(sx, sy),
341
+ rotate: (degrees, cx, cy) => ck.rotate(degrees, cx, cy),
342
+ clear: (color) => ck.clear(color),
343
+ drawAtlas(image, srcRects, dstXforms, paint) {
344
+ const n = srcRects.length;
345
+ if (n === 0) return;
346
+ atlasBuffers.ensureCapacity(n);
347
+ for (let i = 0; i < n; i++) {
348
+ const r = srcRects[i];
349
+ const o = i * 4;
350
+ atlasBuffers.srcs[o] = r.x;
351
+ atlasBuffers.srcs[o + 1] = r.y;
352
+ atlasBuffers.srcs[o + 2] = r.x + r.width;
353
+ atlasBuffers.srcs[o + 3] = r.y + r.height;
354
+ const xf = dstXforms[i];
355
+ atlasBuffers.xforms[o] = xf.scos;
356
+ atlasBuffers.xforms[o + 1] = xf.ssin;
357
+ atlasBuffers.xforms[o + 2] = xf.tx;
358
+ atlasBuffers.xforms[o + 3] = xf.ty;
359
+ }
360
+ ck.drawAtlas(image, atlasBuffers.srcs.subarray(0, n * 4), atlasBuffers.xforms.subarray(0, n * 4), rawPaint(paint), null, null);
361
+ },
362
+ drawImageRect(image, src, dst, paint) {
363
+ const s = src;
364
+ imgSrcScratch[0] = s.x;
365
+ imgSrcScratch[1] = s.y;
366
+ imgSrcScratch[2] = s.x + s.width;
367
+ imgSrcScratch[3] = s.y + s.height;
368
+ const d = dst;
369
+ imgDstScratch[0] = d.x;
370
+ imgDstScratch[1] = d.y;
371
+ imgDstScratch[2] = d.x + d.width;
372
+ imgDstScratch[3] = d.y + d.height;
373
+ ck.drawImageRect(image, imgSrcScratch, imgDstScratch, rawPaint(paint), false);
374
+ },
375
+ drawRect(rect, paint) {
376
+ const r = rect;
377
+ imgSrcScratch[0] = r.x;
378
+ imgSrcScratch[1] = r.y;
379
+ imgSrcScratch[2] = r.x + r.width;
380
+ imgSrcScratch[3] = r.y + r.height;
381
+ ck.drawRect(imgSrcScratch, rawPaint(paint));
382
+ }
383
+ };
166
384
  }
167
385
  function wrapRuntimeEffect(eff) {
168
- return {
169
- makeShader: (uniforms) => eff.makeShader(uniforms),
170
- getUniformCount: () => eff.getUniformCount(),
171
- getUniformFloatCount: () => eff.getUniformFloatCount(),
172
- getUniformName: (i) => eff.getUniformName(i),
173
- getUniform: (i) => {
174
- const u = eff.getUniform(i);
175
- return { columns: u.columns, rows: u.rows, slot: u.slot };
176
- }
177
- };
386
+ return {
387
+ makeShader: (uniforms) => eff.makeShader(uniforms),
388
+ getUniformCount: () => eff.getUniformCount(),
389
+ getUniformFloatCount: () => eff.getUniformFloatCount(),
390
+ getUniformName: (i) => eff.getUniformName(i),
391
+ getUniform: (i) => {
392
+ const u = eff.getUniform(i);
393
+ return {
394
+ columns: u.columns,
395
+ rows: u.rows,
396
+ slot: u.slot
397
+ };
398
+ }
399
+ };
178
400
  }
401
+ /**
402
+ * Create a `FrameRendererModule` backed by CanvasKit.
403
+ *
404
+ * The returned module satisfies the same structural interface that the
405
+ * real RN-Skia module satisfies, so `createFrameRenderer` can accept it.
406
+ *
407
+ * CK differences handled here:
408
+ * - `drawAtlas` takes flat Float32Arrays — the wrapper flattens object pools.
409
+ * - `rotate` is forwarded verbatim (no radians→degrees conversion) to match
410
+ * the native bridge; the dormant radians/degrees mismatch is tracked separately.
411
+ * - `ColorFilter.MakeBlend(color, mode)` takes an EmbindEnumEntity — the
412
+ * wrapper maps the numeric literal (3=SrcOver, 5=SrcIn) to the CK enum.
413
+ * - `RSXform` objects carry `scos/ssin/tx/ty` fields for flat-array flattening.
414
+ */
179
415
  function createWebSkiaModule(kit) {
180
- const atlasBuffers = makeAtlasBuffers();
181
- const colorFilterFactory = {
182
- MakeBlend(color, mode) {
183
- const blendMode = mode === BLEND_SRC_OVER ? kit.BlendMode.SrcOver : mode === BLEND_SRC_IN ? kit.BlendMode.SrcIn : kit.BlendMode.SrcOver;
184
- return kit.ColorFilter.MakeBlend(color, blendMode);
185
- },
186
- MakeMatrix(matrix) {
187
- return kit.ColorFilter.MakeMatrix(matrix);
188
- }
189
- };
190
- const runtimeEffectFactory = {
191
- Make(sksl) {
192
- const eff = kit.RuntimeEffect.Make(sksl);
193
- if (!eff) return null;
194
- return wrapRuntimeEffect(eff);
195
- }
196
- };
197
- const imageFilterFactory = {
198
- MakeDropShadow(dx, dy, sigmaX, sigmaY, color, _input) {
199
- return kit.ImageFilter.MakeDropShadow(dx, dy, sigmaX, sigmaY, color, null);
200
- }
201
- };
202
- return {
203
- XYWHRect(x, y, w, h) {
204
- const r = {
205
- x,
206
- y,
207
- width: w,
208
- height: h,
209
- setXYWH(nx, ny, nw, nh) {
210
- r.x = nx;
211
- r.y = ny;
212
- r.width = nw;
213
- r.height = nh;
214
- }
215
- };
216
- return r;
217
- },
218
- RSXform(scos, ssin, tx, ty) {
219
- const xf = {
220
- scos,
221
- ssin,
222
- tx,
223
- ty,
224
- set(s, si, nx, ny) {
225
- xf.scos = s;
226
- xf.ssin = si;
227
- xf.tx = nx;
228
- xf.ty = ny;
229
- }
230
- };
231
- return xf;
232
- },
233
- Paint() {
234
- const p = new kit.Paint();
235
- const paint = {
236
- _ckPaint: p,
237
- setAlphaf: (a) => p.setAlphaf(a),
238
- setColor: (c) => p.setColor(c),
239
- setColorFilter: (f) => p.setColorFilter(f),
240
- setShader: (s) => p.setShader(s),
241
- setImageFilter: (f) => p.setImageFilter(f)
242
- };
243
- return paint;
244
- },
245
- PictureRecorder() {
246
- const rec = new kit.PictureRecorder();
247
- const recorder = {
248
- beginRecording(bounds) {
249
- const r = bounds;
250
- const ck = rec.beginRecording(kit.XYWHRect(r.x, r.y, r.width, r.height));
251
- return wrapCKCanvas(ck, atlasBuffers);
252
- },
253
- finishRecordingAsPicture() {
254
- return rec.finishRecordingAsPicture();
255
- }
256
- };
257
- return recorder;
258
- },
259
- ColorFilter: colorFilterFactory,
260
- RuntimeEffect: runtimeEffectFactory,
261
- ImageFilter: imageFilterFactory
262
- };
416
+ const atlasBuffers = makeAtlasBuffers();
417
+ return {
418
+ XYWHRect(x, y, w, h) {
419
+ const r = {
420
+ x,
421
+ y,
422
+ width: w,
423
+ height: h,
424
+ setXYWH(nx, ny, nw, nh) {
425
+ r.x = nx;
426
+ r.y = ny;
427
+ r.width = nw;
428
+ r.height = nh;
429
+ }
430
+ };
431
+ return r;
432
+ },
433
+ RSXform(scos, ssin, tx, ty) {
434
+ const xf = {
435
+ scos,
436
+ ssin,
437
+ tx,
438
+ ty,
439
+ set(s, si, nx, ny) {
440
+ xf.scos = s;
441
+ xf.ssin = si;
442
+ xf.tx = nx;
443
+ xf.ty = ny;
444
+ }
445
+ };
446
+ return xf;
447
+ },
448
+ Paint() {
449
+ const p = new kit.Paint();
450
+ return {
451
+ _ckPaint: p,
452
+ setAlphaf: (a) => p.setAlphaf(a),
453
+ setColor: (c) => p.setColor(c),
454
+ setColorFilter: (f) => p.setColorFilter(f),
455
+ setShader: (s) => p.setShader(s),
456
+ setImageFilter: (f) => p.setImageFilter(f)
457
+ };
458
+ },
459
+ PictureRecorder() {
460
+ const rec = new kit.PictureRecorder();
461
+ return {
462
+ beginRecording(bounds) {
463
+ const r = bounds;
464
+ return wrapCKCanvas(rec.beginRecording(kit.XYWHRect(r.x, r.y, r.width, r.height)), atlasBuffers);
465
+ },
466
+ finishRecordingAsPicture() {
467
+ return rec.finishRecordingAsPicture();
468
+ }
469
+ };
470
+ },
471
+ ColorFilter: {
472
+ MakeBlend(color, mode) {
473
+ const blendMode = mode === BLEND_SRC_OVER ? kit.BlendMode.SrcOver : mode === BLEND_SRC_IN ? kit.BlendMode.SrcIn : kit.BlendMode.SrcOver;
474
+ return kit.ColorFilter.MakeBlend(color, blendMode);
475
+ },
476
+ MakeMatrix(matrix) {
477
+ return kit.ColorFilter.MakeMatrix(matrix);
478
+ }
479
+ },
480
+ RuntimeEffect: { Make(sksl) {
481
+ const eff = kit.RuntimeEffect.Make(sksl);
482
+ if (!eff) return null;
483
+ return wrapRuntimeEffect(eff);
484
+ } },
485
+ ImageFilter: { MakeDropShadow(dx, dy, sigmaX, sigmaY, color, _input) {
486
+ return kit.ImageFilter.MakeDropShadow(dx, dy, sigmaX, sigmaY, color, null);
487
+ } }
488
+ };
263
489
  }
264
-
265
- // src/postfx-surface.ts
266
- import {
267
- createPostFxRuntime
268
- } from "@flare-engine/postfx";
269
- function createPostFxSurface(kit, canvas, chain) {
270
- const onscreenOrNull = kit.MakeWebGLCanvasSurface(canvas);
271
- if (!onscreenOrNull) return null;
272
- const onscreen = onscreenOrNull;
273
- let w = Math.max(1, canvas.width);
274
- let h = Math.max(1, canvas.height);
275
- const info = () => ({
276
- width: w,
277
- height: h,
278
- colorType: kit.ColorType.RGBA_8888,
279
- alphaType: kit.AlphaType.Premul,
280
- colorSpace: kit.ColorSpace.SRGB
281
- });
282
- let scene = onscreen.makeSurface(info());
283
- if (!scene) console.warn("[render-web] postfx: scene surface null; frame will be blank");
284
- let pong = onscreen.makeSurface(info());
285
- if (!pong) console.warn("[render-web] postfx: pong surface null; no multi-pass");
286
- const fade = new kit.Paint();
287
- const fx = new kit.Paint();
288
- const scratch = new Float32Array(4);
289
- const rectScratch = new Float32Array(4);
290
- const childrenBuf = [null];
291
- const skia = {
292
- RuntimeEffect: {
293
- Make(sksl) {
294
- const eff = kit.RuntimeEffect.Make(sksl);
295
- if (!eff) return null;
296
- return {
297
- makeShaderWithChildren: (uniforms, children) => eff.makeShaderWithChildren(uniforms, children ?? [])
298
- };
299
- }
300
- }
301
- };
302
- const runtime = createPostFxRuntime(skia);
303
- function blit(img) {
304
- const passes = runtime.supported ? runtime.buildPass(chain, w, h) : [];
305
- if (passes.length === 0) {
306
- onscreen.getCanvas().drawImage(img, 0, 0);
307
- onscreen.flush();
308
- return;
309
- }
310
- let src = img;
311
- const last = passes.length - 1;
312
- rectScratch[0] = 0;
313
- rectScratch[1] = 0;
314
- rectScratch[2] = w;
315
- rectScratch[3] = h;
316
- for (let i = 0; i < passes.length; i++) {
317
- const pass = passes[i];
318
- if (!pass) continue;
319
- const toScreen = i === last;
320
- const target = toScreen ? onscreen : pong;
321
- if (!target) break;
322
- const srcShader = src.makeShaderOptions(
323
- kit.TileMode.Clamp,
324
- kit.TileMode.Clamp,
325
- kit.FilterMode.Linear,
326
- kit.MipmapMode.None
327
- );
328
- childrenBuf[0] = srcShader;
329
- const shader = pass.shader.makeShaderWithChildren(
330
- pass.uniforms,
331
- childrenBuf
332
- );
333
- fx.setShader(shader);
334
- target.getCanvas().drawRect(rectScratch, fx);
335
- fx.setShader(null);
336
- shader?.delete();
337
- srcShader.delete();
338
- target.flush();
339
- if (!toScreen) {
340
- if (src !== img) src.delete();
341
- src = target.makeImageSnapshot();
342
- }
343
- }
344
- if (src !== img) src.delete();
345
- }
346
- return {
347
- get width() {
348
- return w;
349
- },
350
- get height() {
351
- return h;
352
- },
353
- sceneCanvas: () => scene?.getCanvas() ?? null,
354
- onscreenCanvas: () => onscreen.getCanvas(),
355
- clear(bgRgb) {
356
- scene?.getCanvas().clear(kit.Color4f(bgRgb[0] ?? 0, bgRgb[1] ?? 0, bgRgb[2] ?? 0, 1));
357
- scene?.flush();
358
- },
359
- fadeTrail(bgRgb, alpha) {
360
- const sc = scene?.getCanvas();
361
- if (!sc) return;
362
- scratch[0] = bgRgb[0] ?? 0;
363
- scratch[1] = bgRgb[1] ?? 0;
364
- scratch[2] = bgRgb[2] ?? 0;
365
- scratch[3] = alpha;
366
- fade.setColor(scratch);
367
- fade.setBlendMode(kit.BlendMode.SrcOver);
368
- rectScratch[0] = 0;
369
- rectScratch[1] = 0;
370
- rectScratch[2] = w;
371
- rectScratch[3] = h;
372
- sc.drawRect(rectScratch, fade);
373
- },
374
- composite(globalIntensity) {
375
- if (!scene) return;
376
- scene.flush();
377
- chain.globalIntensity = globalIntensity;
378
- const img = scene.makeImageSnapshot();
379
- blit(img);
380
- img.delete();
381
- },
382
- flush() {
383
- onscreen.flush();
384
- },
385
- resize(nextW, nextH) {
386
- w = Math.max(1, Math.floor(nextW));
387
- h = Math.max(1, Math.floor(nextH));
388
- canvas.width = w;
389
- canvas.height = h;
390
- scene?.delete();
391
- pong?.delete();
392
- scene = onscreen.makeSurface(info());
393
- if (!scene) console.warn("[render-web] postfx: scene surface null after resize");
394
- pong = onscreen.makeSurface(info());
395
- if (!pong) console.warn("[render-web] postfx: pong surface null after resize");
396
- },
397
- dispose() {
398
- scene?.delete();
399
- pong?.delete();
400
- fade.delete();
401
- fx.delete();
402
- runtime.reset();
403
- onscreen.delete();
404
- }
405
- };
490
+ //#endregion
491
+ //#region src/web-frame-renderer.ts
492
+ /**
493
+ * Create a `FrameRenderer` backed by CanvasKit (web/WASM).
494
+ *
495
+ * The web analog of `createSkiaFrameRenderer` from `@flare-engine/react`:
496
+ * delegates to `createFrameRenderer(createWebSkiaModule(kit))` so the
497
+ * frame-renderer body is backend-neutral and shared with native.
498
+ *
499
+ * Presentation (drawing the `endFrame()` picture onto a surface and flushing)
500
+ * is the consumer's responsibility — use `createWebSurface` or
501
+ * `createPostFxSurface` for that step.
502
+ */
503
+ function createWebFrameRenderer(kit) {
504
+ return createFrameRenderer(createWebSkiaModule(kit));
505
+ }
506
+ //#endregion
507
+ //#region src/web-surface.ts
508
+ /**
509
+ * Create a `CanvasLike` that draws into a WebGL-backed CanvasKit surface
510
+ * for the given `<canvas>` element.
511
+ *
512
+ * Returns `null` when WebGL is unavailable (e.g. headless test environments).
513
+ * Callers should fall back to a CPU surface in that case.
514
+ *
515
+ * The returned object satisfies `CanvasLike` so it can be passed directly
516
+ * to `Renderer.setCanvas()` and `createFrameRenderer()`.
517
+ *
518
+ * Note: the underlying `SkCanvas` returned by `getCanvas()` is owned by the
519
+ * surface. The surface is not exposed here; the caller should call
520
+ * `surface.flush()` / `surface.delete()` via the `PostFxSurface` wrapper.
521
+ */
522
+ const clearScratch = /* @__PURE__ */ new Float32Array(4);
523
+ /** Unpack a 0xAARRGGBB integer into a Float32Array [r, g, b, a] in [0, 1]. */
524
+ function unpackArgb(out, argb) {
525
+ out[0] = (argb >>> 16 & 255) / 255;
526
+ out[1] = (argb >>> 8 & 255) / 255;
527
+ out[2] = (argb & 255) / 255;
528
+ out[3] = (argb >>> 24 & 255) / 255;
406
529
  }
407
- export {
408
- createPostFxSurface,
409
- createWebSkiaModule,
410
- createWebSurface,
411
- loadCanvasKit
412
- };
530
+ function createWebSurface(kit, canvas) {
531
+ const surface = kit.MakeWebGLCanvasSurface(canvas);
532
+ if (!surface) return null;
533
+ const ck = surface.getCanvas();
534
+ return {
535
+ save: () => ck.save(),
536
+ restore: () => ck.restore(),
537
+ translate: (x, y) => ck.translate(x, y),
538
+ scale: (sx, sy) => ck.scale(sx, sy),
539
+ rotate: (degrees, cx, cy) => ck.rotate(degrees, cx, cy),
540
+ clear: (color) => {
541
+ unpackArgb(clearScratch, color);
542
+ ck.clear(clearScratch);
543
+ }
544
+ };
545
+ }
546
+ //#endregion
547
+ export { createPostFxSurface, createWebFrameRenderer, createWebSkiaModule, createWebSurface, loadCanvasKit };
548
+
413
549
  //# sourceMappingURL=index.mjs.map