@neta-art/cohub-cli 10.19.0 → 10.21.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.
@@ -5912,6 +5912,7 @@ const itemEnvelope$1 = {
5912
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."),
5913
5913
  style: BoardStyleSchema$1.default({}),
5914
5914
  locked: boolean().optional(),
5915
+ autoplay: boolean().optional().describe("true shows live content as the Board opens: an app runs, a video loops muted, a 3D model renders. Ignored for other items and for a video whose props.time follows a timeline."),
5915
5916
  metadata: record(string(), unknown()).optional()
5916
5917
  };
5917
5918
  const boxed$1 = (size) => ({
@@ -7127,6 +7128,7 @@ const NOT_ANIMATABLE = /* @__PURE__ */ new Set([
7127
7128
  "parent",
7128
7129
  "z",
7129
7130
  "locked",
7131
+ "autoplay",
7130
7132
  "metadata",
7131
7133
  "script"
7132
7134
  ]);
@@ -7199,6 +7201,10 @@ function resolveBoardProperty(targetType, property) {
7199
7201
  ok: false,
7200
7202
  message: `Board scripts animate params.<name>, not ${property}`
7201
7203
  };
7204
+ if (/^script\.params\.[^.]+$/.test(property)) return {
7205
+ ok: true,
7206
+ spec: SCRIPT_PARAMETER
7207
+ };
7202
7208
  const path = property.split(".");
7203
7209
  if (path.some((segment) => !segment) || NOT_ANIMATABLE.has(path[0])) return {
7204
7210
  ok: false,
@@ -7588,6 +7594,7 @@ function validateTrack(path, animationId, value, item, animation, track, script,
7588
7594
  if (value.target === animationId || nestsInto(value.target, animationId, animation, track, state)) return [error(`${path}.target`, "ANIMATION_CYCLE", `${animationId} cannot contain itself through ${value.target}`)];
7589
7595
  } else if (script(value.target)) targetType = "script";
7590
7596
  else return [error(`${path}.target`, "TARGET_NOT_FOUND", `target ${value.target} is not an item, animation, Board script or camera`)];
7597
+ if (!keepUnknownProperty && value.property.startsWith("script.") && !item(value.target)?.script) return [error(`${path}.property`, "INVALID_PROPERTY", `${value.target} has no script to animate`)];
7591
7598
  const resolved = resolveBoardProperty(targetType, value.property);
7592
7599
  if (!resolved.ok) return keepUnknownProperty ? [] : [error(`${path}.property`, "INVALID_PROPERTY", resolved.message)];
7593
7600
  for (const [index, keyframe] of value.keyframes.entries()) {
@@ -7960,6 +7967,159 @@ function isBoardRootScript(document, id) {
7960
7967
  return Boolean(document.board?.scripts && Object.hasOwn(document.board.scripts, id));
7961
7968
  }
7962
7969
  //#endregion
7970
+ //#region ../sdk/src/board/model/json.ts
7971
+ function sameJson(a, b) {
7972
+ if (a === b) return true;
7973
+ if (!a || !b || typeof a !== "object" || typeof b !== "object") return false;
7974
+ if (Array.isArray(a) || Array.isArray(b)) {
7975
+ if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
7976
+ for (let index = 0; index < a.length; index += 1) if (!sameJson(a[index], b[index])) return false;
7977
+ return true;
7978
+ }
7979
+ const left = a;
7980
+ const right = b;
7981
+ let members = 0;
7982
+ for (const key of Object.keys(left)) {
7983
+ if (left[key] === void 0) continue;
7984
+ members += 1;
7985
+ if (!sameJson(left[key], right[key])) return false;
7986
+ }
7987
+ for (const key of Object.keys(right)) if (right[key] !== void 0) members -= 1;
7988
+ return members === 0;
7989
+ }
7990
+ //#endregion
7991
+ //#region ../sdk/src/board/model/script-scope.ts
7992
+ const childrenByItems = /* @__PURE__ */ new WeakMap();
7993
+ const everyItem = /* @__PURE__ */ new WeakMap();
7994
+ function childIndex(items) {
7995
+ let index = childrenByItems.get(items);
7996
+ if (!index) {
7997
+ index = /* @__PURE__ */ new Map();
7998
+ for (const [id, item] of Object.entries(items)) {
7999
+ if (!item.parent) continue;
8000
+ const siblings = index.get(item.parent);
8001
+ if (siblings) siblings.push(id);
8002
+ else index.set(item.parent, [id]);
8003
+ }
8004
+ childrenByItems.set(items, index);
8005
+ }
8006
+ return index;
8007
+ }
8008
+ function boardScriptOf(document, id) {
8009
+ return isBoardRootScript(document, id) ? document.board?.scripts?.[id] : document.items[id]?.script;
8010
+ }
8011
+ function boardScriptScope(document, id) {
8012
+ if (isBoardRootScript(document, id)) {
8013
+ let all = everyItem.get(document.items);
8014
+ if (!all) {
8015
+ all = new Set(Object.keys(document.items));
8016
+ everyItem.set(document.items, all);
8017
+ }
8018
+ return all;
8019
+ }
8020
+ const item = document.items[id];
8021
+ const scope = /* @__PURE__ */ new Set([id]);
8022
+ for (const target of Object.values(item?.script?.targets ?? {})) if (document.items[target]) scope.add(target);
8023
+ if (item?.type !== "frame") return scope;
8024
+ const children = childIndex(document.items);
8025
+ const visited = /* @__PURE__ */ new Set([id]);
8026
+ const queue = [id];
8027
+ for (let depth = 0; queue.length && depth < 64; depth++) for (const parent of queue.splice(0)) for (const child of children.get(parent) ?? []) {
8028
+ if (visited.has(child)) continue;
8029
+ visited.add(child);
8030
+ scope.add(child);
8031
+ queue.push(child);
8032
+ }
8033
+ return scope;
8034
+ }
8035
+ function diffBoardScriptItems(copy, document, scope, note) {
8036
+ const changes = {};
8037
+ let changed = false;
8038
+ for (const id of scope) {
8039
+ const item = document.items[id];
8040
+ const previous = copy.get(id);
8041
+ if (!item || previous === item) continue;
8042
+ copy.set(id, item);
8043
+ if (previous && sameJson(previous, item)) continue;
8044
+ changes[id] = item;
8045
+ changed = true;
8046
+ note?.(id, previous ? "changed" : "added");
8047
+ }
8048
+ if (copy.size > scope.size) for (const id of copy.keys()) {
8049
+ if (scope.has(id)) continue;
8050
+ copy.delete(id);
8051
+ changes[id] = null;
8052
+ changed = true;
8053
+ note?.(id, "removed");
8054
+ }
8055
+ return changed ? changes : null;
8056
+ }
8057
+ function supersedes(pending, event) {
8058
+ if (pending.type !== event.type) return false;
8059
+ if (event.type === "viewchange" || event.type === "selectionchange") return true;
8060
+ if (event.type === "pointermove") return pending.pointerId === event.pointerId;
8061
+ if (event.type !== "gesture") return false;
8062
+ const a = pending.data;
8063
+ const b = event.data;
8064
+ return a.id === b.id && a.phase === "update" && b.phase === "update";
8065
+ }
8066
+ function boardScriptListens(output, event) {
8067
+ return !output || event.type === "viewchange" || output.listens.includes(event.type);
8068
+ }
8069
+ function queueBoardScriptEvent(queue, event) {
8070
+ let queued = queue.length - 1;
8071
+ while (queued >= 0 && !supersedes(queue[queued], event)) queued--;
8072
+ if (queued >= 0 && (event.type !== "pointermove" || queued === queue.length - 1)) queue.splice(queued, 1);
8073
+ if (queue.length >= 128) return false;
8074
+ queue.push(event);
8075
+ return true;
8076
+ }
8077
+ function boardScriptEmit(document, sender, input) {
8078
+ const message = input;
8079
+ if (!message || typeof message.target !== "string" || typeof message.type !== "string" || !message.type) throw new Error("emit() takes a target id and an event type.");
8080
+ const { target, type } = message;
8081
+ if (!isBoardRootScript(document, target) && !boardScriptScope(document, sender).has(target)) throw new Error(`emit() from ${sender} cannot reach ${target}: it is neither in scope nor a Board script.`);
8082
+ const depth = typeof message.depth === "number" && Number.isSafeInteger(message.depth) && message.depth > 0 ? message.depth : 1;
8083
+ if (depth > 16) throw new Error(`emit(${target}, "${type}") from ${sender} is ${depth} handlers deep, past the limit of 16: handlers keep answering each other. Emit from onFrame() to send it on the next step.`);
8084
+ return {
8085
+ target,
8086
+ event: {
8087
+ type,
8088
+ data: message.data,
8089
+ depth
8090
+ }
8091
+ };
8092
+ }
8093
+ function createBoardScriptOutbox(order) {
8094
+ let queued = [];
8095
+ let seq = 0;
8096
+ const waiting = /* @__PURE__ */ new Map();
8097
+ return {
8098
+ get size() {
8099
+ return queued.length;
8100
+ },
8101
+ push(sender, target, event) {
8102
+ const count = waiting.get(target) ?? 0;
8103
+ if (count >= 128) throw new Error(`emit(${target}, "${event.type}") from ${sender}: ${target} already has 128 events waiting.`);
8104
+ waiting.set(target, count + 1);
8105
+ queued.push({
8106
+ rank: order().get(sender) ?? Number.MAX_SAFE_INTEGER,
8107
+ seq: seq++,
8108
+ target,
8109
+ event
8110
+ });
8111
+ },
8112
+ take() {
8113
+ const batch = queued.sort((a, b) => a.rank - b.rank || a.seq - b.seq);
8114
+ queued = [];
8115
+ waiting.clear();
8116
+ const byTarget = /* @__PURE__ */ new Map();
8117
+ for (const { target, event } of batch) byTarget.set(target, [...byTarget.get(target) ?? [], event]);
8118
+ return byTarget;
8119
+ }
8120
+ };
8121
+ }
8122
+ //#endregion
7963
8123
  //#region ../sdk/src/board/model/geometry.ts
7964
8124
  function screenPoint(x, y) {
7965
8125
  return {
@@ -8402,100 +8562,13 @@ function visibleWorldRect(viewport, surfaceWidth, surfaceHeight) {
8402
8562
  };
8403
8563
  }
8404
8564
  //#endregion
8405
- //#region ../sdk/src/board/model/json.ts
8406
- function sameJson(a, b) {
8407
- if (a === b) return true;
8408
- if (!a || !b || typeof a !== "object" || typeof b !== "object") return false;
8409
- if (Array.isArray(a) || Array.isArray(b)) {
8410
- if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
8411
- for (let index = 0; index < a.length; index += 1) if (!sameJson(a[index], b[index])) return false;
8412
- return true;
8413
- }
8414
- const left = a;
8415
- const right = b;
8416
- let members = 0;
8417
- for (const key of Object.keys(left)) {
8418
- if (left[key] === void 0) continue;
8419
- members += 1;
8420
- if (!sameJson(left[key], right[key])) return false;
8421
- }
8422
- for (const key of Object.keys(right)) if (right[key] !== void 0) members -= 1;
8423
- return members === 0;
8424
- }
8425
- //#endregion
8426
- //#region ../sdk/src/board/model/script-scope.ts
8427
- const childrenByItems = /* @__PURE__ */ new WeakMap();
8428
- const everyItem = /* @__PURE__ */ new WeakMap();
8429
- function childIndex(items) {
8430
- let index = childrenByItems.get(items);
8431
- if (!index) {
8432
- index = /* @__PURE__ */ new Map();
8433
- for (const [id, item] of Object.entries(items)) {
8434
- if (!item.parent) continue;
8435
- const siblings = index.get(item.parent);
8436
- if (siblings) siblings.push(id);
8437
- else index.set(item.parent, [id]);
8438
- }
8439
- childrenByItems.set(items, index);
8440
- }
8441
- return index;
8442
- }
8443
- function boardScriptOf(document, id) {
8444
- return isBoardRootScript(document, id) ? document.board?.scripts?.[id] : document.items[id]?.script;
8445
- }
8446
- function boardScriptScope(document, id) {
8447
- if (isBoardRootScript(document, id)) {
8448
- let all = everyItem.get(document.items);
8449
- if (!all) {
8450
- all = new Set(Object.keys(document.items));
8451
- everyItem.set(document.items, all);
8452
- }
8453
- return all;
8454
- }
8455
- const item = document.items[id];
8456
- const scope = /* @__PURE__ */ new Set([id]);
8457
- for (const target of Object.values(item?.script?.targets ?? {})) if (document.items[target]) scope.add(target);
8458
- if (item?.type !== "frame") return scope;
8459
- const children = childIndex(document.items);
8460
- const visited = /* @__PURE__ */ new Set([id]);
8461
- const queue = [id];
8462
- for (let depth = 0; queue.length && depth < 64; depth++) for (const parent of queue.splice(0)) for (const child of children.get(parent) ?? []) {
8463
- if (visited.has(child)) continue;
8464
- visited.add(child);
8465
- scope.add(child);
8466
- queue.push(child);
8467
- }
8468
- return scope;
8469
- }
8470
- function diffBoardScriptItems(copy, document, scope, note) {
8471
- const changes = {};
8472
- let changed = false;
8473
- for (const id of scope) {
8474
- const item = document.items[id];
8475
- const previous = copy.get(id);
8476
- if (!item || previous === item) continue;
8477
- copy.set(id, item);
8478
- if (previous && sameJson(previous, item)) continue;
8479
- changes[id] = item;
8480
- changed = true;
8481
- note?.(id, previous ? "changed" : "added");
8482
- }
8483
- if (copy.size > scope.size) for (const id of copy.keys()) {
8484
- if (scope.has(id)) continue;
8485
- copy.delete(id);
8486
- changes[id] = null;
8487
- changed = true;
8488
- note?.(id, "removed");
8489
- }
8490
- return changed ? changes : null;
8491
- }
8492
- //#endregion
8493
8565
  //#region ../sdk/src/board/model/shader.ts
8494
8566
  const BOARD_SHADER_LIMITS = {
8495
- passes: 8,
8567
+ passes: 16,
8496
8568
  source: 65536,
8497
8569
  sprites: 65536,
8498
8570
  stateEdge: 1024,
8571
+ texel: 1024,
8499
8572
  uniformSlots: 128
8500
8573
  };
8501
8574
  const COMPONENTS = {
@@ -8534,6 +8607,12 @@ function boardShaderUniformValue(uniform, value) {
8534
8607
  while (list.length < size) list.push(0);
8535
8608
  return list;
8536
8609
  }
8610
+ function boardShaderPassLayer(shader, pass) {
8611
+ return pass.layer ?? shader.layer ?? "above";
8612
+ }
8613
+ function boardShaderPassOn(pass, states) {
8614
+ return (pass.name !== void 0 ? states?.[pass.name] : void 0) ?? pass.enabled ?? true;
8615
+ }
8537
8616
  function boardShaderParameters(parameters) {
8538
8617
  const result = [];
8539
8618
  for (const [name, spec] of Object.entries(parameters ?? {})) {
@@ -8555,13 +8634,26 @@ function validateBoardShader(shader) {
8555
8634
  if (value.layer !== void 0 && !BOARD_SHADER_LAYERS.includes(value.layer)) throw new Error(`shader.layer must be ${BOARD_SHADER_LAYERS.join(", ")}.`);
8556
8635
  if (value.surfaces !== void 0 && typeof value.surfaces !== "boolean") throw new Error("shader.surfaces must be a boolean.");
8557
8636
  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.`);
8637
+ const names = /* @__PURE__ */ new Set();
8558
8638
  for (const pass of value.passes) {
8559
8639
  if (!pass || typeof pass.glsl !== "string" || !pass.glsl.trim()) throw new Error("Each shader pass needs glsl source.");
8560
8640
  if (pass.glsl.length > BOARD_SHADER_LIMITS.source) throw new Error("A shader pass exceeds 64 KB of source.");
8641
+ if (pass.layer !== void 0 && !BOARD_SHADER_LAYERS.includes(pass.layer)) throw new Error(`A pass layer must be ${BOARD_SHADER_LAYERS.join(", ")}.`);
8561
8642
  if (pass.sprites !== void 0) {
8562
8643
  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}.`);
8563
- if (value.layer === "filter") throw new Error("Filter passes draw over the owner's box; they cannot draw sprites.");
8644
+ if (boardShaderPassLayer(value, pass) === "filter") throw new Error("Filter passes draw over the owner's box; they cannot draw sprites.");
8564
8645
  }
8646
+ if (pass.texel !== void 0) {
8647
+ if (typeof pass.texel !== "number" || !(pass.texel > 0 && pass.texel <= BOARD_SHADER_LIMITS.texel)) throw new Error(`texel must be a number above 0 and up to ${BOARD_SHADER_LIMITS.texel}.`);
8648
+ if (pass.sprites !== void 0 || boardShaderPassLayer(value, pass) === "filter") throw new Error("texel shades a pass over its box; sprite and filter passes cannot take it.");
8649
+ }
8650
+ if (pass.name !== void 0) {
8651
+ if (typeof pass.name !== "string" || !IDENTIFIER.test(pass.name)) throw new Error(`Invalid pass name: ${String(pass.name)}`);
8652
+ if (names.has(pass.name)) throw new Error(`Pass names must be unique: ${pass.name}`);
8653
+ names.add(pass.name);
8654
+ }
8655
+ if (pass.enabled !== void 0 && typeof pass.enabled !== "boolean") throw new Error("A pass's enabled must be a boolean.");
8656
+ if (pass.enabled === false && pass.name === void 0) throw new Error("A pass that starts off needs a name to turn it on.");
8565
8657
  if (pass.blend !== void 0 && !BOARD_SHADER_BLENDS.includes(pass.blend)) throw new Error(`blend must be ${BOARD_SHADER_BLENDS.join(", ")}.`);
8566
8658
  }
8567
8659
  boardShaderUniforms(value.uniforms);
@@ -8599,6 +8691,33 @@ function parseBoardItem(value) {
8599
8691
  if (!parsed.ok) throw new Error(parsed.diagnostics[0]?.message ?? "Invalid script item.");
8600
8692
  return parsed.item;
8601
8693
  }
8694
+ function presentItem(base, patch) {
8695
+ return presentTransform(base, patch) ?? parseBoardItem(mergePatch(base, patch));
8696
+ }
8697
+ function presentTransform(base, patch) {
8698
+ const next = { ...base };
8699
+ for (const key in patch) {
8700
+ const value = patch[key];
8701
+ if (key === "position") {
8702
+ if (!value || typeof value !== "object") return null;
8703
+ const { x = base.position.x, y = base.position.y, ...rest } = value;
8704
+ if (!Number.isFinite(x) || !Number.isFinite(y)) return null;
8705
+ for (const _ in rest) return null;
8706
+ next.position = {
8707
+ x,
8708
+ y
8709
+ };
8710
+ continue;
8711
+ }
8712
+ if (key === "rotation" || key === "z") {
8713
+ if (!Number.isFinite(value)) return null;
8714
+ } else if (key === "opacity") {
8715
+ if (typeof value !== "number" || !(value >= 0 && value <= 1)) return null;
8716
+ } else if (key !== "visible" || typeof value !== "boolean") return null;
8717
+ next[key] = value;
8718
+ }
8719
+ return next;
8720
+ }
8602
8721
  const DISPLAY_FIELDS = /* @__PURE__ */ new Set([
8603
8722
  "position",
8604
8723
  "size",
@@ -8796,7 +8915,7 @@ function prepareBoardScriptOutput(document, owner, output) {
8796
8915
  const base = document.items[id];
8797
8916
  if (base && scope.has(id)) presented.set(id, {
8798
8917
  base,
8799
- item: parseBoardItem(mergePatch(base, patch))
8918
+ item: presentItem(base, patch)
8800
8919
  });
8801
8920
  }
8802
8921
  const prefix = scriptTemporaryPrefix(owner);
@@ -8828,7 +8947,7 @@ function composeBoardScriptItems(document, scene, outputs, incoming = /* @__PURE
8828
8947
  if (current.base !== base) {
8829
8948
  current = {
8830
8949
  base,
8831
- item: parseBoardItem(mergePatch(base, output.patches[id]))
8950
+ item: presentItem(base, output.patches[id] ?? {})
8832
8951
  };
8833
8952
  prepared.presented.set(id, current);
8834
8953
  }
@@ -8978,42 +9097,46 @@ function bindingsFor(owner, output) {
8978
9097
  function boardScriptTarget(scene, candidates, point, outputs, hitTest) {
8979
9098
  const declared = [...outputs].map(([owner, output]) => bindingsFor(owner, output));
8980
9099
  const prefixes = [...outputs.keys()].map(scriptTemporaryPrefix);
8981
- for (const id of [...candidates].sort((a, b) => scene.indexOf(b) - scene.indexOf(a))) {
8982
- const item = scene.get(id);
8983
- if (!item || scene.opacity(id) <= 0) continue;
8984
- let parent = item.parent;
8985
- let clipped = false;
8986
- for (let depth = 0; parent && depth < 64; depth++) {
8987
- const ancestor = scene.get(parent);
8988
- if (!ancestor) break;
8989
- if (ancestor.type === "frame" && ancestor.props.clip && !frameContainsPoint(ancestor.frame, point)) {
8990
- clipped = true;
8991
- break;
8992
- }
8993
- parent = ancestor.parent;
8994
- }
8995
- if (clipped) continue;
8996
- for (const byItem of declared) {
8997
- const hits = byItem.get(id);
8998
- if (!hits) continue;
8999
- const local = applyMatrix$1(invertMatrix(scene.layout.matrix(id)), point);
9000
- for (let i = hits.length - 1; i >= 0; i--) {
9001
- const binding = hits[i];
9002
- if (!binding) continue;
9003
- const resolved = resolveBoardScriptHit(scene, binding.owner, binding.hit);
9004
- if (!resolved) continue;
9005
- const r = resolved.rect;
9006
- 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 {
9007
- owner: binding.owner,
9008
- target: binding.target
9009
- };
9100
+ const ordered = [...candidates].sort((a, b) => scene.indexOf(b) - scene.indexOf(a));
9101
+ const scan = (over) => {
9102
+ for (const id of ordered) {
9103
+ const item = scene.get(id);
9104
+ if (!item || scene.opacity(id) <= 0) continue;
9105
+ let parent = item.parent;
9106
+ let clipped = false;
9107
+ for (let depth = 0; parent && depth < 64; depth++) {
9108
+ const ancestor = scene.get(parent);
9109
+ if (!ancestor) break;
9110
+ if (ancestor.type === "frame" && ancestor.props.clip && !frameContainsPoint(ancestor.frame, point)) {
9111
+ clipped = true;
9112
+ break;
9113
+ }
9114
+ parent = ancestor.parent;
9115
+ }
9116
+ if (clipped) continue;
9117
+ for (const byItem of declared) {
9118
+ const hits = byItem.get(id);
9119
+ if (!hits) continue;
9120
+ const local = applyMatrix$1(invertMatrix(scene.layout.matrix(id)), point);
9121
+ for (let i = hits.length - 1; i >= 0; i--) {
9122
+ const binding = hits[i];
9123
+ if (!binding || over && !binding.hit.over) continue;
9124
+ const resolved = resolveBoardScriptHit(scene, binding.owner, binding.hit);
9125
+ if (!resolved) continue;
9126
+ const r = resolved.rect;
9127
+ 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 {
9128
+ owner: binding.owner,
9129
+ target: binding.target
9130
+ };
9131
+ }
9010
9132
  }
9133
+ if (over || prefixes.some((prefix) => id.startsWith(prefix))) continue;
9134
+ if (item.type === "frame" && item.props.decoration === "none") continue;
9135
+ if (hitTest(item, point)) return null;
9011
9136
  }
9012
- if (prefixes.some((prefix) => id.startsWith(prefix))) continue;
9013
- if (item.type === "frame" && item.props.decoration === "none") continue;
9014
- if (hitTest(item, point)) return null;
9015
- }
9016
- return null;
9137
+ return null;
9138
+ };
9139
+ return ([...outputs.values()].some((output) => Object.values(output.hits).some((hit) => hit.over)) ? scan(true) : null) ?? scan(false);
9017
9140
  }
9018
9141
  //#endregion
9019
9142
  //#region ../sdk/src/board/model/script-example.ts
@@ -9224,7 +9347,7 @@ function parameterKind(track) {
9224
9347
  function compileBoardTrack(animationId, id, track, targetType) {
9225
9348
  const resolved = resolveBoardProperty(targetType, track.property);
9226
9349
  if (!resolved.ok) return null;
9227
- const kind = targetType === "script" ? parameterKind(track) : resolved.spec.kind;
9350
+ const kind = targetType === "script" || track.property.startsWith("script.params.") ? parameterKind(track) : resolved.spec.kind;
9228
9351
  const times = new Float64Array(track.keyframes.length);
9229
9352
  const values = [];
9230
9353
  const eases = [];
@@ -9514,10 +9637,14 @@ function evaluateBoardAnimations(compiled, times, options = {}) {
9514
9637
  const ordered = [...groups.values()].sort((a, b) => a.path.length - b.path.length);
9515
9638
  for (const group of ordered) {
9516
9639
  const isCamera = group.target === BOARD_CAMERA_TARGET$1;
9517
- const script = isCamera ? void 0 : scripts.get(group.target) ?? compiled.document.board.scripts?.[group.target];
9640
+ const rootScript = isCamera ? void 0 : compiled.document.board.scripts?.[group.target];
9641
+ const itemScript = isCamera || rootScript || group.path[0] !== "script" ? void 0 : compiled.document.items[group.target]?.script;
9642
+ const script = rootScript || itemScript ? scripts.get(group.target) ?? rootScript ?? itemScript : void 0;
9643
+ if (group.path[0] === "script" && !itemScript) continue;
9644
+ const path = itemScript ? group.path.slice(1) : group.path;
9518
9645
  const base = isCamera || script ? void 0 : items.get(group.target) ?? compiled.document.items[group.target];
9519
9646
  if (!isCamera && !script && !base) continue;
9520
- let value = isCamera ? camera[group.path[0]] : readPath$1(script ?? base, group.path);
9647
+ let value = isCamera ? camera[path[0]] : readPath$1(script ?? base, path);
9521
9648
  let orientTrack = null;
9522
9649
  if (group.winner) {
9523
9650
  value = sampleBoardTrack(group.winner, group.winnerTime, resolveColor);
@@ -9532,7 +9659,7 @@ function evaluateBoardAnimations(compiled, times, options = {}) {
9532
9659
  continue;
9533
9660
  }
9534
9661
  if (script) {
9535
- scripts.set(group.target, writePath$1(script, group.path, value));
9662
+ scripts.set(group.target, writePath$1(script, path, value));
9536
9663
  continue;
9537
9664
  }
9538
9665
  let next = writePath$1(base, group.path, value);
@@ -9552,30 +9679,56 @@ function evaluateBoardAnimations(compiled, times, options = {}) {
9552
9679
  times: local
9553
9680
  };
9554
9681
  }
9682
+ const BOARD_SCRIPT_HISTORY_MS = 1e3 / 30;
9683
+ function boardAnimatesScriptParams(document) {
9684
+ return Object.values(document.animations).some((animation) => Object.values(animation.tracks).some((track) => /^(script\.)?params\./.test(track.property)));
9685
+ }
9555
9686
  function withBoardScripts(document, scripts) {
9687
+ if (scripts.size === 0) return document;
9556
9688
  const stored = document.board.scripts;
9557
- if (scripts.size === 0 || !stored) return document;
9558
- const next = { ...stored };
9689
+ let board = document.board;
9690
+ let items = document.items;
9559
9691
  for (const [id, script] of scripts) {
9560
- const base = stored[id];
9561
- if (base) next[id] = {
9562
- ...base,
9563
- params: script.params
9692
+ const root = stored?.[id];
9693
+ if (root) {
9694
+ if (board === document.board) board = {
9695
+ ...board,
9696
+ scripts: { ...stored }
9697
+ };
9698
+ board.scripts[id] = {
9699
+ ...root,
9700
+ params: script.params
9701
+ };
9702
+ continue;
9703
+ }
9704
+ const item = items[id];
9705
+ if (!item?.script) continue;
9706
+ if (items === document.items) items = { ...items };
9707
+ items[id] = {
9708
+ ...item,
9709
+ script: {
9710
+ ...item.script,
9711
+ params: script.params
9712
+ }
9564
9713
  };
9565
9714
  }
9566
- return {
9715
+ return board === document.board && items === document.items ? document : {
9567
9716
  ...document,
9568
- board: {
9569
- ...document.board,
9570
- scripts: next
9571
- }
9717
+ board,
9718
+ items
9572
9719
  };
9573
9720
  }
9574
9721
  function applyBoardEvaluation(document, evaluation) {
9575
9722
  const scripted = withBoardScripts(document, evaluation.scripts);
9576
9723
  if (evaluation.items.size === 0) return scripted;
9577
- const items = { ...document.items };
9578
- for (const [id, item] of evaluation.items) items[id] = item;
9724
+ const items = { ...scripted.items };
9725
+ for (const [id, item] of evaluation.items) {
9726
+ const script = scripted.items[id]?.script;
9727
+ items[id] = script && script !== document.items[id]?.script ? {
9728
+ ...item,
9729
+ script
9730
+ } : item;
9731
+ }
9579
9732
  return {
9580
9733
  ...scripted,
9581
9734
  items
@@ -11595,9 +11748,10 @@ function resolveRegion(scene, region) {
11595
11748
  };
11596
11749
  const rect = itemBounds(frame.frame);
11597
11750
  return {
11598
- items: scene.items.filter((item) => item.id !== region.id && visible(item, rect)),
11751
+ items: scene.items.filter((item) => item.id === region.id || visible(item, rect)),
11599
11752
  rect,
11600
- padding: 0
11753
+ padding: 0,
11754
+ page: region.id
11601
11755
  };
11602
11756
  }
11603
11757
  case "rect": {
@@ -11635,7 +11789,8 @@ function planBoardExport(input) {
11635
11789
  width: Math.max(1, Math.floor(world.width * scale)),
11636
11790
  height: Math.max(1, Math.floor(world.height * scale)),
11637
11791
  items: resolved.items,
11638
- clamped: scale < safeRequest - 1e-6
11792
+ clamped: scale < safeRequest - 1e-6,
11793
+ ...resolved.page ? { page: resolved.page } : {}
11639
11794
  };
11640
11795
  }
11641
11796
  //#endregion
@@ -13099,6 +13254,61 @@ function createBoardRegistry(definitions = []) {
13099
13254
  }
13100
13255
  const defaultBoardRegistry = createBoardRegistry();
13101
13256
  //#endregion
13257
+ //#region ../sdk/src/board/model/autoplay.ts
13258
+ const text = (value) => typeof value === "string" && value.length > 0 ? value : void 0;
13259
+ function boardAppMetadata(item) {
13260
+ if (item?.type !== "frame" || !item.metadata) return null;
13261
+ const value = item.metadata.cohubApp;
13262
+ if (!value || typeof value !== "object") return null;
13263
+ const app = value;
13264
+ const appId = text(app.appId);
13265
+ const ref = text(app.ref);
13266
+ const url = text(app.url);
13267
+ const name = text(app.name);
13268
+ if (!appId || !ref || !url || !name) return null;
13269
+ const icon = text(app.icon);
13270
+ const cover = text(app.cover);
13271
+ const themeColor = text(app.themeColor);
13272
+ return {
13273
+ appId,
13274
+ ref,
13275
+ url,
13276
+ name,
13277
+ ...icon ? { icon } : {},
13278
+ ...cover ? { cover } : {},
13279
+ ...themeColor ? { themeColor } : {}
13280
+ };
13281
+ }
13282
+ function boardAutoplayKind(item) {
13283
+ if (!item) return null;
13284
+ if (item.type === "video") return item.props.time === void 0 ? "video" : null;
13285
+ if (item.type === "task") return boardAutoplayVideo(item) ? "video" : null;
13286
+ if (isBoardModelItem(item)) return "model";
13287
+ return boardAppMetadata(item) ? "app" : null;
13288
+ }
13289
+ function boardAutoplayVideo(item) {
13290
+ if (item.type === "video") return item.props.time === void 0 ? item.props.src : null;
13291
+ if (item.type !== "task" || item.props.snapshot.status !== "completed") return null;
13292
+ const artifact = featuredTaskArtifact(item.props.snapshot.artifacts);
13293
+ return artifact?.type === "video" ? artifact.url : null;
13294
+ }
13295
+ function boardAutoplayLoops(scene, at) {
13296
+ const loops = [];
13297
+ for (const item of scene.items) {
13298
+ const src = item.autoplay ? boardAutoplayVideo(item) : null;
13299
+ if (src) loops.push({
13300
+ id: item.id,
13301
+ kind: "video",
13302
+ src,
13303
+ time: at,
13304
+ volume: 0,
13305
+ shown: scene.shown(item.id),
13306
+ loop: true
13307
+ });
13308
+ }
13309
+ return loops;
13310
+ }
13311
+ //#endregion
13102
13312
  //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/environment-browser/browserExt.mjs
13103
13313
  const browserExt = {
13104
13314
  extension: {
@@ -20516,6 +20726,91 @@ function pointInTriangle(px, py, x1, y1, x2, y2, x3, y3) {
20516
20726
  return u >= 0 && v >= 0 && u + v < 1;
20517
20727
  }
20518
20728
  //#endregion
20729
+ //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/filters/defaults/alpha/alpha.frag.mjs
20730
+ 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";
20731
+ //#endregion
20732
+ //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/filters/defaults/alpha/alpha.wgsl.mjs
20733
+ 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}";
20734
+ //#endregion
20735
+ //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/filters/defaults/alpha/AlphaFilter.mjs
20736
+ const _AlphaFilter = class _AlphaFilter extends Filter {
20737
+ constructor(options) {
20738
+ options = {
20739
+ ..._AlphaFilter.defaultOptions,
20740
+ ...options
20741
+ };
20742
+ const gpuProgram = GpuProgram.from({
20743
+ vertex: {
20744
+ source: source$2,
20745
+ entryPoint: "mainVertex"
20746
+ },
20747
+ fragment: {
20748
+ source: source$2,
20749
+ entryPoint: "mainFragment"
20750
+ }
20751
+ });
20752
+ const glProgram = GlProgram.from({
20753
+ vertex: vertex$2,
20754
+ fragment: fragment$3,
20755
+ name: "alpha-filter"
20756
+ });
20757
+ const { alpha, ...rest } = options;
20758
+ const alphaUniforms = new UniformGroup({ uAlpha: {
20759
+ value: alpha,
20760
+ type: "f32"
20761
+ } });
20762
+ super({
20763
+ ...rest,
20764
+ gpuProgram,
20765
+ glProgram,
20766
+ resources: { alphaUniforms }
20767
+ });
20768
+ }
20769
+ /**
20770
+ * The alpha value of the filter.
20771
+ * Controls the transparency of the filtered display object.
20772
+ * @example
20773
+ * ```ts
20774
+ * // Create filter with initial alpha
20775
+ * const filter = new AlphaFilter({ alpha: 0.5 });
20776
+ *
20777
+ * // Update alpha value dynamically
20778
+ * filter.alpha = 0.8;
20779
+ * ```
20780
+ * @default 1
20781
+ * @remarks
20782
+ * - 0 = fully transparent
20783
+ * - 1 = fully opaque
20784
+ * - Values are clamped between 0 and 1
20785
+ */
20786
+ get alpha() {
20787
+ return this.resources.alphaUniforms.uniforms.uAlpha;
20788
+ }
20789
+ set alpha(value) {
20790
+ this.resources.alphaUniforms.uniforms.uAlpha = value;
20791
+ }
20792
+ };
20793
+ /**
20794
+ * Default options for the AlphaFilter.
20795
+ * @example
20796
+ * ```ts
20797
+ * AlphaFilter.defaultOptions = {
20798
+ * alpha: 0.5, // Default alpha value
20799
+ * };
20800
+ * // Use default options
20801
+ * const filter = new AlphaFilter(); // Uses default alpha of 0.5
20802
+ * ```
20803
+ */
20804
+ _AlphaFilter.defaultOptions = {
20805
+ /**
20806
+ * Amount of alpha transparency to apply.
20807
+ * - 0 = fully transparent
20808
+ * - 1 = fully opaque (default)
20809
+ * @default 1
20810
+ */
20811
+ alpha: 1 };
20812
+ let AlphaFilter = _AlphaFilter;
20813
+ //#endregion
20519
20814
  //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/filters/defaults/color-matrix/colorMatrixFilter.frag.mjs
20520
20815
  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";
20521
20816
  //#endregion
@@ -31677,6 +31972,230 @@ var CanvasRenderer = class extends AbstractRenderer {
31677
31972
  }
31678
31973
  };
31679
31974
  //#endregion
31975
+ //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/rendering/renderers/gl/shader/GlProgramData.mjs
31976
+ var GlProgramData = class {
31977
+ /**
31978
+ * Makes a new Pixi program.
31979
+ * @param program - webgl program
31980
+ * @param uniformData - uniforms
31981
+ */
31982
+ constructor(program, uniformData) {
31983
+ this.program = program;
31984
+ this.uniformData = uniformData;
31985
+ this.uniformGroups = {};
31986
+ this.uniformDirtyGroups = {};
31987
+ this.uniformBlockBindings = {};
31988
+ }
31989
+ /** Destroys this program. */
31990
+ destroy() {
31991
+ this.uniformData = null;
31992
+ this.uniformGroups = null;
31993
+ this.uniformDirtyGroups = null;
31994
+ this.uniformBlockBindings = null;
31995
+ this.program = null;
31996
+ }
31997
+ };
31998
+ //#endregion
31999
+ //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/rendering/renderers/gl/shader/program/defaultValue.mjs
32000
+ function booleanArray(size) {
32001
+ const array = new Array(size);
32002
+ for (let i = 0; i < array.length; i++) array[i] = false;
32003
+ return array;
32004
+ }
32005
+ function defaultValue(type, size) {
32006
+ switch (type) {
32007
+ case "float": return 0;
32008
+ case "vec2": return new Float32Array(2 * size);
32009
+ case "vec3": return new Float32Array(3 * size);
32010
+ case "vec4": return new Float32Array(4 * size);
32011
+ case "int":
32012
+ case "uint":
32013
+ case "sampler2D":
32014
+ case "sampler2DArray": return 0;
32015
+ case "ivec2": return new Int32Array(2 * size);
32016
+ case "ivec3": return new Int32Array(3 * size);
32017
+ case "ivec4": return new Int32Array(4 * size);
32018
+ case "uvec2": return new Uint32Array(2 * size);
32019
+ case "uvec3": return new Uint32Array(3 * size);
32020
+ case "uvec4": return new Uint32Array(4 * size);
32021
+ case "bool": return false;
32022
+ case "bvec2": return booleanArray(2 * size);
32023
+ case "bvec3": return booleanArray(3 * size);
32024
+ case "bvec4": return booleanArray(4 * size);
32025
+ case "mat2": return new Float32Array([
32026
+ 1,
32027
+ 0,
32028
+ 0,
32029
+ 1
32030
+ ]);
32031
+ case "mat3": return new Float32Array([
32032
+ 1,
32033
+ 0,
32034
+ 0,
32035
+ 0,
32036
+ 1,
32037
+ 0,
32038
+ 0,
32039
+ 0,
32040
+ 1
32041
+ ]);
32042
+ case "mat4": return new Float32Array([
32043
+ 1,
32044
+ 0,
32045
+ 0,
32046
+ 0,
32047
+ 0,
32048
+ 1,
32049
+ 0,
32050
+ 0,
32051
+ 0,
32052
+ 0,
32053
+ 1,
32054
+ 0,
32055
+ 0,
32056
+ 0,
32057
+ 0,
32058
+ 1
32059
+ ]);
32060
+ }
32061
+ return null;
32062
+ }
32063
+ //#endregion
32064
+ //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/rendering/renderers/gl/shader/program/mapType.mjs
32065
+ let GL_TABLE = null;
32066
+ const GL_TO_GLSL_TYPES = {
32067
+ FLOAT: "float",
32068
+ FLOAT_VEC2: "vec2",
32069
+ FLOAT_VEC3: "vec3",
32070
+ FLOAT_VEC4: "vec4",
32071
+ INT: "int",
32072
+ INT_VEC2: "ivec2",
32073
+ INT_VEC3: "ivec3",
32074
+ INT_VEC4: "ivec4",
32075
+ UNSIGNED_INT: "uint",
32076
+ UNSIGNED_INT_VEC2: "uvec2",
32077
+ UNSIGNED_INT_VEC3: "uvec3",
32078
+ UNSIGNED_INT_VEC4: "uvec4",
32079
+ BOOL: "bool",
32080
+ BOOL_VEC2: "bvec2",
32081
+ BOOL_VEC3: "bvec3",
32082
+ BOOL_VEC4: "bvec4",
32083
+ FLOAT_MAT2: "mat2",
32084
+ FLOAT_MAT3: "mat3",
32085
+ FLOAT_MAT4: "mat4",
32086
+ SAMPLER_2D: "sampler2D",
32087
+ INT_SAMPLER_2D: "sampler2D",
32088
+ UNSIGNED_INT_SAMPLER_2D: "sampler2D",
32089
+ SAMPLER_2D_SHADOW: "sampler2DShadow",
32090
+ SAMPLER_CUBE: "samplerCube",
32091
+ INT_SAMPLER_CUBE: "samplerCube",
32092
+ UNSIGNED_INT_SAMPLER_CUBE: "samplerCube",
32093
+ SAMPLER_CUBE_SHADOW: "samplerCubeShadow",
32094
+ SAMPLER_2D_ARRAY: "sampler2DArray",
32095
+ INT_SAMPLER_2D_ARRAY: "sampler2DArray",
32096
+ UNSIGNED_INT_SAMPLER_2D_ARRAY: "sampler2DArray",
32097
+ SAMPLER_2D_ARRAY_SHADOW: "sampler2DArrayShadow"
32098
+ };
32099
+ const GLSL_TO_VERTEX_TYPES = {
32100
+ float: "float32",
32101
+ vec2: "float32x2",
32102
+ vec3: "float32x3",
32103
+ vec4: "float32x4",
32104
+ int: "sint32",
32105
+ ivec2: "sint32x2",
32106
+ ivec3: "sint32x3",
32107
+ ivec4: "sint32x4",
32108
+ uint: "uint32",
32109
+ uvec2: "uint32x2",
32110
+ uvec3: "uint32x3",
32111
+ uvec4: "uint32x4",
32112
+ bool: "uint32",
32113
+ bvec2: "uint32x2",
32114
+ bvec3: "uint32x3",
32115
+ bvec4: "uint32x4"
32116
+ };
32117
+ function mapType(gl, type) {
32118
+ if (!GL_TABLE) {
32119
+ const typeNames = Object.keys(GL_TO_GLSL_TYPES);
32120
+ GL_TABLE = {};
32121
+ for (let i = 0; i < typeNames.length; ++i) {
32122
+ const tn = typeNames[i];
32123
+ GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn];
32124
+ }
32125
+ }
32126
+ return GL_TABLE[type];
32127
+ }
32128
+ function mapGlToVertexFormat(gl, type) {
32129
+ const typeValue = mapType(gl, type);
32130
+ return GLSL_TO_VERTEX_TYPES[typeValue] || "float32";
32131
+ }
32132
+ //#endregion
32133
+ //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/rendering/renderers/gl/shader/program/extractAttributesFromGlProgram.mjs
32134
+ function extractAttributesFromGlProgram(program, gl, sortAttributes = false) {
32135
+ const attributes = {};
32136
+ const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
32137
+ for (let i = 0; i < totalAttributes; i++) {
32138
+ const attribData = gl.getActiveAttrib(program, i);
32139
+ if (attribData.name.startsWith("gl_")) continue;
32140
+ const format = mapGlToVertexFormat(gl, attribData.type);
32141
+ attributes[attribData.name] = {
32142
+ location: 0,
32143
+ format,
32144
+ stride: getAttributeInfoFromFormat(format).stride,
32145
+ offset: 0,
32146
+ instance: false,
32147
+ start: 0
32148
+ };
32149
+ }
32150
+ const keys = Object.keys(attributes);
32151
+ if (sortAttributes) {
32152
+ keys.sort((a, b) => a > b ? 1 : -1);
32153
+ for (let i = 0; i < keys.length; i++) {
32154
+ attributes[keys[i]].location = i;
32155
+ gl.bindAttribLocation(program, i, keys[i]);
32156
+ }
32157
+ gl.linkProgram(program);
32158
+ } else for (let i = 0; i < keys.length; i++) attributes[keys[i]].location = gl.getAttribLocation(program, keys[i]);
32159
+ return attributes;
32160
+ }
32161
+ //#endregion
32162
+ //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/rendering/renderers/gl/shader/program/getUboData.mjs
32163
+ function getUboData(program, gl) {
32164
+ if (!gl.ACTIVE_UNIFORM_BLOCKS) return {};
32165
+ const uniformBlocks = {};
32166
+ const totalUniformsBlocks = gl.getProgramParameter(program, gl.ACTIVE_UNIFORM_BLOCKS);
32167
+ for (let i = 0; i < totalUniformsBlocks; i++) {
32168
+ const name = gl.getActiveUniformBlockName(program, i);
32169
+ uniformBlocks[name] = {
32170
+ name,
32171
+ index: gl.getUniformBlockIndex(program, name),
32172
+ size: gl.getActiveUniformBlockParameter(program, i, gl.UNIFORM_BLOCK_DATA_SIZE)
32173
+ };
32174
+ }
32175
+ return uniformBlocks;
32176
+ }
32177
+ //#endregion
32178
+ //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/rendering/renderers/gl/shader/program/getUniformData.mjs
32179
+ function getUniformData(program, gl) {
32180
+ const uniforms = {};
32181
+ const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
32182
+ for (let i = 0; i < totalUniforms; i++) {
32183
+ const uniformData = gl.getActiveUniform(program, i);
32184
+ const name = uniformData.name.replace(/\[.*?\]$/, "");
32185
+ const isArray = !!uniformData.name.match(/\[.*?\]$/);
32186
+ const type = mapType(gl, uniformData.type);
32187
+ uniforms[name] = {
32188
+ name,
32189
+ index: i,
32190
+ type,
32191
+ size: uniformData.size,
32192
+ isArray,
32193
+ value: defaultValue(type, uniformData.size)
32194
+ };
32195
+ }
32196
+ return uniforms;
32197
+ }
32198
+ //#endregion
31680
32199
  //#region ../../node_modules/.pnpm/pixi.js@8.20.1/node_modules/pixi.js/lib/scene/particle-container/canvas/CanvasParticleContainerAdaptor.mjs
31681
32200
  var CanvasParticleContainerAdaptor = class {
31682
32201
  execute(particleContainerPipe, container) {
@@ -37949,6 +38468,11 @@ function inspectBoardScene(scene, limit = 100, ids) {
37949
38468
  code: "effect-follow-unused",
37950
38469
  item: item.id
37951
38470
  });
38471
+ const unfinished = item.type === "task" && (item.props.snapshot.status === "pending" || item.props.snapshot.status === "running");
38472
+ if (item.autoplay && !unfinished && !boardAutoplayKind(item)) push({
38473
+ code: "autoplay-unused",
38474
+ item: item.id
38475
+ });
37952
38476
  }
37953
38477
  let glyphBudget = 256;
37954
38478
  for (const item of texts) {
@@ -38948,6 +39472,7 @@ function shaderPasses() {
38948
39472
  return passes;
38949
39473
  }
38950
39474
  const TEXELS_PER_DEVIATION = 4;
39475
+ const SAMPLED_TEXELS_PER_DEVIATION = 8;
38951
39476
  const MAX_HALVINGS = 5;
38952
39477
  function gaussian(filters, input, output, deviation, clear, first) {
38953
39478
  const { horizontal, vertical, copy } = shaderPasses();
@@ -38993,6 +39518,7 @@ var BoardBlurFilter = class extends Filter {
38993
39518
  this.radius = radius;
38994
39519
  this.deviation = radius * zoom;
38995
39520
  this.padding = Math.ceil(radius * 3 * zoom);
39521
+ this.resolution = this.deviation > SAMPLED_TEXELS_PER_DEVIATION ? SAMPLED_TEXELS_PER_DEVIATION / this.deviation : "inherit";
38996
39522
  this.css = `blur(${radius * zoom}px)`;
38997
39523
  }
38998
39524
  apply(filters, input, output, clearMode) {
@@ -39057,7 +39583,9 @@ var BoardShadowFilter = class extends Filter {
39057
39583
  };
39058
39584
  const filtersByContainer = /* @__PURE__ */ new WeakMap();
39059
39585
  function hasBoardEffects(style) {
39060
- return Boolean(style && (style.filter || style.shadow || style.blend && style.blend !== "normal"));
39586
+ if (!style) return false;
39587
+ const shadow = style.shadow && (style.shadow.opacity ?? BOARD_SHADOW_DEFAULTS.opacity) > 0;
39588
+ return Boolean(shadow || style.filter && (style.filter.blur || colorSteps(style.filter).length) || style.blend && style.blend !== "normal");
39061
39589
  }
39062
39590
  function resolveShadow(shadow, context) {
39063
39591
  return {
@@ -39090,7 +39618,8 @@ function syncBoardEffects(container, style, context) {
39090
39618
  const filter = style?.filter;
39091
39619
  const blurs = context.blurs !== false;
39092
39620
  const blur = blurs ? filter?.blur ?? 0 : 0;
39093
- const shadow = blurs && style?.shadow ? resolveShadow(style.shadow, context) : null;
39621
+ const resolved = blurs && style?.shadow ? resolveShadow(style.shadow, context) : null;
39622
+ const shadow = resolved && resolved.alpha > 0 ? resolved : null;
39094
39623
  const colored = colorSteps(filter).length > 0;
39095
39624
  let parts = filtersByContainer.get(container);
39096
39625
  if (!colored && blur <= 0 && !shadow) {
@@ -39278,6 +39807,27 @@ function syncFrameGroup(entry, item, context) {
39278
39807
  function syncBoardItemEffects(container, item, context) {
39279
39808
  syncBoardEffects(container, item.type === "frame" ? void 0 : item.style, context);
39280
39809
  }
39810
+ const shaderClips = /* @__PURE__ */ new WeakMap();
39811
+ function clipFrameShaderLayer(layer, item) {
39812
+ const entry = shaderClips.get(layer);
39813
+ if (!isClippingFrame(item)) {
39814
+ if (!entry) return;
39815
+ layer.mask = null;
39816
+ entry.mask.destroy();
39817
+ shaderClips.delete(layer);
39818
+ return;
39819
+ }
39820
+ const { width, height } = item.frame;
39821
+ const sig = `${width},${height}`;
39822
+ if (entry?.sig === sig) return;
39823
+ const mask = entry?.mask ?? layer.addChild(new Graphics());
39824
+ mask.clear().rect(0, 0, width, height).fill(16777215);
39825
+ layer.mask = mask;
39826
+ shaderClips.set(layer, {
39827
+ mask,
39828
+ sig
39829
+ });
39830
+ }
39281
39831
  //#endregion
39282
39832
  //#region ../sdk/src/board/render/audio-waveform.ts
39283
39833
  const DEFAULT_BARS = 44;
@@ -40010,10 +40560,12 @@ function sync$13(container, item, context) {
40010
40560
  const failed = Boolean(key && !texture && context.hasError(key));
40011
40561
  const detailed = boardCardDetailed(context.zoom);
40012
40562
  const elevation = cardElevation(context, item.id);
40563
+ const covered = context.covered?.(item.id) ?? false;
40013
40564
  const sig = [
40014
40565
  key ?? "",
40015
40566
  texture?.uid ?? "none",
40016
40567
  failed,
40568
+ covered,
40017
40569
  width,
40018
40570
  height,
40019
40571
  elevation,
@@ -40034,7 +40586,11 @@ function sync$13(container, item, context) {
40034
40586
  elevation
40035
40587
  });
40036
40588
  if (texture && parts.sprite.texture !== texture) parts.sprite.texture = texture;
40037
- parts.sprite.visible = Boolean(texture);
40589
+ parts.sprite.visible = Boolean(texture) && !covered;
40590
+ if (covered) {
40591
+ parts.chrome.clear();
40592
+ return;
40593
+ }
40038
40594
  if (texture) {
40039
40595
  const inset = Math.min(width, height) * INSET_RATIO;
40040
40596
  const fitted = containRect(width - inset * 2, height - inset * 2, texture.width, texture.height);
@@ -40143,6 +40699,7 @@ const PLAY_HIT = {
40143
40699
  cursor: "pointer"
40144
40700
  };
40145
40701
  function mediaPlayHit(item, point, context) {
40702
+ if (context.covered?.(item.id) || context.mediaTexture?.(item.id)) return null;
40146
40703
  const key = context.assetKey(item);
40147
40704
  return boardMediaActionAt(item, point, context.zoom, {
40148
40705
  materialized: true,
@@ -41037,9 +41594,12 @@ function sync$8(container, item, context) {
41037
41594
  const alpha = (style.stroke ? 1 : .55) * itemAlpha(context, style.stroke);
41038
41595
  const radius = style.radius ?? 4;
41039
41596
  const strokeWidth = style.strokeWidth ?? 1.5;
41040
- const decorated = props.decoration !== "none";
41597
+ const page = context.page === item.id;
41598
+ const decorated = props.decoration !== "none" && (!page || style.fill !== void 0);
41599
+ const outlined = decorated && !page;
41041
41600
  const visualSig = [
41042
41601
  props.decoration,
41602
+ page,
41043
41603
  frame.width,
41044
41604
  frame.height,
41045
41605
  fill,
@@ -41060,7 +41620,7 @@ function sync$8(container, item, context) {
41060
41620
  });
41061
41621
  const pattern = dashPattern(style.dash, strokeWidth);
41062
41622
  const trim = style.trim ?? 1;
41063
- if (decorated && strokeWidth > 0 && trim > 0) {
41623
+ if (outlined && strokeWidth > 0 && trim > 0) {
41064
41624
  if (pattern || trim < 1) tracePolyline(parts.box, trimPolyline(roundRectPoints(frame.width, frame.height, radius), trim), pattern);
41065
41625
  else parts.box.roundRect(0, 0, frame.width, frame.height, radius);
41066
41626
  parts.box.stroke({
@@ -41072,7 +41632,7 @@ function sync$8(container, item, context) {
41072
41632
  });
41073
41633
  }
41074
41634
  }
41075
- parts.label.visible = decorated;
41635
+ parts.label.visible = outlined;
41076
41636
  const title = locked ? `🔒 ${props.label}`.trim() : props.label;
41077
41637
  const labelColor = style.stroke ? baseStroke : context.palette.muted;
41078
41638
  const size = context.style.frameLabelSize;
@@ -42175,7 +42735,8 @@ function sync$3(container, item, context) {
42175
42735
  parts.assetKey = key;
42176
42736
  if (key) context.acquireTexture(key, item);
42177
42737
  }
42178
- const texture = key ? context.getTexture(key) : null;
42738
+ const live = context.mediaTexture?.(item.id) ?? null;
42739
+ const texture = live ?? (key ? context.getTexture(key) : null);
42179
42740
  const previewFailed = Boolean(key && !texture && context.hasError(key));
42180
42741
  const artifact = featuredTaskArtifact(snapshot.artifacts);
42181
42742
  const kind = previewKindFor(artifact);
@@ -42283,7 +42844,7 @@ function sync$3(container, item, context) {
42283
42844
  height: Math.max(1, frame.height - 24 - bottomInset)
42284
42845
  }, context.colors.brand.stroke);
42285
42846
  }
42286
- if (full && (artifact?.type === "audio" || artifact?.type === "video" && texture)) drawPlayBadge(parts.previewArt, frame, context);
42847
+ if (full && (artifact?.type === "audio" || artifact?.type === "video" && texture && !live)) drawPlayBadge(parts.previewArt, frame, context);
42287
42848
  if (surface) {
42288
42849
  const markY = frame.y + frame.height / 2 - (full && label ? 18 : 0);
42289
42850
  drawStateMark(parts.previewArt, surface, frame.x + frame.width / 2, markY, surface === "failed" ? color : context.colors.neutral.stroke);
@@ -42847,7 +43408,7 @@ function sync(container, item, context) {
42847
43408
  } : context.style);
42848
43409
  }
42849
43410
  parts.chrome.clear();
42850
- 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);
43411
+ if (boardCardDetailed(context.zoom) && !live && 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);
42851
43412
  }
42852
43413
  function drawFilmRails(graphics, width, height, rail, hole) {
42853
43414
  const size = Math.min(FILM_HOLE, rail * .45);
@@ -43200,6 +43761,7 @@ const itemEnvelope = {
43200
43761
  visible: boolean().optional().describe("false hides the item and its children; key it on a timeline to show the item only for a span."),
43201
43762
  style: BoardStyleSchema.default({}),
43202
43763
  locked: boolean().optional(),
43764
+ autoplay: boolean().optional().describe("true shows live content as the Board opens: an app runs, a video loops muted, a 3D model renders. Ignored for other items and for a video whose props.time follows a timeline."),
43203
43765
  metadata: record(string(), unknown()).optional()
43204
43766
  };
43205
43767
  const boxed = (size) => ({
@@ -43680,48 +44242,76 @@ function resolveScriptImport(from, specifier) {
43680
44242
  } else parts.push(part);
43681
44243
  }
43682
44244
  const path = parts.join("/");
43683
- if (!isSafeBoardSourcePath(path) || !/\.m?js$/.test(path)) throw new Error(`Invalid module path: ${path}`);
44245
+ if (!isSafeBoardSourcePath(path) || !/\.(m?js|json)$/.test(path)) throw new Error(`Invalid module path: ${path}`);
43684
44246
  return path;
43685
44247
  }
44248
+ function isBoardScriptJson(path) {
44249
+ return path.endsWith(".json");
44250
+ }
43686
44251
  async function loadBoardScriptSources(src, read, timeoutMs = 15e3) {
43687
44252
  if (!isSafeBoardSourcePath(src) || !/\.m?js$/.test(src)) throw new Error("Invalid script entry path.");
43688
44253
  const { init, parse } = await import("./board-kernel/lexer.js");
43689
44254
  await init;
43690
44255
  const sources = {};
43691
- const visiting = /* @__PURE__ */ new Set();
44256
+ const loading = /* @__PURE__ */ new Map();
44257
+ const edges = /* @__PURE__ */ new Map();
43692
44258
  let bytes = 0;
43693
- async function visit(path) {
43694
- if (visiting.has(path)) throw new Error(`Circular module dependency: ${path}`);
43695
- if (sources[path]) return;
43696
- if (Object.keys(sources).length + visiting.size >= 64) throw new Error("A script may load at most 64 modules.");
43697
- visiting.add(path);
43698
- let timer;
43699
- const code = await Promise.race([Promise.resolve().then(() => read(path)), new Promise((_resolve, reject) => {
43700
- timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`Module read timed out: ${path}`)), timeoutMs);
43701
- })]).finally(() => clearTimeout(timer));
43702
- bytes += new TextEncoder().encode(code).byteLength;
43703
- if (bytes > 2e6) throw new Error("Script modules exceed the 2 MB limit.");
43704
- const [imports] = parse(code, path);
43705
- const resolved = [];
43706
- for (const entry of imports) {
43707
- if (entry.d === -2) throw new Error("import.meta is not available in Board scripts.");
43708
- if (entry.n === void 0) throw new Error("Dynamic imports must use a literal relative path.");
43709
- const dependency = resolveScriptImport(path, entry.n);
43710
- await visit(dependency);
43711
- resolved.push({
43712
- start: entry.s,
43713
- end: entry.e,
43714
- path: dependency,
43715
- dynamic: entry.d >= 0
43716
- });
43717
- }
43718
- sources[path] = {
43719
- code,
43720
- imports: resolved
43721
- };
43722
- visiting.delete(path);
44259
+ function load(path) {
44260
+ let promise = loading.get(path);
44261
+ if (promise) return promise;
44262
+ if (loading.size >= 64) throw new Error("A script may load at most 64 modules.");
44263
+ promise = (async () => {
44264
+ let timer;
44265
+ const code = await Promise.race([Promise.resolve().then(() => read(path)), new Promise((_resolve, reject) => {
44266
+ timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`Module read timed out: ${path}`)), timeoutMs);
44267
+ })]).finally(() => clearTimeout(timer));
44268
+ bytes += new TextEncoder().encode(code).byteLength;
44269
+ if (bytes > 2e6) throw new Error("Script modules exceed the 2 MB limit.");
44270
+ if (isBoardScriptJson(path)) {
44271
+ try {
44272
+ JSON.parse(code);
44273
+ } catch {
44274
+ throw new Error(`${path} is not valid JSON.`);
44275
+ }
44276
+ sources[path] = {
44277
+ code,
44278
+ imports: []
44279
+ };
44280
+ return;
44281
+ }
44282
+ const [imports] = parse(code, path);
44283
+ const resolved = [];
44284
+ for (const entry of imports) {
44285
+ if (entry.d === -2) throw new Error("import.meta is not available in Board scripts.");
44286
+ if (entry.n === void 0) throw new Error("Dynamic imports must use a literal relative path.");
44287
+ const typed = entry.d >= 0 ? entry.a >= 0 && /\btype\s*:\s*["']json["']/.test(code.slice(entry.a, entry.se)) : Boolean(entry.at?.some(([key, value]) => key === "type" && value === "json"));
44288
+ if (typed !== isBoardScriptJson(entry.n)) throw new Error(typed ? `Only .json files import with type "json": ${entry.n}` : `Import ${entry.n} with { type: "json" }.`);
44289
+ resolved.push({
44290
+ start: entry.s,
44291
+ end: entry.e,
44292
+ path: resolveScriptImport(path, entry.n),
44293
+ dynamic: entry.d >= 0
44294
+ });
44295
+ }
44296
+ const dependencies = resolved.map((entry) => entry.path);
44297
+ edges.set(path, dependencies);
44298
+ if (dependencies.some((dependency) => importsReach(dependency, path))) throw new Error(`Circular module dependency: ${path}`);
44299
+ await Promise.all(dependencies.map(load));
44300
+ sources[path] = {
44301
+ code,
44302
+ imports: resolved
44303
+ };
44304
+ })();
44305
+ loading.set(path, promise);
44306
+ return promise;
44307
+ }
44308
+ function importsReach(from, target, seen = /* @__PURE__ */ new Set()) {
44309
+ if (from === target) return true;
44310
+ if (seen.has(from)) return false;
44311
+ seen.add(from);
44312
+ return (edges.get(from) ?? []).some((next) => importsReach(next, target, seen));
43723
44313
  }
43724
- await visit(src);
44314
+ await load(src);
43725
44315
  return sources;
43726
44316
  }
43727
44317
  //#endregion
@@ -43745,7 +44335,9 @@ function createScriptRuntime(module, initial, host) {
43745
44335
  let input = initial;
43746
44336
  let disposed = false;
43747
44337
  let stepping = false;
44338
+ let depth = 0;
43748
44339
  let revision = 0;
44340
+ let sceneRevision = 0;
43749
44341
  let randomState = 2166136261;
43750
44342
  for (const char of initial.script.seed ?? initial.id) randomState = Math.imul(randomState ^ char.charCodeAt(0), 16777619) >>> 0;
43751
44343
  const parameterDefaults = Object.fromEntries(Object.entries(module.parameters ?? {}).filter(([, spec]) => spec.default !== void 0).map(([key, spec]) => [key, spec.default]));
@@ -43780,9 +44372,11 @@ function createScriptRuntime(module, initial, host) {
43780
44372
  let view = null;
43781
44373
  let hits = effects?.hits ?? {};
43782
44374
  let uniforms = effects?.uniforms;
43783
- const invalidate = () => {
44375
+ let passes = effects?.passes;
44376
+ const invalidate = (scene = true) => {
43784
44377
  if (disposed) return;
43785
44378
  revision++;
44379
+ if (scene) sceneRevision++;
43786
44380
  host.invalidate();
43787
44381
  };
43788
44382
  const present = (id, patch) => {
@@ -43817,7 +44411,8 @@ function createScriptRuntime(module, initial, host) {
43817
44411
  await host.call("board.emit", {
43818
44412
  target,
43819
44413
  type,
43820
- data
44414
+ data,
44415
+ depth: depth + 1
43821
44416
  });
43822
44417
  },
43823
44418
  get items() {
@@ -43857,7 +44452,7 @@ function createScriptRuntime(module, initial, host) {
43857
44452
  };
43858
44453
  },
43859
44454
  onDispose: (handler) => cleanups.push(handler),
43860
- invalidate,
44455
+ invalidate: () => invalidate(),
43861
44456
  get: (id) => input.items[id],
43862
44457
  present,
43863
44458
  scene(next, options) {
@@ -43888,7 +44483,16 @@ function createScriptRuntime(module, initial, host) {
43888
44483
  ...uniforms,
43889
44484
  ...values
43890
44485
  };
43891
- invalidate();
44486
+ invalidate(false);
44487
+ },
44488
+ passes(next) {
44489
+ 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.");
44490
+ if (Object.entries(next).every(([name, on]) => passes?.[name] === on)) return;
44491
+ passes = {
44492
+ ...passes,
44493
+ ...next
44494
+ };
44495
+ invalidate(false);
43892
44496
  },
43893
44497
  async commit(patch) {
43894
44498
  return await host.call("board.commit", {
@@ -43904,7 +44508,16 @@ function createScriptRuntime(module, initial, host) {
43904
44508
  call: (name, value) => host.call(name, value)
43905
44509
  }
43906
44510
  };
43907
- const setup = module.default?.(context);
44511
+ const seeded = (run) => {
44512
+ const random = Math.random;
44513
+ Math.random = context.random;
44514
+ try {
44515
+ return run();
44516
+ } finally {
44517
+ Math.random = random;
44518
+ }
44519
+ };
44520
+ const setup = seeded(() => module.default?.(context));
43908
44521
  if (typeof setup === "function") cleanups.push(setup);
43909
44522
  return {
43910
44523
  get animated() {
@@ -43915,6 +44528,7 @@ function createScriptRuntime(module, initial, host) {
43915
44528
  for (const id of Object.keys(patches)) if (!next.items[id]) {
43916
44529
  delete patches[id];
43917
44530
  revision++;
44531
+ sceneRevision++;
43918
44532
  }
43919
44533
  params = {
43920
44534
  ...parameterDefaults,
@@ -43935,10 +44549,12 @@ function createScriptRuntime(module, initial, host) {
43935
44549
  };
43936
44550
  stepping = true;
43937
44551
  try {
43938
- for (const handler of frames) {
43939
- const result = handler(frame);
43940
- if (result && typeof result.then === "function") throw new Error("onFrame() handlers must be synchronous.");
43941
- }
44552
+ seeded(() => {
44553
+ for (const handler of frames) {
44554
+ const result = handler(frame);
44555
+ if (result && typeof result.then === "function") throw new Error("onFrame() handlers must be synchronous.");
44556
+ }
44557
+ });
43942
44558
  } finally {
43943
44559
  stepping = false;
43944
44560
  }
@@ -43966,11 +44582,19 @@ function createScriptRuntime(module, initial, host) {
43966
44582
  if (event.type === "viewchange") view = event.data;
43967
44583
  const listeners = handlers.get(event.type);
43968
44584
  if (!listeners?.size) return;
43969
- for (const handler of listeners) handler(event);
44585
+ const outer = depth;
44586
+ depth = event.depth ?? 0;
44587
+ try {
44588
+ seeded(() => {
44589
+ for (const handler of listeners) handler(event);
44590
+ });
44591
+ } finally {
44592
+ depth = outer;
44593
+ }
43970
44594
  invalidate();
43971
44595
  },
43972
44596
  draw(canvas) {
43973
- const result = module.draw?.(canvas, frame);
44597
+ const result = seeded(() => module.draw?.(canvas, frame));
43974
44598
  if (result && typeof result.then === "function") throw new Error("draw() must be synchronous.");
43975
44599
  },
43976
44600
  output() {
@@ -43983,13 +44607,15 @@ function createScriptRuntime(module, initial, host) {
43983
44607
  hits,
43984
44608
  shader: module.shader,
43985
44609
  uniforms,
44610
+ passes,
43986
44611
  listens: [...handlers].filter(([, callbacks]) => callbacks.size).map(([type]) => type),
43987
44612
  animated: this.animated,
43988
44613
  draws: typeof module.draw === "function",
43989
44614
  updating: frames.size > 0,
43990
44615
  frameRate: module.frameRate,
43991
44616
  pixelated: module.pixelated,
43992
- version: revision
44617
+ version: revision,
44618
+ sceneVersion: sceneRevision
43993
44619
  };
43994
44620
  },
43995
44621
  snapshot(includeEffects = true, clone = true) {
@@ -44003,7 +44629,8 @@ function createScriptRuntime(module, initial, host) {
44003
44629
  screen: layers.screen,
44004
44630
  anchor,
44005
44631
  hits,
44006
- uniforms
44632
+ uniforms,
44633
+ passes
44007
44634
  } : void 0
44008
44635
  };
44009
44636
  return clone ? structuredClone(snapshot) : snapshot;
@@ -44018,10 +44645,39 @@ function createScriptRuntime(module, initial, host) {
44018
44645
  layers.screen = {};
44019
44646
  hits = {};
44020
44647
  uniforms = void 0;
44648
+ passes = void 0;
44021
44649
  }
44022
44650
  };
44023
44651
  }
44024
44652
  //#endregion
44653
+ //#region ../sdk/src/board/model/script-calls.ts
44654
+ function layoutBoardScriptText(value) {
44655
+ const input = value;
44656
+ if (!input || typeof input.text !== "string" || input.text.length > 1e4) throw new Error("layoutText() needs text of at most 10000 characters.");
44657
+ for (const key of [
44658
+ "fontSize",
44659
+ "fontWeight",
44660
+ "lineHeight",
44661
+ "width"
44662
+ ]) if (input[key] !== void 0 && !(Number.isFinite(input[key]) && input[key] > 0)) throw new Error(`layoutText() ${key} must be a positive number.`);
44663
+ const { width, height } = layoutBoardText({
44664
+ fontSize: 24,
44665
+ fontWeight: 500,
44666
+ font: "sans",
44667
+ lineHeight: 4 / 3,
44668
+ ...input
44669
+ });
44670
+ return {
44671
+ width,
44672
+ height
44673
+ };
44674
+ }
44675
+ const BOARD_SCRIPT_EXPORT_CALLS = {
44676
+ "board.emit": () => void 0,
44677
+ "board.commit": () => false,
44678
+ "board.layoutText": layoutBoardScriptText
44679
+ };
44680
+ //#endregion
44025
44681
  //#region ../sdk/src/board/render/shader/library.ts
44026
44682
  const BOARD_SHADER_LIBRARY = {
44027
44683
  hash: `
@@ -44330,7 +44986,7 @@ function describeBoardShaderError(log, firstLine, label) {
44330
44986
  function boardShaderStages(shader, label) {
44331
44987
  const stages = shader.passes.flatMap((pass, index) => {
44332
44988
  const name = `${label} pass ${index + 1}`;
44333
- if (shader.layer === "filter") return [{
44989
+ if (boardShaderPassLayer(shader, pass) === "filter") return [{
44334
44990
  name,
44335
44991
  kind: "filter",
44336
44992
  glsl: pass.glsl
@@ -44376,6 +45032,100 @@ function checkBoardShader(shader, parameters, label) {
44376
45032
  }
44377
45033
  }
44378
45034
  //#endregion
45035
+ //#region ../sdk/src/board/render/shader/compile.ts
45036
+ const READY = {
45037
+ poll: () => true,
45038
+ cancel() {}
45039
+ };
45040
+ const COMPLETION_STATUS = 37297;
45041
+ const failures = /* @__PURE__ */ new Map();
45042
+ const parallel = /* @__PURE__ */ new WeakMap();
45043
+ function programs(renderer) {
45044
+ return renderer.shader._programDataHash ?? null;
45045
+ }
45046
+ function adopt(gl, glProgram, program, cache) {
45047
+ glProgram._attributeData = extractAttributesFromGlProgram(program, gl, false);
45048
+ glProgram._uniformData = getUniformData(program, gl);
45049
+ glProgram._uniformBlockData = getUboData(program, gl);
45050
+ const uniforms = {};
45051
+ for (const [name, data] of Object.entries(glProgram._uniformData)) uniforms[name] = {
45052
+ location: gl.getUniformLocation(program, name),
45053
+ value: defaultValue(data.type, data.size)
45054
+ };
45055
+ cache[glProgram._key] = new GlProgramData(program, uniforms);
45056
+ }
45057
+ function lineShift(raw, final) {
45058
+ return final.split("\n").length - raw.split("\n").length;
45059
+ }
45060
+ function compileBoardProgram(renderer, glProgram, source, label, wait) {
45061
+ if (renderer.type !== RendererType.WEBGL) return READY;
45062
+ const failure = failures.get(glProgram._key);
45063
+ if (failure) throw new Error(failure);
45064
+ const cache = programs(renderer);
45065
+ if (cache?.[glProgram._key]) return READY;
45066
+ const gl = renderer.gl;
45067
+ if (!parallel.has(gl)) parallel.set(gl, Boolean(gl.getExtension("KHR_parallel_shader_compile")));
45068
+ const job = {
45069
+ gl,
45070
+ program: gl.createProgram(),
45071
+ shaders: [gl.createShader(gl.VERTEX_SHADER), gl.createShader(gl.FRAGMENT_SHADER)]
45072
+ };
45073
+ const vertex = glProgram.vertex;
45074
+ const fragment = glProgram.fragment;
45075
+ const stages = [{
45076
+ shader: job.shaders[0],
45077
+ code: vertex,
45078
+ first: source.firstLine.vertex + lineShift(source.vertex, vertex),
45079
+ name: "vertex"
45080
+ }, {
45081
+ shader: job.shaders[1],
45082
+ code: fragment,
45083
+ first: source.firstLine.fragment + lineShift(source.fragment, fragment),
45084
+ name: "fragment"
45085
+ }];
45086
+ for (const { shader, code } of stages) {
45087
+ gl.shaderSource(shader, code);
45088
+ gl.compileShader(shader);
45089
+ gl.attachShader(job.program, shader);
45090
+ }
45091
+ gl.linkProgram(job.program);
45092
+ let done = false;
45093
+ const finish = () => {
45094
+ done = true;
45095
+ let error = null;
45096
+ if (!gl.getProgramParameter(job.program, gl.LINK_STATUS) && !gl.isContextLost()) {
45097
+ for (const { shader, first, name } of stages) if (!error && !gl.getShaderParameter(shader, gl.COMPILE_STATUS)) error = describeBoardShaderError(gl.getShaderInfoLog(shader) ?? "", first, `${label} (${name})`);
45098
+ error ??= `${label}: ${gl.getProgramInfoLog(job.program) ?? "the shader failed to link"}`;
45099
+ }
45100
+ for (const shader of job.shaders) gl.deleteShader(shader);
45101
+ if (error || !cache || gl.isContextLost()) {
45102
+ gl.deleteProgram(job.program);
45103
+ if (error) {
45104
+ if (failures.size > 256) failures.clear();
45105
+ failures.set(glProgram._key, error);
45106
+ throw new Error(error);
45107
+ }
45108
+ return true;
45109
+ }
45110
+ if (cache[glProgram._key]) gl.deleteProgram(job.program);
45111
+ else adopt(gl, glProgram, job.program, cache);
45112
+ return true;
45113
+ };
45114
+ if (wait || !parallel.get(gl)) {
45115
+ finish();
45116
+ return READY;
45117
+ }
45118
+ return {
45119
+ poll: () => done || (gl.getProgramParameter(job.program, COMPLETION_STATUS) === true ? finish() : false),
45120
+ cancel() {
45121
+ if (done) return;
45122
+ done = true;
45123
+ for (const shader of job.shaders) gl.deleteShader(shader);
45124
+ gl.deleteProgram(job.program);
45125
+ }
45126
+ };
45127
+ }
45128
+ //#endregion
44379
45129
  //#region ../sdk/src/board/render/shader/quad.ts
44380
45130
  function boardQuadGeometry(instanceCount = 1) {
44381
45131
  return new Geometry({
@@ -44403,14 +45153,18 @@ function boardQuadGeometry(instanceCount = 1) {
44403
45153
  instanceCount
44404
45154
  });
44405
45155
  }
45156
+ function boardGlProgram(name, source) {
45157
+ return GlProgram.from({
45158
+ name,
45159
+ vertex: source.vertex,
45160
+ fragment: source.fragment,
45161
+ preferredFragmentPrecision: "highp"
45162
+ });
45163
+ }
44406
45164
  function boardShaderMesh(name, source, resources, geometry = boardQuadGeometry()) {
45165
+ const glProgram = source instanceof GlProgram ? source : boardGlProgram(name, source);
44407
45166
  const shader = new Shader({
44408
- glProgram: GlProgram.from({
44409
- name,
44410
- vertex: source.vertex,
44411
- fragment: source.fragment,
44412
- preferredFragmentPrecision: "highp"
44413
- }),
45167
+ glProgram,
44414
45168
  resources
44415
45169
  });
44416
45170
  return {
@@ -44453,6 +45207,8 @@ const STEP_MS = 1e3 / 60;
44453
45207
  const STEPS_PER_FRAME = 8;
44454
45208
  const MAX_LAG = 60;
44455
45209
  const MAX_REPLAY = 36e3;
45210
+ const CHECKPOINT_STEPS = 600;
45211
+ const CHECKPOINTS = 6;
44456
45212
  const PIXI_TYPES = {
44457
45213
  float: "f32",
44458
45214
  int: "i32",
@@ -44467,46 +45223,6 @@ const SIZES = {
44467
45223
  vec3: 3,
44468
45224
  vec4: 4
44469
45225
  };
44470
- const compiled = /* @__PURE__ */ new Map();
44471
- function check(renderer, program, label) {
44472
- if (renderer.type !== RendererType.WEBGL) return;
44473
- const key = `${program.vertex}\u0000${program.fragment}`;
44474
- let error = compiled.get(key);
44475
- if (error === void 0) {
44476
- const gl = renderer.gl;
44477
- error = null;
44478
- const shaders = [];
44479
- const glProgram = gl.createProgram();
44480
- for (const [stage, type, source, first] of [[
44481
- "vertex",
44482
- gl.VERTEX_SHADER,
44483
- program.vertex,
44484
- program.firstLine.vertex
44485
- ], [
44486
- "fragment",
44487
- gl.FRAGMENT_SHADER,
44488
- program.fragment,
44489
- program.firstLine.fragment
44490
- ]]) {
44491
- const shader = gl.createShader(type);
44492
- if (!shader) continue;
44493
- gl.shaderSource(shader, source);
44494
- gl.compileShader(shader);
44495
- shaders.push(shader);
44496
- if (!error && !gl.getShaderParameter(shader, gl.COMPILE_STATUS) && !gl.isContextLost()) error = describeBoardShaderError(gl.getShaderInfoLog(shader) ?? "", first, `${label} (${stage})`);
44497
- gl.attachShader(glProgram, shader);
44498
- }
44499
- if (!error) {
44500
- gl.linkProgram(glProgram);
44501
- if (!gl.getProgramParameter(glProgram, gl.LINK_STATUS) && !gl.isContextLost()) error = `${label}: ${gl.getProgramInfoLog(glProgram) ?? "the shader failed to link"}`;
44502
- }
44503
- for (const shader of shaders) gl.deleteShader(shader);
44504
- gl.deleteProgram(glProgram);
44505
- if (compiled.size > 256) compiled.clear();
44506
- compiled.set(key, error);
44507
- }
44508
- if (error) throw new Error(error);
44509
- }
44510
45226
  const placing = /* @__PURE__ */ new WeakMap();
44511
45227
  function canPlaceSprites(renderer) {
44512
45228
  let supported = placing.get(renderer);
@@ -44682,8 +45398,99 @@ function seedOf(value) {
44682
45398
  function boardShaderSeed(seed) {
44683
45399
  return seedOf(seed);
44684
45400
  }
44685
- function createBoardShaderLayer(renderer, shader, parameters, label) {
44686
- const layer = shader.layer ?? "above";
45401
+ const TEXEL_GROWTH = 128;
45402
+ function createTexels(drawn, pass) {
45403
+ const root = new Container();
45404
+ root.addChild(new Mesh({
45405
+ geometry: drawn.geometry,
45406
+ shader: drawn.shader
45407
+ }));
45408
+ const sprite = new Sprite({
45409
+ texture: Texture.EMPTY,
45410
+ label: "board-shader-texels"
45411
+ });
45412
+ sprite.blendMode = pass.blend ?? "normal";
45413
+ sprite.visible = false;
45414
+ return {
45415
+ size: pass.texel ?? 1,
45416
+ root,
45417
+ sprite,
45418
+ target: null,
45419
+ rect: null
45420
+ };
45421
+ }
45422
+ function texelRect(frame, size) {
45423
+ const [a, b] = frame.localToGlobal;
45424
+ if (Math.hypot(a, b) * frame.density * Math.min(1, frame.shading ?? 1) * size <= 1) return null;
45425
+ const { region, view } = frame;
45426
+ const left = Math.floor(Math.max(region.x, view.x) / size) * size;
45427
+ const top = Math.floor(Math.max(region.y, view.y) / size) * size;
45428
+ const right = Math.ceil(Math.min(region.x + region.width, view.x + view.width) / size) * size;
45429
+ const bottom = Math.ceil(Math.min(region.y + region.height, view.y + view.height) / size) * size;
45430
+ return right > left && bottom > top ? {
45431
+ x: left,
45432
+ y: top,
45433
+ width: right - left,
45434
+ height: bottom - top
45435
+ } : null;
45436
+ }
45437
+ function drawTexels(renderer, texels, rect) {
45438
+ const width = Math.round(rect.width / texels.size);
45439
+ const height = Math.round(rect.height / texels.size);
45440
+ let target = texels.target;
45441
+ if (!target || target.width < width || target.height < height) {
45442
+ releaseTexels(texels);
45443
+ const grow = (edge) => Math.ceil(edge / TEXEL_GROWTH) * TEXEL_GROWTH;
45444
+ target = RenderTexture.create({
45445
+ width: grow(width),
45446
+ height: grow(height),
45447
+ resolution: 1,
45448
+ scaleMode: "nearest",
45449
+ antialias: false,
45450
+ autoGenerateMipmaps: false
45451
+ });
45452
+ texels.target = target;
45453
+ texels.sprite.texture = new Texture({
45454
+ source: target.source,
45455
+ frame: new Rectangle(0, 0, width, height),
45456
+ dynamic: true
45457
+ });
45458
+ }
45459
+ const texture = texels.sprite.texture;
45460
+ if (texture.frame.width !== width || texture.frame.height !== height) {
45461
+ texture.frame.width = width;
45462
+ texture.frame.height = height;
45463
+ texture.update();
45464
+ }
45465
+ texels.root.scale.set(1 / texels.size);
45466
+ texels.root.position.set(-rect.x / texels.size, -rect.y / texels.size);
45467
+ renderer.render({
45468
+ container: texels.root,
45469
+ target,
45470
+ clear: true,
45471
+ clearColor: [
45472
+ 0,
45473
+ 0,
45474
+ 0,
45475
+ 0
45476
+ ]
45477
+ });
45478
+ texels.sprite.position.set(rect.x, rect.y);
45479
+ texels.sprite.scale.set(texels.size);
45480
+ }
45481
+ function releaseTexels(texels) {
45482
+ if (!texels.target) return;
45483
+ texels.sprite.texture.destroy();
45484
+ texels.sprite.texture = Texture.EMPTY;
45485
+ texels.target.destroy(true);
45486
+ texels.target = null;
45487
+ }
45488
+ function destroyTexels(texels) {
45489
+ releaseTexels(texels);
45490
+ texels.sprite.destroy();
45491
+ texels.root.destroy({ children: true });
45492
+ }
45493
+ function createBoardShaderLayer(renderer, shader, parameters, label, options = {}) {
44687
45494
  const uniforms = boardShaderUniforms(shader.uniforms);
44688
45495
  const surfaces = shader.surfaces === true;
44689
45496
  const hasState = shader.state !== void 0;
@@ -44693,19 +45500,21 @@ function createBoardShaderLayer(renderer, shader, parameters, label) {
44693
45500
  surfaces,
44694
45501
  state: hasState
44695
45502
  };
45503
+ const compiles = [];
44696
45504
  const program = (kind, glsl, name) => {
44697
- let built;
44698
45505
  try {
44699
- built = buildBoardShaderProgram({
45506
+ const built = buildBoardShaderProgram({
44700
45507
  ...base,
44701
45508
  kind,
44702
45509
  glsl
44703
45510
  });
45511
+ const glProgram = boardGlProgram(`board-shader-${kind}`, built);
45512
+ compiles.push(compileBoardProgram(renderer, glProgram, built, name, options.wait === true));
45513
+ return glProgram;
44704
45514
  } catch (error) {
44705
- throw new Error(`${name}: ${error instanceof Error ? error.message : String(error)}`);
45515
+ const message = error instanceof Error ? error.message : String(error);
45516
+ throw new Error(message.startsWith(name) ? message : `${name}: ${message}`);
44706
45517
  }
44707
- check(renderer, built, name);
44708
- return built;
44709
45518
  };
44710
45519
  const group = boardUniforms(parameters, uniforms);
44711
45520
  const textures = {};
@@ -44713,20 +45522,19 @@ function createBoardShaderLayer(renderer, shader, parameters, label) {
44713
45522
  if (hasState) textures.uCohubState = Texture.EMPTY.source;
44714
45523
  const meshes = [];
44715
45524
  const filters = [];
44716
- const container = layer === "filter" ? null : new Container({ label: `board-shader-${label}` });
45525
+ const containers = {
45526
+ below: null,
45527
+ above: null
45528
+ };
45529
+ const area = new Rectangle();
44717
45530
  const place = canPlaceSprites(renderer);
44718
45531
  let placementsStale = true;
44719
45532
  shader.passes.forEach((pass, index) => {
44720
45533
  const name = `${label} pass ${index + 1}`;
45534
+ const layer = boardShaderPassLayer(shader, pass);
44721
45535
  if (layer === "filter") {
44722
- const built = program("filter", pass.glsl, name);
44723
45536
  const filter = new Filter({
44724
- glProgram: GlProgram.from({
44725
- name: `board-shader-filter`,
44726
- vertex: built.vertex,
44727
- fragment: built.fragment,
44728
- preferredFragmentPrecision: "highp"
44729
- }),
45537
+ glProgram: program("filter", pass.glsl, name),
44730
45538
  resources: {
44731
45539
  cohubUniforms: group,
44732
45540
  ...textures
@@ -44734,7 +45542,10 @@ function createBoardShaderLayer(renderer, shader, parameters, label) {
44734
45542
  padding: 0,
44735
45543
  resolution: "inherit"
44736
45544
  });
44737
- filters.push(filter);
45545
+ filters.push({
45546
+ filter,
45547
+ pass
45548
+ });
44738
45549
  return;
44739
45550
  }
44740
45551
  const sprites = pass.sprites ?? 0;
@@ -44756,11 +45567,19 @@ function createBoardShaderLayer(renderer, shader, parameters, label) {
44756
45567
  });
44757
45568
  const drawn = boardShaderMesh("board-shader", program(kind, pass.glsl, name), resources, boardQuadGeometry(Math.max(1, sprites)));
44758
45569
  drawn.mesh.blendMode = pass.blend ?? "normal";
44759
- container?.addChild(drawn.mesh);
45570
+ containers[layer] ??= new Container({ label: `board-shader-${label}-${layer}` });
45571
+ const container = containers[layer];
45572
+ container.boundsArea = area;
45573
+ container.addChild(drawn.mesh);
45574
+ const texels = pass.texel ? createTexels(drawn, pass) : null;
45575
+ if (texels) container.addChild(texels.sprite);
44760
45576
  meshes.push({
44761
45577
  ...drawn,
45578
+ pass,
44762
45579
  sprites,
44763
- placement
45580
+ placement,
45581
+ scaler: null,
45582
+ texels
44764
45583
  });
44765
45584
  });
44766
45585
  let state = null;
@@ -44783,6 +45602,7 @@ function createBoardShaderLayer(renderer, shader, parameters, label) {
44783
45602
  const blank = new Container();
44784
45603
  let time = 0;
44785
45604
  let quality = 1;
45605
+ let compiled = compiles.length === 0;
44786
45606
  let last = null;
44787
45607
  const stateRegion = (frame) => shader.state?.bounds ?? frame.region;
44788
45608
  function fill(target, frame, geometry, step) {
@@ -44842,9 +45662,41 @@ function createBoardShaderLayer(renderer, shader, parameters, label) {
44842
45662
  }
44843
45663
  target.update();
44844
45664
  }
45665
+ const checkpoints = [];
45666
+ let surfaceKey = "";
45667
+ const copier = new Sprite();
45668
+ copier.blendMode = "none";
45669
+ const copy = (target, from, to) => {
45670
+ copier.texture = from;
45671
+ target.render({
45672
+ container: copier,
45673
+ target: to,
45674
+ clear: true,
45675
+ clearColor: [
45676
+ 0,
45677
+ 0,
45678
+ 0,
45679
+ 0
45680
+ ]
45681
+ });
45682
+ };
45683
+ const inputs = ({ time: _time, ...frame }) => JSON.stringify([frame, surfaceKey]);
45684
+ function checkpoint(target, state, key) {
45685
+ if (checkpoints.some((entry) => entry.steps === state.steps && entry.key === key)) return;
45686
+ const texture = (checkpoints.length >= CHECKPOINTS ? checkpoints.shift() : void 0)?.texture ?? boardRenderTarget(state.read.width, state.read.height, state.read.source.format);
45687
+ copy(target, state.read, texture);
45688
+ checkpoints.push({
45689
+ steps: state.steps,
45690
+ key,
45691
+ texture
45692
+ });
45693
+ }
44845
45694
  function advance(target, state, frame, catchUp) {
44846
45695
  const wanted = Math.floor(frame.time / STEP_MS);
45696
+ const key = catchUp ? inputs(frame) : "";
45697
+ let replaying = false;
44847
45698
  if (wanted < state.steps || state.steps < 0) {
45699
+ replaying = catchUp;
44848
45700
  for (const texture of [state.read, state.write]) target.render({
44849
45701
  container: blank,
44850
45702
  target: texture,
@@ -44857,6 +45709,11 @@ function createBoardShaderLayer(renderer, shader, parameters, label) {
44857
45709
  ]
44858
45710
  });
44859
45711
  state.steps = Math.max(0, wanted - MAX_REPLAY);
45712
+ const resume = catchUp ? checkpoints.reduce((best, entry) => entry.key === key && entry.steps <= wanted && entry.steps > (best?.steps ?? state.steps - 1) ? entry : best, null) : null;
45713
+ if (resume) {
45714
+ copy(target, resume.texture, state.read);
45715
+ state.steps = resume.steps;
45716
+ }
44860
45717
  }
44861
45718
  if (!catchUp && wanted - state.steps > MAX_LAG) state.steps = wanted - STEPS_PER_FRAME;
44862
45719
  const limit = catchUp ? Number.POSITIVE_INFINITY : STEPS_PER_FRAME;
@@ -44877,29 +45734,72 @@ function createBoardShaderLayer(renderer, shader, parameters, label) {
44877
45734
  [state.read, state.write] = [state.write, state.read];
44878
45735
  state.steps++;
44879
45736
  ran++;
45737
+ if (replaying && state.steps % CHECKPOINT_STEPS === 0) checkpoint(target, state, key);
44880
45738
  }
44881
45739
  const source = state.read.source;
44882
45740
  for (const { shader, placement } of meshes) {
44883
45741
  shader.resources.uCohubState = source;
44884
45742
  if (placement) placement.mesh.shader.resources.uCohubState = source;
44885
45743
  }
44886
- for (const filter of filters) filter.resources.uCohubState = source;
45744
+ for (const { filter } of filters) filter.resources.uCohubState = source;
44887
45745
  return {
44888
45746
  ran,
44889
45747
  behind: state.steps < wanted
44890
45748
  };
44891
45749
  }
45750
+ function shade(drawn, frame) {
45751
+ const resolution = frame.density * Math.min(1, frame.shading ?? 1);
45752
+ const blend = drawn.pass.blend ?? "normal";
45753
+ if (resolution >= frame.density * .99) {
45754
+ if (!drawn.scaler) return;
45755
+ drawn.mesh.filters = null;
45756
+ drawn.mesh.filterArea = null;
45757
+ drawn.mesh.blendMode = blend;
45758
+ drawn.scaler.destroy();
45759
+ drawn.scaler = null;
45760
+ return;
45761
+ }
45762
+ if (!drawn.scaler) {
45763
+ drawn.scaler = new AlphaFilter({
45764
+ alpha: 1,
45765
+ blendMode: blend
45766
+ });
45767
+ drawn.mesh.blendMode = "normal";
45768
+ drawn.mesh.filters = [drawn.scaler];
45769
+ drawn.mesh.filterArea = area;
45770
+ }
45771
+ drawn.scaler.resolution = resolution;
45772
+ }
44892
45773
  return {
44893
- layer,
44894
- container,
44895
- filters: layer === "filter" ? filters : null,
45774
+ below: containers.below,
45775
+ above: containers.above,
45776
+ filters: filters.length ? filters.map(({ filter }) => filter) : null,
44896
45777
  surfaces,
44897
45778
  animated: hasState,
45779
+ ready() {
45780
+ if (!compiled) compiled = compiles.every((compile) => compile.poll());
45781
+ return compiled;
45782
+ },
44898
45783
  update(frame) {
44899
45784
  if (frame.quality !== quality) {
44900
45785
  quality = frame.quality;
44901
45786
  for (const { geometry, sprites } of meshes) if (sprites) geometry.instanceCount = Math.max(1, Math.round(sprites * quality));
44902
45787
  }
45788
+ area.x = frame.region.x;
45789
+ area.y = frame.region.y;
45790
+ area.width = frame.region.width;
45791
+ area.height = frame.region.height;
45792
+ for (const drawn of meshes) {
45793
+ const on = boardShaderPassOn(drawn.pass, frame.passes);
45794
+ const texels = drawn.texels;
45795
+ if (texels) {
45796
+ texels.rect = on ? texelRect(frame, texels.size) : null;
45797
+ texels.sprite.visible = texels.rect !== null;
45798
+ }
45799
+ drawn.mesh.visible = on && !texels?.rect;
45800
+ if (drawn.mesh.visible && !drawn.sprites) shade(drawn, frame);
45801
+ }
45802
+ for (const { filter, pass } of filters) filter.enabled = boardShaderPassOn(pass, frame.passes);
44903
45803
  fill(group, frame, frame.region);
44904
45804
  for (const { geometry, placement } of meshes) {
44905
45805
  if (!placement) continue;
@@ -44921,8 +45821,9 @@ function createBoardShaderLayer(renderer, shader, parameters, label) {
44921
45821
  ran: 0,
44922
45822
  behind: false
44923
45823
  };
45824
+ for (const { texels } of meshes) if (texels?.rect) drawTexels(target, texels, texels.rect);
44924
45825
  if (placementsStale || stepped.ran) {
44925
- for (const { placement } of meshes) if (placement) target.render({
45826
+ for (const { placement, mesh } of meshes) if (placement && mesh.visible) target.render({
44926
45827
  container: placement.mesh.mesh,
44927
45828
  target: placement.target,
44928
45829
  clear: true,
@@ -44937,8 +45838,12 @@ function createBoardShaderLayer(renderer, shader, parameters, label) {
44937
45838
  }
44938
45839
  return stepped.behind;
44939
45840
  },
44940
- setSurfaces(texture, region) {
44941
- const shaders = [...meshes.flatMap(({ shader, placement }) => placement ? [shader, placement.mesh.shader] : [shader]), ...filters];
45841
+ rewind() {
45842
+ if (state) state.steps = -1;
45843
+ },
45844
+ setSurfaces(texture, region, key = "") {
45845
+ surfaceKey = key;
45846
+ const shaders = [...meshes.flatMap(({ shader, placement }) => placement ? [shader, placement.mesh.shader] : [shader]), ...filters.map(({ filter }) => filter)];
44942
45847
  if (state) shaders.push(state.simulate.shader);
44943
45848
  for (const target of shaders) target.resources.uCohubSurfaces = texture.source;
44944
45849
  const groups = [group, ...meshes.flatMap(({ placement }) => placement ? [placement.uniforms] : [])];
@@ -44955,18 +45860,24 @@ function createBoardShaderLayer(renderer, shader, parameters, label) {
44955
45860
  placementsStale = true;
44956
45861
  },
44957
45862
  destroy() {
45863
+ for (const compile of compiles) compile.cancel();
44958
45864
  for (const drawn of meshes) {
45865
+ drawn.scaler?.destroy();
45866
+ if (drawn.texels) destroyTexels(drawn.texels);
44959
45867
  destroyBoardShaderMesh(drawn);
44960
45868
  if (drawn.placement) destroyPlacement(renderer, drawn.placement);
44961
45869
  }
44962
- container?.destroy();
44963
- for (const filter of filters) filter.destroy();
45870
+ containers.below?.destroy();
45871
+ containers.above?.destroy();
45872
+ for (const { filter } of filters) filter.destroy();
44964
45873
  blank.destroy();
44965
45874
  if (state) {
44966
45875
  destroyBoardShaderMesh(state.simulate);
44967
45876
  state.read.destroy(true);
44968
45877
  state.write.destroy(true);
44969
45878
  }
45879
+ for (const { texture } of checkpoints) texture.destroy(true);
45880
+ copier.destroy();
44970
45881
  }
44971
45882
  };
44972
45883
  }
@@ -45199,6 +46110,15 @@ const LIGHT_BLENDS = /* @__PURE__ */ new Set(["screen", "add"]);
45199
46110
  const SURFACE_EDGE = 512;
45200
46111
  const SURFACE_MARGIN = .25;
45201
46112
  const SURFACE_COARSEN = 1.5;
46113
+ const SURFACE_INTERVAL_MS = 1e3 / 30;
46114
+ function grow(rect, margin) {
46115
+ return {
46116
+ x: rect.x - rect.width * margin,
46117
+ y: rect.y - rect.height * margin,
46118
+ width: rect.width * (1 + 2 * margin),
46119
+ height: rect.height * (1 + 2 * margin)
46120
+ };
46121
+ }
45202
46122
  function surfaceOutline(item) {
45203
46123
  const { width, height } = item.frame;
45204
46124
  const radius = item.style?.radius;
@@ -45225,15 +46145,10 @@ function boardSurfaceOutlines(scene, owner, world, worldToLocal, candidates) {
45225
46145
  }
45226
46146
  return outlines;
45227
46147
  }
45228
- function boardSurfaceRegion(previous, region, margin) {
45229
- if (!margin) return region;
45230
- if (previous && previous.x <= region.x && previous.y <= region.y && previous.x + previous.width >= region.x + region.width && previous.y + previous.height >= region.y + region.height && previous.width <= region.width * (1 + 2 * margin) * SURFACE_COARSEN) return previous;
45231
- return {
45232
- x: region.x - region.width * margin,
45233
- y: region.y - region.height * margin,
45234
- width: region.width * (1 + 2 * margin),
45235
- height: region.height * (1 + 2 * margin)
45236
- };
46148
+ function boardSurfaceRegion(previous, needed, margin) {
46149
+ const grown = grow(needed, margin);
46150
+ 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;
46151
+ return grown;
45237
46152
  }
45238
46153
  function parameterValues(parameters, params, color) {
45239
46154
  const values = {};
@@ -45245,18 +46160,26 @@ function parameterValues(parameters, params, color) {
45245
46160
  }
45246
46161
  return values;
45247
46162
  }
45248
- function sameOutlines(a, b) {
46163
+ function sameOutlines(a, b, tolerance) {
45249
46164
  if (a.length !== b.length) return false;
45250
46165
  for (let index = 0; index < a.length; index++) {
45251
46166
  const left = a[index];
45252
46167
  const right = b[index];
45253
46168
  if (left.length !== right.length) return false;
45254
- for (let point = 0; point < left.length; point++) if (Math.abs(left[point] - right[point]) > .001) return false;
46169
+ for (let point = 0; point < left.length; point++) if (Math.abs(left[point] - right[point]) > tolerance) return false;
45255
46170
  }
45256
46171
  return true;
45257
46172
  }
45258
- function createBoardShaderLayers() {
46173
+ function outlineHash(outlines) {
46174
+ let hash = 2166136261;
46175
+ for (const outline of outlines) for (const value of outline) hash = Math.imul(hash ^ Math.round(value * 8), 16777619) >>> 0;
46176
+ return `${outlines.length}.${hash.toString(36)}`;
46177
+ }
46178
+ function createBoardShaderLayers(options = {}) {
46179
+ const now = options.now ?? (() => performance.now());
46180
+ const interval = options.wait ? 0 : SURFACE_INTERVAL_MS;
45259
46181
  const entries = /* @__PURE__ */ new Map();
46182
+ const compiling = /* @__PURE__ */ new Map();
45260
46183
  const failed = /* @__PURE__ */ new Map();
45261
46184
  let animated = false;
45262
46185
  let pending = false;
@@ -45268,13 +46191,71 @@ function createBoardShaderLayers() {
45268
46191
  entry.layer.destroy();
45269
46192
  entry.surfaces?.destroy();
45270
46193
  }
46194
+ function dropCompiling(id) {
46195
+ compiling.get(id)?.layer.destroy();
46196
+ compiling.delete(id);
46197
+ }
46198
+ function surfaceField(entry, renderer, owner, placement, host, scene, candidates) {
46199
+ const { localToWorld } = placement;
46200
+ const region = owner.root ? boardSurfaceRegion(entry.surfaces?.region ?? null, placement.region, SURFACE_MARGIN) : placement.region;
46201
+ const corners = [
46202
+ applyMatrix$1(localToWorld, region),
46203
+ applyMatrix$1(localToWorld, {
46204
+ x: region.x + region.width,
46205
+ y: region.y + region.height
46206
+ }),
46207
+ applyMatrix$1(localToWorld, {
46208
+ x: region.x + region.width,
46209
+ y: region.y
46210
+ }),
46211
+ applyMatrix$1(localToWorld, {
46212
+ x: region.x,
46213
+ y: region.y + region.height
46214
+ })
46215
+ ];
46216
+ const xs = corners.map((point) => point.x);
46217
+ const ys = corners.map((point) => point.y);
46218
+ const world = {
46219
+ x: Math.min(...xs),
46220
+ y: Math.min(...ys),
46221
+ width: Math.max(...xs) - Math.min(...xs),
46222
+ height: Math.max(...ys) - Math.min(...ys)
46223
+ };
46224
+ const edge = Math.max(64, Math.round(SURFACE_EDGE * (owner.root ? 1.5 : 1) * host.quality));
46225
+ const key = `${[
46226
+ region.x,
46227
+ region.y,
46228
+ region.width,
46229
+ region.height,
46230
+ ...localToWorld
46231
+ ].map((n) => n.toFixed(3)).join(",")}|${edge}`;
46232
+ entry.surfaces ??= createBoardSurfaceField();
46233
+ const moved = key !== entry.surfaceKey;
46234
+ const at = now();
46235
+ if (moved || entry.surfaceScene !== scene && at - entry.surfaceAt >= interval) {
46236
+ entry.surfaceScene = scene;
46237
+ const outlines = boardSurfaceOutlines(scene, owner.id, world, invertMatrix(localToWorld), candidates?.(world));
46238
+ if (moved || !sameOutlines(outlines, entry.outlines, region.width / edge / 2)) {
46239
+ entry.surfaces.build(renderer, region, outlines, edge);
46240
+ entry.outlines = outlines;
46241
+ entry.surfaceAt = at;
46242
+ entry.surfaceSignature = `${key}|${outlineHash(outlines)}`;
46243
+ }
46244
+ entry.surfaceKey = key;
46245
+ } else if (entry.surfaceScene !== scene) pending = true;
46246
+ entry.layer.setSurfaces(entry.surfaces.texture, entry.surfaces.region, entry.surfaceSignature);
46247
+ }
45271
46248
  return {
45272
46249
  get animated() {
45273
46250
  return animated || pending;
45274
46251
  },
45275
46252
  get size() {
45276
- return entries.size;
46253
+ return entries.size + compiling.size;
46254
+ },
46255
+ get compiling() {
46256
+ return compiling.size > 0;
45277
46257
  },
46258
+ layer: (id) => entries.get(id)?.layer ?? null,
45278
46259
  sync(renderer, owners, host, scene, candidates) {
45279
46260
  const alive = /* @__PURE__ */ new Set();
45280
46261
  animated = false;
@@ -45285,31 +46266,44 @@ function createBoardShaderLayers() {
45285
46266
  if (!shader || !signature || failed.get(owner.id) === signature) continue;
45286
46267
  alive.add(owner.id);
45287
46268
  let entry = entries.get(owner.id);
45288
- if (entry && entry.signature !== signature) {
45289
- drop(owner.id, host);
45290
- entry = void 0;
45291
- }
45292
46269
  try {
45293
- if (!entry) {
45294
- entry = {
45295
- owner,
45296
- output,
45297
- signature,
45298
- layer: createBoardShaderLayer(renderer, shader, boardShaderParameters(output.parameters), owner.id),
45299
- surfaces: null,
45300
- surfaceKey: "",
45301
- surfaceScene: null,
45302
- outlines: [],
45303
- placed: false
45304
- };
45305
- entries.set(owner.id, entry);
46270
+ if (entry?.signature !== signature) {
46271
+ let next = compiling.get(owner.id);
46272
+ if (next?.signature !== signature) {
46273
+ dropCompiling(owner.id);
46274
+ next = {
46275
+ signature,
46276
+ layer: createBoardShaderLayer(renderer, shader, boardShaderParameters(output.parameters), owner.id, { wait: options.wait })
46277
+ };
46278
+ compiling.set(owner.id, next);
46279
+ }
46280
+ if (next.layer.ready()) {
46281
+ compiling.delete(owner.id);
46282
+ drop(owner.id, host);
46283
+ entry = {
46284
+ owner,
46285
+ output,
46286
+ signature,
46287
+ layer: next.layer,
46288
+ surfaces: null,
46289
+ surfaceKey: "",
46290
+ surfaceScene: null,
46291
+ surfaceAt: -Infinity,
46292
+ surfaceSignature: "",
46293
+ outlines: [],
46294
+ placed: false
46295
+ };
46296
+ entries.set(owner.id, entry);
46297
+ }
45306
46298
  }
46299
+ if (!entry) continue;
45307
46300
  entry.owner = owner;
45308
- entry.output = output;
46301
+ if (entry.signature === signature) entry.output = output;
46302
+ const drawn = entry.output;
45309
46303
  const placement = host.attach(owner, entry.layer);
45310
46304
  entry.placed = placement !== null;
45311
46305
  if (!placement) continue;
45312
- animated ||= output.animated || entry.layer.animated;
46306
+ animated ||= drawn.animated || entry.layer.animated;
45313
46307
  entry.layer.update({
45314
46308
  time: owner.time,
45315
46309
  region: placement.region,
@@ -45319,77 +46313,42 @@ function createBoardShaderLayers() {
45319
46313
  density: host.density,
45320
46314
  seed: boardShaderSeed(owner.seed),
45321
46315
  quality: host.quality,
46316
+ shading: host.shading,
45322
46317
  dark: host.dark,
45323
- params: parameterValues(output.parameters, owner.params, host.color),
45324
- uniforms: output.uniforms
46318
+ params: parameterValues(drawn.parameters, owner.params, host.color),
46319
+ uniforms: drawn.uniforms,
46320
+ passes: drawn.passes
45325
46321
  });
45326
- if (entry.layer.surfaces) {
45327
- const { localToWorld } = placement;
45328
- const margin = owner.root ? SURFACE_MARGIN : 0;
45329
- const region = boardSurfaceRegion(entry.surfaces?.region ?? null, placement.region, margin);
45330
- const corners = [
45331
- applyMatrix$1(localToWorld, region),
45332
- applyMatrix$1(localToWorld, {
45333
- x: region.x + region.width,
45334
- y: region.y + region.height
45335
- }),
45336
- applyMatrix$1(localToWorld, {
45337
- x: region.x + region.width,
45338
- y: region.y
45339
- }),
45340
- applyMatrix$1(localToWorld, {
45341
- x: region.x,
45342
- y: region.y + region.height
45343
- })
45344
- ];
45345
- const xs = corners.map((point) => point.x);
45346
- const ys = corners.map((point) => point.y);
45347
- const world = {
45348
- x: Math.min(...xs),
45349
- y: Math.min(...ys),
45350
- width: Math.max(...xs) - Math.min(...xs),
45351
- height: Math.max(...ys) - Math.min(...ys)
45352
- };
45353
- const edge = Math.max(64, Math.round(SURFACE_EDGE * (1 + 2 * margin) * host.quality));
45354
- const key = `${[
45355
- region.x,
45356
- region.y,
45357
- region.width,
45358
- region.height,
45359
- ...localToWorld
45360
- ].map((n) => n.toFixed(3)).join(",")}|${edge}`;
45361
- entry.surfaces ??= createBoardSurfaceField();
45362
- if (key !== entry.surfaceKey || entry.surfaceScene !== scene) {
45363
- entry.surfaceScene = scene;
45364
- const outlines = boardSurfaceOutlines(scene, owner.id, world, invertMatrix(localToWorld), candidates?.(world));
45365
- if (key !== entry.surfaceKey || !sameOutlines(outlines, entry.outlines)) entry.surfaces.build(renderer, region, outlines, edge);
45366
- entry.surfaceKey = key;
45367
- entry.outlines = outlines;
45368
- }
45369
- entry.layer.setSurfaces(entry.surfaces.texture, entry.surfaces.region);
45370
- }
46322
+ if (entry.layer.surfaces) surfaceField(entry, renderer, owner, placement, host, scene, candidates);
45371
46323
  } catch (error) {
45372
46324
  host.attach(owner, null);
45373
46325
  drop(owner.id, host);
46326
+ dropCompiling(owner.id);
45374
46327
  failed.set(owner.id, signature);
45375
46328
  host.fault(owner.id, error instanceof Error ? error.message : String(error));
45376
46329
  }
45377
46330
  }
45378
46331
  for (const id of [...entries.keys()]) if (!alive.has(id)) drop(id, host);
46332
+ for (const id of [...compiling.keys()]) if (!alive.has(id)) dropCompiling(id);
45379
46333
  for (const id of [...failed.keys()]) if (!owners.some((owner) => owner.id === id)) failed.delete(id);
45380
46334
  },
45381
46335
  prepare(renderer, catchUp = false) {
45382
46336
  pending = false;
45383
46337
  for (const entry of entries.values()) if (entry.placed && entry.layer.prepare(renderer, { catchUp })) pending = true;
45384
46338
  },
46339
+ rewind() {
46340
+ for (const entry of entries.values()) entry.layer.rewind();
46341
+ },
45385
46342
  detach() {
45386
46343
  for (const entry of entries.values()) {
45387
- entry.layer.container?.removeFromParent();
46344
+ entry.layer.below?.removeFromParent();
46345
+ entry.layer.above?.removeFromParent();
45388
46346
  entry.placed = false;
45389
46347
  }
45390
46348
  },
45391
46349
  destroy() {
45392
46350
  for (const id of [...entries.keys()]) drop(id);
46351
+ for (const id of [...compiling.keys()]) dropCompiling(id);
45393
46352
  failed.clear();
45394
46353
  }
45395
46354
  };
@@ -45545,6 +46504,7 @@ function buildContext(input) {
45545
46504
  scene: input.scene,
45546
46505
  time: input.time ?? 0,
45547
46506
  frameAt: input.frameAt,
46507
+ ...input.page ? { page: input.page } : {},
45548
46508
  selectedIds: /* @__PURE__ */ new Set(),
45549
46509
  hoveredId: null,
45550
46510
  resizingIds: /* @__PURE__ */ new Set(),
@@ -45638,7 +46598,7 @@ function createBoardExportScene(input) {
45638
46598
  }
45639
46599
  root.addChild(world);
45640
46600
  const shaderErrors = [];
45641
- const layers = input.shaders?.owners.length ? input.shaders.layers ?? createBoardShaderLayers() : null;
46601
+ const layers = input.shaders?.owners.length ? input.shaders.layers ?? createBoardShaderLayers({ wait: true }) : null;
45642
46602
  if (layers && input.shaders) {
45643
46603
  const toOutput = [
45644
46604
  input.scale,
@@ -45660,10 +46620,12 @@ function createBoardExportScene(input) {
45660
46620
  const attach = (owner, layer) => {
45661
46621
  if (!layer) return null;
45662
46622
  if (owner.root) {
45663
- if (layer.container) (layer.layer === "below" ? below : above).addChild(layer.container);
46623
+ if (layer.below) below.addChild(layer.below);
46624
+ if (layer.above) above.addChild(layer.above);
45664
46625
  if (layer.filters) {
45665
46626
  filters.set(owner.id, layer.filters);
45666
46627
  setBoardShaderFilters(world, [...filters.values()].flat());
46628
+ world.filterArea = new Rectangle(input.world.x, input.world.y, input.world.width, input.world.height);
45667
46629
  }
45668
46630
  return {
45669
46631
  region: input.world,
@@ -45683,15 +46645,26 @@ function createBoardExportScene(input) {
45683
46645
  const container = containers.get(owner.id);
45684
46646
  if (!item || !container) return null;
45685
46647
  const group = isSelfGroupedFrame(item) ? groups.get(item.id)?.group : void 0;
45686
- if (layer.layer === "below" && layer.container) container.addChildAt(layer.container, 0);
45687
- if (layer.layer === "above" && layer.container) {
46648
+ for (const part of [layer.below, layer.above]) if (part && item.type === "frame") clipFrameShaderLayer(part, item);
46649
+ if (layer.below) container.addChildAt(layer.below, 0);
46650
+ if (layer.above) {
45688
46651
  if (group) {
45689
- positionShell(layer.container, item);
45690
- layer.container.zIndex = Number.MAX_SAFE_INTEGER;
46652
+ positionShell(layer.above, item);
46653
+ layer.above.zIndex = Number.MAX_SAFE_INTEGER;
45691
46654
  }
45692
- (group ?? container).addChild(layer.container);
46655
+ (group ?? container).addChild(layer.above);
46656
+ }
46657
+ if (layer.filters) {
46658
+ const host = group ?? container;
46659
+ setBoardShaderFilters(host, layer.filters);
46660
+ const box = group ? itemBounds(item.frame) : {
46661
+ x: 0,
46662
+ y: 0,
46663
+ width: item.frame.width,
46664
+ height: item.frame.height
46665
+ };
46666
+ host.filterArea = new Rectangle(box.x, box.y, box.width, box.height);
45693
46667
  }
45694
- if (layer.filters) setBoardShaderFilters(group ?? container, layer.filters);
45695
46668
  const localToWorld = boardItemLocalToWorld(item.frame);
45696
46669
  return {
45697
46670
  region: {
@@ -45824,6 +46797,7 @@ function renderBoardExport(renderer, input, options = {}) {
45824
46797
  colorScheme
45825
46798
  }),
45826
46799
  backdropTexture: options.backgroundTexture,
46800
+ ...plan.page ? { page: plan.page } : {},
45827
46801
  ...gpu && owners.length ? { shaders: {
45828
46802
  renderer,
45829
46803
  owners,
@@ -45876,6 +46850,10 @@ function renderBoardExport(renderer, input, options = {}) {
45876
46850
  kind: "shader-failed",
45877
46851
  ...failure
45878
46852
  });
46853
+ if (gpu) for (const miss of boardShaderMisses(scene, plan, owners, exportScene.shaderErrors)) warnings.push({
46854
+ kind: "shader-hidden",
46855
+ ...miss
46856
+ });
45879
46857
  return {
45880
46858
  canvas,
45881
46859
  plan,
@@ -45886,6 +46864,38 @@ function renderBoardExport(renderer, input, options = {}) {
45886
46864
  flattened?.();
45887
46865
  }
45888
46866
  }
46867
+ function boardShaderMisses(scene, plan, owners, failed = []) {
46868
+ const planned = new Set(plan.items.map((item) => item.id));
46869
+ const misses = owners.flatMap(({ id, root, output }) => {
46870
+ if (failed.some((failure) => failure.id === id)) return [];
46871
+ const shader = output.shader;
46872
+ if (shader && !shader.state && shader.passes.every((pass) => !boardShaderPassOn(pass, output.passes))) return [{
46873
+ id,
46874
+ reason: "every pass is switched off (ctx.passes() or enabled: false)"
46875
+ }];
46876
+ if (root) return [];
46877
+ const item = scene.get(id);
46878
+ if (!item) return [{
46879
+ id,
46880
+ reason: "its item is not in the document"
46881
+ }];
46882
+ if (scene.opacity(id) <= 0) return [{
46883
+ id,
46884
+ reason: "its item is hidden (opacity 0 or invisible)"
46885
+ }];
46886
+ if (planned.has(id)) return [];
46887
+ return [{
46888
+ id,
46889
+ reason: exportItemBounds(item, scene) ? "its item is outside the exported area" : "its item is clipped away by a parent frame"
46890
+ }];
46891
+ });
46892
+ const grouped = /* @__PURE__ */ new Map();
46893
+ for (const { id, reason } of misses) grouped.set(reason, [...grouped.get(reason) ?? [], id]);
46894
+ return [...grouped].map(([reason, ids]) => ({
46895
+ ids,
46896
+ reason
46897
+ }));
46898
+ }
45889
46899
  function listIds(ids) {
45890
46900
  return ids.length > 3 ? `${ids.slice(0, 3).join(", ")} and ${ids.length - 3} more` : ids.join(", ");
45891
46901
  }
@@ -45896,6 +46906,7 @@ function describeBoardExportWarning(warning) {
45896
46906
  case "many-items": return `${warning.count} items exported; this may take a moment.`;
45897
46907
  case "shaders-unsupported": return `Shaders need a WebGL renderer; this export ${[warning.omitted.length ? `left out ${listIds(warning.omitted)}` : "", warning.drawn.length ? `drew ${listIds(warning.drawn)} with draw()` : ""].filter(Boolean).join(" and ")}.`;
45898
46908
  case "shader-failed": return `Shader ${warning.id} was left out: ${warning.message}`;
46909
+ case "shader-hidden": return `${warning.ids.length === 1 ? "Shader" : "Shaders"} of ${listIds(warning.ids)} drew nothing: ${warning.reason.replace(/^its item is/, warning.ids.length === 1 ? "its item is" : "their items are")}.`;
45899
46910
  }
45900
46911
  }
45901
46912
  //#endregion
@@ -45949,7 +46960,7 @@ function initializeBoardFonts(registry, fonts) {
45949
46960
  //#region ../sdk/src/board/export/node/scripts.ts
45950
46961
  const WORKER = `
45951
46962
  const {parentPort, workerData} = require('node:worker_threads');
45952
- const {createContext, Script, SourceTextModule} = require('node:vm');
46963
+ const {createContext, Script, SourceTextModule, SyntheticModule} = require('node:vm');
45953
46964
  const {createCanvas, GlobalFonts} = require(workerData.canvasModule);
45954
46965
  (${initializeBoardFonts.toString()})(GlobalFonts, workerData.fonts);
45955
46966
  const instances = new Map();
@@ -45980,10 +46991,15 @@ async function create(data) {
45980
46991
  return parts.join('/');
45981
46992
  };
45982
46993
  const link = (name,ref) => load(resolve(ref.identifier,name));
46994
+ const json = new Script('(text)=>{const freeze=v=>{if(v&&typeof v==="object"&&!Object.isFrozen(v)){Object.freeze(v);for(const k in v)freeze(v[k]);}return v};return freeze(JSON.parse(text))}').runInContext(context);
45983
46995
  function load(path) {
45984
46996
  if(modules.has(path)) return modules.get(path);
45985
46997
  const source=sources[path];
45986
46998
  if(!source) throw new Error('Module is unavailable: '+path);
46999
+ if(path.endsWith('.json')) {
47000
+ const module=new SyntheticModule(['default'],function(){this.setExport('default',json(source.code));},{context,identifier:path});
47001
+ modules.set(path,module);return module;
47002
+ }
45987
47003
  const module=new SourceTextModule(source.code,{context,identifier:path,importModuleDynamically:async name=>{
45988
47004
  const child=load(resolve(path,name));
45989
47005
  if(child.status==='unlinked') await child.link(link);
@@ -46049,6 +47065,16 @@ parentPort.on('message',async data=>{
46049
47065
  } catch(error) { release(data.input?.id);parentPort.postMessage({kind:'sample',error:String(error.stack||error)}); }
46050
47066
  });
46051
47067
  `;
47068
+ function describeBoardScriptLanes(lanes) {
47069
+ return lanes.flatMap(({ lane, thread, running, waiting, scripts }) => {
47070
+ if (!running && !waiting) return [];
47071
+ return [`${`lane ${lane}${thread === null ? "" : ` (worker thread ${thread})`}`}: ${running ? `${running.id} busy for ${(running.ms / 1e3).toFixed(1)} s${running.event ? `, last event ${running.event}` : ""}${running.call ? `, last call ${running.call}` : ""}` : "idle"}${waiting ? `; ${waiting} more request${waiting === 1 ? "" : "s"} queued` : ""} (runs ${scripts.join(", ")})`];
47072
+ });
47073
+ }
47074
+ function describeCall(name, input) {
47075
+ const message = input;
47076
+ return name === "board.emit" && message && typeof message.target === "string" ? `emit(${message.target}, "${String(message.type)}")` : name;
47077
+ }
46052
47078
  function createNodeScriptLanes(renderer, options) {
46053
47079
  const calls = /* @__PURE__ */ new Map();
46054
47080
  const settled = /* @__PURE__ */ new Set();
@@ -46057,8 +47083,11 @@ function createNodeScriptLanes(renderer, options) {
46057
47083
  const lanes = Array.from({ length: concurrency }, () => ({
46058
47084
  worker: null,
46059
47085
  tail: Promise.resolve(),
46060
- graphs: /* @__PURE__ */ new Set()
47086
+ graphs: /* @__PURE__ */ new Set(),
47087
+ running: null,
47088
+ waiting: 0
46061
47089
  }));
47090
+ const activity = /* @__PURE__ */ new Map();
46062
47091
  const assignments = /* @__PURE__ */ new Map();
46063
47092
  const sources = /* @__PURE__ */ new Map();
46064
47093
  const modules = createBoardScriptModuleReader(options.readModule, options.readTimeoutMs);
@@ -46114,6 +47143,10 @@ function createNodeScriptLanes(renderer, options) {
46114
47143
  calls.delete(key);
46115
47144
  }
46116
47145
  if (message.kind !== "call") return;
47146
+ activity.set(message.id ?? "", {
47147
+ ...activity.get(message.id ?? ""),
47148
+ call: describeCall(message.name ?? "", message.input)
47149
+ });
46117
47150
  const answer = (value, error) => {
46118
47151
  if (lane.worker !== worker) return;
46119
47152
  const done = new Promise((resolve) => {
@@ -46138,20 +47171,30 @@ function createNodeScriptLanes(renderer, options) {
46138
47171
  });
46139
47172
  };
46140
47173
  Promise.resolve().then(() => {
46141
- if (!options.call) throw new Error("Capabilities are unavailable during export.");
46142
- return options.call(message.id ?? "", message.name ?? "", message.input);
47174
+ const name = message.name ?? "";
47175
+ if (options.call) return options.call(message.id ?? "", name, message.input);
47176
+ const call = BOARD_SCRIPT_EXPORT_CALLS[name];
47177
+ if (!call) throw new Error("Capabilities are unavailable during export.");
47178
+ return call(message.input);
46143
47179
  }).then((value) => answer(value), (error) => answer(void 0, error instanceof Error ? error.message : String(error)));
46144
47180
  });
46145
47181
  return worker;
46146
47182
  }
46147
- function request(lane, message, register) {
47183
+ function request(lane, message, register, id) {
47184
+ lane.waiting++;
46148
47185
  const task = lane.tail.then(() => new Promise((resolve, reject) => {
47186
+ lane.waiting--;
46149
47187
  if (disposed) return reject(/* @__PURE__ */ new Error("Script host is disposed."));
46150
47188
  const worker = start(lane);
47189
+ if (id) lane.running = {
47190
+ id,
47191
+ since: performance.now()
47192
+ };
46151
47193
  const cleanup = () => {
46152
47194
  clearTimeout(timer);
46153
47195
  worker.off("message", reply);
46154
47196
  lane.reject = void 0;
47197
+ lane.running = null;
46155
47198
  };
46156
47199
  const reply = (value) => {
46157
47200
  if (value.kind !== "sample") return;
@@ -46189,6 +47232,10 @@ function createNodeScriptLanes(renderer, options) {
46189
47232
  if (!Number.isFinite(time) || time < 0 || time > 6e5) return Promise.reject(/* @__PURE__ */ new Error("Script time must be between 0 and 600000 ms."));
46190
47233
  const lane = laneOf(input.id);
46191
47234
  const src = input.script.src;
47235
+ if (events?.length) activity.set(input.id, {
47236
+ ...activity.get(input.id),
47237
+ event: events.map((event) => event.type).join(", ")
47238
+ });
46192
47239
  return request(lane, {
46193
47240
  input,
46194
47241
  src,
@@ -46202,7 +47249,21 @@ function createNodeScriptLanes(renderer, options) {
46202
47249
  draw,
46203
47250
  shaders,
46204
47251
  sources: lane.graphs.has(src) ? void 0 : graph
46205
- }, () => lane.graphs.add(src));
47252
+ }, () => lane.graphs.add(src), input.id);
47253
+ },
47254
+ status() {
47255
+ const now = performance.now();
47256
+ return lanes.map((lane, index) => ({
47257
+ lane: index + 1,
47258
+ thread: lane.worker?.threadId ?? null,
47259
+ running: lane.running && {
47260
+ id: lane.running.id,
47261
+ ms: now - lane.running.since,
47262
+ ...activity.get(lane.running.id)
47263
+ },
47264
+ waiting: lane.waiting,
47265
+ scripts: [...assignments].flatMap(([id, assigned]) => assigned === lane ? [id] : [])
47266
+ }));
46206
47267
  },
46207
47268
  async snapshot(id) {
46208
47269
  const lane = assignments.get(id);
@@ -46212,6 +47273,7 @@ function createNodeScriptLanes(renderer, options) {
46212
47273
  release(id) {
46213
47274
  const lane = assignments.get(id);
46214
47275
  assignments.delete(id);
47276
+ activity.delete(id);
46215
47277
  if (lane) lane.tail = lane.tail.then(() => lane.worker?.postMessage({ release: [id] }));
46216
47278
  },
46217
47279
  assigned: () => assignments.keys(),
@@ -46251,10 +47313,33 @@ function scopedInput(document, { id, script, item }, size) {
46251
47313
  };
46252
47314
  }
46253
47315
  function createNodeBoardScriptHost(renderer, options) {
46254
- const lanes = createNodeScriptLanes(renderer, options);
47316
+ let current = null;
47317
+ let ranks = /* @__PURE__ */ new Map();
47318
+ const outbox = createBoardScriptOutbox(() => ranks);
47319
+ const emitFailures = /* @__PURE__ */ new Map();
47320
+ const lanes = createNodeScriptLanes(renderer, {
47321
+ ...options,
47322
+ async call(id, name, input) {
47323
+ if (name === "board.emit" && current) {
47324
+ try {
47325
+ const { target, event } = boardScriptEmit(current, id, input);
47326
+ outbox.push(id, target, event);
47327
+ } catch (error) {
47328
+ emitFailures.set(id, error instanceof Error ? error.message : String(error));
47329
+ throw error;
47330
+ }
47331
+ return;
47332
+ }
47333
+ const call = BOARD_SCRIPT_EXPORT_CALLS[name];
47334
+ if (!call) throw new Error("Capabilities are unavailable during export.");
47335
+ return call(input);
47336
+ }
47337
+ });
46255
47338
  const textures = /* @__PURE__ */ new Map();
46256
47339
  const outputs = /* @__PURE__ */ new Map();
46257
47340
  const errors = /* @__PURE__ */ new Map();
47341
+ const sampled = /* @__PURE__ */ new Map();
47342
+ const views = /* @__PURE__ */ new Map();
46258
47343
  const key = (id, time) => `${id}|${time}`;
46259
47344
  let disposed = false;
46260
47345
  return {
@@ -46262,6 +47347,8 @@ function createNodeBoardScriptHost(renderer, options) {
46262
47347
  frame: (item, time) => textures.get(key(item.id, time)) ?? null,
46263
47348
  error: (id) => errors.get(id) ?? null,
46264
47349
  release() {},
47350
+ emitFailures,
47351
+ status: () => lanes.status(),
46265
47352
  shaders: (document, time) => boardShaderOwners(document, outputs.get(time) ?? [], () => time),
46266
47353
  document(document, time) {
46267
47354
  const at = outputs.get(time);
@@ -46280,16 +47367,25 @@ function createNodeBoardScriptHost(renderer, options) {
46280
47367
  errors.clear();
46281
47368
  },
46282
47369
  async prepare(items, times, zoom, board, options) {
46283
- const all = Object.fromEntries(items.map(({ id, frame: _frame, ...item }) => [id, item]));
46284
- const document = {
47370
+ const documentOf = (list) => ({
46285
47371
  board: { scripts: board?.scripts },
46286
- items: all
46287
- };
47372
+ items: Object.fromEntries(list.map(({ id, frame: _frame, ...item }) => [id, item]))
47373
+ });
47374
+ const document = documentOf(items);
47375
+ current = document;
47376
+ emitFailures.clear();
46288
47377
  const scripted = boardScriptAttachments(document);
47378
+ ranks = new Map(scripted.map(({ id }, index) => [id, index]));
46289
47379
  const alive = new Set(scripted.map(({ id }) => id));
46290
- for (const id of [...lanes.assigned()]) if (!alive.has(id)) lanes.release(id);
47380
+ for (const id of [...lanes.assigned()]) if (!alive.has(id)) {
47381
+ lanes.release(id);
47382
+ views.delete(id);
47383
+ sampled.delete(id);
47384
+ }
46291
47385
  if (!scripted.length) return;
46292
47386
  const frames = new Map(items.map((item) => [item.id, item.frame]));
47387
+ const viewKey = options?.view ? JSON.stringify(options.view) : null;
47388
+ const prepared = /* @__PURE__ */ new Map();
46293
47389
  await Promise.all(scripted.map(async (attachment) => {
46294
47390
  const { id, item } = attachment;
46295
47391
  try {
@@ -46298,38 +47394,131 @@ function createNodeBoardScriptHost(renderer, options) {
46298
47394
  const width = item ? "size" in item ? item.size.width : frame?.width ?? 0 : 0;
46299
47395
  const height = item ? "size" in item ? item.size.height : frame?.height ?? 0 : 0;
46300
47396
  const scale = Math.min(4, Math.max(.25, zoom), 2048 / Math.max(1, width, height));
46301
- const input = scopedInput(document, attachment, {
47397
+ prepared.set(id, {
47398
+ attachment,
47399
+ graph,
47400
+ input: scopedInput(document, attachment, {
47401
+ width,
47402
+ height
47403
+ }),
46302
47404
  width,
46303
- height
47405
+ height,
47406
+ scale
46304
47407
  });
46305
- for (const time of times) {
46306
- const result = await lanes.sample({
46307
- input,
46308
- graph,
46309
- time,
46310
- scale,
46311
- draw: Boolean(item),
46312
- shaders: options?.shaders
46313
- });
46314
- if (disposed) return;
46315
- if (result.png) {
46316
- const frameKey = key(id, time);
46317
- textures.get(frameKey)?.destroy(true);
46318
- const texture = await renderer.decodeImage(result.png);
46319
- if (result.output.pixelated) texture.source.scaleMode = "nearest";
46320
- textures.set(frameKey, texture);
46321
- }
46322
- let at = outputs.get(time);
46323
- if (!at) {
46324
- at = /* @__PURE__ */ new Map();
46325
- outputs.set(time, at);
46326
- }
46327
- at.set(id, result.output);
46328
- }
46329
47408
  } catch (error) {
46330
47409
  errors.set(id, error instanceof Error ? error.message : String(error));
46331
47410
  }
46332
47411
  }));
47412
+ const keep = async (id, time, events) => {
47413
+ const entry = prepared.get(id);
47414
+ if (!entry || errors.has(id)) return;
47415
+ const { attachment, graph, input, scale } = entry;
47416
+ try {
47417
+ const result = await lanes.sample({
47418
+ input,
47419
+ graph,
47420
+ time,
47421
+ scale,
47422
+ events,
47423
+ draw: Boolean(attachment.item),
47424
+ shaders: options?.shaders
47425
+ });
47426
+ if (disposed) return;
47427
+ if (result.png) {
47428
+ const frameKey = key(id, time);
47429
+ textures.get(frameKey)?.destroy(true);
47430
+ const texture = await renderer.decodeImage(result.png);
47431
+ if (result.output.pixelated) texture.source.scaleMode = "nearest";
47432
+ textures.set(frameKey, texture);
47433
+ }
47434
+ let at = outputs.get(time);
47435
+ if (!at) {
47436
+ at = /* @__PURE__ */ new Map();
47437
+ outputs.set(time, at);
47438
+ }
47439
+ at.set(id, result.output);
47440
+ } catch (error) {
47441
+ errors.set(id, error instanceof Error ? error.message : String(error));
47442
+ }
47443
+ };
47444
+ for (const time of times) {
47445
+ await Promise.all([...prepared].map(async ([id, { attachment, graph, input, width, height, scale }]) => {
47446
+ try {
47447
+ const last = sampled.get(id) ?? 0;
47448
+ if (time < last) views.delete(id);
47449
+ if (options?.history) {
47450
+ const from = last <= time ? last : 0;
47451
+ const run = async (at, document) => {
47452
+ const script = boardScriptOf(document, id);
47453
+ if (script) await lanes.sample({
47454
+ input: scopedInput(document, {
47455
+ ...attachment,
47456
+ script
47457
+ }, {
47458
+ width,
47459
+ height
47460
+ }),
47461
+ graph,
47462
+ time: at,
47463
+ scale,
47464
+ draw: false,
47465
+ shaders: options.shaders
47466
+ });
47467
+ };
47468
+ let before = {
47469
+ at: from,
47470
+ document: options.history(from)
47471
+ };
47472
+ let previous = JSON.stringify(boardScriptOf(before.document, id)?.params);
47473
+ let ran = from;
47474
+ if (from === 0) await run(from, before.document);
47475
+ for (let at = from + BOARD_SCRIPT_HISTORY_MS; at < time; at += BOARD_SCRIPT_HISTORY_MS) {
47476
+ const sample = options.history(at);
47477
+ const key = JSON.stringify(boardScriptOf(sample, id)?.params);
47478
+ if (key !== previous) {
47479
+ if (before.at > ran) await run(before.at, before.document);
47480
+ await run(at, sample);
47481
+ previous = key;
47482
+ ran = at;
47483
+ if (disposed) return;
47484
+ }
47485
+ before = {
47486
+ at,
47487
+ document: sample
47488
+ };
47489
+ }
47490
+ if (JSON.stringify(input.script.params) !== previous && before.at > ran) await run(before.at, before.document);
47491
+ }
47492
+ } catch (error) {
47493
+ errors.set(id, error instanceof Error ? error.message : String(error));
47494
+ return;
47495
+ }
47496
+ sampled.set(id, time);
47497
+ const events = [];
47498
+ const shown = viewKey && `${JSON.stringify({
47499
+ ...attachment.script,
47500
+ params: void 0
47501
+ })}|${viewKey}`;
47502
+ if (shown && views.get(id) !== shown) {
47503
+ views.set(id, shown);
47504
+ events.push({
47505
+ type: "viewchange",
47506
+ data: options?.view
47507
+ });
47508
+ }
47509
+ await keep(id, time, events);
47510
+ }));
47511
+ for (let round = 0; outbox.size && round <= 16 && !disposed; round++) {
47512
+ const delivered = [...outbox.take()].flatMap(([id, events]) => {
47513
+ const output = outputs.get(time)?.get(id);
47514
+ const wanted = events.filter((event) => boardScriptListens(output, event));
47515
+ return wanted.length ? [keep(id, time, wanted)] : [];
47516
+ });
47517
+ await Promise.all(delivered);
47518
+ }
47519
+ outbox.take();
47520
+ }
47521
+ await lanes.idle();
46333
47522
  },
46334
47523
  destroy() {
46335
47524
  disposed = true;
@@ -46487,10 +47676,12 @@ function createNodeBoardScriptRuntime(renderer, options) {
46487
47676
  },
46488
47677
  event(id, event) {
46489
47678
  const entry = entries.get(id);
46490
- if (!entry || entry.error || entry.output && !entry.output.listens.includes(event.type)) return;
46491
- entry.events.push(event);
47679
+ if (!entry || entry.error || !boardScriptListens(entry.output, event)) return true;
47680
+ if (!queueBoardScriptEvent(entry.events, event)) return false;
46492
47681
  callbacks.onFrame();
47682
+ return true;
46493
47683
  },
47684
+ status: () => lanes.status(),
46494
47685
  output: (id) => entries.get(id)?.output ?? null,
46495
47686
  snapshot: (id) => lanes.snapshot(id),
46496
47687
  restore() {
@@ -46988,6 +48179,7 @@ const STRUCTURAL_KEYS = [
46988
48179
  "parent",
46989
48180
  "z",
46990
48181
  "locked",
48182
+ "autoplay",
46991
48183
  "metadata"
46992
48184
  ];
46993
48185
  function keyframe(animations, playhead, recording, id, property, value, storedValue) {
@@ -48503,7 +49695,7 @@ function createDocumentModule(ctx) {
48503
49695
  const previous = scripted;
48504
49696
  scripted = items;
48505
49697
  const changed = [.../* @__PURE__ */ new Set([...previous.keys(), ...items.keys()])].filter((id) => !sameJson(previous.get(id), items.get(id)));
48506
- if (!changed.length) return;
49698
+ if (!changed.length) return changed;
48507
49699
  const restacked = /* @__PURE__ */ new Set();
48508
49700
  rescene(changed.some((id) => {
48509
49701
  const before = previous.get(id) ?? state.base.items[id];
@@ -48512,6 +49704,7 @@ function createDocumentModule(ctx) {
48512
49704
  if (before.z !== after.z) restacked.add(after.parent ?? "");
48513
49705
  return false;
48514
49706
  }) || [...restacked].some(reordered) ? void 0 : changed);
49707
+ return changed;
48515
49708
  }
48516
49709
  function reordered(parent) {
48517
49710
  const { scene } = state;
@@ -48549,10 +49742,10 @@ function createDocumentModule(ctx) {
48549
49742
  state.structureVersion += 1;
48550
49743
  state.geometryVersion += 1;
48551
49744
  }
48552
- function setDraftItem(id, item) {
49745
+ function setDraftItem(id, item, shown) {
48553
49746
  if (!draft.has(id)) {
48554
- const shown = displayItem(id);
48555
- if (shown) draftOrigins.set(id, shown);
49747
+ const origin = shown ?? displayItem(id);
49748
+ if (origin) draftOrigins.set(id, origin);
48556
49749
  }
48557
49750
  draft.set(id, item);
48558
49751
  }
@@ -48562,9 +49755,9 @@ function createDocumentModule(ctx) {
48562
49755
  function dropDraftItem(id) {
48563
49756
  draft.delete(id);
48564
49757
  }
48565
- function writeDraft(changes, structural = false) {
49758
+ function writeDraft(changes, structural = false, shown) {
48566
49759
  if (changes.size === 0) return;
48567
- for (const [id, item] of changes) setDraftItem(id, item);
49760
+ for (const [id, item] of changes) setDraftItem(id, item, shown?.get(id)?.item);
48568
49761
  if (!structural) for (const [id, item] of changes) {
48569
49762
  const before = state.scene.get(id);
48570
49763
  if (!item || !before || before.parent !== item.parent || before.z !== item.z || !sameJson(arrowBindings(before), arrowBindings(item))) {
@@ -49370,7 +50563,7 @@ function createInteractionModule(ctx) {
49370
50563
  const translating = {
49371
50564
  type: "translating",
49372
50565
  start: gesture.world,
49373
- origin: ctx.selection.framesFor([gesture.itemId]),
50566
+ ...ctx.selection.grab([gesture.itemId]),
49374
50567
  moved: false,
49375
50568
  duplicate: false
49376
50569
  };
@@ -49398,7 +50591,7 @@ function createInteractionModule(ctx) {
49398
50591
  state.interaction = {
49399
50592
  type: "translating",
49400
50593
  start: last?.world ?? (gesture.type === "pressing" ? gesture.world : rectCenter(item.frame)),
49401
- origin: ctx.selection.framesFor([item.id]),
50594
+ ...ctx.selection.grab([item.id]),
49402
50595
  moved: false,
49403
50596
  duplicate: false,
49404
50597
  held: true
@@ -49435,7 +50628,7 @@ function createInteractionModule(ctx) {
49435
50628
  state.interaction = {
49436
50629
  type: "translating",
49437
50630
  start: event.world,
49438
- origin: ctx.selection.framesFor(ctx.selection.movable()),
50631
+ ...ctx.selection.grab(ctx.selection.movable()),
49439
50632
  moved: false,
49440
50633
  duplicate: event.altKey,
49441
50634
  ...tap ? { tap } : {}
@@ -49582,13 +50775,13 @@ function createInteractionModule(ctx) {
49582
50775
  pivot,
49583
50776
  startAngle: angleFrom(pivot, event.world),
49584
50777
  current: event.world,
49585
- origin: ctx.selection.framesFor(ctx.selection.movable()),
50778
+ ...ctx.selection.grab(ctx.selection.movable()),
49586
50779
  moved: false
49587
50780
  };
49588
50781
  return;
49589
50782
  }
49590
50783
  if (control?.kind === "resize" && bounds && transform) {
49591
- const origin = ctx.selection.framesFor(ctx.selection.movable());
50784
+ const { origin, grabbed } = ctx.selection.grab(ctx.selection.movable());
49592
50785
  const single = origin.size === 1 ? { ...[...origin.values()][0] } : null;
49593
50786
  const edge = frameHandlePosition(transform.frame, control.handle);
49594
50787
  const grab = {
@@ -49601,6 +50794,7 @@ function createInteractionModule(ctx) {
49601
50794
  single,
49602
50795
  bounds,
49603
50796
  origin,
50797
+ grabbed,
49604
50798
  grab,
49605
50799
  moved: false
49606
50800
  };
@@ -49692,7 +50886,7 @@ function createInteractionModule(ctx) {
49692
50886
  state.selection = roots;
49693
50887
  current = {
49694
50888
  ...current,
49695
- origin: ctx.selection.framesFor(roots),
50889
+ ...ctx.selection.grab(roots),
49696
50890
  duplicate: false
49697
50891
  };
49698
50892
  }
@@ -49720,7 +50914,7 @@ function createInteractionModule(ctx) {
49720
50914
  ty += snap.dy;
49721
50915
  state.snapGuides = snap.guides;
49722
50916
  } else state.snapGuides = [];
49723
- ctx.document.writeDraft(ctx.selection.placed(shift(tx, ty)));
50917
+ ctx.document.writeDraft(ctx.selection.placed(shift(tx, ty), current.grabbed), false, current.grabbed);
49724
50918
  let dropTargetId = null;
49725
50919
  for (const parent of dropParents(current.origin, true).values()) if (parent) dropTargetId = parent;
49726
50920
  if ((current.dropTargetId ?? null) !== dropTargetId) state.interaction = {
@@ -49750,7 +50944,7 @@ function createInteractionModule(ctx) {
49750
50944
  if (frame) frames.set(id, frame);
49751
50945
  });
49752
50946
  }
49753
- ctx.document.writeDraft(ctx.selection.placed(frames));
50947
+ ctx.document.writeDraft(ctx.selection.placed(frames, gesture.grabbed), false, gesture.grabbed);
49754
50948
  }
49755
50949
  function rotate(gesture, event) {
49756
50950
  if (!gesture.moved && !dragged(event)) return;
@@ -49770,7 +50964,7 @@ function createInteractionModule(ctx) {
49770
50964
  rotation: normalizeRotation(frame.rotation)
49771
50965
  });
49772
50966
  });
49773
- ctx.document.writeDraft(ctx.selection.placed(frames));
50967
+ ctx.document.writeDraft(ctx.selection.placed(frames, gesture.grabbed), false, gesture.grabbed);
49774
50968
  }
49775
50969
  function dragArrowHandle(gesture, event) {
49776
50970
  if (!gesture.moved) {
@@ -50617,11 +51811,30 @@ function createSelectionModule(ctx) {
50617
51811
  }
50618
51812
  return frames;
50619
51813
  }
50620
- function placed(frames) {
51814
+ function grab(ids) {
51815
+ const { layout } = state.scene;
51816
+ const origin = framesFor(ids);
51817
+ const grabbed = /* @__PURE__ */ new Map();
51818
+ for (const id of origin.keys()) {
51819
+ const item = ctx.document.displayItem(id);
51820
+ if (item) grabbed.set(id, {
51821
+ item,
51822
+ parent: item.parent && layout.has(item.parent) ? layout.matrix(item.parent) : IDENTITY_MATRIX,
51823
+ box: layout.box(id)
51824
+ });
51825
+ }
51826
+ return {
51827
+ origin,
51828
+ grabbed
51829
+ };
51830
+ }
51831
+ function placed(frames, from) {
50621
51832
  const changes = /* @__PURE__ */ new Map();
50622
51833
  for (const [id, frame] of frames) {
51834
+ const grabbed = from?.get(id);
50623
51835
  const item = state.scene.get(id);
50624
- if (item) changes.set(id, sceneItemToItem({
51836
+ if (grabbed) changes.set(id, placeItem(grabbed.item, frame, grabbed.parent, grabbed.box));
51837
+ else if (item) changes.set(id, sceneItemToItem({
50625
51838
  ...item,
50626
51839
  frame
50627
51840
  }, state.scene.layout));
@@ -50707,6 +51920,22 @@ function createSelectionModule(ctx) {
50707
51920
  return unlocked;
50708
51921
  }, state.selection);
50709
51922
  }
51923
+ const autoplayable = () => items().filter((item) => !item.locked && boardAutoplayKind(item));
51924
+ function autoplay() {
51925
+ const eligible = autoplayable();
51926
+ return eligible.length > 0 ? eligible.every((item) => item.autoplay) : null;
51927
+ }
51928
+ function setAutoplay(on) {
51929
+ edit((item) => {
51930
+ if (!boardAutoplayKind(item) || Boolean(item.autoplay) === on) return null;
51931
+ if (on) return {
51932
+ ...item,
51933
+ autoplay: true
51934
+ };
51935
+ const { autoplay: _autoplay, ...rest } = item;
51936
+ return rest;
51937
+ }, autoplayable().map((item) => item.id));
51938
+ }
50710
51939
  function setColor(color) {
50711
51940
  edit((item) => {
50712
51941
  switch (item.type) {
@@ -50796,6 +52025,7 @@ function createSelectionModule(ctx) {
50796
52025
  clear: () => set([]),
50797
52026
  selectAll: () => set(state.scene.children(void 0).slice()),
50798
52027
  framesFor,
52028
+ grab,
50799
52029
  placed,
50800
52030
  movable,
50801
52031
  carries,
@@ -50805,6 +52035,8 @@ function createSelectionModule(ctx) {
50805
52035
  canFillFrame: () => framed().length > 0,
50806
52036
  fillFrame,
50807
52037
  toggleLock,
52038
+ autoplay,
52039
+ setAutoplay,
50808
52040
  setColor,
50809
52041
  setStyle,
50810
52042
  setProps,
@@ -51049,6 +52281,9 @@ function createBoardEditor(options) {
51049
52281
  return items.length > 0 && items.every((item) => item.locked);
51050
52282
  });
51051
52283
  },
52284
+ get selectionAutoplay() {
52285
+ return read(["scene", "selection"], selection.autoplay);
52286
+ },
51052
52287
  get bounds() {
51053
52288
  return read(["scene", "selection"], selection.bounds);
51054
52289
  },
@@ -51292,6 +52527,7 @@ function createBoardEditor(options) {
51292
52527
  },
51293
52528
  fillFrame: selection.fillFrame,
51294
52529
  toggleSelectionLock: selection.toggleLock,
52530
+ setSelectionAutoplay: selection.setAutoplay,
51295
52531
  setSelectionColor: selection.setColor,
51296
52532
  setSelectionStyle: selection.setStyle,
51297
52533
  setSelectionProps: selection.setProps,
@@ -51710,6 +52946,7 @@ const DEFAULT_TOOLS = ["select", "hand"];
51710
52946
  //#endregion
51711
52947
  //#region ../sdk/src/board/stage/script-controller.ts
51712
52948
  const ACTIVATION_MS = 5e3;
52949
+ const MOTION_MS = 1e3;
51713
52950
  const USER_EVENTS = /* @__PURE__ */ new Set([
51714
52951
  "pointerdown",
51715
52952
  "pointerup",
@@ -51739,6 +52976,8 @@ function createBoardScriptController(options) {
51739
52976
  const interactive = /* @__PURE__ */ new Set();
51740
52977
  const screens = /* @__PURE__ */ new Set();
51741
52978
  const activations = /* @__PURE__ */ new Map();
52979
+ const emitFailures = /* @__PURE__ */ new Map();
52980
+ const moved = /* @__PURE__ */ new Map();
51742
52981
  const listeners = /* @__PURE__ */ new Set();
51743
52982
  let version = 0;
51744
52983
  let composed = {
@@ -51830,41 +53069,31 @@ function createBoardScriptController(options) {
51830
53069
  capabilities: {
51831
53070
  ...options.capabilities,
51832
53071
  "board.emit": async (id, value) => {
51833
- const message = value;
51834
- if (!message || typeof message.target !== "string" || typeof message.type !== "string" || !boardScriptScope(editor.document, id).has(message.target)) throw new Error("Invalid script event target.");
51835
- if (activated(id)) activations.set(message.target, activations.get(id) ?? now());
51836
- host?.event(message.target, {
51837
- type: message.type,
51838
- data: message.data
51839
- });
53072
+ try {
53073
+ const { target, event } = boardScriptEmit(editor.document, id, value);
53074
+ if (activated(id)) activations.set(target, activations.get(id) ?? now());
53075
+ if (host && !host.event(target, event)) throw new Error(`emit(${target}, "${event.type}") from ${id}: ${target} already has 128 events waiting.`);
53076
+ } catch (error) {
53077
+ emitFailures.set(id, error instanceof Error ? error.message : String(error));
53078
+ throw error;
53079
+ }
51840
53080
  },
51841
53081
  "board.commit": (id, value) => {
51842
53082
  const { patch, frame } = value;
51843
53083
  return commits.commit(id, patch, !frame && activated(id));
51844
53084
  },
51845
- "board.layoutText": async (_id, value) => {
51846
- const input = value;
51847
- if (!input || typeof input.text !== "string" || input.text.length > 1e4) throw new Error("layoutText() needs text of at most 10000 characters.");
51848
- for (const key of [
51849
- "fontSize",
51850
- "fontWeight",
51851
- "lineHeight",
51852
- "width"
51853
- ]) if (input[key] !== void 0 && !(Number.isFinite(input[key]) && input[key] > 0)) throw new Error(`layoutText() ${key} must be a positive number.`);
51854
- const { width, height } = layoutBoardText({
51855
- fontSize: 24,
51856
- fontWeight: 500,
51857
- font: "sans",
51858
- lineHeight: 4 / 3,
51859
- ...input
51860
- });
51861
- return {
51862
- width,
51863
- height
51864
- };
51865
- }
53085
+ "board.layoutText": async (_id, value) => layoutBoardScriptText(value)
51866
53086
  },
51867
53087
  onOutput: (id, output) => {
53088
+ const previous = outputs.get(id);
53089
+ if (output && previous && output.sceneVersion !== void 0 && output.sceneVersion === previous.sceneVersion) {
53090
+ Object.assign(previous, {
53091
+ uniforms: output.uniforms,
53092
+ passes: output.passes,
53093
+ version: output.version
53094
+ });
53095
+ return false;
53096
+ }
51868
53097
  if (output) {
51869
53098
  prepareBoardScriptOutput(editor.document, id, output);
51870
53099
  cancelPointers(id, output.hits);
@@ -51898,10 +53127,12 @@ function createBoardScriptController(options) {
51898
53127
  screens.clear();
51899
53128
  outputs.clear();
51900
53129
  activations.clear();
53130
+ emitFailures.clear();
51901
53131
  presses.clear();
51902
53132
  gesture = null;
51903
53133
  router.clear();
51904
53134
  editor.setScriptItems(/* @__PURE__ */ new Map());
53135
+ moved.clear();
51905
53136
  hover = null;
51906
53137
  composed = {
51907
53138
  ...composed,
@@ -51927,7 +53158,8 @@ function createBoardScriptController(options) {
51927
53158
  const items = composeBoardScriptItems(editor.document, editor.scene, outputs, animation, camera, (owner, error) => host?.fault(owner, error instanceof Error ? error.message : String(error)), editor.gestureActive ? editor.scene.layout : void 0);
51928
53159
  const presented = new Set([...outputs.values()].flatMap((output) => Object.keys(output.patches)));
51929
53160
  for (const id of animation.keys()) if (!presented.has(id)) items.delete(id);
51930
- editor.setScriptItems(items);
53161
+ const at = now();
53162
+ for (const id of editor.setScriptItems(items)) if (items.has(id)) moved.set(id, at);
51931
53163
  composed = {
51932
53164
  version,
51933
53165
  document: editor.document,
@@ -52104,6 +53336,9 @@ function createBoardScriptController(options) {
52104
53336
  get hovering() {
52105
53337
  return hover !== null;
52106
53338
  },
53339
+ get hovered() {
53340
+ return hover;
53341
+ },
52107
53342
  get paused() {
52108
53343
  return paused;
52109
53344
  },
@@ -52119,6 +53354,11 @@ function createBoardScriptController(options) {
52119
53354
  animated = next;
52120
53355
  },
52121
53356
  compose,
53357
+ moving() {
53358
+ const at = now();
53359
+ for (const [id, changed] of moved) if (at - changed > MOTION_MS) moved.delete(id);
53360
+ return moved.keys();
53361
+ },
52122
53362
  sync,
52123
53363
  pointer,
52124
53364
  key(event) {
@@ -52150,6 +53390,7 @@ function createBoardScriptController(options) {
52150
53390
  return current && !paused ? boardShaderOwners(scriptDocument(), outputs, (id) => current.clock(id)) : [];
52151
53391
  },
52152
53392
  error: (id) => host?.error(id) ?? null,
53393
+ emitFailures,
52153
53394
  async snapshot() {
52154
53395
  const result = {};
52155
53396
  await Promise.all([...outputs.keys()].map(async (id) => {
@@ -52178,6 +53419,24 @@ function createBoardScriptController(options) {
52178
53419
  //#endregion
52179
53420
  //#region ../sdk/src/board/testing/index.ts
52180
53421
  const FRAME_MS = 1e3 / 60;
53422
+ function describeInteraction(editor) {
53423
+ const interaction = editor.interaction;
53424
+ const ids = () => editor.selection.join(", ");
53425
+ switch (interaction.type) {
53426
+ case "idle":
53427
+ case "pressing": return null;
53428
+ case "translating": return interaction.moved ? `move ${[...interaction.origin.keys()].join(", ")}` : null;
53429
+ case "resizing": return `resize ${ids()}`;
53430
+ case "rotating": return `rotate ${ids()}`;
53431
+ case "brushing": return "select box";
53432
+ case "panning": return interaction.moved ? "pan" : null;
53433
+ case "drawing": return "draw";
53434
+ case "creatingBox": return `create ${interaction.kind}`;
53435
+ case "creatingArrow": return "create arrow";
53436
+ case "creatingText": return "create text";
53437
+ case "draggingArrowHandle": return `arrow ${interaction.which} handle`;
53438
+ }
53439
+ }
52181
53440
  async function createBoardScriptHarness(options) {
52182
53441
  const renderer = options.renderer ?? await createNodeBoardRenderer();
52183
53442
  const commits = [];
@@ -52241,7 +53500,7 @@ async function createBoardScriptHarness(options) {
52241
53500
  if (!runTimers() && !runtime?.queued) break;
52242
53501
  }
52243
53502
  }
52244
- function pointerEvent(point, phase, input = {}) {
53503
+ function pointerEvent(point, phase, input = {}, pressed = phase !== "up") {
52245
53504
  const { x, y, zoom } = editor.camera;
52246
53505
  return {
52247
53506
  pointerId: input.pointerId ?? 1,
@@ -52252,21 +53511,58 @@ async function createBoardScriptHarness(options) {
52252
53511
  ctrlKey: input.ctrlKey ?? false,
52253
53512
  metaKey: input.metaKey ?? false,
52254
53513
  button: 0,
52255
- buttons: phase === "up" ? 0 : 1,
53514
+ buttons: pressed ? 1 : 0,
52256
53515
  pointerType: input.pointerType ?? "mouse",
52257
53516
  cancelled: false,
52258
53517
  pressure: .5
52259
53518
  };
52260
53519
  }
52261
- async function pointer(phase, point, input) {
52262
- const event = pointerEvent(point, phase, input);
52263
- if (!controller.pointer(phase, event)) {
53520
+ let press = null;
53521
+ function editorHit(event) {
53522
+ const control = editor.tool === "select" && selectionTransformControlAt(editor.selectionTransform, event.world, editor.camera.zoom, event.pointerType, editor.controlOutset);
53523
+ if (control) return {
53524
+ on: "handle",
53525
+ handle: control.kind === "rotate" ? "rotate" : control.handle
53526
+ };
53527
+ const item = editor.pickAt(event.world, event.pointerType);
53528
+ if (item) return {
53529
+ on: "item",
53530
+ id: item.id,
53531
+ type: item.type
53532
+ };
53533
+ const under = editor.itemAt(event.world);
53534
+ return {
53535
+ on: "empty",
53536
+ ...under ? { under: under.id } : {}
53537
+ };
53538
+ }
53539
+ async function pointer(phase, point, input, pressed) {
53540
+ const event = pointerEvent(point, phase, input, pressed);
53541
+ const hit = phase === "down" ? editorHit(event) : null;
53542
+ const routed = controller.pointer(phase, event);
53543
+ const target = routed ? controller.hovered : null;
53544
+ if (phase === "down") press = {
53545
+ down: target ? {
53546
+ on: "script",
53547
+ ...target
53548
+ } : hit,
53549
+ taken: target ? `script ${target.owner}/${target.target}` : null
53550
+ };
53551
+ if (!routed) {
52264
53552
  if (phase === "down") editor.pointerDown(event);
52265
53553
  else if (phase === "move") editor.pointerMove(event);
52266
53554
  else editor.pointerUp(event);
52267
53555
  }
53556
+ if (press && !routed) press.taken = describeInteraction(editor) ?? press.taken;
52268
53557
  clock += FRAME_MS;
52269
53558
  await frame();
53559
+ if (phase !== "up" || !press) return null;
53560
+ const done = {
53561
+ down: press.down,
53562
+ taken: press.taken ?? (press.down.on === "empty" ? "nothing" : "tap")
53563
+ };
53564
+ press = null;
53565
+ return done;
52270
53566
  }
52271
53567
  await frame();
52272
53568
  return {
@@ -52282,6 +53578,10 @@ async function createBoardScriptHarness(options) {
52282
53578
  },
52283
53579
  output: (id) => controller.output(id),
52284
53580
  error: (id) => controller.error(id),
53581
+ get emitFailures() {
53582
+ return controller.emitFailures;
53583
+ },
53584
+ status: () => runtime?.status() ?? [],
52285
53585
  async advance(ms = FRAME_MS) {
52286
53586
  const end = clock + ms;
52287
53587
  while (clock < end) {
@@ -52292,15 +53592,19 @@ async function createBoardScriptHarness(options) {
52292
53592
  pointer,
52293
53593
  async tap(point, input) {
52294
53594
  await pointer("down", point, input);
52295
- await pointer("up", point, input);
53595
+ return await pointer("up", point, input);
52296
53596
  },
52297
53597
  async drag(points, input) {
52298
53598
  const [first, ...rest] = points;
52299
- if (!first) return;
53599
+ if (!first) return null;
52300
53600
  await pointer("down", first, input);
52301
53601
  for (const point of rest) await pointer("move", point, input);
52302
- await pointer("up", points.at(-1) ?? first, input);
53602
+ return pointer("up", points.at(-1) ?? first, input);
53603
+ },
53604
+ async move(points, input) {
53605
+ for (const point of points) await pointer("move", point, input, false);
52303
53606
  },
53607
+ snapshot: () => controller.snapshot(),
52304
53608
  async key(type, key) {
52305
53609
  controller.key({
52306
53610
  type,
@@ -52353,4 +53657,4 @@ async function createBoardScriptHarness(options) {
52353
53657
  };
52354
53658
  }
52355
53659
  //#endregion
52356
- export { BOARD_SCRIPT_DRAWING_EXAMPLE, BOARD_SCRIPT_RAIN_EXAMPLE, 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, measureBoardText, parseBoardDocument, planBoardExport, prepareBoardExport, selectBoardExportAssets };
53660
+ export { BOARD_SCRIPT_DRAWING_EXAMPLE, BOARD_SCRIPT_RAIN_EXAMPLE, boardAnimatesScriptParams, boardAssetKey, boardAssetKeySource, boardAutoplayLoops, boardFrameRegions, boardMediaRate, boardMediaSpans, boardPathTrack, boardPlacePatch, boardRegionStep, boardRenderTheme, boardScriptAttachments, boardSequence, boardSequencePatch, boardShaderParameters, boardTextureEdge, boardTexturePixels, boardTimedMedia, buildBoardScene, checkBoardShader, createBoardAnimationSampler, createBoardRenderSampler, createBoardScriptHarness, createNodeBoardRenderer, createNodeBoardScriptHost, describeBoardExportWarning, describeBoardScriptLanes, exportBoardImageBytes, hasBoardScripts, inspectBoardItems, inspectBoardScene, itemBounds, measureBoardText, parseBoardDocument, planBoardExport, prepareBoardExport, rectsIntersect, selectBoardExportAssets };