@neta-art/cohub-cli 10.18.0 → 10.20.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.
@@ -5909,6 +5909,7 @@ const itemEnvelope$1 = {
5909
5909
  y: .5
5910
5910
  }).describe("Rotation and scale origin as fractions of the size."),
5911
5911
  opacity: ratio$1.default(1),
5912
+ visible: boolean().optional().describe("false hides the item and its children; key it on a timeline to show the item only for a span."),
5912
5913
  style: BoardStyleSchema$1.default({}),
5913
5914
  locked: boolean().optional(),
5914
5915
  metadata: record(string(), unknown()).optional()
@@ -6058,7 +6059,8 @@ const mediaProps$1 = {
6058
6059
  };
6059
6060
  const timedFileProps$1 = {
6060
6061
  ...mediaProps$1,
6061
- time: nonNegative$1.optional().describe("Playback position in milliseconds; animate props.time to play it on a timeline.")
6062
+ time: nonNegative$1.optional().describe("Playback position in milliseconds; animate props.time to play it on a timeline. It sounds while its time moves forward."),
6063
+ volume: ratio$1.optional().describe("Loudness from 0 to 1; defaults to 1. Animate it to fade.")
6062
6064
  };
6063
6065
  const BoardCropSchema$1 = object({
6064
6066
  x: ratio$1,
@@ -7197,6 +7199,10 @@ function resolveBoardProperty(targetType, property) {
7197
7199
  ok: false,
7198
7200
  message: `Board scripts animate params.<name>, not ${property}`
7199
7201
  };
7202
+ if (/^script\.params\.[^.]+$/.test(property)) return {
7203
+ ok: true,
7204
+ spec: SCRIPT_PARAMETER
7205
+ };
7200
7206
  const path = property.split(".");
7201
7207
  if (path.some((segment) => !segment) || NOT_ANIMATABLE.has(path[0])) return {
7202
7208
  ok: false,
@@ -7586,6 +7592,7 @@ function validateTrack(path, animationId, value, item, animation, track, script,
7586
7592
  if (value.target === animationId || nestsInto(value.target, animationId, animation, track, state)) return [error(`${path}.target`, "ANIMATION_CYCLE", `${animationId} cannot contain itself through ${value.target}`)];
7587
7593
  } else if (script(value.target)) targetType = "script";
7588
7594
  else return [error(`${path}.target`, "TARGET_NOT_FOUND", `target ${value.target} is not an item, animation, Board script or camera`)];
7595
+ if (!keepUnknownProperty && value.property.startsWith("script.") && !item(value.target)?.script) return [error(`${path}.property`, "INVALID_PROPERTY", `${value.target} has no script to animate`)];
7589
7596
  const resolved = resolveBoardProperty(targetType, value.property);
7590
7597
  if (!resolved.ok) return keepUnknownProperty ? [] : [error(`${path}.property`, "INVALID_PROPERTY", resolved.message)];
7591
7598
  for (const [index, keyframe] of value.keyframes.entries()) {
@@ -8532,6 +8539,12 @@ function boardShaderUniformValue(uniform, value) {
8532
8539
  while (list.length < size) list.push(0);
8533
8540
  return list;
8534
8541
  }
8542
+ function boardShaderPassLayer(shader, pass) {
8543
+ return pass.layer ?? shader.layer ?? "above";
8544
+ }
8545
+ function boardShaderPassOn(pass, states) {
8546
+ return (pass.name !== void 0 ? states?.[pass.name] : void 0) ?? pass.enabled ?? true;
8547
+ }
8535
8548
  function boardShaderParameters(parameters) {
8536
8549
  const result = [];
8537
8550
  for (const [name, spec] of Object.entries(parameters ?? {})) {
@@ -8553,13 +8566,22 @@ function validateBoardShader(shader) {
8553
8566
  if (value.layer !== void 0 && !BOARD_SHADER_LAYERS.includes(value.layer)) throw new Error(`shader.layer must be ${BOARD_SHADER_LAYERS.join(", ")}.`);
8554
8567
  if (value.surfaces !== void 0 && typeof value.surfaces !== "boolean") throw new Error("shader.surfaces must be a boolean.");
8555
8568
  if (!Array.isArray(value.passes) || value.passes.length < 1 || value.passes.length > BOARD_SHADER_LIMITS.passes) throw new Error(`shader.passes takes 1 to ${BOARD_SHADER_LIMITS.passes} passes.`);
8569
+ const names = /* @__PURE__ */ new Set();
8556
8570
  for (const pass of value.passes) {
8557
8571
  if (!pass || typeof pass.glsl !== "string" || !pass.glsl.trim()) throw new Error("Each shader pass needs glsl source.");
8558
8572
  if (pass.glsl.length > BOARD_SHADER_LIMITS.source) throw new Error("A shader pass exceeds 64 KB of source.");
8573
+ if (pass.layer !== void 0 && !BOARD_SHADER_LAYERS.includes(pass.layer)) throw new Error(`A pass layer must be ${BOARD_SHADER_LAYERS.join(", ")}.`);
8559
8574
  if (pass.sprites !== void 0) {
8560
8575
  if (!Number.isSafeInteger(pass.sprites) || pass.sprites < 1 || pass.sprites > BOARD_SHADER_LIMITS.sprites) throw new Error(`sprites must be an integer from 1 to ${BOARD_SHADER_LIMITS.sprites}.`);
8561
- if (value.layer === "filter") throw new Error("Filter passes draw over the owner's box; they cannot draw sprites.");
8576
+ if (boardShaderPassLayer(value, pass) === "filter") throw new Error("Filter passes draw over the owner's box; they cannot draw sprites.");
8577
+ }
8578
+ if (pass.name !== void 0) {
8579
+ if (typeof pass.name !== "string" || !IDENTIFIER.test(pass.name)) throw new Error(`Invalid pass name: ${String(pass.name)}`);
8580
+ if (names.has(pass.name)) throw new Error(`Pass names must be unique: ${pass.name}`);
8581
+ names.add(pass.name);
8562
8582
  }
8583
+ if (pass.enabled !== void 0 && typeof pass.enabled !== "boolean") throw new Error("A pass's enabled must be a boolean.");
8584
+ if (pass.enabled === false && pass.name === void 0) throw new Error("A pass that starts off needs a name to turn it on.");
8563
8585
  if (pass.blend !== void 0 && !BOARD_SHADER_BLENDS.includes(pass.blend)) throw new Error(`blend must be ${BOARD_SHADER_BLENDS.join(", ")}.`);
8564
8586
  }
8565
8587
  boardShaderUniforms(value.uniforms);
@@ -8976,42 +8998,46 @@ function bindingsFor(owner, output) {
8976
8998
  function boardScriptTarget(scene, candidates, point, outputs, hitTest) {
8977
8999
  const declared = [...outputs].map(([owner, output]) => bindingsFor(owner, output));
8978
9000
  const prefixes = [...outputs.keys()].map(scriptTemporaryPrefix);
8979
- for (const id of [...candidates].sort((a, b) => scene.indexOf(b) - scene.indexOf(a))) {
8980
- const item = scene.get(id);
8981
- if (!item || scene.opacity(id) <= 0) continue;
8982
- let parent = item.parent;
8983
- let clipped = false;
8984
- for (let depth = 0; parent && depth < 64; depth++) {
8985
- const ancestor = scene.get(parent);
8986
- if (!ancestor) break;
8987
- if (ancestor.type === "frame" && ancestor.props.clip && !frameContainsPoint(ancestor.frame, point)) {
8988
- clipped = true;
8989
- break;
8990
- }
8991
- parent = ancestor.parent;
8992
- }
8993
- if (clipped) continue;
8994
- for (const byItem of declared) {
8995
- const hits = byItem.get(id);
8996
- if (!hits) continue;
8997
- const local = applyMatrix$1(invertMatrix(scene.layout.matrix(id)), point);
8998
- for (let i = hits.length - 1; i >= 0; i--) {
8999
- const binding = hits[i];
9000
- if (!binding) continue;
9001
- const resolved = resolveBoardScriptHit(scene, binding.owner, binding.hit);
9002
- if (!resolved) continue;
9003
- const r = resolved.rect;
9004
- if (local.x >= r.x && local.y >= r.y && local.x <= r.x + r.width && local.y <= r.y + r.height && ("x" in binding.hit || hitTest(item, point))) return {
9005
- owner: binding.owner,
9006
- target: binding.target
9007
- };
9001
+ const ordered = [...candidates].sort((a, b) => scene.indexOf(b) - scene.indexOf(a));
9002
+ const scan = (over) => {
9003
+ for (const id of ordered) {
9004
+ const item = scene.get(id);
9005
+ if (!item || scene.opacity(id) <= 0) continue;
9006
+ let parent = item.parent;
9007
+ let clipped = false;
9008
+ for (let depth = 0; parent && depth < 64; depth++) {
9009
+ const ancestor = scene.get(parent);
9010
+ if (!ancestor) break;
9011
+ if (ancestor.type === "frame" && ancestor.props.clip && !frameContainsPoint(ancestor.frame, point)) {
9012
+ clipped = true;
9013
+ break;
9014
+ }
9015
+ parent = ancestor.parent;
9016
+ }
9017
+ if (clipped) continue;
9018
+ for (const byItem of declared) {
9019
+ const hits = byItem.get(id);
9020
+ if (!hits) continue;
9021
+ const local = applyMatrix$1(invertMatrix(scene.layout.matrix(id)), point);
9022
+ for (let i = hits.length - 1; i >= 0; i--) {
9023
+ const binding = hits[i];
9024
+ if (!binding || over && !binding.hit.over) continue;
9025
+ const resolved = resolveBoardScriptHit(scene, binding.owner, binding.hit);
9026
+ if (!resolved) continue;
9027
+ const r = resolved.rect;
9028
+ if (local.x >= r.x && local.y >= r.y && local.x <= r.x + r.width && local.y <= r.y + r.height && ("x" in binding.hit || hitTest(item, point))) return {
9029
+ owner: binding.owner,
9030
+ target: binding.target
9031
+ };
9032
+ }
9008
9033
  }
9034
+ if (over || prefixes.some((prefix) => id.startsWith(prefix))) continue;
9035
+ if (item.type === "frame" && item.props.decoration === "none") continue;
9036
+ if (hitTest(item, point)) return null;
9009
9037
  }
9010
- if (prefixes.some((prefix) => id.startsWith(prefix))) continue;
9011
- if (item.type === "frame" && item.props.decoration === "none") continue;
9012
- if (hitTest(item, point)) return null;
9013
- }
9014
- return null;
9038
+ return null;
9039
+ };
9040
+ return ([...outputs.values()].some((output) => Object.values(output.hits).some((hit) => hit.over)) ? scan(true) : null) ?? scan(false);
9015
9041
  }
9016
9042
  //#endregion
9017
9043
  //#region ../sdk/src/board/model/script-example.ts
@@ -9056,10 +9082,10 @@ const glsl = \`
9056
9082
  const float SPEED = 1400.0; // screen pixels per second, at any zoom
9057
9083
  const float SPLASH = 0.38; // seconds a splash lasts
9058
9084
 
9059
- struct Drop { vec2 start; vec2 heading; float reach; float age; float landing; bool lands; };
9085
+ struct Drop { vec2 start; vec2 heading; float reach; float travelled; float landing; bool lands; };
9060
9086
 
9061
9087
  // Drops respawn every cycle at new seeded places, anywhere in view.
9062
- Drop drop(int index, float pixel) {
9088
+ Drop drop(int index, float pixel, bool streak) {
9063
9089
  float speed = SPEED * pixel;
9064
9090
  float cycle = board.view.w * 0.6 / speed + SPLASH;
9065
9091
  float clock = board.time + hash(index, 7) * cycle;
@@ -9068,17 +9094,18 @@ Drop drop(int index, float pixel) {
9068
9094
  d.heading = normalize(vec2(params.wind, 1.0));
9069
9095
  d.start = board.view.xy + vec2(hash(key, 1) * 1.2 - 0.1, hash(key, 2) * 0.9 - 0.15) * board.view.zw;
9070
9096
  d.reach = (0.25 + hash(key, 3) * 0.55) * board.view.w;
9071
- d.age = mod(clock, cycle);
9097
+ d.travelled = mod(clock, cycle) * speed;
9072
9098
  d.lands = false;
9073
9099
  d.landing = d.reach;
9074
9100
  if (surface(d.start).inside) { d.reach = 0.0; return d; }
9101
+ float limit = min(d.reach, streak ? d.travelled + 0.15 * d.reach : d.travelled);
9075
9102
  // Sphere-trace the item edges along the drop's path.
9076
- float travelled = 0.0;
9103
+ float ahead = 0.0;
9077
9104
  for (int i = 0; i < 40 && params.splash > 0.5; i++) {
9078
- float gap = surface(d.start + d.heading * travelled).distance;
9079
- if (gap < pixel) { d.lands = true; d.landing = travelled; break; }
9080
- travelled += max(gap, 2.0 * pixel);
9081
- if (travelled > d.reach) break;
9105
+ float gap = surface(d.start + d.heading * ahead).distance;
9106
+ if (gap < pixel) { d.lands = true; d.landing = ahead; break; }
9107
+ ahead += max(gap, 2.0 * pixel);
9108
+ if (ahead > limit) break;
9082
9109
  }
9083
9110
  return d;
9084
9111
  }
@@ -9087,15 +9114,14 @@ Sprite sprite(int id) {
9087
9114
  int index = id / PARTS;
9088
9115
  int part = id - index * PARTS;
9089
9116
  Sprite s = makeSprite(vec2(0.0), vec2(0.0));
9090
- if (hash(index, 11) > params.density) { s.visible = false; return s; }
9117
+ if (hash(index, 11) > params.density || (part > 0 && params.splash < 0.5)) { s.visible = false; return s; }
9091
9118
  float pixel = 1.0 / board.zoom;
9092
9119
  vec4 tint = board.dark > 0.5 ? vec4(0.75, 0.84, 1.0, 0.5) : vec4(0.3, 0.4, 0.55, 0.45);
9093
- Drop d = drop(index, pixel);
9094
- float travelled = d.age * SPEED * pixel;
9120
+ Drop d = drop(index, pixel, part == 0);
9095
9121
  if (part == 0) {
9096
9122
  float end = d.lands ? d.landing : d.reach;
9097
- float head = min(travelled, end);
9098
- float tail = max(0.0, head - 34.0 * pixel);
9123
+ float head = min(d.travelled, end);
9124
+ float tail = max(0.0, d.travelled - 34.0 * pixel);
9099
9125
  s.visible = head > tail;
9100
9126
  vec2 a = d.start + d.heading * tail;
9101
9127
  vec2 b = d.start + d.heading * head;
@@ -9106,7 +9132,7 @@ Sprite sprite(int id) {
9106
9132
  s.color = vec4(tint.rgb, tint.a * smoothstep(0.0, 0.08 * d.reach, head) * fade);
9107
9133
  return s;
9108
9134
  }
9109
- float age = (travelled - d.landing) / (SPEED * pixel);
9135
+ float age = (d.travelled - d.landing) / (SPEED * pixel);
9110
9136
  if (!d.lands || age < 0.0 || age > SPLASH) { s.visible = false; return s; }
9111
9137
  vec2 hit = d.start + d.heading * d.landing;
9112
9138
  vec2 normal = surface(hit - d.heading * 2.0 * pixel).normal;
@@ -9219,10 +9245,10 @@ function parameterKind(track) {
9219
9245
  if (values.every((value) => BoardColorSchema$1.safeParse(value).success)) return "color";
9220
9246
  return "discrete";
9221
9247
  }
9222
- function compileTrack(animationId, id, track, targetType) {
9248
+ function compileBoardTrack(animationId, id, track, targetType) {
9223
9249
  const resolved = resolveBoardProperty(targetType, track.property);
9224
9250
  if (!resolved.ok) return null;
9225
- const kind = targetType === "script" ? parameterKind(track) : resolved.spec.kind;
9251
+ const kind = targetType === "script" || track.property.startsWith("script.params.") ? parameterKind(track) : resolved.spec.kind;
9226
9252
  const times = new Float64Array(track.keyframes.length);
9227
9253
  const values = [];
9228
9254
  const eases = [];
@@ -9277,7 +9303,7 @@ function compileAnimation(animationId, animation, document) {
9277
9303
  for (const [id, track] of Object.entries(tracks).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) {
9278
9304
  const targetType = track.target === "camera" ? BOARD_CAMERA_TARGET$1 : document.animations[track.target] ? "animation" : document.board.scripts?.[track.target] ? "script" : document.items[track.target]?.type;
9279
9305
  if (!targetType) continue;
9280
- const entry = compileTrack(animationId, id, track, targetType);
9306
+ const entry = compileBoardTrack(animationId, id, track, targetType);
9281
9307
  if (!entry) continue;
9282
9308
  (targetType === "animation" ? children : compiled).push(entry);
9283
9309
  }
@@ -9512,10 +9538,14 @@ function evaluateBoardAnimations(compiled, times, options = {}) {
9512
9538
  const ordered = [...groups.values()].sort((a, b) => a.path.length - b.path.length);
9513
9539
  for (const group of ordered) {
9514
9540
  const isCamera = group.target === BOARD_CAMERA_TARGET$1;
9515
- const script = isCamera ? void 0 : scripts.get(group.target) ?? compiled.document.board.scripts?.[group.target];
9541
+ const rootScript = isCamera ? void 0 : compiled.document.board.scripts?.[group.target];
9542
+ const itemScript = isCamera || rootScript || group.path[0] !== "script" ? void 0 : compiled.document.items[group.target]?.script;
9543
+ const script = rootScript || itemScript ? scripts.get(group.target) ?? rootScript ?? itemScript : void 0;
9544
+ if (group.path[0] === "script" && !itemScript) continue;
9545
+ const path = itemScript ? group.path.slice(1) : group.path;
9516
9546
  const base = isCamera || script ? void 0 : items.get(group.target) ?? compiled.document.items[group.target];
9517
9547
  if (!isCamera && !script && !base) continue;
9518
- let value = isCamera ? camera[group.path[0]] : readPath$1(script ?? base, group.path);
9548
+ let value = isCamera ? camera[path[0]] : readPath$1(script ?? base, path);
9519
9549
  let orientTrack = null;
9520
9550
  if (group.winner) {
9521
9551
  value = sampleBoardTrack(group.winner, group.winnerTime, resolveColor);
@@ -9530,7 +9560,7 @@ function evaluateBoardAnimations(compiled, times, options = {}) {
9530
9560
  continue;
9531
9561
  }
9532
9562
  if (script) {
9533
- scripts.set(group.target, writePath$1(script, group.path, value));
9563
+ scripts.set(group.target, writePath$1(script, path, value));
9534
9564
  continue;
9535
9565
  }
9536
9566
  let next = writePath$1(base, group.path, value);
@@ -9550,49 +9580,61 @@ function evaluateBoardAnimations(compiled, times, options = {}) {
9550
9580
  times: local
9551
9581
  };
9552
9582
  }
9583
+ const BOARD_SCRIPT_HISTORY_MS = 1e3 / 30;
9584
+ function boardAnimatesScriptParams(document) {
9585
+ return Object.values(document.animations).some((animation) => Object.values(animation.tracks).some((track) => /^(script\.)?params\./.test(track.property)));
9586
+ }
9553
9587
  function withBoardScripts(document, scripts) {
9588
+ if (scripts.size === 0) return document;
9554
9589
  const stored = document.board.scripts;
9555
- if (scripts.size === 0 || !stored) return document;
9556
- const next = { ...stored };
9590
+ let board = document.board;
9591
+ let items = document.items;
9557
9592
  for (const [id, script] of scripts) {
9558
- const base = stored[id];
9559
- if (base) next[id] = {
9560
- ...base,
9561
- params: script.params
9593
+ const root = stored?.[id];
9594
+ if (root) {
9595
+ if (board === document.board) board = {
9596
+ ...board,
9597
+ scripts: { ...stored }
9598
+ };
9599
+ board.scripts[id] = {
9600
+ ...root,
9601
+ params: script.params
9602
+ };
9603
+ continue;
9604
+ }
9605
+ const item = items[id];
9606
+ if (!item?.script) continue;
9607
+ if (items === document.items) items = { ...items };
9608
+ items[id] = {
9609
+ ...item,
9610
+ script: {
9611
+ ...item.script,
9612
+ params: script.params
9613
+ }
9562
9614
  };
9563
9615
  }
9564
- return {
9616
+ return board === document.board && items === document.items ? document : {
9565
9617
  ...document,
9566
- board: {
9567
- ...document.board,
9568
- scripts: next
9569
- }
9618
+ board,
9619
+ items
9570
9620
  };
9571
9621
  }
9572
9622
  function applyBoardEvaluation(document, evaluation) {
9573
9623
  const scripted = withBoardScripts(document, evaluation.scripts);
9574
9624
  if (evaluation.items.size === 0) return scripted;
9575
- const items = { ...document.items };
9576
- for (const [id, item] of evaluation.items) items[id] = item;
9625
+ const items = { ...scripted.items };
9626
+ for (const [id, item] of evaluation.items) {
9627
+ const script = scripted.items[id]?.script;
9628
+ items[id] = script && script !== document.items[id]?.script ? {
9629
+ ...item,
9630
+ script
9631
+ } : item;
9632
+ }
9577
9633
  return {
9578
9634
  ...scripted,
9579
9635
  items
9580
9636
  };
9581
9637
  }
9582
- function boardDocumentAt(document, animationId, time, options = {}) {
9583
- const compiled = compileBoardAnimations(document);
9584
- const times = /* @__PURE__ */ new Map();
9585
- for (const [id, animation] of compiled.animations) if (animation.header.play === "always") times.set(id, boardAnimationTime(animation.header, time) ?? 0);
9586
- if (animationId) {
9587
- const animation = compiled.animations.get(animationId);
9588
- if (animation) times.set(animationId, Math.min(Math.max(0, time), animation.header.duration));
9589
- }
9590
- const evaluation = evaluateBoardAnimations(compiled, times, options);
9591
- return {
9592
- document: applyBoardEvaluation(document, evaluation),
9593
- evaluation
9594
- };
9595
- }
9596
9638
  //#endregion
9597
9639
  //#region ../sdk/src/board/model/scene.ts
9598
9640
  const EPSILON = 1e-6;
@@ -9680,16 +9722,18 @@ function buildBoardScene(document, previous) {
9680
9722
  return result;
9681
9723
  },
9682
9724
  binders: (id) => binders.get(id) ?? [],
9683
- opacity: (id) => cumulativeOpacity((key) => items[key], id)
9725
+ opacity: (id) => cumulativeOpacity((key) => items[key], id),
9726
+ shown: (id) => cumulativeOpacity((key) => items[key], id, true) > 0
9684
9727
  };
9685
9728
  }
9686
- function cumulativeOpacity(lookup, id) {
9729
+ function cumulativeOpacity(lookup, id, presence = false) {
9687
9730
  let value = 1;
9688
9731
  let cursor = id;
9689
9732
  for (let depth = 0; cursor && depth < 64; depth += 1) {
9690
9733
  const item = lookup(cursor);
9691
9734
  if (!item) break;
9692
- value *= item.opacity;
9735
+ if (item.visible === false) return 0;
9736
+ if (!presence) value *= item.opacity;
9693
9737
  cursor = item.parent;
9694
9738
  }
9695
9739
  return value;
@@ -9725,7 +9769,8 @@ function refreshBoardScene(previous, lookup, ids) {
9725
9769
  items: sceneItems,
9726
9770
  get: (id) => overrides.get(id) ?? base.get(id),
9727
9771
  layout,
9728
- opacity: (id) => cumulativeOpacity(lookup, id)
9772
+ opacity: (id) => cumulativeOpacity(lookup, id),
9773
+ shown: (id) => cumulativeOpacity(lookup, id, true) > 0
9729
9774
  };
9730
9775
  refreshed.set(scene, {
9731
9776
  base,
@@ -9981,6 +10026,494 @@ function resolveBoardAnimationCamera(override, bounds, surface, time, base = {
9981
10026
  return camera;
9982
10027
  }
9983
10028
  //#endregion
10029
+ //#region ../sdk/src/board/model/items/id.ts
10030
+ function createBoardEntityId() {
10031
+ const cryptoRef = globalThis.crypto;
10032
+ if (cryptoRef && typeof cryptoRef.randomUUID === "function") return cryptoRef.randomUUID();
10033
+ return `c-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
10034
+ }
10035
+ function createBoardItemId() {
10036
+ return `item_${createBoardEntityId()}`;
10037
+ }
10038
+ const VISIBLE = "visible";
10039
+ function newBoardTrackId(tracks, target, property) {
10040
+ const id = `${target}-${property.replaceAll(".", "-")}`;
10041
+ return id.length <= 160 && !Object.hasOwn(tracks, id) ? id : createBoardEntityId();
10042
+ }
10043
+ function findBoardKeyTrack(tracks, target, property) {
10044
+ return Object.entries(tracks).find(([, track]) => track.target === target && track.property === property && track.composite === "replace");
10045
+ }
10046
+ function targetType(document, target) {
10047
+ if (target === "camera") return BOARD_CAMERA_TARGET$1;
10048
+ if (document.animations[target]) return "animation";
10049
+ if (document.board.scripts?.[target]) return "script";
10050
+ return document.items[target]?.type ?? null;
10051
+ }
10052
+ function boardPlayProperty(document, target) {
10053
+ const type = targetType(document, target);
10054
+ return type === "video" || type === "audio" ? "props.time" : type === "animation" ? "time" : null;
10055
+ }
10056
+ function boardPlayLength(document, target) {
10057
+ const item = document.items[target];
10058
+ if (item?.type === "video" || item?.type === "audio") return item.props.snapshot?.durationMs || null;
10059
+ return document.animations[target]?.duration ?? null;
10060
+ }
10061
+ function visibleSpan(track, duration) {
10062
+ let start = null;
10063
+ let lastShown = -1;
10064
+ let end = null;
10065
+ for (const keyframe of track.keyframes) if (keyframe.value !== false) {
10066
+ start ??= keyframe.at;
10067
+ lastShown = keyframe.at;
10068
+ end = null;
10069
+ } else if (start !== null && end === null) end = keyframe.at;
10070
+ return start === null ? null : {
10071
+ start,
10072
+ end: end ?? Math.max(duration, lastShown)
10073
+ };
10074
+ }
10075
+ function boardClipSpan(tracks, duration) {
10076
+ if (tracks.visible) return visibleSpan(tracks.visible, duration);
10077
+ const first = tracks.play?.keyframes[0];
10078
+ const last = tracks.play?.keyframes.at(-1);
10079
+ return first && last && last.at > first.at ? {
10080
+ start: first.at,
10081
+ end: last.at
10082
+ } : null;
10083
+ }
10084
+ function boardTargetSpan(document, animation, target) {
10085
+ const property = boardPlayProperty(document, target);
10086
+ return boardClipSpan({
10087
+ visible: findBoardKeyTrack(animation.tracks, target, VISIBLE)?.[1],
10088
+ play: property ? findBoardKeyTrack(animation.tracks, target, property)?.[1] : void 0
10089
+ }, animation.duration);
10090
+ }
10091
+ function visibleKeyframes(start, end) {
10092
+ if (end <= start) return [{
10093
+ at: 0,
10094
+ value: false
10095
+ }];
10096
+ return [
10097
+ ...start > 0 ? [{
10098
+ at: 0,
10099
+ value: false
10100
+ }] : [],
10101
+ {
10102
+ at: start,
10103
+ value: true
10104
+ },
10105
+ {
10106
+ at: end,
10107
+ value: false
10108
+ }
10109
+ ];
10110
+ }
10111
+ function normalizeVisible(keyframes) {
10112
+ const sorted = keyframes.map((keyframe, index) => ({
10113
+ keyframe,
10114
+ index
10115
+ })).sort((a, b) => a.keyframe.at - b.keyframe.at || a.index - b.index);
10116
+ const result = [];
10117
+ for (const { keyframe } of sorted) {
10118
+ if (result.at(-1)?.at === keyframe.at) result.pop();
10119
+ if (result.at(-1)?.value === keyframe.value) continue;
10120
+ result.push(keyframe);
10121
+ }
10122
+ if (result[0]?.value !== false && (result[0]?.at ?? 0) > 0) result.unshift({
10123
+ at: 0,
10124
+ value: false
10125
+ });
10126
+ return result;
10127
+ }
10128
+ function withDuration(animation, end) {
10129
+ return end > animation.duration ? {
10130
+ ...animation,
10131
+ duration: Math.ceil(end)
10132
+ } : animation;
10133
+ }
10134
+ function setTrack(tracks, target, property, keyframes, interpolation = "auto") {
10135
+ const existing = findBoardKeyTrack(tracks, target, property);
10136
+ const id = existing?.[0] ?? newBoardTrackId(tracks, target, property);
10137
+ tracks[id] = existing ? {
10138
+ ...existing[1],
10139
+ keyframes
10140
+ } : {
10141
+ target,
10142
+ property,
10143
+ keyframes,
10144
+ composite: "replace",
10145
+ interpolation
10146
+ };
10147
+ }
10148
+ function sampleTrack(document, track, time) {
10149
+ const type = targetType(document, track.target);
10150
+ const compiled = type ? compileBoardTrack("", "", track, type) : null;
10151
+ if (compiled) return sampleBoardTrack(compiled, time);
10152
+ return [...track.keyframes].reverse().find((keyframe) => keyframe.at <= time)?.value ?? track.keyframes[0]?.value;
10153
+ }
10154
+ function slope(a, b) {
10155
+ if (!a || !b || b.at <= a.at || typeof a.value !== "number" || typeof b.value !== "number") return 0;
10156
+ return (b.value - a.value) / (b.at - a.at);
10157
+ }
10158
+ function playValue(document, track, time) {
10159
+ const { keyframes } = track;
10160
+ const first = keyframes[0];
10161
+ const last = keyframes.at(-1);
10162
+ if (time < first.at) return Math.max(0, first.value - slope(first, keyframes[1]) * (first.at - time));
10163
+ if (time > last.at) return Math.max(0, last.value + slope(keyframes.at(-2), last) * (time - last.at));
10164
+ const value = sampleTrack(document, track, time);
10165
+ return typeof value === "number" ? value : 0;
10166
+ }
10167
+ function shiftKeyframes(keyframes, shift) {
10168
+ return keyframes.map((keyframe) => ({
10169
+ ...keyframe,
10170
+ at: keyframe.at + shift
10171
+ }));
10172
+ }
10173
+ function withoutAnchor(track) {
10174
+ const [first, second] = track.keyframes;
10175
+ return track.property === VISIBLE && first?.at === 0 && first.value === false && second ? track.keyframes.slice(1) : track.keyframes;
10176
+ }
10177
+ function boardPlaceTarget(document, animation, target, placement) {
10178
+ const at = Math.max(0, Math.round(placement.at));
10179
+ const existing = boardTargetSpan(document, animation, target);
10180
+ if (existing) return boardShiftTargets(document, animation, [target], at - existing.start);
10181
+ const rate = placement.rate && placement.rate > 0 ? placement.rate : 1;
10182
+ const from = Math.max(0, placement.from ?? 0);
10183
+ const length = boardPlayLength(document, target);
10184
+ const remaining = length !== null && length > from ? (length - from) / rate : null;
10185
+ const duration = Math.max(40, Math.round(placement.duration ?? remaining ?? 3e3));
10186
+ const tracks = { ...animation.tracks };
10187
+ if (document.items[target]) setTrack(tracks, target, VISIBLE, visibleKeyframes(at, at + duration), "step");
10188
+ const property = boardPlayProperty(document, target);
10189
+ if (property) setTrack(tracks, target, property, [{
10190
+ at,
10191
+ value: from
10192
+ }, {
10193
+ at: at + duration,
10194
+ value: from + duration * rate
10195
+ }]);
10196
+ return withDuration({
10197
+ ...animation,
10198
+ tracks
10199
+ }, at + duration);
10200
+ }
10201
+ function boardShiftTargets(document, animation, targets, delta) {
10202
+ const owned = Object.entries(animation.tracks).filter(([, track]) => targets.includes(track.target));
10203
+ const spans = targets.map((target) => boardTargetSpan(document, animation, target));
10204
+ const keyed = Math.min(...owned.map(([, track]) => withoutAnchor(track)[0]?.at ?? Number.POSITIVE_INFINITY));
10205
+ const earliest = Math.min(...spans.map((span) => span?.start ?? keyed));
10206
+ if (!Number.isFinite(earliest)) return animation;
10207
+ const shift = Math.round(Math.max(delta, -earliest));
10208
+ if (shift === 0) return animation;
10209
+ const tracks = { ...animation.tracks };
10210
+ let end = Math.max(0, ...spans.map((span) => span ? span.end + shift : 0));
10211
+ for (const [id, track] of owned) {
10212
+ let body = withoutAnchor(track);
10213
+ if ((body[0]?.at ?? 0) < -shift) {
10214
+ const after = cutTrack(document, {
10215
+ ...track,
10216
+ keyframes: [...body]
10217
+ }, -shift).after;
10218
+ body = after.length ? after : [{
10219
+ ...body.at(-1),
10220
+ at: -shift
10221
+ }];
10222
+ }
10223
+ const moved = shiftKeyframes(body, shift);
10224
+ const keyframes = track.property === VISIBLE ? normalizeVisible(moved) : moved;
10225
+ tracks[id] = {
10226
+ ...track,
10227
+ keyframes
10228
+ };
10229
+ if (!spans.some(Boolean)) end = Math.max(end, keyframes.at(-1)?.at ?? 0);
10230
+ }
10231
+ return withDuration({
10232
+ ...animation,
10233
+ tracks
10234
+ }, end);
10235
+ }
10236
+ function boardTrimLimits(document, animation, target) {
10237
+ const property = boardPlayProperty(document, target);
10238
+ const play = property ? findBoardKeyTrack(animation.tracks, target, property)?.[1] : void 0;
10239
+ const first = play?.keyframes[0];
10240
+ const last = play?.keyframes.at(-1);
10241
+ if (!play || !first || !last) return {
10242
+ start: 0,
10243
+ end: Number.POSITIVE_INFINITY
10244
+ };
10245
+ const head = slope(first, play.keyframes[1]);
10246
+ const tail = slope(play.keyframes.at(-2), last);
10247
+ const length = boardPlayLength(document, target);
10248
+ const start = head > 0 && typeof first.value === "number" ? first.at - first.value / head : 0;
10249
+ const end = tail > 0 && length !== null && typeof last.value === "number" ? last.at + (length - last.value) / tail : Number.POSITIVE_INFINITY;
10250
+ return {
10251
+ start: Math.max(0, Math.ceil(start)),
10252
+ end: Math.max(last.at, Math.floor(end))
10253
+ };
10254
+ }
10255
+ function boardTrimTarget(document, animation, target, edge, at) {
10256
+ const span = boardTargetSpan(document, animation, target);
10257
+ if (!span) return animation;
10258
+ const limits = boardTrimLimits(document, animation, target);
10259
+ const time = edge === "start" ? Math.round(Math.min(Math.max(at, limits.start), span.end - 40)) : Math.round(Math.max(Math.min(at, limits.end), span.start + 40));
10260
+ if (time === span[edge]) return animation;
10261
+ const next = edge === "start" ? {
10262
+ start: time,
10263
+ end: span.end
10264
+ } : {
10265
+ start: span.start,
10266
+ end: time
10267
+ };
10268
+ const tracks = { ...animation.tracks };
10269
+ if (findBoardKeyTrack(tracks, target, VISIBLE)) setTrack(tracks, target, VISIBLE, visibleKeyframes(next.start, next.end), "step");
10270
+ const property = boardPlayProperty(document, target);
10271
+ const play = property ? findBoardKeyTrack(tracks, target, property) : void 0;
10272
+ if (play) {
10273
+ const [id, track] = play;
10274
+ const first = track.keyframes[0];
10275
+ const last = track.keyframes.at(-1);
10276
+ let keyframes;
10277
+ if (time > first.at && time < last.at) keyframes = cutTrack(document, track, time)[edge === "start" ? "after" : "before"];
10278
+ else {
10279
+ const cut = {
10280
+ at: time,
10281
+ value: playValue(document, track, time)
10282
+ };
10283
+ keyframes = edge === "start" ? [cut, ...track.keyframes.filter((keyframe) => keyframe.at > time)] : [...track.keyframes.filter((keyframe) => keyframe.at < time), cut];
10284
+ }
10285
+ tracks[id] = {
10286
+ ...track,
10287
+ keyframes
10288
+ };
10289
+ }
10290
+ return withDuration({
10291
+ ...animation,
10292
+ tracks
10293
+ }, next.end);
10294
+ }
10295
+ function cutValue(document, track, at) {
10296
+ return {
10297
+ at,
10298
+ value: sampleTrack(document, track, at)
10299
+ };
10300
+ }
10301
+ const CURVES = {
10302
+ ease: [
10303
+ .25,
10304
+ .1,
10305
+ .25,
10306
+ 1
10307
+ ],
10308
+ "ease-in": [
10309
+ .42,
10310
+ 0,
10311
+ 1,
10312
+ 1
10313
+ ],
10314
+ "ease-out": [
10315
+ 0,
10316
+ 0,
10317
+ .58,
10318
+ 1
10319
+ ],
10320
+ "ease-in-out": [
10321
+ .42,
10322
+ 0,
10323
+ .58,
10324
+ 1
10325
+ ]
10326
+ };
10327
+ function curveOf(ease) {
10328
+ const key = ease.trim();
10329
+ const known = CURVES[key];
10330
+ if (known) return known;
10331
+ const numbers = /^cubic-bezier\(([^)]+)\)$/.exec(key)?.[1]?.split(",").map(Number);
10332
+ return numbers?.length === 4 && numbers.every(Number.isFinite) ? numbers : null;
10333
+ }
10334
+ const format = (curve) => `cubic-bezier(${curve.map((value) => Number(value.toFixed(4))).join(", ")})`;
10335
+ function splitEase(ease, progress) {
10336
+ const curve = ease && ease.trim() !== "linear" ? curveOf(ease) : null;
10337
+ if (!ease || !curve) return [ease, ease];
10338
+ const [x1, y1, x2, y2] = curve;
10339
+ const bezier = (a, b, t) => 3 * a * t * (1 - t) ** 2 + 3 * b * t ** 2 * (1 - t) + t ** 3;
10340
+ let low = 0;
10341
+ let high = 1;
10342
+ for (let index = 0; index < 40; index += 1) {
10343
+ const mid = (low + high) / 2;
10344
+ if (bezier(x1, x2, mid) < progress) low = mid;
10345
+ else high = mid;
10346
+ }
10347
+ const t = (low + high) / 2;
10348
+ const lerp = (a, b) => a + (b - a) * t;
10349
+ const p01 = [lerp(0, x1), lerp(0, y1)];
10350
+ const p12 = [lerp(x1, x2), lerp(y1, y2)];
10351
+ const p23 = [lerp(x2, 1), lerp(y2, 1)];
10352
+ const p012 = [lerp(p01[0], p12[0]), lerp(p01[1], p12[1])];
10353
+ const p123 = [lerp(p12[0], p23[0]), lerp(p12[1], p23[1])];
10354
+ const [x, y] = [lerp(p012[0], p123[0]), lerp(p012[1], p123[1])];
10355
+ if (x <= 0 || x >= 1 || Math.abs(y) < 1e-9 || Math.abs(1 - y) < 1e-9) return [ease, ease];
10356
+ return [format([
10357
+ p01[0] / x,
10358
+ p01[1] / y,
10359
+ p012[0] / x,
10360
+ p012[1] / y
10361
+ ]), format([
10362
+ (p123[0] - x) / (1 - x),
10363
+ (p123[1] - y) / (1 - y),
10364
+ (p23[0] - x) / (1 - x),
10365
+ (p23[1] - y) / (1 - y)
10366
+ ])];
10367
+ }
10368
+ function withEase(keyframe, ease) {
10369
+ const { ease: _ease, ...rest } = keyframe;
10370
+ return ease && ease !== "linear" ? {
10371
+ ...rest,
10372
+ ease
10373
+ } : rest;
10374
+ }
10375
+ function cutTrack(document, track, time) {
10376
+ const { keyframes } = track;
10377
+ const index = keyframes.findIndex((keyframe) => keyframe.at >= time);
10378
+ const before = keyframes.filter((keyframe) => keyframe.at <= time);
10379
+ const after = keyframes.filter((keyframe) => keyframe.at >= time);
10380
+ const a = keyframes[index - 1];
10381
+ const b = keyframes[index];
10382
+ if (!a || !b || b.at === time) return {
10383
+ before,
10384
+ after
10385
+ };
10386
+ const value = cutValue(document, track, time).value;
10387
+ const [left, right] = track.interpolation === "step" ? [b.ease, b.ease] : splitEase(b.ease, (time - a.at) / (b.at - a.at));
10388
+ return {
10389
+ before: [...before, withEase({
10390
+ at: time,
10391
+ value
10392
+ }, left)],
10393
+ after: [
10394
+ {
10395
+ at: time,
10396
+ value
10397
+ },
10398
+ withEase(b, right),
10399
+ ...after.slice(1)
10400
+ ]
10401
+ };
10402
+ }
10403
+ function boardSplitTarget(document, animation, target, copies, at) {
10404
+ const span = boardTargetSpan(document, animation, target);
10405
+ const time = Math.round(at);
10406
+ if (!span || time < span.start + 40 || time > span.end - 40) return null;
10407
+ const tracks = { ...animation.tracks };
10408
+ for (const [id, track] of Object.entries(animation.tracks)) {
10409
+ const copy = copies.get(track.target);
10410
+ if (!copy) continue;
10411
+ const own = track.property === VISIBLE ? boardTargetSpan(document, animation, track.target) : null;
10412
+ let before;
10413
+ let after;
10414
+ if (own) {
10415
+ before = visibleKeyframes(own.start, Math.min(own.end, time));
10416
+ after = visibleKeyframes(Math.max(own.start, time), own.end);
10417
+ } else {
10418
+ const index = track.keyframes.findIndex((keyframe) => keyframe.at >= time);
10419
+ const next = index < 0 ? track.keyframes.length : index;
10420
+ before = track.keyframes.slice(0, next + 2);
10421
+ after = track.keyframes.slice(Math.max(0, next - 2));
10422
+ }
10423
+ tracks[id] = {
10424
+ ...track,
10425
+ keyframes: before
10426
+ };
10427
+ tracks[newBoardTrackId(tracks, copy, track.property)] = {
10428
+ ...structuredClone(track),
10429
+ target: copy,
10430
+ keyframes: after
10431
+ };
10432
+ }
10433
+ const copy = copies.get(target);
10434
+ if (document.items[target] && !findBoardKeyTrack(animation.tracks, target, VISIBLE)) {
10435
+ setTrack(tracks, target, VISIBLE, visibleKeyframes(span.start, time), "step");
10436
+ setTrack(tracks, copy, VISIBLE, visibleKeyframes(time, span.end), "step");
10437
+ }
10438
+ return {
10439
+ ...animation,
10440
+ tracks
10441
+ };
10442
+ }
10443
+ function boardRemoveTarget(animation, target) {
10444
+ const tracks = Object.fromEntries(Object.entries(animation.tracks).filter(([, track]) => track.target !== target));
10445
+ return Object.keys(tracks).length === Object.keys(animation.tracks).length ? animation : {
10446
+ ...animation,
10447
+ tracks
10448
+ };
10449
+ }
10450
+ function retime(animation, keyframes, markers, duration) {
10451
+ const tracks = {};
10452
+ for (const [id, track] of Object.entries(animation.tracks)) {
10453
+ const next = track.property === VISIBLE ? normalizeVisible(keyframes(track)) : keyframes(track);
10454
+ if (track.property === VISIBLE) tracks[id] = {
10455
+ ...track,
10456
+ keyframes: next.length ? next : [{
10457
+ at: 0,
10458
+ value: false
10459
+ }]
10460
+ };
10461
+ else if (next.length) tracks[id] = {
10462
+ ...track,
10463
+ keyframes: next
10464
+ };
10465
+ }
10466
+ return {
10467
+ ...animation,
10468
+ tracks,
10469
+ markers,
10470
+ duration: Math.max(1, Math.round(duration))
10471
+ };
10472
+ }
10473
+ function join(before, after) {
10474
+ const last = before.at(-1);
10475
+ const [first, second] = after;
10476
+ if (!last || !first || first.at !== last.at) return [...before, ...after];
10477
+ if (sameJson(first.value, last.value) || second && second.at <= first.at + 1) return [...before, ...after.slice(1)];
10478
+ return [
10479
+ ...before,
10480
+ {
10481
+ ...first,
10482
+ at: first.at + 1
10483
+ },
10484
+ ...after.slice(1)
10485
+ ];
10486
+ }
10487
+ function boardRemoveTime(document, animation, from, to) {
10488
+ const start = Math.max(0, Math.round(Math.min(from, to)));
10489
+ const end = Math.round(Math.max(from, to));
10490
+ const length = end - start;
10491
+ if (length <= 0) return animation;
10492
+ return retime(animation, (track) => {
10493
+ const { before } = cutTrack(document, track, start);
10494
+ const after = shiftKeyframes(cutTrack(document, track, end).after, -length);
10495
+ return track.property === VISIBLE ? [...before, ...after] : join(before, after);
10496
+ }, animation.markers.filter((marker) => marker.at <= start || marker.at >= end).map((marker) => marker.at >= end ? {
10497
+ ...marker,
10498
+ at: marker.at - length
10499
+ } : marker), animation.duration - (Math.min(end, animation.duration) - Math.min(start, animation.duration)));
10500
+ }
10501
+ function boardInsertTime(document, animation, at, length) {
10502
+ const time = Math.max(0, Math.round(at));
10503
+ const gap = Math.round(length);
10504
+ if (gap <= 0) return animation;
10505
+ return retime(animation, (track) => {
10506
+ const body = withoutAnchor(track);
10507
+ const anchor = track.keyframes.slice(0, track.keyframes.length - body.length);
10508
+ if ((body[0]?.at ?? 0) >= time) return [...anchor, ...shiftKeyframes(body, gap)];
10509
+ const { before, after } = cutTrack(document, track, time);
10510
+ return after.some((keyframe) => keyframe.at > time) ? [...before, ...shiftKeyframes(after, gap)] : before;
10511
+ }, animation.markers.map((marker) => marker.at > time ? {
10512
+ ...marker,
10513
+ at: marker.at + gap
10514
+ } : marker), time < animation.duration ? animation.duration + gap : animation.duration);
10515
+ }
10516
+ //#endregion
9984
10517
  //#region ../sdk/src/board/model/authoring.ts
9985
10518
  function validateChapterComposition(document, chapters) {
9986
10519
  const uses = /* @__PURE__ */ new Map();
@@ -10116,6 +10649,39 @@ function boardSequencePatch(document, id, chapters) {
10116
10649
  if (!result.ok) throw new Error(result.diagnostics.map((entry) => `${entry.path}: ${entry.message}`).join("; "));
10117
10650
  return patch;
10118
10651
  }
10652
+ function boardPlacePatch(document, id, targets, placement) {
10653
+ BoardIdSchema$1.parse(id);
10654
+ const existing = document.animations[id];
10655
+ let animation = existing ?? {
10656
+ duration: 1,
10657
+ play: "manual",
10658
+ delay: 0,
10659
+ loop: false,
10660
+ end: "hold",
10661
+ markers: [],
10662
+ tracks: {}
10663
+ };
10664
+ let at = placement.at;
10665
+ for (const target of targets) {
10666
+ if (target === id || !document.items[target] && !document.animations[target]) throw new Error(`${target} is not an item or animation on this Board.`);
10667
+ animation = boardPlaceTarget(document, animation, target, {
10668
+ ...placement,
10669
+ at
10670
+ });
10671
+ if (!placement.together) at = boardTargetSpan(document, animation, target)?.end ?? at;
10672
+ }
10673
+ const tracks = Object.fromEntries(Object.entries(animation.tracks).filter(([key, track]) => existing?.tracks[key] !== track));
10674
+ const patch = { animations: { [id]: existing ? {
10675
+ duration: animation.duration,
10676
+ tracks
10677
+ } : {
10678
+ ...animation,
10679
+ tracks
10680
+ } } };
10681
+ const result = applyBoardPatchToDocument(document, patch);
10682
+ if (!result.ok) throw new Error(result.diagnostics.map((entry) => `${entry.path}: ${entry.message}`).join("; "));
10683
+ return patch;
10684
+ }
10119
10685
  function boardPathTrack(target, points, options) {
10120
10686
  const { duration, at = 0, samples = 64, orient = false } = options;
10121
10687
  if (points.length < 2 || points.length > 1e4 || points.some((p) => !Number.isFinite(p.x) || !Number.isFinite(p.y))) throw new Error("A path needs 2 to 10000 finite points.");
@@ -10161,6 +10727,105 @@ function boardPathTrack(target, points, options) {
10161
10727
  })
10162
10728
  };
10163
10729
  }
10730
+ //#endregion
10731
+ //#region ../sdk/src/board/model/media-spans.ts
10732
+ const BOARD_MEDIA_RATES = {
10733
+ min: .25,
10734
+ max: 4
10735
+ };
10736
+ function boardTimedMedia(scene, ids) {
10737
+ const result = [];
10738
+ const items = ids ? Array.from(ids, (id) => scene.get(id)) : scene.items;
10739
+ for (const item of items) {
10740
+ if (item?.type !== "video" && item?.type !== "audio") continue;
10741
+ const { time, volume, src } = item.props;
10742
+ if (time === void 0 || !parseBoardMediaSource$1(src)) continue;
10743
+ result.push({
10744
+ id: item.id,
10745
+ kind: item.type,
10746
+ src,
10747
+ time,
10748
+ volume: volume ?? 1,
10749
+ shown: scene.shown(item.id)
10750
+ });
10751
+ }
10752
+ return result;
10753
+ }
10754
+ function boardMediaRate(from, to) {
10755
+ const elapsed = to.at - from.at;
10756
+ if (elapsed <= 0) return 0;
10757
+ const rate = (to.time - from.time) / elapsed;
10758
+ return rate >= BOARD_MEDIA_RATES.min && rate <= BOARD_MEDIA_RATES.max ? rate : 0;
10759
+ }
10760
+ function sameRate(a, b) {
10761
+ return Math.abs(a - b) <= .01 * Math.max(a, b);
10762
+ }
10763
+ function simplify(points) {
10764
+ const result = [];
10765
+ for (const point of points) {
10766
+ const a = result.at(-2);
10767
+ const b = result.at(-1);
10768
+ if (a && b && point.at > a.at && Math.abs(a.value + (b.at - a.at) / (point.at - a.at) * (point.value - a.value) - b.value) < .001) result.pop();
10769
+ result.push(point);
10770
+ }
10771
+ return result;
10772
+ }
10773
+ function boardMediaSpans(samples) {
10774
+ const spans = [];
10775
+ const open = /* @__PURE__ */ new Map();
10776
+ const previous = /* @__PURE__ */ new Map();
10777
+ for (const { at, media } of samples) {
10778
+ const seen = /* @__PURE__ */ new Set();
10779
+ for (const state of media) {
10780
+ seen.add(state.id);
10781
+ const before = previous.get(state.id);
10782
+ previous.set(state.id, {
10783
+ at,
10784
+ state
10785
+ });
10786
+ const span = open.get(state.id);
10787
+ const rate = before?.state.shown && state.shown && before.state.src === state.src ? boardMediaRate({
10788
+ at: before.at,
10789
+ time: before.state.time
10790
+ }, {
10791
+ at,
10792
+ time: state.time
10793
+ }) : 0;
10794
+ if (span && rate && sameRate(rate, span.rate)) {
10795
+ span.end = at;
10796
+ span.volume.push({
10797
+ at,
10798
+ value: state.volume
10799
+ });
10800
+ continue;
10801
+ }
10802
+ if (span) open.delete(state.id);
10803
+ if (!before || !rate) continue;
10804
+ const next = {
10805
+ id: state.id,
10806
+ kind: state.kind,
10807
+ src: state.src,
10808
+ start: before.at,
10809
+ end: at,
10810
+ from: before.state.time,
10811
+ rate,
10812
+ volume: [{
10813
+ at: before.at,
10814
+ value: before.state.volume
10815
+ }, {
10816
+ at,
10817
+ value: state.volume
10818
+ }]
10819
+ };
10820
+ open.set(state.id, next);
10821
+ spans.push(next);
10822
+ }
10823
+ for (const id of open.keys()) if (!seen.has(id)) open.delete(id);
10824
+ for (const id of previous.keys()) if (!seen.has(id)) previous.delete(id);
10825
+ }
10826
+ for (const span of spans) span.volume = simplify(span.volume);
10827
+ return spans;
10828
+ }
10164
10829
  const CURVE_SEGMENTS = 20;
10165
10830
  const ORTHOGONAL_SNAP = .5;
10166
10831
  const SIDE_NORMALS = {
@@ -12150,16 +12815,6 @@ const builtinBoardItems = [
12150
12815
  customItem
12151
12816
  ];
12152
12817
  //#endregion
12153
- //#region ../sdk/src/board/model/items/id.ts
12154
- function createBoardEntityId() {
12155
- const cryptoRef = globalThis.crypto;
12156
- if (cryptoRef && typeof cryptoRef.randomUUID === "function") return cryptoRef.randomUUID();
12157
- return `c-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
12158
- }
12159
- function createBoardItemId() {
12160
- return `item_${createBoardEntityId()}`;
12161
- }
12162
- //#endregion
12163
12818
  //#region ../sdk/src/board/model/items/create.ts
12164
12819
  const DEFAULT_MODEL_SIZE = {
12165
12820
  width: 264,
@@ -19915,6 +20570,91 @@ function pointInTriangle(px, py, x1, y1, x2, y2, x3, y3) {
19915
20570
  return u >= 0 && v >= 0 && u + v < 1;
19916
20571
  }
19917
20572
  //#endregion
20573
+ //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/filters/defaults/alpha/alpha.frag.mjs
20574
+ var fragment$3 = "\nin vec2 vTextureCoord;\n\nout vec4 finalColor;\n\nuniform float uAlpha;\nuniform sampler2D uTexture;\n\nvoid main()\n{\n finalColor = texture(uTexture, vTextureCoord) * uAlpha;\n}\n";
20575
+ //#endregion
20576
+ //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/filters/defaults/alpha/alpha.wgsl.mjs
20577
+ var source$2 = "struct GlobalFilterUniforms {\n uInputSize:vec4<f32>,\n uInputPixel:vec4<f32>,\n uInputClamp:vec4<f32>,\n uOutputFrame:vec4<f32>,\n uGlobalFrame:vec4<f32>,\n uOutputTexture:vec4<f32>,\n};\n\nstruct AlphaUniforms {\n uAlpha:f32,\n};\n\n@group(0) @binding(0) var<uniform> gfu: GlobalFilterUniforms;\n@group(0) @binding(1) var uTexture: texture_2d<f32>;\n@group(0) @binding(2) var uSampler : sampler;\n\n@group(1) @binding(0) var<uniform> alphaUniforms : AlphaUniforms;\n\nstruct VSOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) uv : vec2<f32>\n };\n\nfn filterVertexPosition(aPosition:vec2<f32>) -> vec4<f32>\n{\n var position = aPosition * gfu.uOutputFrame.zw + gfu.uOutputFrame.xy;\n\n position.x = position.x * (2.0 / gfu.uOutputTexture.x) - 1.0;\n position.y = position.y * (2.0*gfu.uOutputTexture.z / gfu.uOutputTexture.y) - gfu.uOutputTexture.z;\n\n return vec4(position, 0.0, 1.0);\n}\n\nfn filterTextureCoord( aPosition:vec2<f32> ) -> vec2<f32>\n{\n return aPosition * (gfu.uOutputFrame.zw * gfu.uInputSize.zw);\n}\n\nfn globalTextureCoord( aPosition:vec2<f32> ) -> vec2<f32>\n{\n return (aPosition.xy / gfu.uGlobalFrame.zw) + (gfu.uGlobalFrame.xy / gfu.uGlobalFrame.zw); \n}\n\nfn getSize() -> vec2<f32>\n{\n return gfu.uGlobalFrame.zw;\n}\n \n@vertex\nfn mainVertex(\n @location(0) aPosition : vec2<f32>, \n) -> VSOutput {\n return VSOutput(\n filterVertexPosition(aPosition),\n filterTextureCoord(aPosition)\n );\n}\n\n@fragment\nfn mainFragment(\n @location(0) uv: vec2<f32>,\n @builtin(position) position: vec4<f32>\n) -> @location(0) vec4<f32> {\n \n var sample = textureSample(uTexture, uSampler, uv);\n \n return sample * alphaUniforms.uAlpha;\n}";
20578
+ //#endregion
20579
+ //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/filters/defaults/alpha/AlphaFilter.mjs
20580
+ const _AlphaFilter = class _AlphaFilter extends Filter {
20581
+ constructor(options) {
20582
+ options = {
20583
+ ..._AlphaFilter.defaultOptions,
20584
+ ...options
20585
+ };
20586
+ const gpuProgram = GpuProgram.from({
20587
+ vertex: {
20588
+ source: source$2,
20589
+ entryPoint: "mainVertex"
20590
+ },
20591
+ fragment: {
20592
+ source: source$2,
20593
+ entryPoint: "mainFragment"
20594
+ }
20595
+ });
20596
+ const glProgram = GlProgram.from({
20597
+ vertex: vertex$2,
20598
+ fragment: fragment$3,
20599
+ name: "alpha-filter"
20600
+ });
20601
+ const { alpha, ...rest } = options;
20602
+ const alphaUniforms = new UniformGroup({ uAlpha: {
20603
+ value: alpha,
20604
+ type: "f32"
20605
+ } });
20606
+ super({
20607
+ ...rest,
20608
+ gpuProgram,
20609
+ glProgram,
20610
+ resources: { alphaUniforms }
20611
+ });
20612
+ }
20613
+ /**
20614
+ * The alpha value of the filter.
20615
+ * Controls the transparency of the filtered display object.
20616
+ * @example
20617
+ * ```ts
20618
+ * // Create filter with initial alpha
20619
+ * const filter = new AlphaFilter({ alpha: 0.5 });
20620
+ *
20621
+ * // Update alpha value dynamically
20622
+ * filter.alpha = 0.8;
20623
+ * ```
20624
+ * @default 1
20625
+ * @remarks
20626
+ * - 0 = fully transparent
20627
+ * - 1 = fully opaque
20628
+ * - Values are clamped between 0 and 1
20629
+ */
20630
+ get alpha() {
20631
+ return this.resources.alphaUniforms.uniforms.uAlpha;
20632
+ }
20633
+ set alpha(value) {
20634
+ this.resources.alphaUniforms.uniforms.uAlpha = value;
20635
+ }
20636
+ };
20637
+ /**
20638
+ * Default options for the AlphaFilter.
20639
+ * @example
20640
+ * ```ts
20641
+ * AlphaFilter.defaultOptions = {
20642
+ * alpha: 0.5, // Default alpha value
20643
+ * };
20644
+ * // Use default options
20645
+ * const filter = new AlphaFilter(); // Uses default alpha of 0.5
20646
+ * ```
20647
+ */
20648
+ _AlphaFilter.defaultOptions = {
20649
+ /**
20650
+ * Amount of alpha transparency to apply.
20651
+ * - 0 = fully transparent
20652
+ * - 1 = fully opaque (default)
20653
+ * @default 1
20654
+ */
20655
+ alpha: 1 };
20656
+ let AlphaFilter = _AlphaFilter;
20657
+ //#endregion
19918
20658
  //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/filters/defaults/color-matrix/colorMatrixFilter.frag.mjs
19919
20659
  var fragment$2 = "\nin vec2 vTextureCoord;\nin vec4 vColor;\n\nout vec4 finalColor;\n\nuniform float uColorMatrix[20];\nuniform float uAlpha;\n\nuniform sampler2D uTexture;\n\nfloat rand(vec2 co)\n{\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main()\n{\n vec4 color = texture(uTexture, vTextureCoord);\n float randomValue = rand(gl_FragCoord.xy * 0.2);\n float diff = (randomValue - 0.5) * 0.5;\n\n if (uAlpha == 0.0) {\n finalColor = color;\n return;\n }\n\n if (color.a > 0.0) {\n color.rgb /= color.a;\n }\n\n vec4 result;\n\n result.r = (uColorMatrix[0] * color.r);\n result.r += (uColorMatrix[1] * color.g);\n result.r += (uColorMatrix[2] * color.b);\n result.r += (uColorMatrix[3] * color.a);\n result.r += uColorMatrix[4];\n\n result.g = (uColorMatrix[5] * color.r);\n result.g += (uColorMatrix[6] * color.g);\n result.g += (uColorMatrix[7] * color.b);\n result.g += (uColorMatrix[8] * color.a);\n result.g += uColorMatrix[9];\n\n result.b = (uColorMatrix[10] * color.r);\n result.b += (uColorMatrix[11] * color.g);\n result.b += (uColorMatrix[12] * color.b);\n result.b += (uColorMatrix[13] * color.a);\n result.b += uColorMatrix[14];\n\n result.a = (uColorMatrix[15] * color.r);\n result.a += (uColorMatrix[16] * color.g);\n result.a += (uColorMatrix[17] * color.b);\n result.a += (uColorMatrix[18] * color.a);\n result.a += uColorMatrix[19];\n\n vec3 rgb = mix(color.rgb, result.rgb, uAlpha);\n\n // Premultiply alpha again.\n rgb *= result.a;\n\n finalColor = vec4(rgb, result.a);\n}\n";
19920
20660
  //#endregion
@@ -31076,6 +31816,230 @@ var CanvasRenderer = class extends AbstractRenderer {
31076
31816
  }
31077
31817
  };
31078
31818
  //#endregion
31819
+ //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/rendering/renderers/gl/shader/GlProgramData.mjs
31820
+ var GlProgramData = class {
31821
+ /**
31822
+ * Makes a new Pixi program.
31823
+ * @param program - webgl program
31824
+ * @param uniformData - uniforms
31825
+ */
31826
+ constructor(program, uniformData) {
31827
+ this.program = program;
31828
+ this.uniformData = uniformData;
31829
+ this.uniformGroups = {};
31830
+ this.uniformDirtyGroups = {};
31831
+ this.uniformBlockBindings = {};
31832
+ }
31833
+ /** Destroys this program. */
31834
+ destroy() {
31835
+ this.uniformData = null;
31836
+ this.uniformGroups = null;
31837
+ this.uniformDirtyGroups = null;
31838
+ this.uniformBlockBindings = null;
31839
+ this.program = null;
31840
+ }
31841
+ };
31842
+ //#endregion
31843
+ //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/rendering/renderers/gl/shader/program/defaultValue.mjs
31844
+ function booleanArray(size) {
31845
+ const array = new Array(size);
31846
+ for (let i = 0; i < array.length; i++) array[i] = false;
31847
+ return array;
31848
+ }
31849
+ function defaultValue(type, size) {
31850
+ switch (type) {
31851
+ case "float": return 0;
31852
+ case "vec2": return new Float32Array(2 * size);
31853
+ case "vec3": return new Float32Array(3 * size);
31854
+ case "vec4": return new Float32Array(4 * size);
31855
+ case "int":
31856
+ case "uint":
31857
+ case "sampler2D":
31858
+ case "sampler2DArray": return 0;
31859
+ case "ivec2": return new Int32Array(2 * size);
31860
+ case "ivec3": return new Int32Array(3 * size);
31861
+ case "ivec4": return new Int32Array(4 * size);
31862
+ case "uvec2": return new Uint32Array(2 * size);
31863
+ case "uvec3": return new Uint32Array(3 * size);
31864
+ case "uvec4": return new Uint32Array(4 * size);
31865
+ case "bool": return false;
31866
+ case "bvec2": return booleanArray(2 * size);
31867
+ case "bvec3": return booleanArray(3 * size);
31868
+ case "bvec4": return booleanArray(4 * size);
31869
+ case "mat2": return new Float32Array([
31870
+ 1,
31871
+ 0,
31872
+ 0,
31873
+ 1
31874
+ ]);
31875
+ case "mat3": return new Float32Array([
31876
+ 1,
31877
+ 0,
31878
+ 0,
31879
+ 0,
31880
+ 1,
31881
+ 0,
31882
+ 0,
31883
+ 0,
31884
+ 1
31885
+ ]);
31886
+ case "mat4": return new Float32Array([
31887
+ 1,
31888
+ 0,
31889
+ 0,
31890
+ 0,
31891
+ 0,
31892
+ 1,
31893
+ 0,
31894
+ 0,
31895
+ 0,
31896
+ 0,
31897
+ 1,
31898
+ 0,
31899
+ 0,
31900
+ 0,
31901
+ 0,
31902
+ 1
31903
+ ]);
31904
+ }
31905
+ return null;
31906
+ }
31907
+ //#endregion
31908
+ //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/rendering/renderers/gl/shader/program/mapType.mjs
31909
+ let GL_TABLE = null;
31910
+ const GL_TO_GLSL_TYPES = {
31911
+ FLOAT: "float",
31912
+ FLOAT_VEC2: "vec2",
31913
+ FLOAT_VEC3: "vec3",
31914
+ FLOAT_VEC4: "vec4",
31915
+ INT: "int",
31916
+ INT_VEC2: "ivec2",
31917
+ INT_VEC3: "ivec3",
31918
+ INT_VEC4: "ivec4",
31919
+ UNSIGNED_INT: "uint",
31920
+ UNSIGNED_INT_VEC2: "uvec2",
31921
+ UNSIGNED_INT_VEC3: "uvec3",
31922
+ UNSIGNED_INT_VEC4: "uvec4",
31923
+ BOOL: "bool",
31924
+ BOOL_VEC2: "bvec2",
31925
+ BOOL_VEC3: "bvec3",
31926
+ BOOL_VEC4: "bvec4",
31927
+ FLOAT_MAT2: "mat2",
31928
+ FLOAT_MAT3: "mat3",
31929
+ FLOAT_MAT4: "mat4",
31930
+ SAMPLER_2D: "sampler2D",
31931
+ INT_SAMPLER_2D: "sampler2D",
31932
+ UNSIGNED_INT_SAMPLER_2D: "sampler2D",
31933
+ SAMPLER_2D_SHADOW: "sampler2DShadow",
31934
+ SAMPLER_CUBE: "samplerCube",
31935
+ INT_SAMPLER_CUBE: "samplerCube",
31936
+ UNSIGNED_INT_SAMPLER_CUBE: "samplerCube",
31937
+ SAMPLER_CUBE_SHADOW: "samplerCubeShadow",
31938
+ SAMPLER_2D_ARRAY: "sampler2DArray",
31939
+ INT_SAMPLER_2D_ARRAY: "sampler2DArray",
31940
+ UNSIGNED_INT_SAMPLER_2D_ARRAY: "sampler2DArray",
31941
+ SAMPLER_2D_ARRAY_SHADOW: "sampler2DArrayShadow"
31942
+ };
31943
+ const GLSL_TO_VERTEX_TYPES = {
31944
+ float: "float32",
31945
+ vec2: "float32x2",
31946
+ vec3: "float32x3",
31947
+ vec4: "float32x4",
31948
+ int: "sint32",
31949
+ ivec2: "sint32x2",
31950
+ ivec3: "sint32x3",
31951
+ ivec4: "sint32x4",
31952
+ uint: "uint32",
31953
+ uvec2: "uint32x2",
31954
+ uvec3: "uint32x3",
31955
+ uvec4: "uint32x4",
31956
+ bool: "uint32",
31957
+ bvec2: "uint32x2",
31958
+ bvec3: "uint32x3",
31959
+ bvec4: "uint32x4"
31960
+ };
31961
+ function mapType(gl, type) {
31962
+ if (!GL_TABLE) {
31963
+ const typeNames = Object.keys(GL_TO_GLSL_TYPES);
31964
+ GL_TABLE = {};
31965
+ for (let i = 0; i < typeNames.length; ++i) {
31966
+ const tn = typeNames[i];
31967
+ GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn];
31968
+ }
31969
+ }
31970
+ return GL_TABLE[type];
31971
+ }
31972
+ function mapGlToVertexFormat(gl, type) {
31973
+ const typeValue = mapType(gl, type);
31974
+ return GLSL_TO_VERTEX_TYPES[typeValue] || "float32";
31975
+ }
31976
+ //#endregion
31977
+ //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/rendering/renderers/gl/shader/program/extractAttributesFromGlProgram.mjs
31978
+ function extractAttributesFromGlProgram(program, gl, sortAttributes = false) {
31979
+ const attributes = {};
31980
+ const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
31981
+ for (let i = 0; i < totalAttributes; i++) {
31982
+ const attribData = gl.getActiveAttrib(program, i);
31983
+ if (attribData.name.startsWith("gl_")) continue;
31984
+ const format = mapGlToVertexFormat(gl, attribData.type);
31985
+ attributes[attribData.name] = {
31986
+ location: 0,
31987
+ format,
31988
+ stride: getAttributeInfoFromFormat(format).stride,
31989
+ offset: 0,
31990
+ instance: false,
31991
+ start: 0
31992
+ };
31993
+ }
31994
+ const keys = Object.keys(attributes);
31995
+ if (sortAttributes) {
31996
+ keys.sort((a, b) => a > b ? 1 : -1);
31997
+ for (let i = 0; i < keys.length; i++) {
31998
+ attributes[keys[i]].location = i;
31999
+ gl.bindAttribLocation(program, i, keys[i]);
32000
+ }
32001
+ gl.linkProgram(program);
32002
+ } else for (let i = 0; i < keys.length; i++) attributes[keys[i]].location = gl.getAttribLocation(program, keys[i]);
32003
+ return attributes;
32004
+ }
32005
+ //#endregion
32006
+ //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/rendering/renderers/gl/shader/program/getUboData.mjs
32007
+ function getUboData(program, gl) {
32008
+ if (!gl.ACTIVE_UNIFORM_BLOCKS) return {};
32009
+ const uniformBlocks = {};
32010
+ const totalUniformsBlocks = gl.getProgramParameter(program, gl.ACTIVE_UNIFORM_BLOCKS);
32011
+ for (let i = 0; i < totalUniformsBlocks; i++) {
32012
+ const name = gl.getActiveUniformBlockName(program, i);
32013
+ uniformBlocks[name] = {
32014
+ name,
32015
+ index: gl.getUniformBlockIndex(program, name),
32016
+ size: gl.getActiveUniformBlockParameter(program, i, gl.UNIFORM_BLOCK_DATA_SIZE)
32017
+ };
32018
+ }
32019
+ return uniformBlocks;
32020
+ }
32021
+ //#endregion
32022
+ //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/rendering/renderers/gl/shader/program/getUniformData.mjs
32023
+ function getUniformData(program, gl) {
32024
+ const uniforms = {};
32025
+ const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
32026
+ for (let i = 0; i < totalUniforms; i++) {
32027
+ const uniformData = gl.getActiveUniform(program, i);
32028
+ const name = uniformData.name.replace(/\[.*?\]$/, "");
32029
+ const isArray = !!uniformData.name.match(/\[.*?\]$/);
32030
+ const type = mapType(gl, uniformData.type);
32031
+ uniforms[name] = {
32032
+ name,
32033
+ index: i,
32034
+ type,
32035
+ size: uniformData.size,
32036
+ isArray,
32037
+ value: defaultValue(type, uniformData.size)
32038
+ };
32039
+ }
32040
+ return uniforms;
32041
+ }
32042
+ //#endregion
31079
32043
  //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/scene/particle-container/canvas/CanvasParticleContainerAdaptor.mjs
31080
32044
  var CanvasParticleContainerAdaptor = class {
31081
32045
  execute(particleContainerPipe, container) {
@@ -38266,6 +39230,9 @@ function colorSteps(filter) {
38266
39230
  }
38267
39231
  var BoardColorFilter = class extends ColorMatrixFilter {
38268
39232
  css = "";
39233
+ constructor() {
39234
+ super({ resolution: "inherit" });
39235
+ }
38269
39236
  set(filter) {
38270
39237
  const steps = colorSteps(filter);
38271
39238
  this.css = steps.map(({ step, value }) => step.css(value)).join(" ");
@@ -38343,21 +39310,47 @@ function shaderPasses() {
38343
39310
  };
38344
39311
  return passes;
38345
39312
  }
38346
- function gaussian(filters, input, output, deviation, clear) {
38347
- const { horizontal, vertical } = shaderPasses();
39313
+ const TEXELS_PER_DEVIATION = 4;
39314
+ const MAX_HALVINGS = 5;
39315
+ function gaussian(filters, input, output, deviation, clear, first) {
39316
+ const { horizontal, vertical, copy } = shaderPasses();
39317
+ const resolution = input.source.resolution;
39318
+ const halvings = Math.max(0, Math.min(MAX_HALVINGS, Math.floor(Math.log2(deviation * resolution / TEXELS_PER_DEVIATION))));
39319
+ const borrowed = [];
39320
+ const borrow = (scale) => {
39321
+ const texture = TexturePool.getOptimalTexture(input.frame.width, input.frame.height, resolution * scale, false);
39322
+ borrowed.push(texture);
39323
+ return texture;
39324
+ };
39325
+ let source = input;
39326
+ let scale = 1;
39327
+ for (let step = 0; step < Math.max(halvings, first ? 1 : 0); step++) {
39328
+ if (step < halvings) scale /= 2;
39329
+ const next = borrow(scale);
39330
+ filters.applyFilter(step === 0 && first ? first : copy, source, next, true);
39331
+ source = next;
39332
+ }
38348
39333
  horizontal.resources.blurUniforms.uniforms.uStep = [deviation / 4, 0];
38349
39334
  vertical.resources.blurUniforms.uniforms.uStep = [0, deviation / 4];
38350
- const between = TexturePool.getSameSizeTexture(input);
38351
- filters.applyFilter(horizontal, input, between, true);
38352
- filters.applyFilter(vertical, between, output, clear);
38353
- TexturePool.returnTexture(between);
39335
+ const between = borrow(scale);
39336
+ filters.applyFilter(horizontal, source, between, true);
39337
+ if (scale === 1) filters.applyFilter(vertical, between, output, clear);
39338
+ else {
39339
+ const blurred = borrow(scale);
39340
+ filters.applyFilter(vertical, between, blurred, true);
39341
+ filters.applyFilter(copy, blurred, output, clear);
39342
+ }
39343
+ for (const texture of borrowed) TexturePool.returnTexture(texture);
38354
39344
  }
38355
39345
  var BoardBlurFilter = class extends Filter {
38356
39346
  css = "";
38357
39347
  radius = 0;
38358
39348
  deviation = 0;
38359
39349
  constructor() {
38360
- super({ glProgram: program("board-copy", COPY_FRAGMENT) });
39350
+ super({
39351
+ glProgram: program("board-copy", COPY_FRAGMENT),
39352
+ resolution: "inherit"
39353
+ });
38361
39354
  }
38362
39355
  set(radius, zoom) {
38363
39356
  this.radius = radius;
@@ -38384,6 +39377,7 @@ var BoardShadowFilter = class extends Filter {
38384
39377
  deviation = 0;
38385
39378
  constructor() {
38386
39379
  super({
39380
+ resolution: "inherit",
38387
39381
  glProgram: program("board-shadow", SHADOW_FRAGMENT),
38388
39382
  resources: { shadowUniforms: {
38389
39383
  uOffset: {
@@ -38416,12 +39410,9 @@ var BoardShadowFilter = class extends Filter {
38416
39410
  }
38417
39411
  apply(filters, input, output, clearMode) {
38418
39412
  const { copy } = shaderPasses();
38419
- const shadow = TexturePool.getSameSizeTexture(input);
38420
- filters.applyFilter(this, input, shadow, true);
38421
- if (this.deviation > 0) gaussian(filters, shadow, output, this.deviation, clearMode);
38422
- else filters.applyFilter(copy, shadow, output, clearMode);
39413
+ if (this.deviation > 0) gaussian(filters, input, output, this.deviation, clearMode, this);
39414
+ else filters.applyFilter(this, input, output, clearMode);
38423
39415
  filters.applyFilter(copy, input, output, false);
38424
- TexturePool.returnTexture(shadow);
38425
39416
  }
38426
39417
  getCanvasFilterString() {
38427
39418
  return this.css;
@@ -38429,7 +39420,9 @@ var BoardShadowFilter = class extends Filter {
38429
39420
  };
38430
39421
  const filtersByContainer = /* @__PURE__ */ new WeakMap();
38431
39422
  function hasBoardEffects(style) {
38432
- return Boolean(style && (style.filter || style.shadow || style.blend && style.blend !== "normal"));
39423
+ if (!style) return false;
39424
+ const shadow = style.shadow && (style.shadow.opacity ?? BOARD_SHADOW_DEFAULTS.opacity) > 0;
39425
+ return Boolean(shadow || style.filter && (style.filter.blur || colorSteps(style.filter).length) || style.blend && style.blend !== "normal");
38433
39426
  }
38434
39427
  function resolveShadow(shadow, context) {
38435
39428
  return {
@@ -38462,7 +39455,8 @@ function syncBoardEffects(container, style, context) {
38462
39455
  const filter = style?.filter;
38463
39456
  const blurs = context.blurs !== false;
38464
39457
  const blur = blurs ? filter?.blur ?? 0 : 0;
38465
- const shadow = blurs && style?.shadow ? resolveShadow(style.shadow, context) : null;
39458
+ const resolved = blurs && style?.shadow ? resolveShadow(style.shadow, context) : null;
39459
+ const shadow = resolved && resolved.alpha > 0 ? resolved : null;
38466
39460
  const colored = colorSteps(filter).length > 0;
38467
39461
  let parts = filtersByContainer.get(container);
38468
39462
  if (!colored && blur <= 0 && !shadow) {
@@ -38908,6 +39902,32 @@ function roundRectPoints(width, height, radius) {
38908
39902
  worldPoint(width - r, 0)
38909
39903
  ];
38910
39904
  }
39905
+ function shapeOutlinePoints(geometry, width, height, radius) {
39906
+ const p = (x, y) => worldPoint(x, y);
39907
+ switch (geometry) {
39908
+ case "ellipse": {
39909
+ const segments = 64;
39910
+ return Array.from({ length: 65 }, (_, index) => {
39911
+ const angle = -Math.PI / 2 + index / segments * Math.PI * 2;
39912
+ return p(width / 2 + Math.cos(angle) * width / 2, height / 2 + Math.sin(angle) * height / 2);
39913
+ });
39914
+ }
39915
+ case "diamond": return [
39916
+ p(width / 2, 0),
39917
+ p(width, height / 2),
39918
+ p(width / 2, height),
39919
+ p(0, height / 2),
39920
+ p(width / 2, 0)
39921
+ ];
39922
+ case "triangle": return [
39923
+ p(width / 2, 0),
39924
+ p(width, height),
39925
+ p(0, height),
39926
+ p(width / 2, 0)
39927
+ ];
39928
+ default: return roundRectPoints(width, height, radius);
39929
+ }
39930
+ }
38911
39931
  const SHADOW_LAYERS = 5;
38912
39932
  function traceCardOutline(graphics, rect, style, grow = 0) {
38913
39933
  const x = rect.x - grow;
@@ -39452,7 +40472,8 @@ const modelCardRenderer = {
39452
40472
  const BOARD_PLAY_MEDIA = "play-media";
39453
40473
  function mediaPlayBadgeVisible(item, zoom, options) {
39454
40474
  if (!options.materialized) return false;
39455
- if (item.type === "video" || item.type === "audio") return true;
40475
+ if (item.type === "video") return item.props.time === void 0;
40476
+ if (item.type === "audio") return true;
39456
40477
  if (isBoardModelItem(item)) return boardCardDetailed(zoom);
39457
40478
  if (item.type !== "task" || !boardCardDetailed(zoom)) return false;
39458
40479
  const artifact = featuredTaskArtifact(item.props.snapshot.artifacts);
@@ -40482,7 +41503,6 @@ const frameCardRenderer = {
40482
41503
  };
40483
41504
  //#endregion
40484
41505
  //#region ../sdk/src/board/render/renderers/shape-card-renderer.ts
40485
- const DEFAULT_ROUNDED_RADIUS = 8;
40486
41506
  const partsByContainer$7 = /* @__PURE__ */ new WeakMap();
40487
41507
  const pathCache = /* @__PURE__ */ new Map();
40488
41508
  function parsedPath(d) {
@@ -40521,7 +41541,7 @@ function traceShapeOutline(graphics, props, width, height, radius) {
40521
41541
  graphics.moveTo(width / 2, 0).lineTo(width, height).lineTo(0, height).closePath();
40522
41542
  return;
40523
41543
  case "rounded":
40524
- graphics.roundRect(0, 0, width, height, radius ?? DEFAULT_ROUNDED_RADIUS);
41544
+ graphics.roundRect(0, 0, width, height, radius ?? 8);
40525
41545
  return;
40526
41546
  case "path": {
40527
41547
  const parsed = props.path ? parsedPath(props.path) : null;
@@ -40538,32 +41558,6 @@ function traceShapeOutline(graphics, props, width, height, radius) {
40538
41558
  else graphics.rect(0, 0, width, height);
40539
41559
  }
40540
41560
  }
40541
- function outlinePoints(geometry, width, height, radius) {
40542
- const p = (x, y) => worldPoint(x, y);
40543
- switch (geometry) {
40544
- case "ellipse": {
40545
- const segments = 64;
40546
- return Array.from({ length: 65 }, (_, index) => {
40547
- const angle = -Math.PI / 2 + index / segments * Math.PI * 2;
40548
- return p(width / 2 + Math.cos(angle) * width / 2, height / 2 + Math.sin(angle) * height / 2);
40549
- });
40550
- }
40551
- case "diamond": return [
40552
- p(width / 2, 0),
40553
- p(width, height / 2),
40554
- p(width / 2, height),
40555
- p(0, height / 2),
40556
- p(width / 2, 0)
40557
- ];
40558
- case "triangle": return [
40559
- p(width / 2, 0),
40560
- p(width, height),
40561
- p(0, height),
40562
- p(width / 2, 0)
40563
- ];
40564
- default: return roundRectPoints(width, height, radius);
40565
- }
40566
- }
40567
41561
  function sync$7(container, item, context) {
40568
41562
  const parts = partsByContainer$7.get(container);
40569
41563
  if (!parts) return;
@@ -40603,8 +41597,8 @@ function sync$7(container, item, context) {
40603
41597
  const partial = style.trim !== void 0 && style.trim < 1;
40604
41598
  if (strokeWidth > 0 && (!partial || style.trim)) {
40605
41599
  if ((pattern || partial) && props.geometry !== "path") {
40606
- const radius = style.radius ?? (props.geometry === "rounded" ? DEFAULT_ROUNDED_RADIUS : 0);
40607
- tracePolyline(parts.shape, trimPolyline(outlinePoints(props.geometry, width, height, radius), style.trim), pattern);
41600
+ const radius = style.radius ?? (props.geometry === "rounded" ? 8 : 0);
41601
+ tracePolyline(parts.shape, trimPolyline(shapeOutlinePoints(props.geometry, width, height, radius), style.trim), pattern);
40608
41602
  } else traceShapeOutline(parts.shape, props, width, height, style.radius);
40609
41603
  parts.shape.stroke({
40610
41604
  color: stroke,
@@ -42168,8 +43162,9 @@ function sync(container, item, context) {
42168
43162
  text: duration ? `${title} · ${duration}` : title,
42169
43163
  width
42170
43164
  }, context);
43165
+ const live = context.mediaTexture?.(item.id) ?? null;
42171
43166
  const key = context.assetKey(item);
42172
- const texture = key ? context.getTexture(key) : null;
43167
+ const texture = live ?? (key ? context.getTexture(key) : null);
42173
43168
  const elevation = cardElevation(context, item.id);
42174
43169
  const sig = [
42175
43170
  key ?? "",
@@ -42178,6 +43173,7 @@ function sync(container, item, context) {
42178
43173
  height,
42179
43174
  elevation,
42180
43175
  boardCardDetailed(context.zoom),
43176
+ item.props.time === void 0,
42181
43177
  context.themeKey
42182
43178
  ].join("|");
42183
43179
  if (sig === parts.sig) return;
@@ -42217,7 +43213,7 @@ function sync(container, item, context) {
42217
43213
  } : context.style);
42218
43214
  }
42219
43215
  parts.chrome.clear();
42220
- if (boardCardDetailed(context.zoom)) drawMediaPlayKey(parts.chrome, screen.x + screen.width / 2, screen.y + screen.height / 2, Math.min(18, Math.min(screen.width, screen.height) * .16), context);
43216
+ if (boardCardDetailed(context.zoom) && item.props.time === void 0) drawMediaPlayKey(parts.chrome, screen.x + screen.width / 2, screen.y + screen.height / 2, Math.min(18, Math.min(screen.width, screen.height) * .16), context);
42221
43217
  }
42222
43218
  function drawFilmRails(graphics, width, height, rail, hole) {
42223
43219
  const size = Math.min(FILM_HOLE, rail * .45);
@@ -42567,6 +43563,7 @@ const itemEnvelope = {
42567
43563
  y: .5
42568
43564
  }).describe("Rotation and scale origin as fractions of the size."),
42569
43565
  opacity: ratio.default(1),
43566
+ visible: boolean().optional().describe("false hides the item and its children; key it on a timeline to show the item only for a span."),
42570
43567
  style: BoardStyleSchema.default({}),
42571
43568
  locked: boolean().optional(),
42572
43569
  metadata: record(string(), unknown()).optional()
@@ -42716,7 +43713,8 @@ const mediaProps = {
42716
43713
  };
42717
43714
  const timedFileProps = {
42718
43715
  ...mediaProps,
42719
- time: nonNegative.optional().describe("Playback position in milliseconds; animate props.time to play it on a timeline.")
43716
+ time: nonNegative.optional().describe("Playback position in milliseconds; animate props.time to play it on a timeline. It sounds while its time moves forward."),
43717
+ volume: ratio.optional().describe("Loudness from 0 to 1; defaults to 1. Animate it to fade.")
42720
43718
  };
42721
43719
  const BoardCropSchema = object({
42722
43720
  x: ratio,
@@ -43056,40 +44054,51 @@ async function loadBoardScriptSources(src, read, timeoutMs = 15e3) {
43056
44054
  const { init, parse } = await import("./board-kernel/lexer.js");
43057
44055
  await init;
43058
44056
  const sources = {};
43059
- const visiting = /* @__PURE__ */ new Set();
44057
+ const loading = /* @__PURE__ */ new Map();
44058
+ const edges = /* @__PURE__ */ new Map();
43060
44059
  let bytes = 0;
43061
- async function visit(path) {
43062
- if (visiting.has(path)) throw new Error(`Circular module dependency: ${path}`);
43063
- if (sources[path]) return;
43064
- if (Object.keys(sources).length + visiting.size >= 64) throw new Error("A script may load at most 64 modules.");
43065
- visiting.add(path);
43066
- let timer;
43067
- const code = await Promise.race([Promise.resolve().then(() => read(path)), new Promise((_resolve, reject) => {
43068
- timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`Module read timed out: ${path}`)), timeoutMs);
43069
- })]).finally(() => clearTimeout(timer));
43070
- bytes += new TextEncoder().encode(code).byteLength;
43071
- if (bytes > 2e6) throw new Error("Script modules exceed the 2 MB limit.");
43072
- const [imports] = parse(code, path);
43073
- const resolved = [];
43074
- for (const entry of imports) {
43075
- if (entry.d === -2) throw new Error("import.meta is not available in Board scripts.");
43076
- if (entry.n === void 0) throw new Error("Dynamic imports must use a literal relative path.");
43077
- const dependency = resolveScriptImport(path, entry.n);
43078
- await visit(dependency);
43079
- resolved.push({
43080
- start: entry.s,
43081
- end: entry.e,
43082
- path: dependency,
43083
- dynamic: entry.d >= 0
43084
- });
43085
- }
43086
- sources[path] = {
43087
- code,
43088
- imports: resolved
43089
- };
43090
- visiting.delete(path);
44060
+ function load(path) {
44061
+ let promise = loading.get(path);
44062
+ if (promise) return promise;
44063
+ if (loading.size >= 64) throw new Error("A script may load at most 64 modules.");
44064
+ promise = (async () => {
44065
+ let timer;
44066
+ const code = await Promise.race([Promise.resolve().then(() => read(path)), new Promise((_resolve, reject) => {
44067
+ timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`Module read timed out: ${path}`)), timeoutMs);
44068
+ })]).finally(() => clearTimeout(timer));
44069
+ bytes += new TextEncoder().encode(code).byteLength;
44070
+ if (bytes > 2e6) throw new Error("Script modules exceed the 2 MB limit.");
44071
+ const [imports] = parse(code, path);
44072
+ const resolved = [];
44073
+ for (const entry of imports) {
44074
+ if (entry.d === -2) throw new Error("import.meta is not available in Board scripts.");
44075
+ if (entry.n === void 0) throw new Error("Dynamic imports must use a literal relative path.");
44076
+ resolved.push({
44077
+ start: entry.s,
44078
+ end: entry.e,
44079
+ path: resolveScriptImport(path, entry.n),
44080
+ dynamic: entry.d >= 0
44081
+ });
44082
+ }
44083
+ const dependencies = resolved.map((entry) => entry.path);
44084
+ edges.set(path, dependencies);
44085
+ if (dependencies.some((dependency) => importsReach(dependency, path))) throw new Error(`Circular module dependency: ${path}`);
44086
+ await Promise.all(dependencies.map(load));
44087
+ sources[path] = {
44088
+ code,
44089
+ imports: resolved
44090
+ };
44091
+ })();
44092
+ loading.set(path, promise);
44093
+ return promise;
44094
+ }
44095
+ function importsReach(from, target, seen = /* @__PURE__ */ new Set()) {
44096
+ if (from === target) return true;
44097
+ if (seen.has(from)) return false;
44098
+ seen.add(from);
44099
+ return (edges.get(from) ?? []).some((next) => importsReach(next, target, seen));
43091
44100
  }
43092
- await visit(src);
44101
+ await load(src);
43093
44102
  return sources;
43094
44103
  }
43095
44104
  //#endregion
@@ -43114,6 +44123,7 @@ function createScriptRuntime(module, initial, host) {
43114
44123
  let disposed = false;
43115
44124
  let stepping = false;
43116
44125
  let revision = 0;
44126
+ let sceneRevision = 0;
43117
44127
  let randomState = 2166136261;
43118
44128
  for (const char of initial.script.seed ?? initial.id) randomState = Math.imul(randomState ^ char.charCodeAt(0), 16777619) >>> 0;
43119
44129
  const parameterDefaults = Object.fromEntries(Object.entries(module.parameters ?? {}).filter(([, spec]) => spec.default !== void 0).map(([key, spec]) => [key, spec.default]));
@@ -43148,9 +44158,11 @@ function createScriptRuntime(module, initial, host) {
43148
44158
  let view = null;
43149
44159
  let hits = effects?.hits ?? {};
43150
44160
  let uniforms = effects?.uniforms;
43151
- const invalidate = () => {
44161
+ let passes = effects?.passes;
44162
+ const invalidate = (scene = true) => {
43152
44163
  if (disposed) return;
43153
44164
  revision++;
44165
+ if (scene) sceneRevision++;
43154
44166
  host.invalidate();
43155
44167
  };
43156
44168
  const present = (id, patch) => {
@@ -43225,7 +44237,7 @@ function createScriptRuntime(module, initial, host) {
43225
44237
  };
43226
44238
  },
43227
44239
  onDispose: (handler) => cleanups.push(handler),
43228
- invalidate,
44240
+ invalidate: () => invalidate(),
43229
44241
  get: (id) => input.items[id],
43230
44242
  present,
43231
44243
  scene(next, options) {
@@ -43256,7 +44268,16 @@ function createScriptRuntime(module, initial, host) {
43256
44268
  ...uniforms,
43257
44269
  ...values
43258
44270
  };
43259
- invalidate();
44271
+ invalidate(false);
44272
+ },
44273
+ passes(next) {
44274
+ if (!next || typeof next !== "object" || Object.values(next).some((on) => typeof on !== "boolean")) throw new Error("passes() takes a record of pass names and booleans.");
44275
+ if (Object.entries(next).every(([name, on]) => passes?.[name] === on)) return;
44276
+ passes = {
44277
+ ...passes,
44278
+ ...next
44279
+ };
44280
+ invalidate(false);
43260
44281
  },
43261
44282
  async commit(patch) {
43262
44283
  return await host.call("board.commit", {
@@ -43272,7 +44293,16 @@ function createScriptRuntime(module, initial, host) {
43272
44293
  call: (name, value) => host.call(name, value)
43273
44294
  }
43274
44295
  };
43275
- const setup = module.default?.(context);
44296
+ const seeded = (run) => {
44297
+ const random = Math.random;
44298
+ Math.random = context.random;
44299
+ try {
44300
+ return run();
44301
+ } finally {
44302
+ Math.random = random;
44303
+ }
44304
+ };
44305
+ const setup = seeded(() => module.default?.(context));
43276
44306
  if (typeof setup === "function") cleanups.push(setup);
43277
44307
  return {
43278
44308
  get animated() {
@@ -43283,6 +44313,7 @@ function createScriptRuntime(module, initial, host) {
43283
44313
  for (const id of Object.keys(patches)) if (!next.items[id]) {
43284
44314
  delete patches[id];
43285
44315
  revision++;
44316
+ sceneRevision++;
43286
44317
  }
43287
44318
  params = {
43288
44319
  ...parameterDefaults,
@@ -43303,10 +44334,12 @@ function createScriptRuntime(module, initial, host) {
43303
44334
  };
43304
44335
  stepping = true;
43305
44336
  try {
43306
- for (const handler of frames) {
43307
- const result = handler(frame);
43308
- if (result && typeof result.then === "function") throw new Error("onFrame() handlers must be synchronous.");
43309
- }
44337
+ seeded(() => {
44338
+ for (const handler of frames) {
44339
+ const result = handler(frame);
44340
+ if (result && typeof result.then === "function") throw new Error("onFrame() handlers must be synchronous.");
44341
+ }
44342
+ });
43310
44343
  } finally {
43311
44344
  stepping = false;
43312
44345
  }
@@ -43334,11 +44367,13 @@ function createScriptRuntime(module, initial, host) {
43334
44367
  if (event.type === "viewchange") view = event.data;
43335
44368
  const listeners = handlers.get(event.type);
43336
44369
  if (!listeners?.size) return;
43337
- for (const handler of listeners) handler(event);
44370
+ seeded(() => {
44371
+ for (const handler of listeners) handler(event);
44372
+ });
43338
44373
  invalidate();
43339
44374
  },
43340
44375
  draw(canvas) {
43341
- const result = module.draw?.(canvas, frame);
44376
+ const result = seeded(() => module.draw?.(canvas, frame));
43342
44377
  if (result && typeof result.then === "function") throw new Error("draw() must be synchronous.");
43343
44378
  },
43344
44379
  output() {
@@ -43351,13 +44386,15 @@ function createScriptRuntime(module, initial, host) {
43351
44386
  hits,
43352
44387
  shader: module.shader,
43353
44388
  uniforms,
44389
+ passes,
43354
44390
  listens: [...handlers].filter(([, callbacks]) => callbacks.size).map(([type]) => type),
43355
44391
  animated: this.animated,
43356
44392
  draws: typeof module.draw === "function",
43357
44393
  updating: frames.size > 0,
43358
44394
  frameRate: module.frameRate,
43359
44395
  pixelated: module.pixelated,
43360
- version: revision
44396
+ version: revision,
44397
+ sceneVersion: sceneRevision
43361
44398
  };
43362
44399
  },
43363
44400
  snapshot(includeEffects = true, clone = true) {
@@ -43371,7 +44408,8 @@ function createScriptRuntime(module, initial, host) {
43371
44408
  screen: layers.screen,
43372
44409
  anchor,
43373
44410
  hits,
43374
- uniforms
44411
+ uniforms,
44412
+ passes
43375
44413
  } : void 0
43376
44414
  };
43377
44415
  return clone ? structuredClone(snapshot) : snapshot;
@@ -43386,10 +44424,39 @@ function createScriptRuntime(module, initial, host) {
43386
44424
  layers.screen = {};
43387
44425
  hits = {};
43388
44426
  uniforms = void 0;
44427
+ passes = void 0;
43389
44428
  }
43390
44429
  };
43391
44430
  }
43392
44431
  //#endregion
44432
+ //#region ../sdk/src/board/model/script-calls.ts
44433
+ function layoutBoardScriptText(value) {
44434
+ const input = value;
44435
+ if (!input || typeof input.text !== "string" || input.text.length > 1e4) throw new Error("layoutText() needs text of at most 10000 characters.");
44436
+ for (const key of [
44437
+ "fontSize",
44438
+ "fontWeight",
44439
+ "lineHeight",
44440
+ "width"
44441
+ ]) if (input[key] !== void 0 && !(Number.isFinite(input[key]) && input[key] > 0)) throw new Error(`layoutText() ${key} must be a positive number.`);
44442
+ const { width, height } = layoutBoardText({
44443
+ fontSize: 24,
44444
+ fontWeight: 500,
44445
+ font: "sans",
44446
+ lineHeight: 4 / 3,
44447
+ ...input
44448
+ });
44449
+ return {
44450
+ width,
44451
+ height
44452
+ };
44453
+ }
44454
+ const BOARD_SCRIPT_EXPORT_CALLS = {
44455
+ "board.emit": () => void 0,
44456
+ "board.commit": () => false,
44457
+ "board.layoutText": layoutBoardScriptText
44458
+ };
44459
+ //#endregion
43393
44460
  //#region ../sdk/src/board/render/shader/library.ts
43394
44461
  const BOARD_SHADER_LIBRARY = {
43395
44462
  hash: `
@@ -43453,6 +44520,12 @@ float luminance(vec3 c) { return dot(c, vec3(0.2126, 0.7152, 0.0722)); }
43453
44520
  //#endregion
43454
44521
  //#region ../sdk/src/board/render/shader/program.ts
43455
44522
  const BOARD_SHADER_ITERATIONS = 65536;
44523
+ const BOARD_SPRITE_PLACEMENTS = [
44524
+ "uCohubSpriteGeometry",
44525
+ "uCohubSpriteColor",
44526
+ "uCohubSpriteData",
44527
+ "uCohubSpriteRotation"
44528
+ ];
43456
44529
  const FORBIDDEN = [
43457
44530
  [/#\s*(version|extension|pragma|line)\b/, "#version, #extension, #pragma and #line are set by Cohub"],
43458
44531
  [/\b(uniform|attribute|varying|layout)\b/, "declare uniforms in shader.uniforms; inputs and outputs belong to Cohub"],
@@ -43543,7 +44616,8 @@ function declarations(input, stage) {
43543
44616
  "precision highp float;",
43544
44617
  "precision highp int;",
43545
44618
  "precision highp sampler2D;",
43546
- stage === "vertex" ? "#define COHUB_VERTEX 1" : "#define COHUB_FRAGMENT 1"
44619
+ stage === "vertex" ? "#define COHUB_VERTEX 1" : "#define COHUB_FRAGMENT 1",
44620
+ `#define COHUB_SPRITE_COLUMNS 256`
43547
44621
  ];
43548
44622
  if (stage === "vertex") lines.push("#define dFdx(x) ((x) * 0.0)", "#define dFdy(x) ((x) * 0.0)", "#define fwidth(x) ((x) * 0.0)", "#define discard return vec4(0.0)");
43549
44623
  lines.push("struct Board { float time; float delta; int frame; vec2 size; vec4 view; vec2 resolution; float zoom; float seed; float quality; float dark; };", "uniform Board board;");
@@ -43566,6 +44640,22 @@ vec4 cohubClip(vec2 local) {
43566
44640
  return vec4((m * vec3(local, 1.0)).xy, 0.0, 1.0);
43567
44641
  }`;
43568
44642
  const VARYINGS = "vec2 vCohubUv; vec2 vCohubLocal; vec4 vCohubColor; vec4 vCohubData;";
44643
+ function spriteVertex(out) {
44644
+ return `in vec2 aPosition;
44645
+ ${CLIP}
44646
+ ${out}
44647
+ void cohubEmit(vec2 position, vec2 size, float rotation, vec4 color, vec4 data) {
44648
+ vec2 corner = (aPosition - 0.5) * size;
44649
+ float c = cos(rotation);
44650
+ float r = sin(rotation);
44651
+ vec2 local = position + vec2(corner.x * c - corner.y * r, corner.x * r + corner.y * c);
44652
+ gl_Position = cohubClip(local);
44653
+ vCohubUv = aPosition;
44654
+ vCohubLocal = local;
44655
+ vCohubColor = color;
44656
+ vCohubData = data;
44657
+ }`;
44658
+ }
43569
44659
  function vertexMain(kind) {
43570
44660
  const out = VARYINGS.split(" ").reduce((text, part, index) => text + (index % 2 ? `${part} ` : `out ${part} `), "");
43571
44661
  if (kind === "filter") return `in vec2 aPosition;
@@ -43582,22 +44672,20 @@ void main() {
43582
44672
  vCohubColor = vec4(1.0);
43583
44673
  vCohubData = vec4(0.0);
43584
44674
  }`;
43585
- if (kind === "sprites") return `in vec2 aPosition;
43586
- ${CLIP}
43587
- ${out}
44675
+ if (kind === "placed") return `${spriteVertex(out)}
44676
+ ${BOARD_SPRITE_PLACEMENTS.map((name) => `uniform sampler2D ${name};`).join("\n")}
44677
+ void main() {
44678
+ ivec2 at = ivec2(gl_InstanceID % COHUB_SPRITE_COLUMNS, gl_InstanceID / COHUB_SPRITE_COLUMNS);
44679
+ vec4 placed = texelFetch(uCohubSpriteGeometry, at, 0);
44680
+ if (placed.z <= 0.0 || placed.w <= 0.0) { gl_Position = vec4(2.0, 2.0, 2.0, 1.0); return; }
44681
+ cohubEmit(placed.xy, placed.zw, texelFetch(uCohubSpriteRotation, at, 0).x, texelFetch(uCohubSpriteColor, at, 0), texelFetch(uCohubSpriteData, at, 0));
44682
+ }`;
44683
+ if (kind === "sprites") return `${spriteVertex(out)}
43588
44684
  void main() {
43589
44685
  cohubIterations = 0;
43590
44686
  Sprite s = sprite(gl_InstanceID);
43591
44687
  if (!s.visible || s.size.x <= 0.0 || s.size.y <= 0.0) { gl_Position = vec4(2.0, 2.0, 2.0, 1.0); return; }
43592
- vec2 corner = (aPosition - 0.5) * s.size;
43593
- float c = cos(s.rotation);
43594
- float r = sin(s.rotation);
43595
- vec2 local = s.position + vec2(corner.x * c - corner.y * r, corner.x * r + corner.y * c);
43596
- gl_Position = cohubClip(local);
43597
- vCohubUv = aPosition;
43598
- vCohubLocal = local;
43599
- vCohubColor = s.color;
43600
- vCohubData = s.data;
44688
+ cohubEmit(s.position, s.size, s.rotation, s.color, s.data);
43601
44689
  }`;
43602
44690
  return `in vec2 aPosition;
43603
44691
  uniform vec4 uCohubGeometry;
@@ -43613,7 +44701,25 @@ void main() {
43613
44701
  }`;
43614
44702
  }
43615
44703
  function fragmentMain(kind) {
43616
- return `${VARYINGS.split(" ").reduce((text, part, index) => text + (index % 2 ? `${part} ` : `in ${part} `), "")}
44704
+ const inputs = VARYINGS.split(" ").reduce((text, part, index) => text + (index % 2 ? `${part} ` : `in ${part} `), "");
44705
+ if (kind === "place") return `uniform int uCohubSpriteCount;
44706
+ layout(location = 0) out vec4 cohubGeometry;
44707
+ layout(location = 1) out vec4 cohubColor;
44708
+ layout(location = 2) out vec4 cohubData;
44709
+ layout(location = 3) out vec4 cohubRotation;
44710
+ void main() {
44711
+ cohubIterations = 0;
44712
+ ivec2 at = ivec2(gl_FragCoord.xy);
44713
+ int id = at.y * COHUB_SPRITE_COLUMNS + at.x;
44714
+ if (id >= uCohubSpriteCount) { cohubGeometry = vec4(0.0); return; }
44715
+ Sprite s = sprite(id);
44716
+ bool shown = s.visible && s.size.x > 0.0 && s.size.y > 0.0;
44717
+ cohubGeometry = shown ? vec4(s.position, s.size) : vec4(0.0);
44718
+ cohubColor = s.color;
44719
+ cohubData = s.data;
44720
+ cohubRotation = vec4(s.rotation, 0.0, 0.0, 0.0);
44721
+ }`;
44722
+ return `${inputs}
43617
44723
  ${kind === "filter" ? "in vec2 vTextureCoord;" : "uniform vec4 uColor;"}
43618
44724
  out vec4 finalColor;
43619
44725
  void main() {
@@ -43629,16 +44735,18 @@ function lineCount(text) {
43629
44735
  function buildBoardShaderProgram(input) {
43630
44736
  const { code, includes } = prepareBoardShaderSource(input.glsl);
43631
44737
  const library = includes.map((name) => BOARD_SHADER_LIBRARY[name]).join("\n");
43632
- const stage = (name) => {
43633
- const head = `${declarations(input, name)}\n${library}`;
43634
- const main = name === "vertex" ? vertexMain(input.kind) : fragmentMain(input.kind);
44738
+ const author = (role, main) => {
44739
+ const head = `${declarations(input, role)}\n${library}`;
43635
44740
  return {
43636
44741
  source: `${head}\n${code}\n${main}\n`,
43637
44742
  firstLine: lineCount(head) + 1
43638
44743
  };
43639
44744
  };
43640
- const vertex = stage("vertex");
43641
- const fragment = stage("fragment");
44745
+ const vertex = input.kind === "sprites" ? author("vertex", vertexMain(input.kind)) : {
44746
+ source: `${declarations(input, "vertex")}\n${vertexMain(input.kind)}\n`,
44747
+ firstLine: 1
44748
+ };
44749
+ const fragment = author(input.kind === "place" ? "vertex" : "fragment", fragmentMain(input.kind));
43642
44750
  return {
43643
44751
  vertex: vertex.source,
43644
44752
  fragment: fragment.source,
@@ -43655,11 +44763,28 @@ function describeBoardShaderError(log, firstLine, label) {
43655
44763
  })).slice(0, 4).join("; ") || "the shader failed to compile"}`;
43656
44764
  }
43657
44765
  function boardShaderStages(shader, label) {
43658
- const stages = shader.passes.map((pass, index) => ({
43659
- name: `${label} pass ${index + 1}`,
43660
- kind: shader.layer === "filter" ? "filter" : pass.sprites ? "sprites" : "box",
43661
- glsl: pass.glsl
43662
- }));
44766
+ const stages = shader.passes.flatMap((pass, index) => {
44767
+ const name = `${label} pass ${index + 1}`;
44768
+ if (boardShaderPassLayer(shader, pass) === "filter") return [{
44769
+ name,
44770
+ kind: "filter",
44771
+ glsl: pass.glsl
44772
+ }];
44773
+ if (!pass.sprites) return [{
44774
+ name,
44775
+ kind: "box",
44776
+ glsl: pass.glsl
44777
+ }];
44778
+ return [{
44779
+ name,
44780
+ kind: "place",
44781
+ glsl: pass.glsl
44782
+ }, {
44783
+ name,
44784
+ kind: "placed",
44785
+ glsl: pass.glsl
44786
+ }];
44787
+ });
43663
44788
  if (shader.state) stages.push({
43664
44789
  name: `${label} state`,
43665
44790
  kind: "simulate",
@@ -43686,6 +44811,100 @@ function checkBoardShader(shader, parameters, label) {
43686
44811
  }
43687
44812
  }
43688
44813
  //#endregion
44814
+ //#region ../sdk/src/board/render/shader/compile.ts
44815
+ const READY = {
44816
+ poll: () => true,
44817
+ cancel() {}
44818
+ };
44819
+ const COMPLETION_STATUS = 37297;
44820
+ const failures = /* @__PURE__ */ new Map();
44821
+ const parallel = /* @__PURE__ */ new WeakMap();
44822
+ function programs(renderer) {
44823
+ return renderer.shader._programDataHash ?? null;
44824
+ }
44825
+ function adopt(gl, glProgram, program, cache) {
44826
+ glProgram._attributeData = extractAttributesFromGlProgram(program, gl, false);
44827
+ glProgram._uniformData = getUniformData(program, gl);
44828
+ glProgram._uniformBlockData = getUboData(program, gl);
44829
+ const uniforms = {};
44830
+ for (const [name, data] of Object.entries(glProgram._uniformData)) uniforms[name] = {
44831
+ location: gl.getUniformLocation(program, name),
44832
+ value: defaultValue(data.type, data.size)
44833
+ };
44834
+ cache[glProgram._key] = new GlProgramData(program, uniforms);
44835
+ }
44836
+ function lineShift(raw, final) {
44837
+ return final.split("\n").length - raw.split("\n").length;
44838
+ }
44839
+ function compileBoardProgram(renderer, glProgram, source, label, wait) {
44840
+ if (renderer.type !== RendererType.WEBGL) return READY;
44841
+ const failure = failures.get(glProgram._key);
44842
+ if (failure) throw new Error(failure);
44843
+ const cache = programs(renderer);
44844
+ if (cache?.[glProgram._key]) return READY;
44845
+ const gl = renderer.gl;
44846
+ if (!parallel.has(gl)) parallel.set(gl, Boolean(gl.getExtension("KHR_parallel_shader_compile")));
44847
+ const job = {
44848
+ gl,
44849
+ program: gl.createProgram(),
44850
+ shaders: [gl.createShader(gl.VERTEX_SHADER), gl.createShader(gl.FRAGMENT_SHADER)]
44851
+ };
44852
+ const vertex = glProgram.vertex;
44853
+ const fragment = glProgram.fragment;
44854
+ const stages = [{
44855
+ shader: job.shaders[0],
44856
+ code: vertex,
44857
+ first: source.firstLine.vertex + lineShift(source.vertex, vertex),
44858
+ name: "vertex"
44859
+ }, {
44860
+ shader: job.shaders[1],
44861
+ code: fragment,
44862
+ first: source.firstLine.fragment + lineShift(source.fragment, fragment),
44863
+ name: "fragment"
44864
+ }];
44865
+ for (const { shader, code } of stages) {
44866
+ gl.shaderSource(shader, code);
44867
+ gl.compileShader(shader);
44868
+ gl.attachShader(job.program, shader);
44869
+ }
44870
+ gl.linkProgram(job.program);
44871
+ let done = false;
44872
+ const finish = () => {
44873
+ done = true;
44874
+ let error = null;
44875
+ if (!gl.getProgramParameter(job.program, gl.LINK_STATUS) && !gl.isContextLost()) {
44876
+ for (const { shader, first, name } of stages) if (!error && !gl.getShaderParameter(shader, gl.COMPILE_STATUS)) error = describeBoardShaderError(gl.getShaderInfoLog(shader) ?? "", first, `${label} (${name})`);
44877
+ error ??= `${label}: ${gl.getProgramInfoLog(job.program) ?? "the shader failed to link"}`;
44878
+ }
44879
+ for (const shader of job.shaders) gl.deleteShader(shader);
44880
+ if (error || !cache || gl.isContextLost()) {
44881
+ gl.deleteProgram(job.program);
44882
+ if (error) {
44883
+ if (failures.size > 256) failures.clear();
44884
+ failures.set(glProgram._key, error);
44885
+ throw new Error(error);
44886
+ }
44887
+ return true;
44888
+ }
44889
+ if (cache[glProgram._key]) gl.deleteProgram(job.program);
44890
+ else adopt(gl, glProgram, job.program, cache);
44891
+ return true;
44892
+ };
44893
+ if (wait || !parallel.get(gl)) {
44894
+ finish();
44895
+ return READY;
44896
+ }
44897
+ return {
44898
+ poll: () => done || (gl.getProgramParameter(job.program, COMPLETION_STATUS) === true ? finish() : false),
44899
+ cancel() {
44900
+ if (done) return;
44901
+ done = true;
44902
+ for (const shader of job.shaders) gl.deleteShader(shader);
44903
+ gl.deleteProgram(job.program);
44904
+ }
44905
+ };
44906
+ }
44907
+ //#endregion
43689
44908
  //#region ../sdk/src/board/render/shader/quad.ts
43690
44909
  function boardQuadGeometry(instanceCount = 1) {
43691
44910
  return new Geometry({
@@ -43713,14 +44932,18 @@ function boardQuadGeometry(instanceCount = 1) {
43713
44932
  instanceCount
43714
44933
  });
43715
44934
  }
44935
+ function boardGlProgram(name, source) {
44936
+ return GlProgram.from({
44937
+ name,
44938
+ vertex: source.vertex,
44939
+ fragment: source.fragment,
44940
+ preferredFragmentPrecision: "highp"
44941
+ });
44942
+ }
43716
44943
  function boardShaderMesh(name, source, resources, geometry = boardQuadGeometry()) {
44944
+ const glProgram = source instanceof GlProgram ? source : boardGlProgram(name, source);
43717
44945
  const shader = new Shader({
43718
- glProgram: GlProgram.from({
43719
- name,
43720
- vertex: source.vertex,
43721
- fragment: source.fragment,
43722
- preferredFragmentPrecision: "highp"
43723
- }),
44946
+ glProgram,
43724
44947
  resources
43725
44948
  });
43726
44949
  return {
@@ -43763,6 +44986,8 @@ const STEP_MS = 1e3 / 60;
43763
44986
  const STEPS_PER_FRAME = 8;
43764
44987
  const MAX_LAG = 60;
43765
44988
  const MAX_REPLAY = 36e3;
44989
+ const CHECKPOINT_STEPS = 600;
44990
+ const CHECKPOINTS = 6;
43766
44991
  const PIXI_TYPES = {
43767
44992
  float: "f32",
43768
44993
  int: "i32",
@@ -43777,45 +45002,50 @@ const SIZES = {
43777
45002
  vec3: 3,
43778
45003
  vec4: 4
43779
45004
  };
43780
- const compiled = /* @__PURE__ */ new Map();
43781
- function check(renderer, program, label) {
43782
- if (renderer.type !== RendererType.WEBGL) return;
43783
- const key = `${program.vertex}\u0000${program.fragment}`;
43784
- let error = compiled.get(key);
43785
- if (error === void 0) {
43786
- const gl = renderer.gl;
43787
- error = null;
43788
- const shaders = [];
43789
- const glProgram = gl.createProgram();
43790
- for (const [stage, type, source, first] of [[
43791
- "vertex",
43792
- gl.VERTEX_SHADER,
43793
- program.vertex,
43794
- program.firstLine.vertex
43795
- ], [
43796
- "fragment",
43797
- gl.FRAGMENT_SHADER,
43798
- program.fragment,
43799
- program.firstLine.fragment
43800
- ]]) {
43801
- const shader = gl.createShader(type);
43802
- if (!shader) continue;
43803
- gl.shaderSource(shader, source);
43804
- gl.compileShader(shader);
43805
- shaders.push(shader);
43806
- if (!error && !gl.getShaderParameter(shader, gl.COMPILE_STATUS) && !gl.isContextLost()) error = describeBoardShaderError(gl.getShaderInfoLog(shader) ?? "", first, `${label} (${stage})`);
43807
- gl.attachShader(glProgram, shader);
43808
- }
43809
- if (!error) {
43810
- gl.linkProgram(glProgram);
43811
- if (!gl.getProgramParameter(glProgram, gl.LINK_STATUS) && !gl.isContextLost()) error = `${label}: ${gl.getProgramInfoLog(glProgram) ?? "the shader failed to link"}`;
43812
- }
43813
- for (const shader of shaders) gl.deleteShader(shader);
43814
- gl.deleteProgram(glProgram);
43815
- if (compiled.size > 256) compiled.clear();
43816
- compiled.set(key, error);
45005
+ const placing = /* @__PURE__ */ new WeakMap();
45006
+ function canPlaceSprites(renderer) {
45007
+ let supported = placing.get(renderer);
45008
+ if (supported === void 0) {
45009
+ const gl = renderer.type === RendererType.WEBGL ? renderer.gl : null;
45010
+ supported = Boolean(gl?.getExtension("EXT_color_buffer_float") && gl.getParameter(gl.MAX_DRAW_BUFFERS) >= BOARD_SPRITE_PLACEMENTS.length);
45011
+ placing.set(renderer, supported);
45012
+ }
45013
+ return supported;
45014
+ }
45015
+ function createPlacement(mesh, uniforms, sprites) {
45016
+ mesh.mesh.blendMode = "none";
45017
+ const height = Math.ceil(sprites / 256);
45018
+ const textures = BOARD_SPRITE_PLACEMENTS.map(() => new TextureSource({
45019
+ width: 256,
45020
+ height,
45021
+ resolution: 1,
45022
+ format: "rgba32float",
45023
+ scaleMode: "nearest",
45024
+ autoGenerateMipmaps: false
45025
+ }));
45026
+ return {
45027
+ mesh,
45028
+ uniforms,
45029
+ target: new RenderTarget({
45030
+ colorTextures: textures,
45031
+ width: 256,
45032
+ height,
45033
+ resolution: 1
45034
+ }),
45035
+ textures
45036
+ };
45037
+ }
45038
+ function destroyPlacement(renderer, placement) {
45039
+ const system = renderer.renderTarget;
45040
+ const gpu = system._gpuRenderTargetHash?.[placement.target.uid];
45041
+ if (gpu && system._gpuRenderTargetHash) {
45042
+ system._gpuRenderTargetHash[placement.target.uid] = null;
45043
+ system.adaptor?.destroyGpuRenderTarget(gpu);
43817
45044
  }
43818
- if (error) throw new Error(error);
45045
+ system._renderSurfaceToRenderTargetHash?.delete(placement.target);
45046
+ placement.target.destroy();
45047
+ for (const texture of placement.textures) texture.destroy();
45048
+ destroyBoardShaderMesh(placement.mesh);
43819
45049
  }
43820
45050
  function boardUniforms(parameters, uniforms) {
43821
45051
  const vec = (size) => new Float32Array(size);
@@ -43864,6 +45094,10 @@ function boardUniforms(parameters, uniforms) {
43864
45094
  value: vec(4),
43865
45095
  type: "vec4<f32>"
43866
45096
  },
45097
+ uCohubSpriteCount: {
45098
+ value: 0,
45099
+ type: "i32"
45100
+ },
43867
45101
  uCohubRegion: {
43868
45102
  value: vec(4),
43869
45103
  type: "vec4<f32>"
@@ -43943,8 +45177,7 @@ function seedOf(value) {
43943
45177
  function boardShaderSeed(seed) {
43944
45178
  return seedOf(seed);
43945
45179
  }
43946
- function createBoardShaderLayer(renderer, shader, parameters, label) {
43947
- const layer = shader.layer ?? "above";
45180
+ function createBoardShaderLayer(renderer, shader, parameters, label, options = {}) {
43948
45181
  const uniforms = boardShaderUniforms(shader.uniforms);
43949
45182
  const surfaces = shader.surfaces === true;
43950
45183
  const hasState = shader.state !== void 0;
@@ -43954,19 +45187,21 @@ function createBoardShaderLayer(renderer, shader, parameters, label) {
43954
45187
  surfaces,
43955
45188
  state: hasState
43956
45189
  };
45190
+ const compiles = [];
43957
45191
  const program = (kind, glsl, name) => {
43958
- let built;
43959
45192
  try {
43960
- built = buildBoardShaderProgram({
45193
+ const built = buildBoardShaderProgram({
43961
45194
  ...base,
43962
45195
  kind,
43963
45196
  glsl
43964
45197
  });
45198
+ const glProgram = boardGlProgram(`board-shader-${kind}`, built);
45199
+ compiles.push(compileBoardProgram(renderer, glProgram, built, name, options.wait === true));
45200
+ return glProgram;
43965
45201
  } catch (error) {
43966
- throw new Error(`${name}: ${error instanceof Error ? error.message : String(error)}`);
45202
+ const message = error instanceof Error ? error.message : String(error);
45203
+ throw new Error(message.startsWith(name) ? message : `${name}: ${message}`);
43967
45204
  }
43968
- check(renderer, built, name);
43969
- return built;
43970
45205
  };
43971
45206
  const group = boardUniforms(parameters, uniforms);
43972
45207
  const textures = {};
@@ -43974,37 +45209,61 @@ function createBoardShaderLayer(renderer, shader, parameters, label) {
43974
45209
  if (hasState) textures.uCohubState = Texture.EMPTY.source;
43975
45210
  const meshes = [];
43976
45211
  const filters = [];
43977
- const container = layer === "filter" ? null : new Container({ label: `board-shader-${label}` });
45212
+ const containers = {
45213
+ below: null,
45214
+ above: null
45215
+ };
45216
+ const area = new Rectangle();
45217
+ const place = canPlaceSprites(renderer);
45218
+ let placementsStale = true;
43978
45219
  shader.passes.forEach((pass, index) => {
43979
45220
  const name = `${label} pass ${index + 1}`;
45221
+ const layer = boardShaderPassLayer(shader, pass);
43980
45222
  if (layer === "filter") {
43981
- const built = program("filter", pass.glsl, name);
43982
45223
  const filter = new Filter({
43983
- glProgram: GlProgram.from({
43984
- name: `board-shader-filter`,
43985
- vertex: built.vertex,
43986
- fragment: built.fragment,
43987
- preferredFragmentPrecision: "highp"
43988
- }),
45224
+ glProgram: program("filter", pass.glsl, name),
43989
45225
  resources: {
43990
45226
  cohubUniforms: group,
43991
45227
  ...textures
43992
45228
  },
43993
- padding: 0
45229
+ padding: 0,
45230
+ resolution: "inherit"
45231
+ });
45232
+ filters.push({
45233
+ filter,
45234
+ pass
43994
45235
  });
43995
- filters.push(filter);
43996
45236
  return;
43997
45237
  }
43998
45238
  const sprites = pass.sprites ?? 0;
43999
- const drawn = boardShaderMesh("board-shader", program(sprites ? "sprites" : "box", pass.glsl, name), {
45239
+ let placement = null;
45240
+ if (sprites && place) {
45241
+ const own = boardUniforms(parameters, uniforms);
45242
+ placement = createPlacement(boardShaderMesh("board-shader-place", program("place", pass.glsl, name), {
45243
+ cohubUniforms: own,
45244
+ ...textures
45245
+ }), own, sprites);
45246
+ }
45247
+ const kind = !sprites ? "box" : placement ? "placed" : "sprites";
45248
+ const resources = {
44000
45249
  cohubUniforms: group,
44001
45250
  ...textures
44002
- }, boardQuadGeometry(Math.max(1, sprites)));
45251
+ };
45252
+ placement?.textures.forEach((texture, slot) => {
45253
+ resources[BOARD_SPRITE_PLACEMENTS[slot]] = texture;
45254
+ });
45255
+ const drawn = boardShaderMesh("board-shader", program(kind, pass.glsl, name), resources, boardQuadGeometry(Math.max(1, sprites)));
44003
45256
  drawn.mesh.blendMode = pass.blend ?? "normal";
44004
- container?.addChild(drawn.mesh);
45257
+ containers[layer] ??= new Container({ label: `board-shader-${label}-${layer}` });
45258
+ const container = containers[layer];
45259
+ container.boundsArea = area;
45260
+ container.addChild(drawn.mesh);
44005
45261
  meshes.push({
44006
45262
  ...drawn,
44007
- sprites
45263
+ pass,
45264
+ sprites,
45265
+ placement,
45266
+ scaler: null
44008
45267
  });
44009
45268
  });
44010
45269
  let state = null;
@@ -44027,6 +45286,7 @@ function createBoardShaderLayer(renderer, shader, parameters, label) {
44027
45286
  const blank = new Container();
44028
45287
  let time = 0;
44029
45288
  let quality = 1;
45289
+ let compiled = compiles.length === 0;
44030
45290
  let last = null;
44031
45291
  const stateRegion = (frame) => shader.state?.bounds ?? frame.region;
44032
45292
  function fill(target, frame, geometry, step) {
@@ -44086,28 +45346,163 @@ function createBoardShaderLayer(renderer, shader, parameters, label) {
44086
45346
  }
44087
45347
  target.update();
44088
45348
  }
45349
+ const checkpoints = [];
45350
+ let surfaceKey = "";
45351
+ const copier = new Sprite();
45352
+ copier.blendMode = "none";
45353
+ const copy = (target, from, to) => {
45354
+ copier.texture = from;
45355
+ target.render({
45356
+ container: copier,
45357
+ target: to,
45358
+ clear: true,
45359
+ clearColor: [
45360
+ 0,
45361
+ 0,
45362
+ 0,
45363
+ 0
45364
+ ]
45365
+ });
45366
+ };
45367
+ const inputs = ({ time: _time, ...frame }) => JSON.stringify([frame, surfaceKey]);
45368
+ function checkpoint(target, state, key) {
45369
+ if (checkpoints.some((entry) => entry.steps === state.steps && entry.key === key)) return;
45370
+ const texture = (checkpoints.length >= CHECKPOINTS ? checkpoints.shift() : void 0)?.texture ?? boardRenderTarget(state.read.width, state.read.height, state.read.source.format);
45371
+ copy(target, state.read, texture);
45372
+ checkpoints.push({
45373
+ steps: state.steps,
45374
+ key,
45375
+ texture
45376
+ });
45377
+ }
45378
+ function advance(target, state, frame, catchUp) {
45379
+ const wanted = Math.floor(frame.time / STEP_MS);
45380
+ const key = catchUp ? inputs(frame) : "";
45381
+ let replaying = false;
45382
+ if (wanted < state.steps || state.steps < 0) {
45383
+ replaying = catchUp;
45384
+ for (const texture of [state.read, state.write]) target.render({
45385
+ container: blank,
45386
+ target: texture,
45387
+ clear: true,
45388
+ clearColor: [
45389
+ 0,
45390
+ 0,
45391
+ 0,
45392
+ 0
45393
+ ]
45394
+ });
45395
+ state.steps = Math.max(0, wanted - MAX_REPLAY);
45396
+ const resume = catchUp ? checkpoints.reduce((best, entry) => entry.key === key && entry.steps <= wanted && entry.steps > (best?.steps ?? state.steps - 1) ? entry : best, null) : null;
45397
+ if (resume) {
45398
+ copy(target, resume.texture, state.read);
45399
+ state.steps = resume.steps;
45400
+ }
45401
+ }
45402
+ if (!catchUp && wanted - state.steps > MAX_LAG) state.steps = wanted - STEPS_PER_FRAME;
45403
+ const limit = catchUp ? Number.POSITIVE_INFINITY : STEPS_PER_FRAME;
45404
+ let ran = 0;
45405
+ while (state.steps < wanted && ran < limit) {
45406
+ fill(state.uniforms, frame, {
45407
+ x: 0,
45408
+ y: 0,
45409
+ width: state.write.width,
45410
+ height: state.write.height
45411
+ }, state.steps);
45412
+ state.simulate.shader.resources.uCohubState = state.read.source;
45413
+ target.render({
45414
+ container: state.simulate.mesh,
45415
+ target: state.write,
45416
+ clear: true
45417
+ });
45418
+ [state.read, state.write] = [state.write, state.read];
45419
+ state.steps++;
45420
+ ran++;
45421
+ if (replaying && state.steps % CHECKPOINT_STEPS === 0) checkpoint(target, state, key);
45422
+ }
45423
+ const source = state.read.source;
45424
+ for (const { shader, placement } of meshes) {
45425
+ shader.resources.uCohubState = source;
45426
+ if (placement) placement.mesh.shader.resources.uCohubState = source;
45427
+ }
45428
+ for (const { filter } of filters) filter.resources.uCohubState = source;
45429
+ return {
45430
+ ran,
45431
+ behind: state.steps < wanted
45432
+ };
45433
+ }
45434
+ function shade(drawn, frame) {
45435
+ const resolution = frame.density * Math.min(1, frame.shading ?? 1);
45436
+ const blend = drawn.pass.blend ?? "normal";
45437
+ if (resolution >= frame.density * .99) {
45438
+ if (!drawn.scaler) return;
45439
+ drawn.mesh.filters = null;
45440
+ drawn.mesh.filterArea = null;
45441
+ drawn.mesh.blendMode = blend;
45442
+ drawn.scaler.destroy();
45443
+ drawn.scaler = null;
45444
+ return;
45445
+ }
45446
+ if (!drawn.scaler) {
45447
+ drawn.scaler = new AlphaFilter({
45448
+ alpha: 1,
45449
+ blendMode: blend
45450
+ });
45451
+ drawn.mesh.blendMode = "normal";
45452
+ drawn.mesh.filters = [drawn.scaler];
45453
+ drawn.mesh.filterArea = area;
45454
+ }
45455
+ drawn.scaler.resolution = resolution;
45456
+ }
44089
45457
  return {
44090
- layer,
44091
- container,
44092
- filters: layer === "filter" ? filters : null,
45458
+ below: containers.below,
45459
+ above: containers.above,
45460
+ filters: filters.length ? filters.map(({ filter }) => filter) : null,
44093
45461
  surfaces,
44094
45462
  animated: hasState,
45463
+ ready() {
45464
+ if (!compiled) compiled = compiles.every((compile) => compile.poll());
45465
+ return compiled;
45466
+ },
44095
45467
  update(frame) {
44096
- fill(group, frame, frame.region);
44097
- time = frame.time;
44098
- last = frame;
44099
45468
  if (frame.quality !== quality) {
44100
45469
  quality = frame.quality;
44101
45470
  for (const { geometry, sprites } of meshes) if (sprites) geometry.instanceCount = Math.max(1, Math.round(sprites * quality));
44102
45471
  }
45472
+ area.x = frame.region.x;
45473
+ area.y = frame.region.y;
45474
+ area.width = frame.region.width;
45475
+ area.height = frame.region.height;
45476
+ for (const drawn of meshes) {
45477
+ drawn.mesh.visible = boardShaderPassOn(drawn.pass, frame.passes);
45478
+ if (!drawn.sprites) shade(drawn, frame);
45479
+ }
45480
+ for (const { filter, pass } of filters) filter.enabled = boardShaderPassOn(pass, frame.passes);
45481
+ fill(group, frame, frame.region);
45482
+ for (const { geometry, placement } of meshes) {
45483
+ if (!placement) continue;
45484
+ placement.uniforms.uniforms.uCohubSpriteCount = geometry.instanceCount;
45485
+ fill(placement.uniforms, frame, {
45486
+ x: 0,
45487
+ y: 0,
45488
+ width: 256,
45489
+ height: Math.ceil(geometry.instanceCount / 256)
45490
+ });
45491
+ }
45492
+ time = frame.time;
45493
+ last = frame;
45494
+ placementsStale = true;
44103
45495
  },
44104
45496
  prepare(target, options) {
44105
- if (!state || !last) return false;
44106
- const wanted = Math.floor(last.time / STEP_MS);
44107
- if (wanted < state.steps || state.steps < 0) {
44108
- for (const texture of [state.read, state.write]) target.render({
44109
- container: blank,
44110
- target: texture,
45497
+ if (!last) return false;
45498
+ const stepped = state ? advance(target, state, last, options?.catchUp === true) : {
45499
+ ran: 0,
45500
+ behind: false
45501
+ };
45502
+ if (placementsStale || stepped.ran) {
45503
+ for (const { placement, mesh } of meshes) if (placement && mesh.visible) target.render({
45504
+ container: placement.mesh.mesh,
45505
+ target: placement.target,
44111
45506
  clear: true,
44112
45507
  clearColor: [
44113
45508
  0,
@@ -44116,38 +45511,21 @@ function createBoardShaderLayer(renderer, shader, parameters, label) {
44116
45511
  0
44117
45512
  ]
44118
45513
  });
44119
- state.steps = Math.max(0, wanted - MAX_REPLAY);
45514
+ placementsStale = false;
44120
45515
  }
44121
- if (!options?.catchUp && wanted - state.steps > MAX_LAG) state.steps = wanted - STEPS_PER_FRAME;
44122
- const limit = options?.catchUp ? Number.POSITIVE_INFINITY : STEPS_PER_FRAME;
44123
- let ran = 0;
44124
- while (state.steps < wanted && ran < limit) {
44125
- fill(state.uniforms, last, {
44126
- x: 0,
44127
- y: 0,
44128
- width: state.write.width,
44129
- height: state.write.height
44130
- }, state.steps);
44131
- state.simulate.shader.resources.uCohubState = state.read.source;
44132
- target.render({
44133
- container: state.simulate.mesh,
44134
- target: state.write,
44135
- clear: true
44136
- });
44137
- [state.read, state.write] = [state.write, state.read];
44138
- state.steps++;
44139
- ran++;
44140
- }
44141
- const source = state.read.source;
44142
- for (const { shader } of meshes) shader.resources.uCohubState = source;
44143
- for (const filter of filters) filter.resources.uCohubState = source;
44144
- return state.steps < wanted;
44145
- },
44146
- setSurfaces(texture, region) {
44147
- for (const { shader } of meshes) shader.resources.uCohubSurfaces = texture.source;
44148
- for (const filter of filters) filter.resources.uCohubSurfaces = texture.source;
44149
- if (state) state.simulate.shader.resources.uCohubSurfaces = texture.source;
44150
- for (const target of state ? [group, state.uniforms] : [group]) {
45516
+ return stepped.behind;
45517
+ },
45518
+ rewind() {
45519
+ if (state) state.steps = -1;
45520
+ },
45521
+ setSurfaces(texture, region, key = "") {
45522
+ surfaceKey = key;
45523
+ const shaders = [...meshes.flatMap(({ shader, placement }) => placement ? [shader, placement.mesh.shader] : [shader]), ...filters.map(({ filter }) => filter)];
45524
+ if (state) shaders.push(state.simulate.shader);
45525
+ for (const target of shaders) target.resources.uCohubSurfaces = texture.source;
45526
+ const groups = [group, ...meshes.flatMap(({ placement }) => placement ? [placement.uniforms] : [])];
45527
+ if (state) groups.push(state.uniforms);
45528
+ for (const target of groups) {
44151
45529
  setUniform(target, "uCohubSurfaceRegion", [
44152
45530
  region.x,
44153
45531
  region.y,
@@ -44156,17 +45534,26 @@ function createBoardShaderLayer(renderer, shader, parameters, label) {
44156
45534
  ]);
44157
45535
  target.update();
44158
45536
  }
45537
+ placementsStale = true;
44159
45538
  },
44160
45539
  destroy() {
44161
- for (const drawn of meshes) destroyBoardShaderMesh(drawn);
44162
- container?.destroy();
44163
- for (const filter of filters) filter.destroy();
45540
+ for (const compile of compiles) compile.cancel();
45541
+ for (const drawn of meshes) {
45542
+ drawn.scaler?.destroy();
45543
+ destroyBoardShaderMesh(drawn);
45544
+ if (drawn.placement) destroyPlacement(renderer, drawn.placement);
45545
+ }
45546
+ containers.below?.destroy();
45547
+ containers.above?.destroy();
45548
+ for (const { filter } of filters) filter.destroy();
44164
45549
  blank.destroy();
44165
45550
  if (state) {
44166
45551
  destroyBoardShaderMesh(state.simulate);
44167
45552
  state.read.destroy(true);
44168
45553
  state.write.destroy(true);
44169
45554
  }
45555
+ for (const { texture } of checkpoints) texture.destroy(true);
45556
+ copier.destroy();
44170
45557
  }
44171
45558
  };
44172
45559
  }
@@ -44392,35 +45779,53 @@ const SKIPPED = /* @__PURE__ */ new Set([
44392
45779
  "frame",
44393
45780
  "arrow",
44394
45781
  "draw",
44395
- "effect"
45782
+ "effect",
45783
+ "text"
44396
45784
  ]);
45785
+ const LIGHT_BLENDS = /* @__PURE__ */ new Set(["screen", "add"]);
44397
45786
  const SURFACE_EDGE = 512;
45787
+ const SURFACE_MARGIN = .25;
45788
+ const SURFACE_COARSEN = 1.5;
45789
+ const SURFACE_INTERVAL_MS = 1e3 / 30;
45790
+ function grow(rect, margin) {
45791
+ return {
45792
+ x: rect.x - rect.width * margin,
45793
+ y: rect.y - rect.height * margin,
45794
+ width: rect.width * (1 + 2 * margin),
45795
+ height: rect.height * (1 + 2 * margin)
45796
+ };
45797
+ }
45798
+ function surfaceOutline(item) {
45799
+ const { width, height } = item.frame;
45800
+ const radius = item.style?.radius;
45801
+ if (item.type === "shape") {
45802
+ const { geometry } = item.props;
45803
+ return shapeOutlinePoints(geometry, width, height, radius ?? (geometry === "rounded" ? 8 : 0));
45804
+ }
45805
+ return roundRectPoints(width, height, radius ?? 0);
45806
+ }
44398
45807
  function boardSurfaceOutlines(scene, owner, world, worldToLocal, candidates) {
44399
45808
  const prefix = scriptTemporaryPrefix(owner);
44400
45809
  const outlines = [];
44401
45810
  const items = candidates ? [...candidates].map((id) => scene.get(id)).filter((item) => Boolean(item)) : scene.items;
44402
45811
  for (const item of items) {
44403
- if (item.id === owner || SKIPPED.has(item.type) || item.id.startsWith(prefix) || scene.opacity(item.id) <= 0) continue;
45812
+ if (item.id === owner || SKIPPED.has(item.type) || LIGHT_BLENDS.has(item.style?.blend ?? "") || item.id.startsWith(prefix) || scene.opacity(item.id) <= 0) continue;
44404
45813
  if (!rectsIntersect(itemBounds(item.frame), world)) continue;
44405
- const ellipse = item.type === "shape" && item.props.geometry === "ellipse";
45814
+ const { width, height } = item.frame;
44406
45815
  const points = [];
44407
- const corners = ellipse ? Array.from({ length: 24 }, (_, index) => {
44408
- const angle = index / 24 * Math.PI * 2;
44409
- return [.5 + Math.cos(angle) / 2, .5 + Math.sin(angle) / 2];
44410
- }) : [
44411
- [0, 0],
44412
- [1, 0],
44413
- [1, 1],
44414
- [0, 1]
44415
- ];
44416
- for (const [u, v] of corners) {
44417
- const local = applyMatrix$1(worldToLocal, framePoint(item.frame, u, v));
45816
+ for (const point of surfaceOutline(item)) {
45817
+ const local = applyMatrix$1(worldToLocal, framePoint(item.frame, width ? point.x / width : 0, height ? point.y / height : 0));
44418
45818
  points.push(local.x, local.y);
44419
45819
  }
44420
45820
  outlines.push(points);
44421
45821
  }
44422
45822
  return outlines;
44423
45823
  }
45824
+ function boardSurfaceRegion(previous, needed, margin) {
45825
+ const grown = grow(needed, margin);
45826
+ if (previous && previous.x <= needed.x && previous.y <= needed.y && previous.x + previous.width >= needed.x + needed.width && previous.y + previous.height >= needed.y + needed.height && previous.width <= grown.width * SURFACE_COARSEN && previous.height <= grown.height * SURFACE_COARSEN) return previous;
45827
+ return grown;
45828
+ }
44424
45829
  function parameterValues(parameters, params, color) {
44425
45830
  const values = {};
44426
45831
  for (const [name, spec] of Object.entries(parameters ?? {})) {
@@ -44431,18 +45836,26 @@ function parameterValues(parameters, params, color) {
44431
45836
  }
44432
45837
  return values;
44433
45838
  }
44434
- function sameOutlines(a, b) {
45839
+ function sameOutlines(a, b, tolerance) {
44435
45840
  if (a.length !== b.length) return false;
44436
45841
  for (let index = 0; index < a.length; index++) {
44437
45842
  const left = a[index];
44438
45843
  const right = b[index];
44439
45844
  if (left.length !== right.length) return false;
44440
- for (let point = 0; point < left.length; point++) if (Math.abs(left[point] - right[point]) > .001) return false;
45845
+ for (let point = 0; point < left.length; point++) if (Math.abs(left[point] - right[point]) > tolerance) return false;
44441
45846
  }
44442
45847
  return true;
44443
45848
  }
44444
- function createBoardShaderLayers() {
45849
+ function outlineHash(outlines) {
45850
+ let hash = 2166136261;
45851
+ for (const outline of outlines) for (const value of outline) hash = Math.imul(hash ^ Math.round(value * 8), 16777619) >>> 0;
45852
+ return `${outlines.length}.${hash.toString(36)}`;
45853
+ }
45854
+ function createBoardShaderLayers(options = {}) {
45855
+ const now = options.now ?? (() => performance.now());
45856
+ const interval = options.wait ? 0 : SURFACE_INTERVAL_MS;
44445
45857
  const entries = /* @__PURE__ */ new Map();
45858
+ const compiling = /* @__PURE__ */ new Map();
44446
45859
  const failed = /* @__PURE__ */ new Map();
44447
45860
  let animated = false;
44448
45861
  let pending = false;
@@ -44454,13 +45867,71 @@ function createBoardShaderLayers() {
44454
45867
  entry.layer.destroy();
44455
45868
  entry.surfaces?.destroy();
44456
45869
  }
45870
+ function dropCompiling(id) {
45871
+ compiling.get(id)?.layer.destroy();
45872
+ compiling.delete(id);
45873
+ }
45874
+ function surfaceField(entry, renderer, owner, placement, host, scene, candidates) {
45875
+ const { localToWorld } = placement;
45876
+ const region = owner.root ? boardSurfaceRegion(entry.surfaces?.region ?? null, placement.region, SURFACE_MARGIN) : placement.region;
45877
+ const corners = [
45878
+ applyMatrix$1(localToWorld, region),
45879
+ applyMatrix$1(localToWorld, {
45880
+ x: region.x + region.width,
45881
+ y: region.y + region.height
45882
+ }),
45883
+ applyMatrix$1(localToWorld, {
45884
+ x: region.x + region.width,
45885
+ y: region.y
45886
+ }),
45887
+ applyMatrix$1(localToWorld, {
45888
+ x: region.x,
45889
+ y: region.y + region.height
45890
+ })
45891
+ ];
45892
+ const xs = corners.map((point) => point.x);
45893
+ const ys = corners.map((point) => point.y);
45894
+ const world = {
45895
+ x: Math.min(...xs),
45896
+ y: Math.min(...ys),
45897
+ width: Math.max(...xs) - Math.min(...xs),
45898
+ height: Math.max(...ys) - Math.min(...ys)
45899
+ };
45900
+ const edge = Math.max(64, Math.round(SURFACE_EDGE * (owner.root ? 1.5 : 1) * host.quality));
45901
+ const key = `${[
45902
+ region.x,
45903
+ region.y,
45904
+ region.width,
45905
+ region.height,
45906
+ ...localToWorld
45907
+ ].map((n) => n.toFixed(3)).join(",")}|${edge}`;
45908
+ entry.surfaces ??= createBoardSurfaceField();
45909
+ const moved = key !== entry.surfaceKey;
45910
+ const at = now();
45911
+ if (moved || entry.surfaceScene !== scene && at - entry.surfaceAt >= interval) {
45912
+ entry.surfaceScene = scene;
45913
+ const outlines = boardSurfaceOutlines(scene, owner.id, world, invertMatrix(localToWorld), candidates?.(world));
45914
+ if (moved || !sameOutlines(outlines, entry.outlines, region.width / edge / 2)) {
45915
+ entry.surfaces.build(renderer, region, outlines, edge);
45916
+ entry.outlines = outlines;
45917
+ entry.surfaceAt = at;
45918
+ entry.surfaceSignature = `${key}|${outlineHash(outlines)}`;
45919
+ }
45920
+ entry.surfaceKey = key;
45921
+ } else if (entry.surfaceScene !== scene) pending = true;
45922
+ entry.layer.setSurfaces(entry.surfaces.texture, entry.surfaces.region, entry.surfaceSignature);
45923
+ }
44457
45924
  return {
44458
45925
  get animated() {
44459
45926
  return animated || pending;
44460
45927
  },
44461
45928
  get size() {
44462
- return entries.size;
45929
+ return entries.size + compiling.size;
45930
+ },
45931
+ get compiling() {
45932
+ return compiling.size > 0;
44463
45933
  },
45934
+ layer: (id) => entries.get(id)?.layer ?? null,
44464
45935
  sync(renderer, owners, host, scene, candidates) {
44465
45936
  const alive = /* @__PURE__ */ new Set();
44466
45937
  animated = false;
@@ -44471,31 +45942,44 @@ function createBoardShaderLayers() {
44471
45942
  if (!shader || !signature || failed.get(owner.id) === signature) continue;
44472
45943
  alive.add(owner.id);
44473
45944
  let entry = entries.get(owner.id);
44474
- if (entry && entry.signature !== signature) {
44475
- drop(owner.id, host);
44476
- entry = void 0;
44477
- }
44478
45945
  try {
44479
- if (!entry) {
44480
- entry = {
44481
- owner,
44482
- output,
44483
- signature,
44484
- layer: createBoardShaderLayer(renderer, shader, boardShaderParameters(output.parameters), owner.id),
44485
- surfaces: null,
44486
- surfaceKey: "",
44487
- surfaceScene: null,
44488
- outlines: [],
44489
- placed: false
44490
- };
44491
- entries.set(owner.id, entry);
45946
+ if (entry?.signature !== signature) {
45947
+ let next = compiling.get(owner.id);
45948
+ if (next?.signature !== signature) {
45949
+ dropCompiling(owner.id);
45950
+ next = {
45951
+ signature,
45952
+ layer: createBoardShaderLayer(renderer, shader, boardShaderParameters(output.parameters), owner.id, { wait: options.wait })
45953
+ };
45954
+ compiling.set(owner.id, next);
45955
+ }
45956
+ if (next.layer.ready()) {
45957
+ compiling.delete(owner.id);
45958
+ drop(owner.id, host);
45959
+ entry = {
45960
+ owner,
45961
+ output,
45962
+ signature,
45963
+ layer: next.layer,
45964
+ surfaces: null,
45965
+ surfaceKey: "",
45966
+ surfaceScene: null,
45967
+ surfaceAt: -Infinity,
45968
+ surfaceSignature: "",
45969
+ outlines: [],
45970
+ placed: false
45971
+ };
45972
+ entries.set(owner.id, entry);
45973
+ }
44492
45974
  }
45975
+ if (!entry) continue;
44493
45976
  entry.owner = owner;
44494
- entry.output = output;
45977
+ if (entry.signature === signature) entry.output = output;
45978
+ const drawn = entry.output;
44495
45979
  const placement = host.attach(owner, entry.layer);
44496
45980
  entry.placed = placement !== null;
44497
45981
  if (!placement) continue;
44498
- animated ||= output.animated || entry.layer.animated;
45982
+ animated ||= drawn.animated || entry.layer.animated;
44499
45983
  entry.layer.update({
44500
45984
  time: owner.time,
44501
45985
  region: placement.region,
@@ -44505,75 +45989,42 @@ function createBoardShaderLayers() {
44505
45989
  density: host.density,
44506
45990
  seed: boardShaderSeed(owner.seed),
44507
45991
  quality: host.quality,
45992
+ shading: host.shading,
44508
45993
  dark: host.dark,
44509
- params: parameterValues(output.parameters, owner.params, host.color),
44510
- uniforms: output.uniforms
45994
+ params: parameterValues(drawn.parameters, owner.params, host.color),
45995
+ uniforms: drawn.uniforms,
45996
+ passes: drawn.passes
44511
45997
  });
44512
- if (entry.layer.surfaces) {
44513
- const { region, localToWorld } = placement;
44514
- const corners = [
44515
- applyMatrix$1(localToWorld, region),
44516
- applyMatrix$1(localToWorld, {
44517
- x: region.x + region.width,
44518
- y: region.y + region.height
44519
- }),
44520
- applyMatrix$1(localToWorld, {
44521
- x: region.x + region.width,
44522
- y: region.y
44523
- }),
44524
- applyMatrix$1(localToWorld, {
44525
- x: region.x,
44526
- y: region.y + region.height
44527
- })
44528
- ];
44529
- const xs = corners.map((point) => point.x);
44530
- const ys = corners.map((point) => point.y);
44531
- const world = {
44532
- x: Math.min(...xs),
44533
- y: Math.min(...ys),
44534
- width: Math.max(...xs) - Math.min(...xs),
44535
- height: Math.max(...ys) - Math.min(...ys)
44536
- };
44537
- const edge = Math.max(64, Math.round(SURFACE_EDGE * host.quality));
44538
- const key = `${[
44539
- region.x,
44540
- region.y,
44541
- region.width,
44542
- region.height,
44543
- ...localToWorld
44544
- ].map((n) => n.toFixed(3)).join(",")}|${edge}`;
44545
- entry.surfaces ??= createBoardSurfaceField();
44546
- if (key !== entry.surfaceKey || entry.surfaceScene !== scene) {
44547
- entry.surfaceScene = scene;
44548
- const outlines = boardSurfaceOutlines(scene, owner.id, world, invertMatrix(localToWorld), candidates?.(world));
44549
- if (key !== entry.surfaceKey || !sameOutlines(outlines, entry.outlines)) entry.surfaces.build(renderer, region, outlines, edge);
44550
- entry.surfaceKey = key;
44551
- entry.outlines = outlines;
44552
- }
44553
- entry.layer.setSurfaces(entry.surfaces.texture, entry.surfaces.region);
44554
- }
45998
+ if (entry.layer.surfaces) surfaceField(entry, renderer, owner, placement, host, scene, candidates);
44555
45999
  } catch (error) {
44556
46000
  host.attach(owner, null);
44557
46001
  drop(owner.id, host);
46002
+ dropCompiling(owner.id);
44558
46003
  failed.set(owner.id, signature);
44559
46004
  host.fault(owner.id, error instanceof Error ? error.message : String(error));
44560
46005
  }
44561
46006
  }
44562
46007
  for (const id of [...entries.keys()]) if (!alive.has(id)) drop(id, host);
46008
+ for (const id of [...compiling.keys()]) if (!alive.has(id)) dropCompiling(id);
44563
46009
  for (const id of [...failed.keys()]) if (!owners.some((owner) => owner.id === id)) failed.delete(id);
44564
46010
  },
44565
46011
  prepare(renderer, catchUp = false) {
44566
46012
  pending = false;
44567
46013
  for (const entry of entries.values()) if (entry.placed && entry.layer.prepare(renderer, { catchUp })) pending = true;
44568
46014
  },
46015
+ rewind() {
46016
+ for (const entry of entries.values()) entry.layer.rewind();
46017
+ },
44569
46018
  detach() {
44570
46019
  for (const entry of entries.values()) {
44571
- entry.layer.container?.removeFromParent();
46020
+ entry.layer.below?.removeFromParent();
46021
+ entry.layer.above?.removeFromParent();
44572
46022
  entry.placed = false;
44573
46023
  }
44574
46024
  },
44575
46025
  destroy() {
44576
46026
  for (const id of [...entries.keys()]) drop(id);
46027
+ for (const id of [...compiling.keys()]) dropCompiling(id);
44577
46028
  failed.clear();
44578
46029
  }
44579
46030
  };
@@ -44822,7 +46273,7 @@ function createBoardExportScene(input) {
44822
46273
  }
44823
46274
  root.addChild(world);
44824
46275
  const shaderErrors = [];
44825
- const layers = input.shaders?.owners.length ? input.shaders.layers ?? createBoardShaderLayers() : null;
46276
+ const layers = input.shaders?.owners.length ? input.shaders.layers ?? createBoardShaderLayers({ wait: true }) : null;
44826
46277
  if (layers && input.shaders) {
44827
46278
  const toOutput = [
44828
46279
  input.scale,
@@ -44844,10 +46295,12 @@ function createBoardExportScene(input) {
44844
46295
  const attach = (owner, layer) => {
44845
46296
  if (!layer) return null;
44846
46297
  if (owner.root) {
44847
- if (layer.container) (layer.layer === "below" ? below : above).addChild(layer.container);
46298
+ if (layer.below) below.addChild(layer.below);
46299
+ if (layer.above) above.addChild(layer.above);
44848
46300
  if (layer.filters) {
44849
46301
  filters.set(owner.id, layer.filters);
44850
46302
  setBoardShaderFilters(world, [...filters.values()].flat());
46303
+ world.filterArea = new Rectangle(input.world.x, input.world.y, input.world.width, input.world.height);
44851
46304
  }
44852
46305
  return {
44853
46306
  region: input.world,
@@ -44867,15 +46320,25 @@ function createBoardExportScene(input) {
44867
46320
  const container = containers.get(owner.id);
44868
46321
  if (!item || !container) return null;
44869
46322
  const group = isSelfGroupedFrame(item) ? groups.get(item.id)?.group : void 0;
44870
- if (layer.layer === "below" && layer.container) container.addChildAt(layer.container, 0);
44871
- if (layer.layer === "above" && layer.container) {
46323
+ if (layer.below) container.addChildAt(layer.below, 0);
46324
+ if (layer.above) {
44872
46325
  if (group) {
44873
- positionShell(layer.container, item);
44874
- layer.container.zIndex = Number.MAX_SAFE_INTEGER;
46326
+ positionShell(layer.above, item);
46327
+ layer.above.zIndex = Number.MAX_SAFE_INTEGER;
44875
46328
  }
44876
- (group ?? container).addChild(layer.container);
46329
+ (group ?? container).addChild(layer.above);
46330
+ }
46331
+ if (layer.filters) {
46332
+ const host = group ?? container;
46333
+ setBoardShaderFilters(host, layer.filters);
46334
+ const box = group ? itemBounds(item.frame) : {
46335
+ x: 0,
46336
+ y: 0,
46337
+ width: item.frame.width,
46338
+ height: item.frame.height
46339
+ };
46340
+ host.filterArea = new Rectangle(box.x, box.y, box.width, box.height);
44877
46341
  }
44878
- if (layer.filters) setBoardShaderFilters(group ?? container, layer.filters);
44879
46342
  const localToWorld = boardItemLocalToWorld(item.frame);
44880
46343
  return {
44881
46344
  region: {
@@ -45322,8 +46785,11 @@ function createNodeScriptLanes(renderer, options) {
45322
46785
  });
45323
46786
  };
45324
46787
  Promise.resolve().then(() => {
45325
- if (!options.call) throw new Error("Capabilities are unavailable during export.");
45326
- return options.call(message.id ?? "", message.name ?? "", message.input);
46788
+ const name = message.name ?? "";
46789
+ if (options.call) return options.call(message.id ?? "", name, message.input);
46790
+ const call = BOARD_SCRIPT_EXPORT_CALLS[name];
46791
+ if (!call) throw new Error("Capabilities are unavailable during export.");
46792
+ return call(message.input);
45327
46793
  }).then((value) => answer(value), (error) => answer(void 0, error instanceof Error ? error.message : String(error)));
45328
46794
  });
45329
46795
  return worker;
@@ -45439,6 +46905,7 @@ function createNodeBoardScriptHost(renderer, options) {
45439
46905
  const textures = /* @__PURE__ */ new Map();
45440
46906
  const outputs = /* @__PURE__ */ new Map();
45441
46907
  const errors = /* @__PURE__ */ new Map();
46908
+ const sampled = /* @__PURE__ */ new Map();
45442
46909
  const key = (id, time) => `${id}|${time}`;
45443
46910
  let disposed = false;
45444
46911
  return {
@@ -45464,11 +46931,11 @@ function createNodeBoardScriptHost(renderer, options) {
45464
46931
  errors.clear();
45465
46932
  },
45466
46933
  async prepare(items, times, zoom, board, options) {
45467
- const all = Object.fromEntries(items.map(({ id, frame: _frame, ...item }) => [id, item]));
45468
- const document = {
46934
+ const documentOf = (list) => ({
45469
46935
  board: { scripts: board?.scripts },
45470
- items: all
45471
- };
46936
+ items: Object.fromEntries(list.map(({ id, frame: _frame, ...item }) => [id, item]))
46937
+ });
46938
+ const document = documentOf(items);
45472
46939
  const scripted = boardScriptAttachments(document);
45473
46940
  const alive = new Set(scripted.map(({ id }) => id));
45474
46941
  for (const id of [...lanes.assigned()]) if (!alive.has(id)) lanes.release(id);
@@ -45487,6 +46954,51 @@ function createNodeBoardScriptHost(renderer, options) {
45487
46954
  height
45488
46955
  });
45489
46956
  for (const time of times) {
46957
+ const last = sampled.get(id) ?? 0;
46958
+ if (options?.history) {
46959
+ const from = last <= time ? last : 0;
46960
+ const run = async (at, document) => {
46961
+ const script = boardScriptOf(document, id);
46962
+ if (script) await lanes.sample({
46963
+ input: scopedInput(document, {
46964
+ ...attachment,
46965
+ script
46966
+ }, {
46967
+ width,
46968
+ height
46969
+ }),
46970
+ graph,
46971
+ time: at,
46972
+ scale,
46973
+ draw: false,
46974
+ shaders: options.shaders
46975
+ });
46976
+ };
46977
+ let before = {
46978
+ at: from,
46979
+ document: options.history(from)
46980
+ };
46981
+ let previous = JSON.stringify(boardScriptOf(before.document, id)?.params);
46982
+ let ran = from;
46983
+ if (from === 0) await run(from, before.document);
46984
+ for (let at = from + BOARD_SCRIPT_HISTORY_MS; at < time; at += BOARD_SCRIPT_HISTORY_MS) {
46985
+ const sample = options.history(at);
46986
+ const key = JSON.stringify(boardScriptOf(sample, id)?.params);
46987
+ if (key !== previous) {
46988
+ if (before.at > ran) await run(before.at, before.document);
46989
+ await run(at, sample);
46990
+ previous = key;
46991
+ ran = at;
46992
+ if (disposed) return;
46993
+ }
46994
+ before = {
46995
+ at,
46996
+ document: sample
46997
+ };
46998
+ }
46999
+ if (JSON.stringify(input.script.params) !== previous && before.at > ran) await run(before.at, before.document);
47000
+ }
47001
+ sampled.set(id, time);
45490
47002
  const result = await lanes.sample({
45491
47003
  input,
45492
47004
  graph,
@@ -46174,13 +47686,6 @@ const STRUCTURAL_KEYS = [
46174
47686
  "locked",
46175
47687
  "metadata"
46176
47688
  ];
46177
- function newBoardTrackId(tracks, target, property) {
46178
- const id = `${target}-${property.replaceAll(".", "-")}`;
46179
- return id.length <= 160 && !Object.hasOwn(tracks, id) ? id : createBoardEntityId();
46180
- }
46181
- function findBoardKeyTrack(tracks, target, property) {
46182
- return Object.entries(tracks).find(([, track]) => track.target === target && track.property === property && track.composite === "replace");
46183
- }
46184
47689
  function keyframe(animations, playhead, recording, id, property, value, storedValue) {
46185
47690
  const animation = animations[playhead.animationId];
46186
47691
  if (!animation) return false;
@@ -46687,14 +48192,20 @@ function createAnimationModule(ctx) {
46687
48192
  animation
46688
48193
  } : null;
46689
48194
  }
46690
- function commitAnimation(id, animation) {
46691
- const patch = diffBoardEdits(state.base, {
48195
+ function commitAnimation(id, animation, items = {}) {
48196
+ if (animation === state.base.animations[id] && Object.keys(items).length === 0) return true;
48197
+ const next = {
46692
48198
  ...state.base,
48199
+ items: {
48200
+ ...state.base.items,
48201
+ ...items
48202
+ },
46693
48203
  animations: {
46694
48204
  ...state.base.animations,
46695
48205
  [id]: animation
46696
48206
  }
46697
- }, []);
48207
+ };
48208
+ const patch = diffBoardEdits(state.base, next, Object.keys(items));
46698
48209
  try {
46699
48210
  ctx.document.commitPatch(patch)?.catch(() => {});
46700
48211
  return true;
@@ -47010,7 +48521,78 @@ function createAnimationModule(ctx) {
47010
48521
  });
47011
48522
  return id;
47012
48523
  }
48524
+ function placeOnTimeline(targets, at, options = {}) {
48525
+ const found = editing();
48526
+ if (!found) return false;
48527
+ let animation = found.animation;
48528
+ let cursor = Math.max(0, at);
48529
+ for (const target of targets) {
48530
+ if (target === found.id || (state.base.animations[target] ? plays(target, found.id) : !state.base.items[target])) continue;
48531
+ animation = boardPlaceTarget(state.base, animation, target, {
48532
+ ...options,
48533
+ at: cursor
48534
+ });
48535
+ const span = boardTargetSpan(state.base, animation, target);
48536
+ if (!options.together && span) cursor = span.end;
48537
+ }
48538
+ return commitAnimation(found.id, animation);
48539
+ }
48540
+ function shiftOnTimeline(targets, delta) {
48541
+ const found = editing();
48542
+ if (found) commitAnimation(found.id, boardShiftTargets(state.base, found.animation, targets, delta));
48543
+ }
48544
+ function trimOnTimeline(target, edge, at) {
48545
+ const found = editing();
48546
+ if (found) commitAnimation(found.id, boardTrimTarget(state.base, found.animation, target, edge, at));
48547
+ }
48548
+ function removeFromTimeline(targets) {
48549
+ const found = editing();
48550
+ if (!found) return;
48551
+ let animation = found.animation;
48552
+ for (const target of targets) animation = boardRemoveTarget(animation, target);
48553
+ commitAnimation(found.id, animation);
48554
+ }
48555
+ function splitAtPlayhead(targets) {
48556
+ const found = editing();
48557
+ if (!found) return [];
48558
+ let animation = found.animation;
48559
+ const items = {};
48560
+ const roots = [];
48561
+ for (const target of ctx.query.rootsOf(targets)) {
48562
+ if (!state.base.items[target]) continue;
48563
+ const subtree = [...ctx.query.withSubtrees([target])];
48564
+ const source = Object.fromEntries(subtree.flatMap((id) => state.base.items[id] ? [[id, state.base.items[id]]] : []));
48565
+ const idMap = new Map(subtree.map((id) => [id, createBoardItemId()]));
48566
+ const split = boardSplitTarget(state.base, animation, target, idMap, found.time);
48567
+ if (!split) continue;
48568
+ animation = split;
48569
+ Object.assign(items, remapItems(source, idMap));
48570
+ const copy = idMap.get(target);
48571
+ const { parent } = state.base.items[target];
48572
+ if (parent) items[copy] = {
48573
+ ...items[copy],
48574
+ parent
48575
+ };
48576
+ roots.push(copy);
48577
+ }
48578
+ return roots.length && commitAnimation(found.id, animation, items) ? roots : [];
48579
+ }
48580
+ function insertTime(at, length) {
48581
+ const found = editing();
48582
+ if (found) commitAnimation(found.id, boardInsertTime(state.base, found.animation, at, length));
48583
+ }
48584
+ function removeTime(from, to) {
48585
+ const found = editing();
48586
+ if (found) commitAnimation(found.id, boardRemoveTime(state.base, found.animation, from, to));
48587
+ }
47013
48588
  return {
48589
+ placeOnTimeline,
48590
+ shiftOnTimeline,
48591
+ trimOnTimeline,
48592
+ removeFromTimeline,
48593
+ splitAtPlayhead,
48594
+ insertTime,
48595
+ removeTime,
47014
48596
  setPlayhead,
47015
48597
  setRecording,
47016
48598
  keyProperty,
@@ -49498,7 +51080,7 @@ function createQueryModule(ctx) {
49498
51080
  ensureSpatial();
49499
51081
  for (const id of spatial.idsAtPoint(point)) {
49500
51082
  const item = state.scene.get(id);
49501
- if (!state.base.items[id] || item?.type !== "frame" || exclude?.has(id)) continue;
51083
+ if (!state.base.items[id] || item?.type !== "frame" || exclude?.has(id) || !state.scene.shown(id)) continue;
49502
51084
  if (registry.hitTest(item, point)) return item;
49503
51085
  }
49504
51086
  return null;
@@ -49525,6 +51107,7 @@ function createQueryModule(ctx) {
49525
51107
  return enclosed.sort((a, b) => scene.indexOf(a.id) - scene.indexOf(b.id));
49526
51108
  }
49527
51109
  function hitsItem(item, point) {
51110
+ if (!state.scene.shown(item.id) && !state.selection.includes(item.id)) return false;
49528
51111
  if (item.type === "arrow") return distanceToArrow(resolveSceneArrow(item, state.scene), point) <= arrowHitRadius(item.style.strokeWidth) / Math.min(1, state.camera.zoom);
49529
51112
  return registry.hitTest(item, point);
49530
51113
  }
@@ -49558,7 +51141,7 @@ function createQueryModule(ctx) {
49558
51141
  height: reach * 2
49559
51142
  })) {
49560
51143
  const item = state.scene.get(id);
49561
- if (!pickable(item, id)) continue;
51144
+ if (!pickable(item, id) || !(state.scene.shown(id) || state.selection.includes(id))) continue;
49562
51145
  const distance = item.type === "arrow" ? distanceToArrow(resolveSceneArrow(item, state.scene), point) - arrowHitRadius(item.style.strokeWidth) / Math.min(1, state.camera.zoom) : distanceToFrame(item.frame, point);
49563
51146
  if (distance > 0 && distance < best) {
49564
51147
  nearest = item;
@@ -49580,7 +51163,7 @@ function createQueryModule(ctx) {
49580
51163
  const candidates = selection.length === 1 ? [...selection, ...nearby] : nearby;
49581
51164
  for (const id of new Set(candidates)) {
49582
51165
  const item = scene.get(id);
49583
- if (!item || !state.base.items[id] || isLocked(item)) continue;
51166
+ if (!item || !state.base.items[id] || isLocked(item) || !scene.shown(id)) continue;
49584
51167
  if (item.type === "frame" && rectContainsPoint(frameLabelHitRect(item.frame, frameLabelSize), point)) return item;
49585
51168
  if (item.type === "arrow") {
49586
51169
  const resolved = resolveSceneArrow(item, scene);
@@ -49774,6 +51357,31 @@ function createSelectionModule(ctx) {
49774
51357
  if (ids.length < 3) return;
49775
51358
  ctx.document.commitItems(placed(distributeFrames(framesFor(ids), axis)));
49776
51359
  }
51360
+ function framed() {
51361
+ return movable().flatMap((id) => {
51362
+ const item = state.scene.get(id);
51363
+ const parent = item?.parent ? state.scene.get(item.parent) : void 0;
51364
+ return item && parent?.type === "frame" && hasAuthoredSize(item.type) ? [[id, parent.frame]] : [];
51365
+ });
51366
+ }
51367
+ function fillFrame() {
51368
+ const frames = /* @__PURE__ */ new Map();
51369
+ for (const [id, outer] of framed()) {
51370
+ const own = state.scene.get(id)?.frame;
51371
+ if (!own?.width || !own.height) continue;
51372
+ const scale = Math.max(outer.width / own.width, outer.height / own.height);
51373
+ const width = own.width * scale;
51374
+ const height = own.height * scale;
51375
+ frames.set(id, {
51376
+ x: outer.x + (outer.width - width) / 2,
51377
+ y: outer.y + (outer.height - height) / 2,
51378
+ width,
51379
+ height,
51380
+ rotation: outer.rotation
51381
+ });
51382
+ }
51383
+ ctx.document.commitItems(placed(frames));
51384
+ }
49777
51385
  function edit(update, ids = ctx.query.unlockedIds(state.selection)) {
49778
51386
  const changes = /* @__PURE__ */ new Map();
49779
51387
  for (const id of ids) {
@@ -49890,6 +51498,8 @@ function createSelectionModule(ctx) {
49890
51498
  nudge,
49891
51499
  align,
49892
51500
  distribute,
51501
+ canFillFrame: () => framed().length > 0,
51502
+ fillFrame,
49893
51503
  toggleLock,
49894
51504
  setColor,
49895
51505
  setStyle,
@@ -50373,6 +51983,10 @@ function createBoardEditor(options) {
50373
51983
  nudgeSelection: selection.nudge,
50374
51984
  alignSelection: selection.align,
50375
51985
  distributeSelection: selection.distribute,
51986
+ get canFillFrame() {
51987
+ return read(["selection", "scene"], () => selection.canFillFrame());
51988
+ },
51989
+ fillFrame: selection.fillFrame,
50376
51990
  toggleSelectionLock: selection.toggleLock,
50377
51991
  setSelectionColor: selection.setColor,
50378
51992
  setSelectionStyle: selection.setStyle,
@@ -50422,6 +52036,13 @@ function createBoardEditor(options) {
50422
52036
  deleteAnimation: animation.deleteAnimation,
50423
52037
  createAnimation: animation.createAnimation,
50424
52038
  createSequence: animation.createSequence,
52039
+ placeOnTimeline: animation.placeOnTimeline,
52040
+ shiftOnTimeline: animation.shiftOnTimeline,
52041
+ trimOnTimeline: animation.trimOnTimeline,
52042
+ removeFromTimeline: animation.removeFromTimeline,
52043
+ splitAtPlayhead: animation.splitAtPlayhead,
52044
+ insertTime: animation.insertTime,
52045
+ removeTime: animation.removeTime,
50425
52046
  pointerDown: interaction.pointerDown,
50426
52047
  pointerMove: interaction.pointerMove,
50427
52048
  pointerUp: interaction.pointerUp,
@@ -50906,7 +52527,7 @@ function createBoardScriptController(options) {
50906
52527
  ...options.capabilities,
50907
52528
  "board.emit": async (id, value) => {
50908
52529
  const message = value;
50909
- if (!message || typeof message.target !== "string" || typeof message.type !== "string" || !boardScriptScope(editor.document, id).has(message.target)) throw new Error("Invalid script event target.");
52530
+ if (!message || typeof message.target !== "string" || typeof message.type !== "string" || !(isBoardRootScript(editor.document, message.target) || boardScriptScope(editor.document, id).has(message.target))) throw new Error("Invalid script event target.");
50910
52531
  if (activated(id)) activations.set(message.target, activations.get(id) ?? now());
50911
52532
  host?.event(message.target, {
50912
52533
  type: message.type,
@@ -50917,29 +52538,18 @@ function createBoardScriptController(options) {
50917
52538
  const { patch, frame } = value;
50918
52539
  return commits.commit(id, patch, !frame && activated(id));
50919
52540
  },
50920
- "board.layoutText": async (_id, value) => {
50921
- const input = value;
50922
- if (!input || typeof input.text !== "string" || input.text.length > 1e4) throw new Error("layoutText() needs text of at most 10000 characters.");
50923
- for (const key of [
50924
- "fontSize",
50925
- "fontWeight",
50926
- "lineHeight",
50927
- "width"
50928
- ]) if (input[key] !== void 0 && !(Number.isFinite(input[key]) && input[key] > 0)) throw new Error(`layoutText() ${key} must be a positive number.`);
50929
- const { width, height } = layoutBoardText({
50930
- fontSize: 24,
50931
- fontWeight: 500,
50932
- font: "sans",
50933
- lineHeight: 4 / 3,
50934
- ...input
50935
- });
50936
- return {
50937
- width,
50938
- height
50939
- };
50940
- }
52541
+ "board.layoutText": async (_id, value) => layoutBoardScriptText(value)
50941
52542
  },
50942
52543
  onOutput: (id, output) => {
52544
+ const previous = outputs.get(id);
52545
+ if (output && previous && output.sceneVersion !== void 0 && output.sceneVersion === previous.sceneVersion) {
52546
+ Object.assign(previous, {
52547
+ uniforms: output.uniforms,
52548
+ passes: output.passes,
52549
+ version: output.version
52550
+ });
52551
+ return false;
52552
+ }
50943
52553
  if (output) {
50944
52554
  prepareBoardScriptOutput(editor.document, id, output);
50945
52555
  cancelPointers(id, output.hits);
@@ -51316,7 +52926,7 @@ async function createBoardScriptHarness(options) {
51316
52926
  if (!runTimers() && !runtime?.queued) break;
51317
52927
  }
51318
52928
  }
51319
- function pointerEvent(point, phase, input = {}) {
52929
+ function pointerEvent(point, phase, input = {}, pressed = phase !== "up") {
51320
52930
  const { x, y, zoom } = editor.camera;
51321
52931
  return {
51322
52932
  pointerId: input.pointerId ?? 1,
@@ -51327,14 +52937,14 @@ async function createBoardScriptHarness(options) {
51327
52937
  ctrlKey: input.ctrlKey ?? false,
51328
52938
  metaKey: input.metaKey ?? false,
51329
52939
  button: 0,
51330
- buttons: phase === "up" ? 0 : 1,
52940
+ buttons: pressed ? 1 : 0,
51331
52941
  pointerType: input.pointerType ?? "mouse",
51332
52942
  cancelled: false,
51333
52943
  pressure: .5
51334
52944
  };
51335
52945
  }
51336
- async function pointer(phase, point, input) {
51337
- const event = pointerEvent(point, phase, input);
52946
+ async function pointer(phase, point, input, pressed) {
52947
+ const event = pointerEvent(point, phase, input, pressed);
51338
52948
  if (!controller.pointer(phase, event)) {
51339
52949
  if (phase === "down") editor.pointerDown(event);
51340
52950
  else if (phase === "move") editor.pointerMove(event);
@@ -51376,6 +52986,10 @@ async function createBoardScriptHarness(options) {
51376
52986
  for (const point of rest) await pointer("move", point, input);
51377
52987
  await pointer("up", points.at(-1) ?? first, input);
51378
52988
  },
52989
+ async move(points, input) {
52990
+ for (const point of points) await pointer("move", point, input, false);
52991
+ },
52992
+ snapshot: () => controller.snapshot(),
51379
52993
  async key(type, key) {
51380
52994
  controller.key({
51381
52995
  type,
@@ -51428,4 +53042,4 @@ async function createBoardScriptHarness(options) {
51428
53042
  };
51429
53043
  }
51430
53044
  //#endregion
51431
- export { BOARD_SCRIPT_DRAWING_EXAMPLE, BOARD_SCRIPT_RAIN_EXAMPLE, boardAssetKey, boardAssetKeySource, boardDocumentAt, boardFrameRegions, boardPathTrack, boardRegionStep, boardRenderTheme, boardScriptAttachments, boardSequence, boardSequencePatch, boardShaderParameters, boardTextureEdge, boardTexturePixels, buildBoardScene, checkBoardShader, createBoardAnimationSampler, createBoardRenderSampler, createBoardScriptHarness, createNodeBoardRenderer, createNodeBoardScriptHost, describeBoardExportWarning, exportBoardImageBytes, hasBoardScripts, inspectBoardItems, inspectBoardScene, measureBoardText, parseBoardDocument, planBoardExport, prepareBoardExport, selectBoardExportAssets };
53045
+ export { BOARD_SCRIPT_DRAWING_EXAMPLE, BOARD_SCRIPT_RAIN_EXAMPLE, boardAnimatesScriptParams, boardAssetKey, boardAssetKeySource, boardFrameRegions, boardMediaRate, boardMediaSpans, boardPathTrack, boardPlacePatch, boardRegionStep, boardRenderTheme, boardScriptAttachments, boardSequence, boardSequencePatch, boardShaderParameters, boardTextureEdge, boardTexturePixels, boardTimedMedia, buildBoardScene, checkBoardShader, createBoardAnimationSampler, createBoardRenderSampler, createBoardScriptHarness, createNodeBoardRenderer, createNodeBoardScriptHost, describeBoardExportWarning, exportBoardImageBytes, hasBoardScripts, inspectBoardItems, inspectBoardScene, itemBounds, measureBoardText, parseBoardDocument, planBoardExport, prepareBoardExport, rectsIntersect, selectBoardExportAssets };