@rig-c/play 1.27.0 → 1.29.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.
@@ -1,4 +1,4 @@
1
- import { l as loadModel, R as RigPlayer, C as CanvasRenderer, d as discoverTurnDials, n as normalizedDial, r as rememberComposedClip, u as underNoSkin, p as poseRawSetup, f as frameOf, a as frameSource } from "./_play-runtime.js";
1
+ import { u as underNoSkin, o as openTrack, r as readModel, C as CORE_DOCUMENT_SPEC, p as poseRawAnimation, a as CoreInputError, l as loadModel, b as CanvasRenderer, R as RigPlayer, d as discoverTurnDials, n as normalizedDial, c as poseRawSetup, f as frameOf, e as frameSource, g as rememberComposedClip } from "./_play-runtime.js";
2
2
  const ORIGIN = { x: 0, y: 0 };
3
3
  const GAINS = { background: -0.55, figure: 0, foreground: 0.55 };
4
4
  const TIME_CONSTANT = 0.12;
@@ -79,6 +79,44 @@ function createCameraHandoff(transitionSeconds) {
79
79
  }
80
80
  };
81
81
  }
82
+ function createSceneClock(time, transitionSeconds, inside) {
83
+ let phase = time;
84
+ let last = time;
85
+ let from = inside ? 0 : 1;
86
+ let to = from;
87
+ let elapsed = transitionSeconds;
88
+ const integral = (u) => u * u * u * (1 - u / 2);
89
+ const rate = () => {
90
+ const u = transitionSeconds === 0 ? 1 : Math.min(1, elapsed / transitionSeconds);
91
+ return from + (to - from) * u * u * (3 - 2 * u);
92
+ };
93
+ return {
94
+ get phase() {
95
+ return phase;
96
+ },
97
+ aim(hover) {
98
+ const target = hover ? 0 : 1;
99
+ if (target === to) return;
100
+ from = rate();
101
+ to = target;
102
+ elapsed = 0;
103
+ },
104
+ advance(time2) {
105
+ const dt = time2 - last;
106
+ if (!(dt > 0)) return;
107
+ last = time2;
108
+ const ramp = Math.min(dt, Math.max(0, transitionSeconds - elapsed));
109
+ if (ramp > 0) {
110
+ const a = elapsed / transitionSeconds;
111
+ elapsed += ramp;
112
+ const b = elapsed / transitionSeconds;
113
+ const advance = ramp * from + (to - from) * transitionSeconds * (integral(b) - integral(a));
114
+ phase += Math.min(ramp, Math.max(0, advance));
115
+ }
116
+ phase += (dt - ramp) * to;
117
+ }
118
+ };
119
+ }
82
120
  function planeOffsets(camera, mode) {
83
121
  if (mode === "fixed") return { background: ORIGIN, figure: ORIGIN, foreground: ORIGIN };
84
122
  return {
@@ -87,12 +125,569 @@ function planeOffsets(camera, mode) {
87
125
  foreground: planeShift(camera, mode === "pan" ? 1 : GAINS.foreground)
88
126
  };
89
127
  }
128
+ const SCENE_CAMERA_REPORT_MAX_BYTES = 8 * 1024 * 1024;
129
+ const PAN_CURVE_LENGTH = 8;
130
+ const SHA256 = /^[a-f0-9]{64}$/;
131
+ const floatBits = new DataView(new ArrayBuffer(4));
132
+ const typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);
133
+ function isReportBytes(value) {
134
+ return ArrayBuffer.isView(value) && Reflect.get(typedArrayPrototype, Symbol.toStringTag, value) === "Uint8Array";
135
+ }
136
+ function checkSceneCameraReportSize(byteLength, refuse) {
137
+ if (byteLength > SCENE_CAMERA_REPORT_MAX_BYTES) {
138
+ refuse(
139
+ "SCENE_CAMERA_REPORT_TOO_LARGE",
140
+ `observed ${byteLength} raw report bytes with a cap of ${SCENE_CAMERA_REPORT_MAX_BYTES} bytes`
141
+ );
142
+ }
143
+ }
144
+ function decodeSceneCameraReport(bytes, refuse) {
145
+ const byteLength = Reflect.get(typedArrayPrototype, "byteLength", bytes);
146
+ checkSceneCameraReportSize(byteLength, refuse);
147
+ try {
148
+ const buffer = Reflect.get(typedArrayPrototype, "buffer", bytes);
149
+ const byteOffset = Reflect.get(typedArrayPrototype, "byteOffset", bytes);
150
+ const view = new Uint8Array(buffer, byteOffset, byteLength);
151
+ return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(view));
152
+ } catch (error) {
153
+ return refuse("SCENE_CAMERA_REPORT_INVALID", "the scene report is not valid UTF-8 JSON", error);
154
+ }
155
+ }
156
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
157
+ const finite = (value) => typeof value === "number" && Number.isFinite(value);
158
+ const durationValue = (value) => finite(value) && value >= 0;
159
+ const positive = (value) => finite(value) && value > 0;
160
+ const usableZoom = (zoom) => positive(zoom) && positive(1 / zoom);
161
+ const isDigest = (value) => typeof value === "string" && SHA256.test(value);
162
+ const matchesSample = (a, b) => a.pan[0] === b.pan[0] && a.pan[1] === b.pan[1] && a.zoom === b.zoom;
163
+ function readCameraHeader(report, refuse) {
164
+ if (isRecord(report) && report.spec === "spine-parts-scene-report/1") return null;
165
+ if (!isRecord(report) || report.spec !== "spine-parts-scene-report/2" || !isRecord(report.camera)) {
166
+ return refuse("SCENE_CAMERA_REPORT_INVALID", "expected a scene report /1 or a scene report /2 with a camera record");
167
+ }
168
+ const { canvas, camera } = report;
169
+ const { backdrop, fps, coverage, tracks, model_sha256: digest } = camera;
170
+ if (typeof backdrop !== "string" || !backdrop.length || fps !== 12 || !isRecord(tracks) || Object.keys(tracks).length === 0 || !isRecord(coverage) || coverage.status !== "PASS" || coverage.max_edge_overrun_px !== 0 || coverage.nonopaque_source_texels !== 0 || coverage.nonopaque_output_pixels !== 0 || !isRecord(canvas) || !positive(canvas.width) || !positive(canvas.height)) {
171
+ return refuse("SCENE_CAMERA_REPORT_INVALID", "expected a canvas and a keyed 12 fps camera with PASS coverage and zero overruns and alpha counts");
172
+ }
173
+ return { width: canvas.width, height: canvas.height, backdrop, fps, tracks, digest };
174
+ }
175
+ function requireDigest(digest, refuse) {
176
+ if (digest === void 0 || digest === null) {
177
+ return refuse("SCENE_CAMERA_MODEL_MISMATCH", "the scene camera report needs a model SHA-256");
178
+ }
179
+ if (!isDigest(digest)) return refuse("SCENE_CAMERA_REPORT_INVALID", "the model SHA-256 must be 64 lowercase hexadecimal digits");
180
+ return digest;
181
+ }
182
+ function sceneCameraModelDigest(report, refuse) {
183
+ const camera = readCameraHeader(report, refuse);
184
+ return camera === null ? null : requireDigest(camera.digest, refuse);
185
+ }
186
+ const numericBoneChannels = {
187
+ translate: ["x", "y"],
188
+ translatex: ["x"],
189
+ translatey: ["y"],
190
+ scale: ["scaleX", "scaleY"],
191
+ scalex: ["scaleX"],
192
+ scaley: ["scaleY"],
193
+ shear: ["shearX", "shearY"],
194
+ shearx: ["shearX"],
195
+ sheary: ["shearY"],
196
+ rotate: ["rotation"]
197
+ };
198
+ const nameEscapes = { "%25": "%", "%20": " ", "%2E": ".", "%2F": "/" };
199
+ const encodedBone = /^bone ((?:[^%. /]|%25|%20|%2E|%2F)+)\.([a-z]+)$/;
200
+ function bindSceneHold(report, doc, name, view, loop, backdrop, dialBones) {
201
+ const reject = (reason) => ({ behavior: "refused", reason });
202
+ if (!isRecord(report) || !Object.hasOwn(report, "scene_driven")) return { behavior: "additive" };
203
+ const declaration = report.scene_driven;
204
+ if (!isRecord(declaration)) return reject("invalid scene_driven declaration");
205
+ if (!Object.hasOwn(declaration, name)) return { behavior: "additive" };
206
+ const take = declaration[name];
207
+ if (!isRecord(take) || typeof take.view !== "boolean" || !Array.isArray(take.timelines)) {
208
+ return reject(`invalid scene_driven entry for ${JSON.stringify(name)}`);
209
+ }
210
+ if (report.spec !== "spine-parts-scene-report/2") return reject("scene report /1 has no digest-bound keyed camera");
211
+ if (take.view !== (view !== null)) return reject(`scene_driven.view disagrees with keyed camera for ${JSON.stringify(name)}`);
212
+ if (!take.view) return reject(`scene_driven.view is false for ${JSON.stringify(name)}`);
213
+ if (!loop) return reject(`non-looping take ${JSON.stringify(name)}`);
214
+ const animation = doc.animations.find((row) => row.name === name);
215
+ if (animation === void 0) return reject(`unknown take ${JSON.stringify(name)}`);
216
+ const source = animation.timelines;
217
+ const selected = /* @__PURE__ */ new Map();
218
+ const channels = /* @__PURE__ */ new Map();
219
+ for (const address of take.timelines) {
220
+ const match = typeof address === "string" ? encodedBone.exec(address) : null;
221
+ if (match === null || match[0] !== address || !Object.hasOwn(numericBoneChannels, match[2])) {
222
+ return reject(`unsupported or malformed timeline address ${JSON.stringify(address)}`);
223
+ }
224
+ const bone = match[1].replace(/%25|%20|%2E|%2F/g, (escape) => nameEscapes[escape]);
225
+ const property = match[2];
226
+ const target = source.bones.find((row) => row.name === bone);
227
+ if (!target?.timelines.some((timeline) => timeline.kind === property) || selected.get(bone)?.has(property)) {
228
+ return reject(`unresolved or repeated timeline address ${JSON.stringify(address)}`);
229
+ }
230
+ const properties = selected.get(bone) ?? /* @__PURE__ */ new Set();
231
+ properties.add(property);
232
+ selected.set(bone, properties);
233
+ const fields = channels.get(bone) ?? /* @__PURE__ */ new Set();
234
+ for (const field of numericBoneChannels[property]) {
235
+ fields.add(field);
236
+ }
237
+ channels.set(bone, fields);
238
+ }
239
+ for (const target of source.bones) {
240
+ const fields = channels.get(target.name);
241
+ if (!fields) continue;
242
+ for (const { kind } of target.timelines) {
243
+ if (kind === "inherit" || selected.get(target.name)?.has(kind)) continue;
244
+ if (numericBoneChannels[kind].some((field) => fields.has(field))) {
245
+ return reject(`scene and life timelines share a local on bone ${JSON.stringify(target.name)}.${kind}`);
246
+ }
247
+ }
248
+ }
249
+ const slot = doc.slots.find((row) => row.name === backdrop);
250
+ if (!slot) return reject(`unresolved backdrop slot ${JSON.stringify(backdrop)}`);
251
+ const skin = doc.skins.find((row) => row.name === "default");
252
+ const region = slot.setup === null ? void 0 : skin?.attachments[slot.name]?.[slot.setup];
253
+ if (region?.kind !== "region") return reject(`backdrop slot ${JSON.stringify(backdrop)} needs a stable setup region`);
254
+ const ancestry = /* @__PURE__ */ new Set();
255
+ const bonesByName = new Map(doc.bones.map((bone) => [bone.name, bone]));
256
+ for (let bone = bonesByName.get(slot.bone); bone !== void 0; bone = bone.parent === void 0 ? void 0 : bonesByName.get(bone.parent)) {
257
+ ancestry.add(bone.name);
258
+ }
259
+ for (const bone of ancestry) {
260
+ const live = source.bones.find((row) => row.name === bone)?.timelines.find((timeline) => !selected.get(bone)?.has(timeline.kind));
261
+ if (live) return reject(`backdrop ${JSON.stringify(backdrop)} depends on live bone ${JSON.stringify(bone)}.${live.kind}`);
262
+ if (dialBones.has(bone)) return reject(`backdrop ${JSON.stringify(backdrop)} depends on pointer dial bone ${JSON.stringify(bone)}`);
263
+ }
264
+ const slotKey = source.slots.find((row) => row.name === backdrop)?.timelines[0];
265
+ if (slotKey) return reject(`backdrop slot ${JSON.stringify(backdrop)} has a live ${slotKey.kind} timeline`);
266
+ if (source.attachments.some((row) => row.slot === backdrop)) {
267
+ return reject(`backdrop slot ${JSON.stringify(backdrop)} has a live attachment timeline`);
268
+ }
269
+ if (source.drawOrder.length) return reject("backdrop depends on live drawOrder");
270
+ const backdropIndex = doc.slots.indexOf(slot);
271
+ for (const [index, earlier] of doc.slots.slice(0, backdropIndex).entries()) {
272
+ for (const attachment of Object.values(skin?.attachments[earlier.name] ?? {})) {
273
+ const geometry = attachment.geometry;
274
+ if (geometry?.kind !== "clipping") continue;
275
+ const end = doc.slots.findIndex((row) => row.name === geometry.end);
276
+ if (end <= index || end >= backdropIndex) {
277
+ return reject(`backdrop ${JSON.stringify(backdrop)} depends on clipping slot ${JSON.stringify(earlier.name)}`);
278
+ }
279
+ }
280
+ }
281
+ for (const { record } of doc.constraints) {
282
+ if (record === void 0) continue;
283
+ const writesBackdrop = record.kind === "slider" ? record.timelines.bones.some((row) => ancestry.has(row.name)) || record.timelines.slots.some((row) => row.name === backdrop) || record.timelines.attachments.some((row) => row.slot === backdrop) || record.timelines.drawOrder.length > 0 : record.kind === "physics" ? ancestry.has(record.bone) : record.bones.some((bone) => ancestry.has(bone));
284
+ if (writesBackdrop) return reject(`backdrop ${JSON.stringify(backdrop)} depends on ${record.kind} constraint ${JSON.stringify(record.name)}`);
285
+ }
286
+ const backdropSteps = /* @__PURE__ */ new Set();
287
+ for (const { name: name2, timelines } of source.bones) {
288
+ if (!ancestry.has(name2)) continue;
289
+ for (const { keys } of timelines) {
290
+ for (let i = 1; i < keys.length; i++) {
291
+ if (keys[i - 1].curve === "stepped") backdropSteps.add(keys[i].time);
292
+ }
293
+ }
294
+ }
295
+ const owned = [...channels].map(([name2, fields]) => ({ name: name2, fields: [...fields], values: [] }));
296
+ const sampleDoc = underNoSkin(doc);
297
+ let sampler;
298
+ const openSampler = () => openTrack(sampleDoc, name, {
299
+ loop: true,
300
+ reset: "animation",
301
+ // Read authored values before the solve. The sampler has no physics history
302
+ // to advance and its raw poses and events are discarded.
303
+ clock: () => 0,
304
+ adjust(locals) {
305
+ for (const { name: name2, fields, values } of owned) {
306
+ const local = locals.bone(name2);
307
+ for (const [i, field] of fields.entries()) values[i] = local[field];
308
+ }
309
+ }
310
+ });
311
+ return {
312
+ behavior: "hold",
313
+ backdropSteps,
314
+ apply(bones, time) {
315
+ if (owned.length === 0) return;
316
+ const previous = sampler?.trackTime ?? 0;
317
+ if (sampler === void 0 || time < previous || previous + (time - previous) !== time) {
318
+ sampler = openSampler();
319
+ }
320
+ if (time !== sampler.trackTime) sampler.step(time - sampler.trackTime);
321
+ for (const { name: name2, fields, values } of owned) {
322
+ const live = bones.bone(name2);
323
+ for (const [i, field] of fields.entries()) live[field] = values[i];
324
+ }
325
+ }
326
+ };
327
+ }
328
+ function finiteTuple(value, length) {
329
+ return Array.isArray(value) && value.length === length && [...value].every(finite);
330
+ }
331
+ function sceneCameraDriftEvidence(report, refuse) {
332
+ const camera = readCameraHeader(report, refuse);
333
+ if (!camera) return null;
334
+ const { backdrop, width, height, fps, tracks } = camera;
335
+ return {
336
+ backdrop,
337
+ failure(animation, pointer, sweep, backingPixel) {
338
+ const track = tracks[animation];
339
+ if (!isRecord(track) || !durationValue(track.duration) || !durationValue(track.compiled_duration) || !Array.isArray(track.frames)) return "missing sampled backdrop geometry";
340
+ const { duration, compiled_duration: compiled, frames } = track;
341
+ const ticks = Math.ceil(duration * fps);
342
+ const terminal = ticks > 0 && (ticks - 1) / fps >= duration ? ticks - 1 : ticks;
343
+ if (ticks >= 4294967295 || frames.length !== terminal + 1) {
344
+ return `incomplete sampled backdrop geometry at ${fps} fps through ${duration} s`;
345
+ }
346
+ for (const [i, row] of frames.entries()) {
347
+ const at = i === terminal ? duration : i / fps;
348
+ const label = `sample ${i} at ${at} authored s`;
349
+ if (!isRecord(row) || row.frame !== i || row.authored_time !== at || row.compiled_time !== (i === terminal ? compiled : at / duration * compiled) || !usableZoom(row.zoom) || !finiteTuple(row.view, 4) || !Array.isArray(row.backdrop_quad) || row.backdrop_quad.length !== 4 || ![...row.backdrop_quad].every((point) => finiteTuple(point, 2))) {
350
+ return `${label} has invalid backdrop evidence`;
351
+ }
352
+ const { zoom, view: [left, top, right, bottom], backdrop_quad: quad } = row;
353
+ const viewWidth = right - left, viewHeight = bottom - top;
354
+ const tolerance = 4 * Number.EPSILON * Math.max(1, Math.abs(left), Math.abs(top), Math.abs(right), Math.abs(bottom));
355
+ if (!positive(viewWidth) || !positive(viewHeight) || Math.abs(viewWidth - width / zoom) > tolerance || Math.abs(viewHeight - height / zoom) > tolerance) {
356
+ return `${label} has a view inconsistent with its output size and zoom`;
357
+ }
358
+ const px = pointer.x / zoom, py = pointer.y / zoom;
359
+ const sx = sweep.x / zoom, sy = sweep.y / zoom;
360
+ if (![px, py, sx, sy].every(finite)) return `${label} has a nonfinite scene excursion`;
361
+ const gx = backingPixel.x / zoom, gy = backingPixel.y / zoom;
362
+ if (!positive(gx) || !positive(gy)) return `${label} has an invalid backing-pixel edge guard`;
363
+ const edgeTolerance2 = Math.max(tolerance, 4 * Number.EPSILON * Math.max(...quad.flat().map(Math.abs)));
364
+ let winding = 0;
365
+ for (const [edge, [x, y]] of quad.entries()) {
366
+ const [nextX, nextY] = quad[(edge + 1) % 4];
367
+ const dx = nextX - x, dy = nextY - y;
368
+ const length = Math.hypot(dx, dy);
369
+ const nx = -dy / length, ny = dx / length;
370
+ const distance = ([a2, b2]) => nx * (a2 - x) + ny * (b2 - y);
371
+ const a = distance(quad[(edge + 2) % 4]), b = distance(quad[(edge + 3) % 4]);
372
+ if (edge === 0) winding = Math.sign(a);
373
+ const side = ["left", "top", "right", "bottom"][edge];
374
+ if (!positive(length) || !finite(a) || !finite(b) || !(a * winding > 0 && b * winding > 0)) {
375
+ return `${label} has an invalid convex backdrop quad at its ${side} edge`;
376
+ }
377
+ const margin = winding * distance([nx * winding >= 0 ? left : right, ny * winding >= 0 ? top : bottom]);
378
+ const excursion = Math.max(Math.abs(nx * px) + Math.abs(ny * py), Math.abs(nx * sx + ny * sy));
379
+ if (!finite(margin) || !finite(excursion)) return `${label} has nonfinite ${side} edge margin or excursion`;
380
+ const guard = Math.abs(nx) * gx + Math.abs(ny) * gy;
381
+ const requiredExcursion = excursion + guard;
382
+ if (!positive(guard) || !finite(requiredExcursion)) return `${label} has an invalid ${side} edge guard or guarded excursion`;
383
+ if (margin - requiredExcursion < -edgeTolerance2) {
384
+ return `${label}, ${side} edge margin ${margin} scene px, required excursion ${excursion} scene px, edge guard ${guard} scene px`;
385
+ }
386
+ }
387
+ }
388
+ return void 0;
389
+ }
390
+ };
391
+ }
392
+ function storedFloat32(value) {
393
+ const rounded = Math.fround(value);
394
+ if (rounded === 0 || !Number.isFinite(rounded)) return rounded === 0 ? 0 : rounded;
395
+ const magnitude = Math.abs(rounded);
396
+ const sign = rounded < 0 ? "-" : "";
397
+ floatBits.setFloat32(0, magnitude);
398
+ const word = floatBits.getUint32(0);
399
+ const exponent = word >>> 23;
400
+ const significand = BigInt(word & 8388607 | (exponent === 0 ? 0 : 8388608));
401
+ const doubledPower = (exponent === 0 ? -149 : exponent - 150) + 1;
402
+ for (let digits = 1; digits <= 9; digits++) {
403
+ const [mantissa, power] = magnitude.toExponential(digits - 1).split("e");
404
+ const nearest = BigInt(mantissa.replace(".", ""));
405
+ const scale = Number(power) - (digits - 1);
406
+ const candidates = [nearest - 1n, nearest, nearest + 1n].filter(
407
+ (candidate) => candidate > 0n && Math.fround(Number(`${candidate}e${scale}`)) === magnitude
408
+ );
409
+ if (candidates.length === 0) continue;
410
+ const chosen = candidates.reduce((a, b) => {
411
+ let midpoint = a + b;
412
+ let float = significand;
413
+ if (scale >= 0) midpoint *= 10n ** BigInt(scale);
414
+ else float *= 10n ** BigInt(-scale);
415
+ if (doubledPower >= 0) float <<= BigInt(doubledPower);
416
+ else midpoint <<= BigInt(-doubledPower);
417
+ return midpoint < float || midpoint === float && b % 2n === 0n ? b : a;
418
+ });
419
+ return Number(`${sign}${chosen}e${scale}`);
420
+ }
421
+ return rounded;
422
+ }
423
+ function storedTime(time) {
424
+ const named = storedFloat32(time);
425
+ const nearest = Math.fround(time);
426
+ if (named === time || nearest <= time || !Number.isFinite(nearest)) return named;
427
+ floatBits.setFloat32(0, nearest);
428
+ floatBits.setUint32(0, floatBits.getUint32(0) - 1);
429
+ return storedFloat32(floatBits.getFloat32(0));
430
+ }
431
+ function coreSampler(keys, duration, label, refuse) {
432
+ const times = keys.map((key) => storedTime(key.t));
433
+ for (const [i, key] of keys.entries()) {
434
+ if (!Number.isFinite(times[i]) || i > 0 && times[i] <= times[i - 1] || !key.pan.every((value) => Number.isFinite(Math.fround(value))) || !positive(Math.fround(1 / key.zoom))) {
435
+ refuse("SCENE_CAMERA_REPORT_INVALID", `${label} key ${i} cannot be stored in a float32 translation timeline`);
436
+ }
437
+ }
438
+ const name = "camera";
439
+ try {
440
+ const doc = readModel(JSON.stringify({
441
+ spec: CORE_DOCUMENT_SPEC,
442
+ referenceScale: 1,
443
+ stage: null,
444
+ bones: [{ name: "pan" }, { name: "span" }],
445
+ slots: [],
446
+ skins: [],
447
+ constraints: [],
448
+ events: [],
449
+ animations: [{
450
+ name,
451
+ duration,
452
+ slots: [],
453
+ constraints: { ik: [], transform: [], path: [], physics: [], slider: [] },
454
+ attachments: [],
455
+ drawOrder: [],
456
+ events: [],
457
+ bones: [
458
+ { name: "pan", timelines: [{ name: "translate", keys: keys.map((key, i) => ({
459
+ time: times[i],
460
+ x: storedFloat32(key.pan[0]),
461
+ y: storedFloat32(key.pan[1]),
462
+ curve: Array.isArray(key.curve) ? key.curve.slice(0, PAN_CURVE_LENGTH) : key.curve
463
+ })) }] },
464
+ { name: "span", timelines: [{ name: "translatex", keys: keys.map((key, i) => ({
465
+ time: times[i],
466
+ value: storedFloat32(1 / key.zoom),
467
+ curve: Array.isArray(key.curve) ? key.curve.slice(PAN_CURVE_LENGTH) : key.curve
468
+ })) }] }
469
+ ]
470
+ }],
471
+ editorOrder: { skins: [], animations: [name] },
472
+ images: [],
473
+ pageGrids: [],
474
+ droppedStates: [],
475
+ absentParts: [],
476
+ meshBones: [],
477
+ meshes: [],
478
+ physics: [],
479
+ deformTransforms: [],
480
+ trackDerivations: [],
481
+ rig: {},
482
+ pages: [],
483
+ spine: { sha256: "0".repeat(64) }
484
+ }), label);
485
+ return (time) => {
486
+ try {
487
+ const [pan, span] = poseRawAnimation(doc, name, time === 0 ? [] : [time]).at(-1).bones;
488
+ const zoom = 1 / span.worldX;
489
+ if (!finite(pan.worldX) || !finite(pan.worldY) || !usableZoom(zoom)) {
490
+ return refuse("SCENE_CAMERA_VIEW_INVALID", `${label} evaluates at ${time} s to nonfinite pan or unusable zoom`);
491
+ }
492
+ return { pan: [pan.worldX, pan.worldY], zoom };
493
+ } catch (error) {
494
+ if (!(error instanceof CoreInputError)) throw error;
495
+ return refuse("SCENE_CAMERA_VIEW_INVALID", `${label} cannot be evaluated at ${time} s`, error);
496
+ }
497
+ };
498
+ } catch (error) {
499
+ if (!(error instanceof CoreInputError)) throw error;
500
+ return refuse("SCENE_CAMERA_REPORT_INVALID", `${label} cannot be read as a Core timeline`, error);
501
+ }
502
+ }
503
+ function validViewport(view) {
504
+ return isRecord(view) && finite(view.x) && finite(view.y) && positive(view.width) && positive(view.height) && finite(view.x + view.width) && view.x + view.width > view.x && finite(view.y + view.height) && view.y + view.height > view.y;
505
+ }
506
+ function cameraView(stage, { pan, zoom }, label, refuse) {
507
+ const centerX = stage.x + stage.width / 2 + pan[0];
508
+ const centerY = stage.y + (stage.height - (stage.height / 2 + pan[1]));
509
+ const halfWidth = stage.width / zoom / 2;
510
+ const halfHeight = stage.height / zoom / 2;
511
+ const x = centerX - halfWidth;
512
+ const y = centerY - halfHeight;
513
+ const width = centerX + halfWidth - x;
514
+ const height = centerY + halfHeight - y;
515
+ const view = { x, y, width, height };
516
+ if (!usableZoom(zoom) || !validViewport(view) || !positive(width * zoom) || !positive(height * zoom)) {
517
+ refuse("SCENE_CAMERA_VIEW_INVALID", `${label} needs a finite, positive, noncollapsed camera view`);
518
+ }
519
+ return view;
520
+ }
521
+ function readTrack(raw, compiled, stage, label, refuse) {
522
+ if (!isRecord(raw) || !durationValue(raw.duration) || !durationValue(raw.compiled_duration) || typeof raw.loop !== "boolean" || !Array.isArray(raw.keys) || raw.keys.length === 0 || !Array.isArray(raw.frames)) {
523
+ return refuse("SCENE_CAMERA_REPORT_INVALID", `${label} needs keys, durations, a loop flag and a frames list`);
524
+ }
525
+ const { duration, loop } = raw;
526
+ if (raw.compiled_duration !== compiled || duration === 0 !== (compiled === 0)) {
527
+ refuse("SCENE_CAMERA_CLIP_MISMATCH", `${label} cannot map ${duration} authored s and ${raw.compiled_duration} reported compiled s to ${compiled} model s`);
528
+ }
529
+ const keys = [];
530
+ for (const [i, key] of raw.keys.entries()) {
531
+ const at = `${label} key ${i}`;
532
+ if (!isRecord(key) || Object.keys(key).some((field) => !["t", "pan", "zoom", "curve"].includes(field))) {
533
+ return refuse("SCENE_CAMERA_REPORT_INVALID", `${at} needs normalized t, pan, zoom and an optional outgoing curve`);
534
+ }
535
+ const { t, pan, zoom, curve } = key;
536
+ if (!finite(t) || (i === 0 ? t !== 0 : t <= keys[i - 1].t) || !Array.isArray(pan) || pan.length !== 2 || !finite(pan[0]) || !finite(pan[1]) || !usableZoom(zoom)) {
537
+ return refuse("SCENE_CAMERA_REPORT_INVALID", `${at} needs ordered finite seconds from zero, finite pan and positive zoom`);
538
+ }
539
+ if (curve !== void 0) {
540
+ const validCurve = curve === "stepped" || Array.isArray(curve) && curve.length === 12 && [...curve].every(
541
+ (value) => finite(value) && Number.isFinite(Math.fround(value)) && storedFloat32(value) === value
542
+ );
543
+ if (!validCurve || i === raw.keys.length - 1) {
544
+ return refuse("SCENE_CAMERA_REPORT_INVALID", `${at} needs a nonterminal outgoing curve (stepped or twelve float32 decimals)`);
545
+ }
546
+ }
547
+ const normalized = { t, pan: [pan[0], pan[1]], zoom, curve: Array.isArray(curve) ? [...curve] : curve };
548
+ cameraView(stage, normalized, at, refuse);
549
+ keys.push(normalized);
550
+ }
551
+ const first = keys[0], last = keys[keys.length - 1];
552
+ if (last.t !== duration || loop && !matchesSample(first, last)) {
553
+ refuse("SCENE_CAMERA_REPORT_INVALID", `${label} must end at its authored duration and close exactly when looped`);
554
+ }
555
+ const core = keys.some((key) => key.curve !== void 0) ? coreSampler(keys, duration, label, refuse) : void 0;
556
+ const start = core?.(0), end = core?.(Math.fround(storedTime(duration)));
557
+ if (start && end && loop && !matchesSample(start, end)) {
558
+ refuse("SCENE_CAMERA_REPORT_INVALID", `${label} must close exactly at the Core-evaluated loop endpoints`);
559
+ }
560
+ const easedStart = first.curve !== void 0;
561
+ const easedEnd = keys.at(-2)?.curve !== void 0;
562
+ const easedSeam = loop && (easedStart || easedEnd);
563
+ if (start && (easedSeam || easedStart)) cameraView(stage, start, label, refuse);
564
+ if (end && (easedSeam || easedEnd)) cameraView(stage, end, label, refuse);
565
+ const compiledKeys = keys.map((key) => key.t === duration ? compiled : key.t / duration * compiled);
566
+ const authoredKeys = new Map(compiledKeys.map((time, i) => [time, keys[i].t]));
567
+ return {
568
+ duration,
569
+ compiledDuration: compiled,
570
+ loop,
571
+ authoredTime(time) {
572
+ return authoredKeys.get(time) ?? time / compiled * duration;
573
+ },
574
+ sample(time, compiledTime, backdropSteps) {
575
+ if (time === 0 && (easedSeam || easedStart) && start) return start;
576
+ if (time === duration && (easedSeam || easedEnd) && end) return end;
577
+ const sharedStep = (i) => i > 0 && i < keys.length - 1 && keys[i - 1].curve === "stepped" && backdropSteps?.has(Math.fround(compiledKeys[i]));
578
+ let low = 0, high = keys.length - 1;
579
+ while (low < high) {
580
+ const mid = Math.ceil((low + high) / 2);
581
+ const boundary = compiledTime === void 0 ? keys[mid].t : sharedStep(mid) ? Math.fround(compiledKeys[mid]) : compiledKeys[mid];
582
+ if (boundary <= (compiledTime ?? time)) low = mid;
583
+ else high = mid - 1;
584
+ }
585
+ const from = keys[low], to = keys[low + 1];
586
+ if (compiledTime !== void 0 && sharedStep(low)) time = Math.max(from.t, time);
587
+ if (from.curve === "stepped" && core && compiledTime !== void 0) return core(from.t);
588
+ if (from.curve !== void 0 && core) return core(time);
589
+ if (time === from.t || to === void 0) return from;
590
+ const phase = (time - from.t) / (to.t - from.t);
591
+ const mix = (a, b) => a + (b - a) * phase;
592
+ return { pan: [mix(from.pan[0], to.pan[0]), mix(from.pan[1], to.pan[1])], zoom: 1 / mix(1 / from.zoom, 1 / to.zoom) };
593
+ }
594
+ };
595
+ }
596
+ function cameraTimes(track, clock, refuse) {
597
+ const { duration, compiledDuration, loop } = track;
598
+ if (isRecord(clock) && clock.endpoint === "terminal" && !("basis" in clock) && !("seconds" in clock)) {
599
+ return { authoredSeconds: duration, compiledSeconds: compiledDuration };
600
+ }
601
+ if (!isRecord(clock) || clock.endpoint !== void 0 && clock.endpoint !== "phase" || clock.basis !== "authored" && clock.basis !== "compiled" || !durationValue(clock.seconds)) {
602
+ return refuse("SCENE_CAMERA_CLOCK_INVALID", "expected terminal or finite nonnegative phase seconds on the authored or compiled clock");
603
+ }
604
+ const authored = clock.basis === "authored";
605
+ const limit = authored ? duration : compiledDuration;
606
+ const otherLimit = authored ? compiledDuration : duration;
607
+ const time = limit === 0 || clock.seconds === 0 ? 0 : loop ? clock.seconds % limit : Math.min(clock.seconds, limit);
608
+ const otherTime = time === limit ? otherLimit : authored ? time / limit * otherLimit : track.authoredTime(time);
609
+ return authored ? { authoredSeconds: time, compiledSeconds: otherTime } : { authoredSeconds: otherTime, compiledSeconds: time };
610
+ }
611
+ function bindSceneCameraReport(report, model, refuse) {
612
+ const document = isReportBytes(report) ? decodeSceneCameraReport(report, refuse) : report;
613
+ const camera = readCameraHeader(document, refuse);
614
+ if (camera === null) return null;
615
+ if (!validViewport(model?.stage)) return refuse("SCENE_CAMERA_VIEW_INVALID", "the model needs a finite, positive, noncollapsed stage");
616
+ if (model.sha256 !== requireDigest(camera.digest, refuse)) {
617
+ refuse("SCENE_CAMERA_MODEL_MISMATCH", "the scene camera SHA-256 does not match the consumed model");
618
+ }
619
+ const { x, y, width, height } = model.stage;
620
+ const stage = { x, y, width, height };
621
+ if (camera.width !== stage.width || camera.height !== stage.height) {
622
+ refuse("SCENE_CAMERA_MODEL_MISMATCH", "the report canvas dimensions must match the model stage");
623
+ }
624
+ const durations = /* @__PURE__ */ new Map();
625
+ if (!Array.isArray(model.animations)) refuse("SCENE_CAMERA_CLIP_MISMATCH", "the model needs an animation list");
626
+ for (const animation of model.animations) {
627
+ if (!isRecord(animation) || typeof animation.name !== "string" || !animation.name.length || durations.has(animation.name) || !durationValue(animation.duration)) {
628
+ refuse("SCENE_CAMERA_CLIP_MISMATCH", "the model needs unique animation names with finite nonnegative durations");
629
+ }
630
+ durations.set(animation.name, animation.duration);
631
+ }
632
+ const bound = /* @__PURE__ */ new Map();
633
+ for (const [animation, raw] of Object.entries(camera.tracks)) {
634
+ const label = `scene camera track ${JSON.stringify(animation)}`;
635
+ const duration = durations.get(animation);
636
+ if (duration === void 0) return refuse("SCENE_CAMERA_CLIP_MISMATCH", `${label} is absent from the model`);
637
+ bound.set(animation, readTrack(raw, duration, stage, label, refuse));
638
+ }
639
+ const output = Object.freeze({ width: stage.width, height: stage.height });
640
+ return Object.freeze({
641
+ sample(animation, clock, backdropSteps) {
642
+ if (!durations.has(animation)) refuse("SCENE_CAMERA_CLIP_MISMATCH", `unknown model animation ${JSON.stringify(animation)}`);
643
+ const track = bound.get(animation);
644
+ if (!track) return null;
645
+ const times = cameraTimes(track, clock, refuse);
646
+ const compiledPhase = "basis" in clock && clock.basis === "compiled" ? times.compiledSeconds : void 0;
647
+ const { pan, zoom } = track.sample(times.authoredSeconds, compiledPhase, backdropSteps);
648
+ const viewWorld = cameraView(stage, { pan, zoom }, `scene camera track ${JSON.stringify(animation)} at ${times.authoredSeconds} s`, refuse);
649
+ return Object.freeze({
650
+ animation,
651
+ ...times,
652
+ pan: Object.freeze([pan[0], pan[1]]),
653
+ zoom,
654
+ viewWorld: Object.freeze(viewWorld),
655
+ output,
656
+ loop: track.loop
657
+ });
658
+ }
659
+ });
660
+ }
661
+ function sceneCameraTransform(frame, refuse) {
662
+ if (!frame || !validViewport(frame.viewWorld) || !usableZoom(frame.zoom) || !frame.output || !positive(frame.output.width) || !positive(frame.output.height) || !positive(frame.viewWorld.width * frame.zoom) || !positive(frame.viewWorld.height * frame.zoom)) {
663
+ return refuse("SCENE_CAMERA_VIEW_INVALID", "expected finite authored output dimensions and a positive, noncollapsed camera view");
664
+ }
665
+ const { viewWorld, zoom, output } = frame;
666
+ return { origin: { x: viewWorld.x, y: viewWorld.y + viewWorld.height }, zoom, width: output.width, height: output.height };
667
+ }
668
+ function projectSceneCamera(frame, refuse) {
669
+ const { origin, zoom, width, height } = sceneCameraTransform(frame, refuse);
670
+ return {
671
+ worldToOutput: ({ x, y }) => ({ x: (x - origin.x) * zoom, y: (origin.y - y) * zoom }),
672
+ outputToWorld: ({ x, y }) => ({ x: origin.x + x / zoom, y: origin.y - y / zoom }),
673
+ outputClip: { x: 0, y: 0, width, height }
674
+ };
675
+ }
90
676
  class ComposedTakeError extends Error {
91
677
  constructor(code, detail, cause) {
92
678
  super(`${code}: ${detail}`, { cause });
93
679
  this.code = code;
94
680
  }
95
681
  }
