@algorisys/tinyfly 0.86.2 → 0.87.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.
@@ -268,6 +268,21 @@ function smoothPath(ctx, points) {
268
268
  const last = points[points.length - 1];
269
269
  ctx.lineTo(last.x, last.y);
270
270
  }
271
+ function canvasLike(ctx, width, height) {
272
+ if (typeof OffscreenCanvas !== "undefined") return new OffscreenCanvas(width, height);
273
+ const source = ctx.canvas;
274
+ if (source?.ownerDocument) {
275
+ const canvas = source.ownerDocument.createElement("canvas");
276
+ canvas.width = width;
277
+ canvas.height = height;
278
+ return canvas;
279
+ }
280
+ try {
281
+ return source?.constructor ? new source.constructor(width, height) : null;
282
+ } catch {
283
+ return null;
284
+ }
285
+ }
271
286
  const DEG = Math.PI / 180;
272
287
  function has3dTransform(t) {
273
288
  return t.z !== void 0 || t.rotateX !== void 0 || t.rotateY !== void 0 || t.perspective !== void 0 || Array.isArray(t.quaternion) && t.quaternion.length === 4;
@@ -394,21 +409,6 @@ function growTriangle(points, amount) {
394
409
  return { x: p.x + bx / len * reach, y: p.y + by / len * reach };
395
410
  });
396
411
  }
397
- function createLayerCanvas(ctx, width, height) {
398
- if (typeof OffscreenCanvas !== "undefined") return new OffscreenCanvas(width, height);
399
- const source = ctx.canvas;
400
- if (source?.ownerDocument) {
401
- const canvas = source.ownerDocument.createElement("canvas");
402
- canvas.width = width;
403
- canvas.height = height;
404
- return canvas;
405
- }
406
- try {
407
- return source?.constructor ? new source.constructor(width, height) : null;
408
- } catch {
409
- return null;
410
- }
411
- }
412
412
  class CanvasAdapter {
413
413
  targets = /* @__PURE__ */ new Map();
414
414
  targetOrder = [];
@@ -620,7 +620,7 @@ class CanvasAdapter {
620
620
  const height = ctx.canvas?.height ?? 0;
621
621
  if (!(width > 0 && height > 0)) return null;
622
622
  if (!this.layer || this.layer.width !== width || this.layer.height !== height) {
623
- const canvas = createLayerCanvas(ctx, width, height);
623
+ const canvas = canvasLike(ctx, width, height);
624
624
  const layerCtx2 = canvas?.getContext("2d");
625
625
  this.layer = canvas && layerCtx2 ? { canvas, ctx: layerCtx2, width, height } : null;
626
626
  if (!this.layer) return null;
@@ -1118,6 +1118,85 @@ class CanvasAdapter {
1118
1118
  });
1119
1119
  }
1120
1120
  }
