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