682
+ function refuseSceneCamera(code, detail, cause) {
683
+ throw new ComposedTakeError(code, detail, cause);
684
+ }
685
+ function bindSceneCamera(report, model) {
686
+ return bindSceneCameraReport(report, model, refuseSceneCamera);
687
+ }
688
+ function sceneCameraProjection(frame) {
689
+ return projectSceneCamera(frame, refuseSceneCamera);
690
+ }
96
691
  const NEUTRAL = { x: 0, y: 0 };
97
692
  const PLANES = ["background", "figure", "foreground"];
98
693
  const DEFAULT_TRANSITION_MS = 120;
@@ -153,7 +748,7 @@ function bindSlots(assets, options) {
153
748
  }
154
749
  return planes;
155
750
  }
156
- function checkFrame(frame, planes, backdropPlane = "background") {
751
+ function checkFrame(frame, planes, backdropPlane = "background", allowSharedClip = false) {
157
752
  const seen = /* @__PURE__ */ new Set();
158
753
  const clipPlanes = /* @__PURE__ */ new Map();
159
754
  const backdrop = [];
@@ -163,7 +758,7 @@ function checkFrame(frame, planes, backdropPlane = "background") {
163
758
  throw new ComposedTakeError("COMPOSED_SLOT_PARTITION", `unbound or repeated posed slot ${JSON.stringify(slot.slot)}`);
164
759
  }
165
760
  seen.add(slot.slot);
166
- if (slot.clip) {
761
+ if (slot.clip && !allowSharedClip) {
167
762
  const owner = clipPlanes.get(slot.clip);
168
763
  if (owner !== void 0 && owner !== plane) {
169
764
  throw new ComposedTakeError("COMPOSED_CROSS_PLANE_CLIP", `one clip covers ${owner} and ${plane} at ${JSON.stringify(slot.slot)}`);
@@ -177,12 +772,12 @@ function checkFrame(frame, planes, backdropPlane = "background") {
177
772
  function trackError(id, detail) {
178
773
  return new ComposedTakeError("COMPOSED_PLATE_TRACK", `plane ${JSON.stringify(id)} ${detail}`);
179
774
  }
180
- function namedPlanes(assets, options) {
775
+ function namedPlanes(assets, options, animationName = options.animation) {
181
776
  if (!options.planes) return void 0;
182
777
  const read = assets.document;
183
778
  const doc = underNoSkin(read.doc);
184
779
  const skin = doc.skins.find((skin2) => skin2.name === "default");
185
- const animation = doc.animations.find((animation2) => animation2.name === options.animation);
780
+ const animation = doc.animations.find((animation2) => animation2.name === animationName);
186
781
  const setup = poseRawSetup(doc);
187
782
  const setupFrame = frameOf(frameSource(doc, read.parsed), setup);
188
783
  const bones = new Map(doc.bones.map((bone) => [bone.name, bone]));
@@ -294,9 +889,15 @@ function transformFrame(frame, shiftFor, { origin = NEUTRAL, scale = { x: 1, y:
294
889
  const transform = (xy, delta = shift) => xy.map((value, i) => i % 2 === 0 ? (value + delta.x - origin.x) * scale.x : (value - delta.y - origin.y) * scale.y);
295
890
  let clip = slot.clip;
296
891
  if (clip) {
297
- const transformed = clips.get(clip) ?? { ...clip, polygon: transform(clip.polygon) };
298
- clips.set(clip, transformed);
299
- clip = transformed;
892
+ const variants = clips.get(clip) ?? [];
893
+ const existing = variants.find((entry) => entry.shift.x === shift.x && entry.shift.y === shift.y);
894
+ if (existing) clip = existing.clip;
895
+ else {
896
+ const source2 = clip;
897
+ clip = { ...source2, polygon: transform(source2.polygon) };
898
+ variants.push({ shift, clip });
899
+ clips.set(source2, variants);
900
+ }
300
901
  }
301
902
  const positioned = slot.kind === "mesh" ? { ...slot, clip, vertices: transform(slot.vertices) } : { ...slot, clip, corners: setup ? native ? setup.corners : transform(setup.corners, NEUTRAL) : transform(slot.corners) };
302
903
  if (!clipInStockSpace || !slot.clip) return positioned;
@@ -304,6 +905,31 @@ function transformFrame(frame, shiftFor, { origin = NEUTRAL, scale = { x: 1, y:
304
905
  return rememberComposedClip(positioned, source, shift, origin, scale);
305
906
  }) };
306
907
  }
908
+ function drawSceneCamera(renderer, pose, frame, backing, shiftFor = () => NEUTRAL) {
909
+ const { origin, zoom, width, height } = sceneCameraTransform(frame, refuseSceneCamera);
910
+ const pixels = backing === void 0 ? { width: Math.ceil(width), height: Math.ceil(height) } : backing;
911
+ const backingDimension = (value) => Number.isInteger(value) && value > 0 && value <= 4294967295;
912
+ if (!pixels || !backingDimension(pixels.width) || !backingDimension(pixels.height)) {
913
+ refuseSceneCamera("SCENE_CAMERA_VIEW_INVALID", "the backing needs positive integer canvas dimensions");
914
+ }
915
+ const scale = { x: zoom * (pixels.width / width), y: zoom * (pixels.height / height) };
916
+ if (!Object.values(scale).every((value) => Number.isFinite(value) && value > 0)) {
917
+ refuseSceneCamera("SCENE_CAMERA_VIEW_INVALID", "the view cannot be projected into this backing");
918
+ }
919
+ const projected = transformFrame(pose, shiftFor, { origin, scale, clipInStockSpace: true });
920
+ const { viewport, pixelRatio } = renderer;
921
+ try {
922
+ renderer.viewport = { x: 0, y: -pixels.height, width: pixels.width, height: pixels.height };
923
+ renderer.pixelRatio = 1;
924
+ renderer.render(projected);
925
+ } finally {
926
+ renderer.viewport = viewport;
927
+ renderer.pixelRatio = pixelRatio;
928
+ }
929
+ }
930
+ function renderSceneCameraFrame(renderer, pose, frame, backing) {
931
+ drawSceneCamera(renderer, pose, frame, backing);
932
+ }
307
933
  const stageTop = (stage) => stage.y + stage.height;
308
934
  const edgeTolerance = (a, b) => Math.max(Math.abs(a), Math.abs(b), 1) * 2 ** -23;
309
935
  function requireStage(stage) {
@@ -491,10 +1117,82 @@ function checkPlateEnvelopes(stage, layout, mode, excursion, plates, gains, swee
491
1117
  if (uncovered.length) throw fail(`uncovered geometric edges ${uncovered.join(", ")}`);
492
1118
  }
493
1119
  }
1120
+ async function fetchSceneReport(url) {
1121
+ if (typeof url !== "string" || !url.trim()) {
1122
+ return refuseSceneCamera("SCENE_CAMERA_REPORT_INVALID", "expected a scene report URL");
1123
+ }
1124
+ try {
1125
+ const response = await fetch(url);
1126
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
1127
+ if (!response.body) throw new Error("missing response body");
1128
+ const reader = response.body.getReader();
1129
+ let bytes = new Uint8Array(0);
1130
+ let total = 0;
1131
+ try {
1132
+ for (; ; ) {
1133
+ const { value, done } = await reader.read();
1134
+ if (done) break;
1135
+ const observed = total + value.byteLength;
1136
+ checkSceneCameraReportSize(observed, refuseSceneCamera);
1137
+ if (observed > bytes.length) {
1138
+ const capacity = Math.min(SCENE_CAMERA_REPORT_MAX_BYTES, Math.max(observed, bytes.length * 2, 4096));
1139
+ const grown = new Uint8Array(capacity);
1140
+ grown.set(bytes.subarray(0, total));
1141
+ bytes = grown;
1142
+ }
1143
+ bytes.set(value, total);
1144
+ total = observed;
1145
+ }
1146
+ } catch (error) {
1147
+ void reader.cancel().catch(() => {
1148
+ });
1149
+ throw error;
1150
+ } finally {
1151
+ reader.releaseLock();
1152
+ }
1153
+ return decodeSceneCameraReport(bytes.subarray(0, total), refuseSceneCamera);
1154
+ } catch (error) {
1155
+ if (error instanceof ComposedTakeError) throw error;
1156
+ return refuseSceneCamera("SCENE_CAMERA_REPORT_INVALID", `could not read the scene report at ${url}`, error);
1157
+ }
1158
+ }
1159
+ async function hashModelResponse(response) {
1160
+ const subtle = globalThis.crypto?.subtle;
1161
+ if (typeof subtle?.digest !== "function") {
1162
+ return refuseSceneCamera(
1163
+ "SCENE_CAMERA_MODEL_MISMATCH",
1164
+ "could not compute SHA-256 for the exact model response bytes because Web Crypto subtle.digest is unavailable (browsers require a secure context)"
1165
+ );
1166
+ }
1167
+ try {
1168
+ const bytes = await response.clone().arrayBuffer();
1169
+ const digest = await subtle.digest("SHA-256", bytes);
1170
+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
1171
+ } catch (error) {
1172
+ return refuseSceneCamera("SCENE_CAMERA_MODEL_MISMATCH", "could not compute SHA-256 for the exact model response bytes with Web Crypto", error);
1173
+ }
1174
+ }
1175
+ function keyedPlaneGains(planes) {
1176
+ if (!planes) return void 0;
1177
+ const gains = /* @__PURE__ */ new Map();
1178
+ for (const [id, { role, gain, baked }] of Object.entries(planes)) {
1179
+ if (gain !== void 0 && !Number.isFinite(gain)) {
1180
+ throw new ComposedTakeError("COMPOSED_INVALID_DISPLACEMENT", `plane ${JSON.stringify(id)} needs a finite gain`);
1181
+ }
1182
+ if (role === "figure" && (baked !== void 0 || gain !== void 0 && gain !== 0)) {
1183
+ throw trackError(id, "must stay at focal gain 0 without a baked camera track");
1184
+ }
1185
+ gains.set(id, gain ?? (role === "backdrop" ? BACKDROP_GAIN : 0));
1186
+ }
1187
+ return gains;
1188
+ }
494
1189
  async function mountComposedTake(root, options) {
495
1190
  const initial = options.camera ?? "fixed";
496
1191
  checkMode(initial);
497
- if (options.loop !== true) throw new ComposedTakeError("COMPOSED_LOOP_REQUIRED", "declare the existing take as loop: true");
1192
+ const { loop, sceneReportUrl } = options;
1193
+ if (loop !== true && (loop !== false || sceneReportUrl === void 0)) {
1194
+ throw new ComposedTakeError("COMPOSED_LOOP_REQUIRED", "declare the existing take as loop: true");
1195
+ }
498
1196
  const override = options.maxDisplacement;
499
1197
  const validLimit = (limit) => limit && Number.isFinite(limit.x) && limit.x >= 0 && Number.isFinite(limit.y) && limit.y >= 0;
500
1198
  if (override !== void 0 && !validLimit(override)) {
@@ -511,8 +1209,26 @@ async function mountComposedTake(root, options) {
511
1209
  if (!Number.isFinite(options.transitionMs ?? DEFAULT_TRANSITION_MS) || !(transitionSeconds > 0)) {
512
1210
  throw new ComposedTakeError("COMPOSED_INVALID_DISPLACEMENT", "transitionMs must be positive and finite");
513
1211
  }
514
- const assets = await loadModel({ modelUrl: options.modelUrl, regions: "none", setsUrl: null, crossOrigin: "anonymous" }).catch((error) => {
1212
+ const report = sceneReportUrl === void 0 ? void 0 : await fetchSceneReport(sceneReportUrl);
1213
+ const digest = sceneReportUrl === void 0 ? null : sceneCameraModelDigest(report, refuseSceneCamera);
1214
+ if (digest === null && loop !== true) throw new ComposedTakeError("COMPOSED_LOOP_REQUIRED", "declare the existing take as loop: true");
1215
+ let sha256 = "";
1216
+ const assets = await loadModel({
1217
+ modelUrl: options.modelUrl,
1218
+ regions: "none",
1219
+ setsUrl: null,
1220
+ crossOrigin: "anonymous",
1221
+ ...digest === null ? {} : { fetch: async (input, init) => {
1222
+ const response = await fetch(input, init);
1223
+ if (response.ok) {
1224
+ sha256 = await hashModelResponse(response);
1225
+ if (sha256 !== digest) refuseSceneCamera("SCENE_CAMERA_MODEL_MISMATCH", "the scene camera SHA-256 does not match the consumed model");
1226
+ }
1227
+ return response;
1228
+ } }
1229
+ }).catch((error) => {
515
1230
  if (error instanceof Error && /(?:problem\(s\): |; )(?:stage[.: ]|section "stage" is missing(?=; | — |$))/.test(error.message)) {
1231
+ if (digest !== null) refuseSceneCamera("SCENE_CAMERA_VIEW_INVALID", "the compiled model needs a valid stage", error);
516
1232
  throw new ComposedTakeError("COMPOSED_STAGE_REQUIRED", "the compiled model needs a valid stage", error);
517
1233
  }
518
1234
  throw error;
@@ -522,13 +1238,83 @@ async function mountComposedTake(root, options) {
522
1238
  let player;
523
1239
  let audit;
524
1240
  try {
525
- let syncTurn = function(next) {
1241
+ let cameraFor = function(animation, animationTime, loop2, backdropSteps) {
1242
+ const view = bound?.sample(animation, { basis: "compiled", seconds: animationTime }, backdropSteps) ?? null;
1243
+ if (view && view.loop !== loop2) {
1244
+ refuseSceneCamera("SCENE_CAMERA_CLIP_MISMATCH", `loop must match the authored camera track for ${JSON.stringify(animation)}`);
1245
+ }
1246
+ return view;
1247
+ }, planesFor = function(animation) {
1248
+ if (!namedInput) return void 0;
1249
+ let named = legacyPlanes.get(animation);
1250
+ if (!named) {
1251
+ named = namedPlanes(assets, options, animation);
1252
+ legacyPlanes.set(animation, named);
1253
+ }
1254
+ return named;
1255
+ }, configureScene = function(next, animation, loop2, time, reset = false) {
1256
+ if (!reset && scene.mode === next && scene.animation === animation && scene.loop === loop2) return false;
1257
+ const wasHolding = scene.clock !== null;
1258
+ let binding = { behavior: "additive" };
1259
+ if (next === "parallax" && animation !== null) {
1260
+ const key = JSON.stringify([animation, loop2]);
1261
+ binding = bindings.get(key) ?? bindSceneHold(
1262
+ report,
1263
+ assets.document.doc,
1264
+ animation,
1265
+ bound?.sample(animation, { basis: "compiled", seconds: 0 }) ?? null,
1266
+ loop2,
1267
+ driftEvidence?.backdrop,
1268
+ dialBones
1269
+ );
1270
+ bindings.set(key, binding);
1271
+ if (composedTracks && binding.behavior === "hold") {
1272
+ binding = { behavior: "refused", reason: "scene hold requires a single unmixed animation track" };
1273
+ } else if (skin !== void 0 && binding.behavior === "hold") {
1274
+ binding = { behavior: "refused", reason: `backdrop depends on unverified skin ${JSON.stringify(skin)}` };
1275
+ } else if (externalAdjust && binding.behavior === "hold") {
1276
+ binding = { behavior: "refused", reason: "backdrop depends on an external player local adjustment" };
1277
+ }
1278
+ }
1279
+ scene = {
1280
+ mode: next,
1281
+ animation,
1282
+ loop: loop2,
1283
+ binding,
1284
+ clock: binding.behavior === "hold" ? createSceneClock(time, transitionSeconds, hover !== void 0) : null
1285
+ };
1286
+ return wasHolding || scene.clock !== null;
1287
+ }, syncTurn = function(next) {
526
1288
  if (!dials.length) return;
527
1289
  const weight = mode === "parallax" && next === mode ? handoff.weight : 0;
528
1290
  const pointer = weight === 0 ? NEUTRAL : handoff.pointer;
529
1291
  if (weight !== turnInput.weight || pointer.x !== turnInput.pointer.x || pointer.y !== turnInput.pointer.y) {
530
1292
  turnInput = { weight, pointer };
531
1293
  }
1294
+ }, changedExternalAdjust = function(player2) {
1295
+ const current = player2.adjust !== null && player2.adjust !== adjustTurn;
1296
+ if (current === externalAdjust) return false;
1297
+ externalAdjust = current;
1298
+ return true;
1299
+ }, syncAdjust = function(player2, changed) {
1300
+ if (!hasSceneDeclaration) {
1301
+ if (player2.adjust === adjustTurn && posedTurnInput !== turnInput) player2.repose();
1302
+ return;
1303
+ }
1304
+ const needsHook = dials.length > 0 || scene.clock !== null;
1305
+ if (needsHook && player2.adjust === null) player2.adjust = adjustTurn;
1306
+ else if (!needsHook && player2.adjust === adjustTurn) player2.adjust = null;
1307
+ else if (changed || posedTurnInput !== turnInput) player2.repose();
1308
+ }, createCoverageChecks = function() {
1309
+ const renderer2 = audit = new CanvasRenderer(doc.createElement("div"), assets.pageImages);
1310
+ renderer2.backend = backend;
1311
+ const auditBackdrop = backdropAlphaAudit(renderer2);
1312
+ return { renderer: renderer2, auditBackdrop, requireCoverage: backdropGuard(auditBackdrop, stage) };
1313
+ }, applyLegacyLayout = function() {
1314
+ const { native, width, height } = layout;
1315
+ renderer.viewport = native ? stage : { x: 0, y: -height, width, height };
1316
+ renderer.pixelRatio = native ? width / stage.width : 1;
1317
+ legacyLayoutPending = false;
532
1318
  }, measure = function() {
533
1319
  const box = surface.getBoundingClientRect();
534
1320
  const cssWidth = box.width || stage.width;
@@ -541,12 +1327,12 @@ async function mountComposedTake(root, options) {
541
1327
  const native = [stage.x, stage.y, stage.width, stage.height].every(Number.isInteger) && stage.width * pixelRatio === width && stage.height * pixelRatio === height;
542
1328
  const excursion = explicit ?? cameraLimits(cssWidth, cssHeight);
543
1329
  layout = { cssWidth, cssHeight, width, height, dpr, native, excursion };
544
- renderer.viewport = native ? stage : { x: 0, y: -height, width, height };
545
- renderer.pixelRatio = native ? pixelRatio : 1;
1330
+ legacyLayoutPending = true;
1331
+ if (!bound) applyLegacyLayout();
546
1332
  }, cameraExcursionFor = function(next) {
547
1333
  const { excursion } = layout;
548
1334
  return next === "parallax" && dials.length ? { x: excursion.x, y: 0 } : excursion;
549
- }, prepareFrame = function(frame, plates, next, excursion) {
1335
+ }, prepareFrame = function(frame, plates, next, excursion, named) {
550
1336
  const worldX = stage.width / layout.cssWidth;
551
1337
  const worldY = stage.height / layout.cssHeight;
552
1338
  const centered = /* @__PURE__ */ new Map();
@@ -609,7 +1395,7 @@ async function mountComposedTake(root, options) {
609
1395
  positioned = transformFrame(frame, shiftFor, { centered, clipInStockSpace: true });
610
1396
  }
611
1397
  return { frame: positioned, offsets: frameOffsets };
612
- }, checkBackdropAlpha = function(frame, { figureSlots, backdrop }, next) {
1398
+ }, checkBackdropAlpha = function(frame, { figureSlots, backdrop }, next, coverage, auditBackdrop) {
613
1399
  const isFigure = (slot) => figureSlots.has(slot.slot);
614
1400
  const figures = frame.order.filter(isFigure);
615
1401
  const firstFigure = figures.length === figureSlots.size ? figures[0] : poser.slotIdentity().slots.find(isFigure);
@@ -626,40 +1412,118 @@ async function mountComposedTake(root, options) {
626
1412
  if (nonOpaque) {
627
1413
  throw plateCoverageError(backdrop, next, `${nonOpaque} stage pixels have alpha below 255 at ${layout.width} × ${layout.height} backing px`);
628
1414
  }
629
- }, currentFrame = function(next) {
1415
+ }, syncPose = function(next) {
630
1416
  syncTurn(next);
631
- if (posedTurnInput !== turnInput) poser.repose();
1417
+ const entry = poser.entry();
1418
+ const changed = configureScene(
1419
+ next,
1420
+ entry?.animation ?? null,
1421
+ entry?.loop ?? false,
1422
+ entry?.trackTime ?? 0,
1423
+ changedExternalAdjust(poser)
1424
+ );
1425
+ syncAdjust(poser, changed);
1426
+ }, currentFrame = function(named, keyed) {
632
1427
  const frame = poser.posedFrame(null);
633
- if (named) return { frame, backdrop: checkFrame(frame, planes, named.backdrop) };
634
- return { frame, backdrop: checkFrame(frame, planes) };
635
- }, drawMode = function(frame, backdrop, next, switching) {
636
- const plates = named ? livePlates(frame, named, next) : [];
1428
+ return { frame, backdrop: checkFrame(frame, planes, named?.backdrop, keyed) };
1429
+ }, requireKeyedCoverage = function(view, next, excursion) {
1430
+ if (!driftEvidence || next === "fixed") return;
1431
+ const sweep2 = keyedGains && next === "parallax" ? sweepLimit : NEUTRAL;
1432
+ if (excursion.x === 0 && excursion.y === 0 && sweep2.x === 0 && sweep2.y === 0) return;
1433
+ const gain = next === "pan" ? 1 : keyedGains?.get(backdropPlane) ?? BACKDROP_GAIN;
1434
+ const sampledPlane = planes.get(driftEvidence.backdrop);
1435
+ if (gain === 0 && sampledPlane !== void 0 && keyedGains?.get(sampledPlane) === 0) return;
1436
+ const context = `take ${JSON.stringify(view.animation)}, sampled backdrop slot ${JSON.stringify(driftEvidence.backdrop)}, pointer excursion ±[${excursion.x}, ${excursion.y}] CSS px, sweep endpoint [${sweep2.x}, ${sweep2.y}] CSS px, backdrop gain ${gain}`;
1437
+ if (sampledPlane !== backdropPlane) {
1438
+ throw plateCoverageError(backdropPlane, next, `${context} needs that exact slot bound to the backdrop plane`);
1439
+ }
1440
+ const toOutput = ({ x, y }) => ({
1441
+ x: x === 0 ? 0 : x * (view.output.width / layout.cssWidth),
1442
+ y: y === 0 ? 0 : y * (view.output.height / layout.cssHeight)
1443
+ });
1444
+ const backingPixel = { x: view.output.width / layout.width, y: view.output.height / layout.height };
1445
+ const failure = driftEvidence.failure(
1446
+ view.animation,
1447
+ toOutput(planeShift(excursion, gain)),
1448
+ toOutput(planeShift(sweep2, gain)),
1449
+ backingPixel
1450
+ );
1451
+ if (failure) throw plateCoverageError(backdropPlane, next, `${context}; ${failure}`);
1452
+ }, drawKeyedFrame = function(frame, next, excursion, view) {
1453
+ let displayed = planeOffsets(cssTarget(camera, excursion), next);
1454
+ if (keyedGains) {
1455
+ const changingMode = mode !== next;
1456
+ const weight = changingMode ? 0 : handoff.weight;
1457
+ const pointer = cssTarget(changingMode ? NEUTRAL : next === "pan" ? camera : handoff.pointer, excursion);
1458
+ const phase = sweepPeriod === void 0 ? 0 : Math.sin(2 * Math.PI * (poser.time % sweepPeriod / sweepPeriod));
1459
+ const sweep2 = { x: sweepLimit.x * phase, y: sweepLimit.y * phase };
1460
+ const input = next === "pan" ? pointer : {
1461
+ x: (1 - weight) * sweep2.x + weight * pointer.x,
1462
+ y: (1 - weight) * sweep2.y + weight * pointer.y
1463
+ };
1464
+ displayed = Object.fromEntries([...keyedGains].map(([id, gain]) => [
1465
+ id,
1466
+ next === "fixed" ? NEUTRAL : planeShift(input, next === "pan" ? 1 : gain)
1467
+ ]));
1468
+ }
1469
+ const worldX = view.output.width / layout.cssWidth / view.zoom;
1470
+ const worldY = view.output.height / layout.cssHeight / view.zoom;
1471
+ drawSceneCamera(renderer, frame, view, layout, (slot) => {
1472
+ const { x, y } = displayed[planes.get(slot.slot)];
1473
+ return { x: x === 0 ? 0 : x * worldX, y: y === 0 ? 0 : y * worldY };
1474
+ });
1475
+ return displayed;
1476
+ }, drawMode = function(frame, backdrop, next, switching, view, named) {
637
1477
  const excursion = cameraExcursionFor(next);
638
- if (named) checkPlateEnvelopes(stage, layout, next, excursion, plates, named.gains, sweepLimit);
639
- else requireCoverage(backdrop, layout, next);
640
- const prepared = prepareFrame(frame, plates, next, excursion);
641
- if (named) checkBackdropAlpha(prepared.frame, named, next);
642
- renderer.render(prepared.frame);
643
- if (named && mode !== next) {
1478
+ let displayed;
1479
+ if (view) {
1480
+ keyedGains ??= keyedPlaneGains(options.planes);
1481
+ if (keyedAdmission?.animation !== view.animation || keyedAdmission.layout !== layout || keyedAdmission.mode !== next) {
1482
+ requireKeyedCoverage(view, next, excursion);
1483
+ keyedAdmission = { animation: view.animation, layout, mode: next };
1484
+ }
1485
+ displayed = drawKeyedFrame(frame, next, excursion, view);
1486
+ } else {
1487
+ keyedAdmission = void 0;
1488
+ if (legacyLayoutPending) applyLegacyLayout();
1489
+ const checks = coverageChecks ??= createCoverageChecks();
1490
+ const plates = named ? livePlates(frame, named, next) : [];
1491
+ if (named) checkPlateEnvelopes(stage, layout, next, excursion, plates, named.gains, sweepLimit);
1492
+ else checks.requireCoverage(backdrop, layout, next);
1493
+ const prepared = prepareFrame(frame, plates, next, excursion, named);
1494
+ if (named) checkBackdropAlpha(prepared.frame, named, next, checks.renderer, checks.auditBackdrop);
1495
+ renderer.render(prepared.frame);
1496
+ displayed = prepared.offsets;
1497
+ }
1498
+ if (namedInput && mode !== next) {
644
1499
  camera = NEUTRAL;
645
1500
  handoff.reset();
646
1501
  if (next === "parallax" && hover !== void 0) handoff.enter();
647
1502
  }
648
1503
  mode = next;
649
- if (!named && switching && mode === "fixed") camera = target = NEUTRAL;
650
- offsets = prepared.offsets;
651
- if (named && mode === "parallax") handoff.painted();
1504
+ if (!namedInput && mode !== "parallax") hover = void 0;
1505
+ if (!namedInput && switching && mode === "fixed") camera = target = NEUTRAL;
1506
+ offsets = displayed;
1507
+ if (namedInput && mode === "parallax") handoff.painted();
652
1508
  canvas.style.visibility = "";
653
1509
  Object.assign(canvas.style, { width: "100%", height: "100%", transform: "none", pointerEvents: "auto" });
654
1510
  }, select = function(next, switching, allowFallback) {
655
- const { frame, backdrop } = currentFrame(next);
1511
+ syncPose(next);
1512
+ const entry = bound && poser.entry();
1513
+ const backdropSteps = scene.binding.behavior === "hold" ? scene.binding.backdropSteps : void 0;
1514
+ const view = entry?.animation ? cameraFor(entry.animation, scene.clock?.phase ?? entry.animationTime, entry.loop, backdropSteps) : null;
1515
+ drawingKeyed = view !== null;
1516
+ const named = view ? void 0 : planesFor(entry?.animation ?? initialAnimation);
1517
+ const { frame, backdrop } = currentFrame(named, drawingKeyed);
656
1518
  try {
657
- drawMode(frame, backdrop, next, switching);
1519
+ drawMode(frame, backdrop, next, switching, view, named);
658
1520
  } catch (error) {
659
- if (!(error instanceof ComposedTakeError) || error.code !== "COMPOSED_BACKDROP_COVERAGE" || next === "fixed" || !named && !allowFallback) throw error;
1521
+ if (!(error instanceof ComposedTakeError) || error.code !== "COMPOSED_BACKDROP_COVERAGE" || next === "fixed" || !named && !view && !allowFallback) throw error;
660
1522
  try {
661
- const fixed = turnInput.weight === 0 ? { frame, backdrop } : currentFrame("fixed");
662
- drawMode(fixed.frame, fixed.backdrop, "fixed", true);
1523
+ syncPose("fixed");
1524
+ const fixed = currentFrame(named, drawingKeyed);
1525
+ const fixedView = entry?.animation ? cameraFor(entry.animation, entry.animationTime, entry.loop) : null;
1526
+ drawMode(fixed.frame, fixed.backdrop, "fixed", true, fixedView, named);
663
1527
  } catch (fixedError) {
664
1528
  canvas.style.visibility = "hidden";
665
1529
  throw fixedError;
@@ -672,7 +1536,7 @@ async function mountComposedTake(root, options) {
672
1536
  select(mode, false, true);
673
1537
  } catch (error) {
674
1538
  if (error instanceof ComposedTakeError) refusal = error;
675
- if (named) canvas.style.visibility = "hidden";
1539
+ if (namedInput || drawingKeyed) canvas.style.visibility = "hidden";
676
1540
  stopped = true;
677
1541
  if (frameId !== void 0) window.cancelAnimationFrame(frameId);
678
1542
  throw error;
@@ -686,12 +1550,12 @@ async function mountComposedTake(root, options) {
686
1550
  refusal = null;
687
1551
  } catch (error) {
688
1552
  if (error instanceof ComposedTakeError) refusal = error;
689
- if (named && next === "fixed") canvas.style.visibility = "hidden";
1553
+ if ((namedInput || drawingKeyed) && next === "fixed") canvas.style.visibility = "hidden";
690
1554
  throw error;
691
1555
  }
692
1556
  }, advanceCamera = function(elapsed) {
693
1557
  if (!(elapsed > 0)) return;
694
- if (named && mode === "parallax") handoff.advance(elapsed, target);
1558
+ if (namedInput && mode === "parallax") handoff.advance(elapsed, target);
695
1559
  else camera = easeCamera(camera, target, elapsed);
696
1560
  }, syncCamera = function(now) {
697
1561
  const next = Math.max(lastCameraAt, now);
@@ -711,22 +1575,46 @@ async function mountComposedTake(root, options) {
711
1575
  if (autoStart) syncCamera(window.performance.now());
712
1576
  hover = void 0;
713
1577
  target = NEUTRAL;
1578
+ scene.clock?.aim(false);
714
1579
  if (mode === "parallax") handoff.leave();
715
1580
  };
1581
+ const bound = digest === null ? null : bindSceneCameraReport(report, { sha256, stage: assets.stage, animations: assets.animations }, refuseSceneCamera);
1582
+ const driftEvidence = bound && sceneCameraDriftEvidence(report, refuseSceneCamera);
1583
+ const initialView = cameraFor(options.animation, 0, loop);
1584
+ if (!initialView && loop !== true) throw new ComposedTakeError("COMPOSED_LOOP_REQUIRED", "declare the existing take as loop: true");
716
1585
  const stage = requireStage(assets.stage);
717
1586
  const take = assets.animations.find((animation) => animation.name === options.animation);
718
- if (!take || !Number.isFinite(take.duration) || take.duration <= 0) {
1587
+ if (!take || !initialView && (!Number.isFinite(take.duration) || take.duration <= 0)) {
719
1588
  throw new ComposedTakeError("COMPOSED_LOOP_REQUIRED", `no positive-duration animation named ${JSON.stringify(options.animation)}`);
720
1589
  }
1590
+ const initialAnimation = take.name;
721
1591
  const planes = bindSlots(assets, options);
722
- const named = namedPlanes(assets, options);
723
- const dials = named && options.pointerTurn !== false ? discoverTurnDials(assets.document.parsed, assets.animations) : [];
1592
+ const namedInput = options.planes !== void 0;
1593
+ const backdropPlane = Object.entries(options.planes ?? {}).find(([, plane]) => plane.role === "backdrop")?.[0] ?? "background";
1594
+ const legacyPlanes = /* @__PURE__ */ new Map();
1595
+ const initialNamed = initialView ? void 0 : planesFor(initialAnimation);
1596
+ let keyedGains = initialView ? keyedPlaneGains(options.planes) : void 0;
1597
+ const dials = namedInput && options.pointerTurn !== false ? discoverTurnDials(assets.document.parsed, assets.animations) : [];
724
1598
  const handoff = createCameraHandoff(transitionSeconds);
1599
+ const hasSceneDeclaration = typeof report === "object" && report !== null && Object.hasOwn(report, "scene_driven");
725
1600
  let mode = initial;
1601
+ let hover;
1602
+ let scene = { mode: initial, animation: null, loop: false, binding: { behavior: "additive" }, clock: null };
1603
+ const dialBones = new Set(dials.map((dial) => dial.bone));
1604
+ const bindings = /* @__PURE__ */ new Map();
1605
+ let replaying = false;
1606
+ let composedTracks = false;
1607
+ let skin;
1608
+ let externalAdjust = false;
1609
+ configureScene(initial, initialAnimation, loop, 0, true);
726
1610
  let turnInput = { weight: 0, pointer: NEUTRAL };
727
1611
  let posedTurnInput = turnInput;
728
1612
  let turnValues = [];
729
- const adjustTurn = (bones) => {
1613
+ const adjustTurn = (bones, ctx) => {
1614
+ if (!replaying && scene.binding.behavior === "hold" && scene.clock && ctx.animation === scene.animation && ctx.trackTime !== null) {
1615
+ scene.clock.advance(ctx.trackTime);
1616
+ scene.binding.apply(bones, scene.clock.phase);
1617
+ }
730
1618
  const { weight, pointer } = turnInput;
731
1619
  turnValues = dials.map((dial) => {
732
1620
  const { axis, bone, channel, min, max } = dial;
@@ -748,34 +1636,93 @@ async function mountComposedTake(root, options) {
748
1636
  aspectRatio: `${stage.width} / ${stage.height}`
749
1637
  });
750
1638
  root.appendChild(surface);
751
- const poser = player = new RigPlayer(surface, assets, { mode: "canvas", adjust: dials.length ? adjustTurn : null });
1639
+ const poser = player = new RigPlayer(surface, assets, { mode: "canvas", adjust: dials.length || scene.clock ? adjustTurn : null });
1640
+ if (hasSceneDeclaration) {
1641
+ let resetSceneAtEntry = function() {
1642
+ changedExternalAdjust(poser);
1643
+ const entry = poser.entry();
1644
+ const changed = configureScene(mode, entry?.animation ?? null, entry?.loop ?? false, entry?.trackTime ?? 0, true);
1645
+ syncAdjust(poser, changed);
1646
+ }, replay = function(operation) {
1647
+ replaying = true;
1648
+ try {
1649
+ operation();
1650
+ } finally {
1651
+ replaying = false;
1652
+ }
1653
+ }, composeWithoutScene = function(operation) {
1654
+ replay(operation);
1655
+ composedTracks = true;
1656
+ resetSceneAtEntry();
1657
+ };
1658
+ const base = RigPlayer.prototype;
1659
+ const methods = {
1660
+ play(name, options2 = {}) {
1661
+ const { track = 0, mix = 0, alpha = 1, additive = false } = options2;
1662
+ replay(() => base.play.call(poser, name, options2));
1663
+ composedTracks ||= track !== 0 || mix !== 0 || alpha !== 1 || additive;
1664
+ resetSceneAtEntry();
1665
+ },
1666
+ seek(...args) {
1667
+ replay(() => base.seek.call(poser, ...args));
1668
+ resetSceneAtEntry();
1669
+ },
1670
+ queue(...args) {
1671
+ composeWithoutScene(() => base.queue.call(poser, ...args));
1672
+ },
1673
+ clear(...args) {
1674
+ composeWithoutScene(() => base.clear.call(poser, ...args));
1675
+ },
1676
+ queueClear(...args) {
1677
+ composeWithoutScene(() => base.queueClear.call(poser, ...args));
1678
+ },
1679
+ setAlpha(...args) {
1680
+ composeWithoutScene(() => base.setAlpha.call(poser, ...args));
1681
+ }
1682
+ };
1683
+ for (const [name, value] of Object.entries(methods)) {
1684
+ Object.defineProperty(poser, name, { value, configurable: true, writable: true });
1685
+ }
1686
+ const skinProperty = Object.getOwnPropertyDescriptor(base, "skin");
1687
+ Object.defineProperty(poser, "skin", {
1688
+ ...skinProperty,
1689
+ set(name) {
1690
+ if (name === poser.skin) return;
1691
+ replay(() => skinProperty.set.call(poser, name));
1692
+ skin = poser.skin;
1693
+ resetSceneAtEntry();
1694
+ }
1695
+ });
1696
+ }
752
1697
  const renderer = poser.renderer;
753
- const coverage = audit = new CanvasRenderer(doc.createElement("div"), assets.pageImages);
754
- renderer.backend = coverage.backend = options.backend ?? "webgl";
1698
+ const backend = options.backend ?? "webgl";
1699
+ renderer.backend = backend;
1700
+ let coverageChecks;
1701
+ if (!initialView) coverageChecks = createCoverageChecks();
755
1702
  const canvas = renderer.canvas;
756
- poser.play(take.name, { loop: true });
1703
+ poser.play(initialAnimation, { loop });
757
1704
  let offsets = planeOffsets(NEUTRAL, "fixed");
758
1705
  let camera = NEUTRAL;
759
1706
  let target = NEUTRAL;
760
- let hover;
761
1707
  let layout;
1708
+ let keyedAdmission;
1709
+ let legacyLayoutPending = true;
1710
+ let drawingKeyed = initialView !== null;
762
1711
  let refusal = null;
763
1712
  let stopped = false;
764
1713
  let disposed = false;
765
1714
  let frameId;
766
1715
  const window = doc.defaultView;
767
- const auditBackdrop = backdropAlphaAudit(coverage);
768
- const requireCoverage = backdropGuard(auditBackdrop, stage);
769
1716
  const origin = { x: stage.x, y: stageTop(stage) };
770
1717
  const autoStart = options.autoStart !== false;
771
1718
  let lastCameraAt = window.performance.now();
772
1719
  const cssTarget = (point, excursion) => ({ x: point.x * excursion.x, y: point.y * excursion.y });
773
1720
  measure();
774
- select(initial, true, named !== void 0);
1721
+ select(initial, true, initialNamed !== void 0 || initialView !== null);
775
1722
  const boundaryEvent = (event) => event.target === root || event.bubbles;
776
1723
  const aim = (event) => {
777
1724
  if (!event.isPrimary || stopped) return;
778
- if (named) {
1725
+ if (namedInput || scene.clock) {
779
1726
  if (event.pointerType === "touch" || event.type === "pointerenter" && !boundaryEvent(event) || hover !== void 0 && hover !== event.pointerId) return;
780
1727
  if (event.pointerType === "pen" && event.buttons !== 0) {
781
1728
  leave();
@@ -785,33 +1732,37 @@ async function mountComposedTake(root, options) {
785
1732
  if (!Number.isFinite(event.clientX) || !Number.isFinite(event.clientY)) return;
786
1733
  const box = surface.getBoundingClientRect();
787
1734
  if (!(box.width > 0 && box.height > 0)) return;
788
- if (named) {
789
- if (autoStart) syncCamera(window.performance.now());
790
- if (hover === void 0 && mode === "parallax") handoff.enter();
1735
+ if (namedInput || scene.clock) {
1736
+ if (namedInput && autoStart) syncCamera(window.performance.now());
1737
+ if (hover === void 0 && mode === "parallax") {
1738
+ if (namedInput) handoff.enter();
1739
+ scene.clock?.aim(true);
1740
+ }
791
1741
  hover = event.pointerId;
792
1742
  }
793
1743
  target = pointerTarget(event.clientX, event.clientY, box);
794
1744
  };
795
1745
  const recenter = (event) => {
796
1746
  if (!event.isPrimary) return;
797
- if (!named) {
798
- target = NEUTRAL;
799
- return;
800
- }
801
1747
  if (event.pointerType !== "touch" && hover === event.pointerId && (event.type !== "pointerleave" || boundaryEvent(event))) leave();
1748
+ else if (!namedInput && !scene.clock) target = NEUTRAL;
802
1749
  };
803
1750
  const contact = (event) => {
804
1751
  if (event.pointerType === "pen" && event.isPrimary && hover === event.pointerId) leave();
805
1752
  };
1753
+ const hoverEnter = (event) => {
1754
+ if (namedInput || scene.clock) aim(event);
1755
+ };
1756
+ const hoverLost = (event) => {
1757
+ if (namedInput || scene.clock || hover !== void 0) recenter(event);
1758
+ };
806
1759
  root.addEventListener("pointermove", aim, true);
807
1760
  root.addEventListener("pointerleave", recenter, true);
808
1761
  root.addEventListener("pointercancel", recenter, true);
809
- if (named) {
810
- root.addEventListener("pointerenter", aim, true);
811
- root.addEventListener("pointerdown", contact, true);
812
- root.addEventListener("lostpointercapture", recenter, true);
813
- window.addEventListener("blur", leave);
814
- }
1762
+ root.addEventListener("pointerenter", hoverEnter, true);
1763
+ root.addEventListener("pointerdown", contact, true);
1764
+ root.addEventListener("lostpointercapture", hoverLost, true);
1765
+ window.addEventListener("blur", leave);
815
1766
  const observer = new ResizeObserver(() => {
816
1767
  try {
817
1768
  render();
@@ -827,13 +1778,13 @@ async function mountComposedTake(root, options) {
827
1778
  if (disposed || stopped) return;
828
1779
  const elapsed = Math.max(0, (now - last) / 1e3);
829
1780
  last = now;
830
- if (named) {
1781
+ if (namedInput) {
831
1782
  syncCamera(now);
832
1783
  advance(Math.min(elapsed, 1 / 15), 0);
833
1784
  } else {
834
1785
  advance(Math.min(elapsed, 1 / 15), elapsed);
835
1786
  }
836
- if (named || layout.dpr !== window.devicePixelRatio) measure();
1787
+ if (namedInput || layout.dpr !== window.devicePixelRatio) measure();
837
1788
  try {
838
1789
  renderCurrent();
839
1790
  } catch (error) {
@@ -848,6 +1799,11 @@ async function mountComposedTake(root, options) {
848
1799
  get mode() {
849
1800
  return mode;
850
1801
  },
1802
+ get sceneHandoff() {
1803
+ if (scene.clock) return { behavior: "hold", phase: scene.clock.phase };
1804
+ if (scene.binding.behavior === "refused") return { behavior: "refused", phase: null, reason: scene.binding.reason };
1805
+ return { behavior: "additive", phase: null };
1806
+ },
851
1807
  get offsets() {
852
1808
  return offsets;
853
1809
  },
@@ -879,14 +1835,12 @@ async function mountComposedTake(root, options) {
879
1835
  root.removeEventListener("pointermove", aim, true);
880
1836
  root.removeEventListener("pointerleave", recenter, true);
881
1837
  root.removeEventListener("pointercancel", recenter, true);
882
- if (named) {
883
- root.removeEventListener("pointerenter", aim, true);
884
- root.removeEventListener("pointerdown", contact, true);
885
- root.removeEventListener("lostpointercapture", recenter, true);
886
- window.removeEventListener("blur", leave);
887
- }
1838
+ root.removeEventListener("pointerenter", hoverEnter, true);
1839
+ root.removeEventListener("pointerdown", contact, true);
1840
+ root.removeEventListener("lostpointercapture", hoverLost, true);
1841
+ window.removeEventListener("blur", leave);
888
1842
  poser.dispose();
889
- coverage.dispose();
1843
+ audit?.dispose();
890
1844
  surface.remove();
891
1845
  assets.dispose();
892
1846
  }
@@ -901,6 +1855,10 @@ async function mountComposedTake(root, options) {
901
1855
  }
902
1856
  export {
903
1857
  ComposedTakeError,
904
- mountComposedTake
1858
+ SCENE_CAMERA_REPORT_MAX_BYTES,
1859
+ bindSceneCamera,
1860
+ mountComposedTake,
1861
+ renderSceneCameraFrame,
1862
+ sceneCameraProjection
905
1863
  };
906
1864
  //# sourceMappingURL=composed-take.js.map