1121
+ function brightPass(data, threshold) {
1122
+ const pixels = data.length / 4;
1123
+ const out = new Float32Array(pixels * 3);
1124
+ const t = Math.min(0.999, Math.max(0, threshold));
1125
+ for (let i = 0; i < pixels; i++) {
1126
+ const r = data[i * 4] / 255;
1127
+ const g = data[i * 4 + 1] / 255;
1128
+ const b = data[i * 4 + 2] / 255;
1129
+ const a = data[i * 4 + 3] / 255;
1130
+ const peak = Math.max(r, g, b);
1131
+ if (peak <= t) continue;
1132
+ const k = (peak - t) / (1 - t) * a / peak;
1133
+ out[i * 3] = r * k;
1134
+ out[i * 3 + 1] = g * k;
1135
+ out[i * 3 + 2] = b * k;
1136
+ }
1137
+ return out;
1138
+ }
1139
+ function boxPass(source, width, height, radius, horizontal) {
1140
+ const out = new Float32Array(source.length);
1141
+ const lines = horizontal ? height : width;
1142
+ const length = horizontal ? width : height;
1143
+ const at = (line, i) => (horizontal ? line * width + i : i * width + line) * 3;
1144
+ const span = radius * 2 + 1;
1145
+ for (let line = 0; line < lines; line++) {
1146
+ for (let c = 0; c < 3; c++) {
1147
+ let sum = 0;
1148
+ for (let i = -radius; i <= radius; i++) sum += source[at(line, Math.min(length - 1, Math.max(0, i))) + c];
1149
+ for (let i = 0; i < length; i++) {
1150
+ out[at(line, i) + c] = sum / span;
1151
+ const leaving = source[at(line, Math.max(0, i - radius)) + c];
1152
+ const entering = source[at(line, Math.min(length - 1, i + radius + 1)) + c];
1153
+ sum += entering - leaving;
1154
+ }
1155
+ }
1156
+ }
1157
+ return out;
1158
+ }
1159
+ function boxBlur(source, width, height, radius) {
1160
+ const r = Math.max(1, Math.round(radius / Math.sqrt(3)));
1161
+ let out = source;
1162
+ for (let pass = 0; pass < 3; pass++) {
1163
+ out = boxPass(out, width, height, r, true);
1164
+ out = boxPass(out, width, height, r, false);
1165
+ }
1166
+ return out;
1167
+ }
1168
+ function applyBloom(ctx, options = {}) {
1169
+ const canvas = ctx.canvas;
1170
+ const W = canvas.width;
1171
+ const H = canvas.height;
1172
+ if (!(W > 0 && H > 0)) return;
1173
+ const factor = Math.max(1, Math.round(options.downsample ?? 4));
1174
+ const w = Math.max(1, Math.ceil(W / factor));
1175
+ const h = Math.max(1, Math.ceil(H / factor));
1176
+ const small = canvasLike(ctx, w, h);
1177
+ const sctx = small?.getContext("2d");
1178
+ if (!small || !sctx) return;
1179
+ sctx.imageSmoothingEnabled = true;
1180
+ sctx.drawImage(ctx.canvas, 0, 0, w, h);
1181
+ const bright = brightPass(sctx.getImageData(0, 0, w, h).data, options.threshold ?? 0.55);
1182
+ const radius = (options.radius ?? Math.max(W, H) * 0.02) / factor;
1183
+ const glow = boxBlur(bright, w, h, radius);
1184
+ const wide = boxBlur(bright, w, h, radius * 3);
1185
+ const halo = options.halo ?? 0.6;
1186
+ const image = sctx.createImageData(w, h);
1187
+ for (let i = 0; i < w * h; i++) {
1188
+ for (let c = 0; c < 3; c++) image.data[i * 4 + c] = Math.round(Math.min(1, glow[i * 3 + c] + wide[i * 3 + c] * halo) * 255);
1189
+ image.data[i * 4 + 3] = 255;
1190
+ }
1191
+ sctx.putImageData(image, 0, 0);
1192
+ ctx.save();
1193
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
1194
+ ctx.globalCompositeOperation = "lighter";
1195
+ ctx.globalAlpha = Math.max(0, options.strength ?? 0.9);
1196
+ ctx.imageSmoothingEnabled = true;
1197
+ ctx.drawImage(small, 0, 0, W, H);
1198
+ ctx.restore();
1199
+ }
1121
1200
  class FrameRenderer {
1122
1201
  scene;
1123
1202
  fps;
@@ -1167,7 +1246,7 @@ class FrameRenderer {
1167
1246
  if (captions.length > 0) {
1168
1247
  return captions.map((cue, index) => ({ id: cue.id ?? `line-${index}`, time: (cue.start + cue.end) / 2 }));
1169
1248
  }
1170
- const markers = [...this.scene.timeline?.config.markers ?? []].sort((a, b) => a.time - b.time);
1249
+ const markers = [...this.scene.timeline?.config?.markers ?? []].sort((a, b) => a.time - b.time);
1171
1250
  if (markers.length === 0) return [{ id: "middle", time: this.duration / 2 }];
1172
1251
  return markers.map((marker, index) => {
1173
1252
  const end = index + 1 < markers.length ? markers[index + 1].time : this.duration;
@@ -1194,6 +1273,10 @@ class FrameRenderer {
1194
1273
  this.adapter.render(ctx);
1195
1274
  if (this.scene.draw) this.drawIsolated(ctx, this.scene.draw, frame);
1196
1275
  ctx.restore();
1276
+ if (this.scene.bloom) {
1277
+ const options = this.scene.bloom === true ? {} : this.scene.bloom;
1278
+ applyBloom(ctx, options.radius !== void 0 ? { ...options, radius: options.radius * this.scale } : options);
1279
+ }
1197
1280
  }
1198
1281
  /** Run scene code without letting its context changes leak into the rest. */
1199
1282
  drawIsolated(ctx, draw, frame) {
@@ -1294,6 +1377,48 @@ function sceneCaptions(scene, language) {
1294
1377
  if (scene.timeline) return captionCuesFromTimeline(scene.timeline, { language });
1295
1378
  return [];
1296
1379
  }
1380
+ function psnr(a, b) {
1381
+ if (a.length !== b.length) throw new Error("psnr: the images differ in size");
1382
+ let sum = 0;
1383
+ let count = 0;
1384
+ for (let i = 0; i < a.length; i += 4) {
1385
+ for (let c = 0; c < 3; c++) {
1386
+ const d = a[i + c] - b[i + c];
1387
+ sum += d * d;
1388
+ }
1389
+ count += 3;
1390
+ }
1391
+ if (sum === 0) return Infinity;
1392
+ return 10 * Math.log10(255 * 255 / (sum / count));
1393
+ }
1394
+ const CLOSED_DB = 40;
1395
+ const SEAM_SLACK_DB = 3;
1396
+ const db = (value) => Number.isFinite(value) ? `${value.toFixed(2)} dB` : "identical";
1397
+ function loopReport(frames) {
1398
+ const closure = psnr(frames.wrapped, frames.first);
1399
+ const seam = psnr(frames.last, frames.first);
1400
+ const steps = [psnr(frames.first, frames.second), psnr(frames.beforeLast, frames.last)];
1401
+ const worst = Math.min(...steps);
1402
+ if (closure >= CLOSED_DB) {
1403
+ return { closure, seam, steps, loops: true, verdict: `closes: the frame at the duration matches the first (${db(closure)}), so the seam is an ordinary step` };
1404
+ }
1405
+ if (seam >= worst - SEAM_SLACK_DB) {
1406
+ return {
1407
+ closure,
1408
+ seam,
1409
+ steps,
1410
+ loops: true,
1411
+ verdict: `seamless: the last → first step (${db(seam)}) is like an ordinary step (${db(worst)}), though the motion does not repeat exactly (${db(closure)})`
1412
+ };
1413
+ }
1414
+ return {
1415
+ closure,
1416
+ seam,
1417
+ steps,
1418
+ loops: false,
1419
+ verdict: `does not loop: the last → first step (${db(seam)}) differs much more than an ordinary step (${db(worst)}); make every motion repeat over the duration`
1420
+ };
1421
+ }
1297
1422
  let canvasModule;
1298
1423
  function loadCanvas() {
1299
1424
  canvasModule ??= import("@napi-rs/canvas").then(
@@ -1367,6 +1492,21 @@ async function renderStills(scene, options) {
1367
1492
  }
1368
1493
  return files;
1369
1494
  }
1495
+ async function checkLoop(scene, options = {}) {
1496
+ const { renderer, ctx } = await prepare(scene, options);
1497
+ const at = (time, index) => {
1498
+ renderer.render(ctx, time, index);
1499
+ return ctx.getImageData(0, 0, renderer.width, renderer.height).data.slice();
1500
+ };
1501
+ const last = renderer.frameCount - 1;
1502
+ return loopReport({
1503
+ first: at(0, 0),
1504
+ second: at(renderer.frameTime(1), 1),
1505
+ beforeLast: at(renderer.frameTime(Math.max(0, last - 1)), Math.max(0, last - 1)),
1506
+ last: at(renderer.frameTime(last), last),
1507
+ wrapped: at(renderer.duration, last + 1)
1508
+ });
1509
+ }
1370
1510
  function safeName(id) {
1371
1511
  return id.replace(/[^a-zA-Z0-9_-]+/g, "-") || "frame";
1372
1512
  }
@@ -1484,10 +1624,13 @@ function decodeAudio(file, options = {}) {
1484
1624
  });
1485
1625
  }
1486
1626
  export {
1627
+ CLOSED_DB,
1487
1628
  DEFAULT_FPS,
1488
1629
  FrameRenderer,
1630
+ SEAM_SLACK_DB,
1489
1631
  assembleNarration,
1490
1632
  captionCuesFromTimeline,
1633
+ checkLoop,
1491
1634
  decodeAudio,
1492
1635
  encodeWav,
1493
1636
  ffmpegArgs,
@@ -1495,6 +1638,8 @@ export {
1495
1638
  ffmpegExitError,
1496
1639
  ffmpegStartError,
1497
1640
  frameCount,
1641
+ loopReport,
1642
+ psnr,
1498
1643
  renderStills,
1499
1644
  renderVideo,
1500
1645
  sceneCaptions,
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Bloom: light spilling around what is bright, the glow of neon. Applied to
3
+ * a canvas after drawing: the bright parts are found at a reduced size,
4
+ * blurred twice (a tight glow and a wide halo) and added back over the
5
+ * picture.
6
+ *
7
+ * Deterministic: the blur is plain arithmetic (no `ctx.filter`), so the same
8
+ * frame blooms the same in every browser and in Node.
9
+ */
10
+ export interface BloomOptions {
11
+ /**
12
+ * How bright a pixel must be to glow, 0..1, by its brightest channel (so a
13
+ * saturated neon magenta counts as bright). Default 0.55.
14
+ */
15
+ threshold?: number;
16
+ /** How strongly the glow is added, 0.. (default 0.9) */
17
+ strength?: number;
18
+ /** The glow's reach, px at the canvas's size (default 2% of its larger side); the halo reaches 3× further */
19
+ radius?: number;
20
+ /** Work at 1/n of the size: faster and softer (default 4) */
21
+ downsample?: number;
22
+ /** How much of the wide halo joins the glow, 0..1 (default 0.6) */
23
+ halo?: number;
24
+ }
25
+ /**
26
+ * What glows: each pixel scaled by how far its brightest channel is past the
27
+ * threshold (keeping its hue), as linear RGB floats (3 per pixel).
28
+ */
29
+ export declare function brightPass(data: ArrayLike<number>, threshold: number): Float32Array;
30
+ /** A soft blur close to a Gaussian: three box blurs each way. */
31
+ export declare function boxBlur(source: Float32Array, width: number, height: number, radius: number): Float32Array;
32
+ /** Add a bloom to what is already drawn on `ctx` (its whole canvas, in device pixels). */
33
+ export declare function applyBloom(ctx: CanvasRenderingContext2D, options?: BloomOptions): void;
@@ -2,3 +2,5 @@ export * from './canvas-adapter';
2
2
  export * from './sketch';
3
3
  export * from './polyline';
4
4
  export * from './outline';
5
+ export * from './bloom';
6
+ export * from './offscreen';
@@ -0,0 +1,13 @@
1
+ /** A canvas that can be drawn on and drawn from: OffscreenCanvas, a DOM canvas, or a Node canvas. */
2
+ export interface CanvasLike {
3
+ width: number;
4
+ height: number;
5
+ getContext(kind: '2d'): unknown;
6
+ }
7
+ /**
8
+ * An offscreen canvas of the same kind as `ctx`'s: an OffscreenCanvas where
9
+ * there is one (browsers, Workers), else a DOM canvas from `ctx`'s document,
10
+ * else the same canvas class (`@napi-rs/canvas` in Node). Null when none can
11
+ * be made.
12
+ */
13
+ export declare function canvasLike(ctx: CanvasRenderingContext2D, width: number, height: number): CanvasLike | null;
@@ -47,6 +47,8 @@ export * from '../drivers';
47
47
  export * from '../interaction';
48
48
  export * from '../characters';
49
49
  export { tf, live, createLive, Stage, LiveTimeline, CompatTimeline, quickPlay, mapEase, CustomEase, CustomBounce, CustomWiggle, } from '../compat/gsap';
50
+ export { applyBloom } from '../adapters/canvas/bloom';
51
+ export type { BloomOptions } from '../adapters/canvas/bloom';
50
52
  export { createControls, DEFAULT_LABELS } from '../embed/controls';
51
53
  export type { Controls, ControlsOptions, ControlLabels, FullscreenControl } from '../embed/controls';
52
54
  export { mount, mountAll, unmount } from '../embed/mount';
@@ -9,4 +9,5 @@ export * from './scene-captions';
9
9
  export * from './node-video';
10
10
  export * from './narration-audio';
11
11
  export * from './node-audio';
12
+ export * from './loop-check';
12
13
  export { toSRT, toWebVTT, captionCuesFromTimeline, type CaptionCue } from '../engine/export/captions';
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Does a video loop? Pure measurements on rendered frames (RGBA bytes), so a
3
+ * loop can be checked without encoding anything.
4
+ *
5
+ * A loop closes when the frame at time = duration is the frame at time 0:
6
+ * every motion repeats over the duration. Then the step from the last frame
7
+ * back to the first is a step like any other. A loop with a cut, or one that
8
+ * drifts, shows a seam that differs much more than its ordinary steps.
9
+ */
10
+ /** Peak signal-to-noise ratio of two RGBA images (RGB only), dB; Infinity when identical. Higher is more alike. */
11
+ export declare function psnr(a: ArrayLike<number>, b: ArrayLike<number>): number;
12
+ export interface LoopFrames {
13
+ /** The frame at time 0 */
14
+ first: ArrayLike<number>;
15
+ /** The frame after it */
16
+ second: ArrayLike<number>;
17
+ /** The frame before the last */
18
+ beforeLast: ArrayLike<number>;
19
+ /** The last frame */
20
+ last: ArrayLike<number>;
21
+ /** The frame at time = duration: one frame past the end, where the loop comes back round */
22
+ wrapped: ArrayLike<number>;
23
+ }
24
+ export interface LoopReport {
25
+ /** The frame at time = duration against the first: Infinity (or very high) when every motion repeats */
26
+ closure: number;
27
+ /** The last frame → the first: the step a looping player shows */
28
+ seam: number;
29
+ /** Ordinary steps for comparison: first → second, before-last → last */
30
+ steps: [number, number];
31
+ /** True when the loop closes, or its seam differs no more than an ordinary step does */
32
+ loops: boolean;
33
+ /** Why, in a sentence */
34
+ verdict: string;
35
+ }
36
+ /** Above this the frames at 0 and at the duration count as the same picture. */
37
+ export declare const CLOSED_DB = 40;
38
+ /** A seam this much worse than the worse ordinary step stands out. */
39
+ export declare const SEAM_SLACK_DB = 3;
40
+ /** Judge a loop from its frames: does it close, and does its seam look like any other step? */
41
+ export declare function loopReport(frames: LoopFrames): LoopReport;
@@ -1,4 +1,5 @@
1
1
  import type { VideoScene } from './video-scene';
2
+ import { type LoopReport } from './loop-check';
2
3
  /** Options shared by video and stills rendering. */
3
4
  export interface HeadlessOptions {
4
5
  /** Directory that relative `audio` and font paths resolve against (default: cwd) */
@@ -46,3 +47,10 @@ export interface RenderStillsOptions extends HeadlessOptions {
46
47
  * encoding a video. Returns the written file paths.
47
48
  */
48
49
  export declare function renderStills(scene: VideoScene, options: RenderStillsOptions): Promise<string[]>;
50
+ /**
51
+ * Check that a scene loops, rendering only five frames: the first two, the
52
+ * last two, and the one at time = duration. See {@link loopReport}.
53
+ */
54
+ export declare function checkLoop(scene: VideoScene, options?: HeadlessOptions & {
55
+ fps?: number;
56
+ }): Promise<LoopReport>;
@@ -1,6 +1,6 @@
1
1
  import type { AnimationState, TimelineDefinition } from '../engine/types';
2
2
  import type { CaptionCue } from '../engine/export/captions';
3
- import type { CanvasTarget } from '../adapters/canvas';
3
+ import type { BloomOptions, CanvasTarget } from '../adapters/canvas';
4
4
  /**
5
5
  * A video scene: everything needed to render an animation to frames without a
6
6
  * browser.
@@ -33,6 +33,12 @@ export interface VideoScene {
33
33
  background?: string | DrawFunction;
34
34
  /** Immediate-mode drawing, called every frame after the targets */
35
35
  draw?: DrawFunction;
36
+ /**
37
+ * Glow around what is bright, added over each finished frame: `true` for
38
+ * the defaults, or options (threshold, strength, radius in scene px…).
39
+ * See `applyBloom`.
40
+ */
41
+ bloom?: boolean | BloomOptions;
36
42
  /** Soundtrack to mux into the video, relative to the scene file */
37
43
  audio?: string;
38
44
  /** Font files to register before drawing, by family, relative to the scene file */
@@ -185,7 +185,8 @@ export interface Material3D {
185
185
  width: number;
186
186
  color: string;
187
187
  };
188
+ /** Light the surface gives off itself, added after lighting (both modes): neon, screens, lamps; feeds bloom */
189
+ emissive?: string;
188
190
  roughness?: number;
189
191
  metalness?: number;
190
- emissive?: string;
191
192
  }
@@ -20,6 +20,7 @@ export declare function packLights(lights: ResolvedLight[]): LightUniforms;
20
20
  /** A material's numbers for the surface shader, with an object's own colour and opacity over it. */
21
21
  export declare function surfaceUniforms(material: Material3D, color: string | undefined, opacity: number): {
22
22
  color: import("../shading").Rgb;
23
+ emissive: [number, number, number];
23
24
  opacity: number;
24
25
  shading: 0 | 2 | 1 | 3;
25
26
  bands: number;
@@ -19,7 +19,7 @@ export declare const LIGHT_CODE: {
19
19
  readonly spot: 3;
20
20
  };
21
21
  export declare const SURFACE_VERTEX = "#version 300 es\nin vec3 a_position;\nin vec3 a_normal;\nuniform mat4 u_model;\nuniform mat4 u_view;\nuniform mat4 u_projection;\nuniform mat3 u_normalMatrix;\nout vec3 v_world;\nout vec3 v_normal;\nvoid main() {\n vec4 world = u_model * vec4(a_position, 1.0);\n v_world = world.xyz;\n v_normal = u_normalMatrix * a_normal;\n gl_Position = u_projection * u_view * world;\n}\n";
22
- export declare const SURFACE_FRAGMENT = "#version 300 es\nprecision highp float;\n#define MAX_LIGHTS 8\nuniform int u_lightCount;\nuniform int u_lightKind[MAX_LIGHTS];\nuniform vec3 u_lightColor[MAX_LIGHTS];\nuniform float u_lightIntensity[MAX_LIGHTS];\nuniform vec3 u_lightPosition[MAX_LIGHTS];\nuniform vec3 u_lightDirection[MAX_LIGHTS];\nuniform float u_lightRange[MAX_LIGHTS];\nuniform vec2 u_lightCone[MAX_LIGHTS];\nuniform vec3 u_color;\nuniform float u_opacity;\nuniform int u_shading;\nuniform float u_bands;\nuniform vec3 u_eye;\nuniform vec3 u_forward;\nuniform bool u_orthographic;\nuniform bool u_fog;\nuniform vec3 u_fogColor;\nuniform vec2 u_fogRange;\nin vec3 v_world;\nin vec3 v_normal;\nout vec4 outColor;\n\nvec3 lightAt(vec3 p, vec3 n) {\n vec3 total = vec3(0.0);\n for (int i = 0; i < MAX_LIGHTS; i++) {\n if (i >= u_lightCount) break;\n float amount;\n int kind = u_lightKind[i];\n if (kind == 0) {\n amount = u_lightIntensity[i];\n } else if (kind == 1) {\n amount = u_lightIntensity[i] * max(0.0, -dot(n, u_lightDirection[i]));\n } else {\n vec3 toLight = u_lightPosition[i] - p;\n float distance = length(toLight);\n vec3 l = distance > 0.0 ? toLight / distance : n;\n float fade = u_lightRange[i] > 0.0 ? pow(max(0.0, 1.0 - distance / u_lightRange[i]), 2.0) : 1.0;\n amount = u_lightIntensity[i] * max(0.0, dot(n, l)) * fade;\n if (kind == 3) amount *= smoothstep(u_lightCone[i].x, u_lightCone[i].y, -dot(l, u_lightDirection[i]));\n }\n total += u_lightColor[i] * amount;\n }\n return total;\n}\n\nvoid main() {\n vec3 rgb = u_color;\n if (u_shading != 0) {\n // Flat: the face's own normal, from the surface's slope; otherwise the smooth one.\n vec3 n = u_shading == 1 ? normalize(cross(dFdx(v_world), dFdy(v_world))) : normalize(v_normal);\n vec3 toEye = u_orthographic ? -u_forward : normalize(u_eye - v_world);\n if (dot(n, toEye) < 0.0) n = -n;\n vec3 light = lightAt(v_world, n);\n if (u_shading == 3) {\n // Band the brightness, not each channel, so coloured lights keep their hue.\n float level = max(light.r, max(light.g, light.b));\n float steps = max(2.0, floor(u_bands + 0.5));\n float banded = min(1.2, ceil(min(1.0, level) * steps - 1e-6) / steps);\n light = level > 0.0 ? light * (banded / level) : vec3(0.0);\n }\n rgb *= light;\n }\n if (u_fog) {\n float amount = clamp((distance(v_world, u_eye) - u_fogRange.x) / (u_fogRange.y - u_fogRange.x), 0.0, 1.0);\n rgb = mix(rgb, u_fogColor, amount);\n }\n outColor = vec4(clamp(rgb, 0.0, 1.0), u_opacity);\n}\n";
22
+ export declare const SURFACE_FRAGMENT = "#version 300 es\nprecision highp float;\n#define MAX_LIGHTS 8\nuniform int u_lightCount;\nuniform int u_lightKind[MAX_LIGHTS];\nuniform vec3 u_lightColor[MAX_LIGHTS];\nuniform float u_lightIntensity[MAX_LIGHTS];\nuniform vec3 u_lightPosition[MAX_LIGHTS];\nuniform vec3 u_lightDirection[MAX_LIGHTS];\nuniform float u_lightRange[MAX_LIGHTS];\nuniform vec2 u_lightCone[MAX_LIGHTS];\nuniform vec3 u_color;\nuniform vec3 u_emissive;\nuniform float u_opacity;\nuniform int u_shading;\nuniform float u_bands;\nuniform vec3 u_eye;\nuniform vec3 u_forward;\nuniform bool u_orthographic;\nuniform bool u_fog;\nuniform vec3 u_fogColor;\nuniform vec2 u_fogRange;\nin vec3 v_world;\nin vec3 v_normal;\nout vec4 outColor;\n\nvec3 lightAt(vec3 p, vec3 n) {\n vec3 total = vec3(0.0);\n for (int i = 0; i < MAX_LIGHTS; i++) {\n if (i >= u_lightCount) break;\n float amount;\n int kind = u_lightKind[i];\n if (kind == 0) {\n amount = u_lightIntensity[i];\n } else if (kind == 1) {\n amount = u_lightIntensity[i] * max(0.0, -dot(n, u_lightDirection[i]));\n } else {\n vec3 toLight = u_lightPosition[i] - p;\n float distance = length(toLight);\n vec3 l = distance > 0.0 ? toLight / distance : n;\n float fade = u_lightRange[i] > 0.0 ? pow(max(0.0, 1.0 - distance / u_lightRange[i]), 2.0) : 1.0;\n amount = u_lightIntensity[i] * max(0.0, dot(n, l)) * fade;\n if (kind == 3) amount *= smoothstep(u_lightCone[i].x, u_lightCone[i].y, -dot(l, u_lightDirection[i]));\n }\n total += u_lightColor[i] * amount;\n }\n return total;\n}\n\nvoid main() {\n vec3 rgb = u_color;\n if (u_shading != 0) {\n // Flat: the face's own normal, from the surface's slope; otherwise the smooth one.\n vec3 n = u_shading == 1 ? normalize(cross(dFdx(v_world), dFdy(v_world))) : normalize(v_normal);\n vec3 toEye = u_orthographic ? -u_forward : normalize(u_eye - v_world);\n if (dot(n, toEye) < 0.0) n = -n;\n vec3 light = lightAt(v_world, n);\n if (u_shading == 3) {\n // Band the brightness, not each channel, so coloured lights keep their hue.\n float level = max(light.r, max(light.g, light.b));\n float steps = max(2.0, floor(u_bands + 0.5));\n float banded = min(1.2, ceil(min(1.0, level) * steps - 1e-6) / steps);\n light = level > 0.0 ? light * (banded / level) : vec3(0.0);\n }\n rgb *= light;\n }\n rgb += u_emissive;\n if (u_fog) {\n float amount = clamp((distance(v_world, u_eye) - u_fogRange.x) / (u_fogRange.y - u_fogRange.x), 0.0, 1.0);\n rgb = mix(rgb, u_fogColor, amount);\n }\n outColor = vec4(clamp(rgb, 0.0, 1.0), u_opacity);\n}\n";
23
23
  /**
24
24
  * Ink outlines by the inverted hull: each mesh again, its back faces only,
25
25
  * pushed out along their normals by the outline's width in pixels, in the
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@algorisys/tinyfly",
3
- "version": "0.86.2",
3
+ "version": "0.87.0",
4
4
  "type": "module",
5
5
  "description": "Lightweight, API-driven animation engine and editor. The engine is framework-agnostic and runs in browsers, Web Workers, and Node.",
6
6
  "license": "MIT",
@@ -1,85 +0,0 @@
1
- import { vec3 as f } from "@algorisys/tinyfly";
2
- const p = /* @__PURE__ */ new Map();
3
- function b(t) {
4
- const o = p.get(t);
5
- if (o) return o;
6
- let c = [1, 1, 1];
7
- const e = t.trim().replace("#", "");
8
- if (t.trim().startsWith("#") && (e.length === 3 || e.length === 6)) {
9
- const n = e.length === 3 ? e.split("").map((i) => i + i).join("") : e;
10
- c = [0, 2, 4].map((i) => Number.parseInt(n.slice(i, i + 2), 16) / 255);
11
- } else {
12
- const n = t.match(/rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)/);
13
- n && (c = [Number(n[1]) / 255, Number(n[2]) / 255, Number(n[3]) / 255]);
14
- }
15
- return p.size < 512 && p.set(t, c), c;
16
- }
17
- const x = [
18
- { id: "default-ambient", light: "ambient", color: "#ffffff", intensity: 0.35, position: [0, 0, 0], direction: [0, -1, 0], angle: 30 },
19
- { id: "default-key", light: "directional", color: "#ffffff", intensity: 0.8, position: [3, 5, 4], direction: f.normalize([-3, -5, -4]), angle: 30 }
20
- ], y = (t, o, c) => {
21
- const e = Math.min(1, Math.max(0, (c - t) / (o - t)));
22
- return e * e * (3 - 2 * e);
23
- };
24
- function g(t, o, c) {
25
- const e = [0, 0, 0];
26
- for (const n of c) {
27
- const i = b(n.color);
28
- let r;
29
- if (n.light === "ambient")
30
- r = n.intensity;
31
- else if (n.light === "directional")
32
- r = n.intensity * Math.max(0, -f.dot(o, n.direction));
33
- else {
34
- const a = f.subtract(n.position, t), m = f.length(a), d = m > 0 ? f.scale(a, 1 / m) : o, l = n.range ? Math.max(0, 1 - m / n.range) ** 2 : 1;
35
- if (r = n.intensity * Math.max(0, f.dot(o, d)) * l, n.light === "spot") {
36
- const s = Math.cos(n.angle * Math.PI / 180), h = Math.cos(n.angle * 0.8 * Math.PI / 180);
37
- r *= y(s, h, -f.dot(d, n.direction));
38
- }
39
- }
40
- e[0] += i[0] * r, e[1] += i[1] * r, e[2] += i[2] * r;
41
- }
42
- return e;
43
- }
44
- function N(t, o) {
45
- const c = Math.max(2, Math.round(o));
46
- return Math.min(1.2, Math.ceil(Math.min(1, t) * c - 1e-9) / c);
47
- }
48
- function v(t, o) {
49
- return t ? Math.min(1, Math.max(0, (o - t.near) / (t.far - t.near))) : 0;
50
- }
51
- function C(t, o, c, e) {
52
- const n = t.material, i = b(t.color ?? n.color), r = n.shading ?? "lambert";
53
- let a;
54
- if (r === "unlit")
55
- a = [...i];
56
- else {
57
- const l = o.length > 0 ? o : x;
58
- let s;
59
- if (r === "lambert") {
60
- const h = [0, 0, 0];
61
- for (const u of t.vertexNormals) {
62
- const M = g(t.centroid, u, l);
63
- h[0] += M[0] / 3, h[1] += M[1] / 3, h[2] += M[2] / 3;
64
- }
65
- s = h;
66
- } else if (s = g(t.centroid, t.normal, l), r === "toon") {
67
- const h = Math.max(s[0], s[1], s[2]), u = h > 0 ? N(h, n.bands ?? 3) / h : 0;
68
- s = [s[0] * u, s[1] * u, s[2] * u];
69
- }
70
- a = [i[0] * s[0], i[1] * s[1], i[2] * s[2]];
71
- }
72
- const m = v(e, f.distance(t.centroid, c.position));
73
- if (e && m > 0) {
74
- const l = b(e.color);
75
- a = [a[0] + (l[0] - a[0]) * m, a[1] + (l[1] - a[1]) * m, a[2] + (l[2] - a[2]) * m];
76
- }
77
- const d = (l) => Math.round(Math.min(1, Math.max(0, l)) * 255);
78
- return { color: `rgb(${d(a[0])}, ${d(a[1])}, ${d(a[2])})`, alpha: t.opacity };
79
- }
80
- export {
81
- v as f,
82
- g as l,
83
- b as p,
84
- C as s
85
- };