spine-html 1.26.0 → 1.27.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.
@@ -0,0 +1,906 @@
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";
2
+ const ORIGIN = { x: 0, y: 0 };
3
+ const GAINS = { background: -0.55, figure: 0, foreground: 0.55 };
4
+ const TIME_CONSTANT = 0.12;
5
+ const NEUTRAL_THRESHOLD = 1e-5;
6
+ function pointerTarget(clientX, clientY, viewport) {
7
+ const clamp = (value) => Math.max(-1, Math.min(1, value));
8
+ return {
9
+ x: clamp(2 * (clientX - viewport.left) / viewport.width - 1),
10
+ y: clamp(1 - 2 * (clientY - viewport.top) / viewport.height)
11
+ };
12
+ }
13
+ function easeCamera(current, target, elapsed) {
14
+ const weight = -Math.expm1(-elapsed / TIME_CONSTANT);
15
+ const ease = (value, goal) => {
16
+ const next = value + (goal - value) * weight;
17
+ return goal === 0 && Math.abs(next) <= NEUTRAL_THRESHOLD ? 0 : next;
18
+ };
19
+ return { x: ease(current.x, target.x), y: ease(current.y, target.y) };
20
+ }
21
+ function cameraLimits(width, height) {
22
+ return { x: Math.min(64, width * 0.1), y: Math.min(40, height * 0.1) };
23
+ }
24
+ function planeShift(camera, gain) {
25
+ const x = -gain * camera.x;
26
+ const y = gain * camera.y;
27
+ return { x: x === 0 ? 0 : x, y: y === 0 ? 0 : y };
28
+ }
29
+ function createCameraHandoff(transitionSeconds) {
30
+ let phase = "automatic";
31
+ let weight = 0;
32
+ let pointer = ORIGIN;
33
+ let fromWeight = 0;
34
+ let fromPointer = ORIGIN;
35
+ let elapsed = 0;
36
+ function retarget(next) {
37
+ phase = next;
38
+ fromWeight = weight;
39
+ fromPointer = pointer;
40
+ elapsed = 0;
41
+ }
42
+ return {
43
+ get weight() {
44
+ return weight;
45
+ },
46
+ get pointer() {
47
+ return pointer;
48
+ },
49
+ enter() {
50
+ retarget("acquiring");
51
+ },
52
+ leave() {
53
+ retarget("releasing");
54
+ },
55
+ reset() {
56
+ phase = "automatic";
57
+ pointer = ORIGIN;
58
+ weight = 0;
59
+ },
60
+ painted() {
61
+ if (phase === "centered") phase = "tracking";
62
+ },
63
+ advance(dt, target) {
64
+ if (!(dt > 0)) return;
65
+ if (phase === "tracking") pointer = easeCamera(pointer, target, dt);
66
+ if (phase !== "acquiring" && phase !== "releasing") return;
67
+ elapsed += dt;
68
+ const entering = phase === "acquiring";
69
+ if (elapsed >= transitionSeconds * (1 - Number.EPSILON)) {
70
+ weight = entering ? 1 : 0;
71
+ pointer = ORIGIN;
72
+ phase = entering ? "centered" : "automatic";
73
+ return;
74
+ }
75
+ const u = elapsed / transitionSeconds;
76
+ const s = u * u * (3 - 2 * u);
77
+ weight = (1 - s) * fromWeight + s * Number(entering);
78
+ if (entering) pointer = { x: (1 - s) * fromPointer.x, y: (1 - s) * fromPointer.y };
79
+ }
80
+ };
81
+ }
82
+ function planeOffsets(camera, mode) {
83
+ if (mode === "fixed") return { background: ORIGIN, figure: ORIGIN, foreground: ORIGIN };
84
+ return {
85
+ background: planeShift(camera, mode === "pan" ? 1 : GAINS.background),
86
+ figure: planeShift(camera, mode === "pan" ? 1 : GAINS.figure),
87
+ foreground: planeShift(camera, mode === "pan" ? 1 : GAINS.foreground)
88
+ };
89
+ }
90
+ class ComposedTakeError extends Error {
91
+ constructor(code, detail, cause) {
92
+ super(`${code}: ${detail}`, { cause });
93
+ this.code = code;
94
+ }
95
+ }
96
+ const NEUTRAL = { x: 0, y: 0 };
97
+ const PLANES = ["background", "figure", "foreground"];
98
+ const DEFAULT_TRANSITION_MS = 120;
99
+ const BACKDROP_GAIN = -0.55;
100
+ const TURN_FULL_RANGE_AT_STAGE_EDGE = 1;
101
+ function turnCoordinate(axis, point) {
102
+ return axis === "pitch" ? point.y : point.x;
103
+ }
104
+ const ZERO_RANGE = { minX: 0, maxX: 0, minY: 0, maxY: 0 };
105
+ function checkMode(mode) {
106
+ if (mode !== "fixed" && mode !== "pan" && mode !== "parallax") {
107
+ throw new ComposedTakeError("COMPOSED_INVALID_CAMERA", `unknown camera mode ${String(mode)}`);
108
+ }
109
+ }
110
+ function bindSlots(assets, options) {
111
+ const { doc } = assets.document;
112
+ const skin = doc.skins.find((skin2) => skin2.name === "default");
113
+ const drawable = new Set(doc.slots.filter(({ name }) => {
114
+ const entries2 = Object.values(skin?.attachments[name] ?? {});
115
+ return entries2.some(({ kind }) => kind === "region" || kind === "mesh" || kind === "linkedmesh");
116
+ }).map((slot) => slot.name));
117
+ const named = options.planes;
118
+ if (named === void 0 === (options.slots === void 0)) {
119
+ throw new ComposedTakeError("COMPOSED_SLOT_PARTITION", "declare either slots or named planes");
120
+ }
121
+ if (named !== void 0 && (!named || typeof named !== "object" || Array.isArray(named))) {
122
+ throw new ComposedTakeError("COMPOSED_SLOT_PARTITION", "named planes must be a record keyed by plane ID");
123
+ }
124
+ const entries = named === void 0 ? PLANES.map((id) => [id, options.slots?.[id]]).filter(([id, slots]) => id !== "foreground" || slots !== void 0) : Object.entries(named).map(([id, plane]) => [id, plane?.slots]);
125
+ if (named !== void 0) {
126
+ const records = Object.values(named);
127
+ if (records.filter((record) => record?.role === "backdrop").length !== 1 || records.filter((record) => record?.role === "figure").length !== 1) {
128
+ throw new ComposedTakeError("COMPOSED_SLOT_PARTITION", "named planes need one backdrop and one figure");
129
+ }
130
+ }
131
+ const planes = /* @__PURE__ */ new Map();
132
+ for (const [plane, slots] of entries) {
133
+ const role = named?.[plane]?.role;
134
+ if (named && (!plane.trim() || role !== "backdrop" && role !== "overlay" && role !== "figure")) {
135
+ throw new ComposedTakeError("COMPOSED_SLOT_PARTITION", `${JSON.stringify(plane)} needs a valid plane ID and role`);
136
+ }
137
+ if (!Array.isArray(slots) || (named ? slots.length === 0 : plane !== "foreground" && slots.length === 0)) {
138
+ throw new ComposedTakeError("COMPOSED_SLOT_PARTITION", `${plane} needs an explicit slot list`);
139
+ }
140
+ if (named && role !== "figure" && slots.length !== 1) {
141
+ throw new ComposedTakeError("COMPOSED_SLOT_PARTITION", `${plane} must bind exactly one compiled plate slot`);
142
+ }
143
+ for (const slot of slots) {
144
+ if (!drawable.has(slot) || planes.has(slot)) {
145
+ throw new ComposedTakeError("COMPOSED_SLOT_PARTITION", `${plane} has a non-drawable or duplicate slot ${JSON.stringify(slot)}`);
146
+ }
147
+ planes.set(slot, plane);
148
+ }
149
+ }
150
+ const missing = [...drawable].filter((slot) => !planes.has(slot));
151
+ if (missing.length) {
152
+ throw new ComposedTakeError("COMPOSED_SLOT_PARTITION", `unbound drawable slots ${missing.join(", ")}`);
153
+ }
154
+ return planes;
155
+ }
156
+ function checkFrame(frame, planes, backdropPlane = "background") {
157
+ const seen = /* @__PURE__ */ new Set();
158
+ const clipPlanes = /* @__PURE__ */ new Map();
159
+ const backdrop = [];
160
+ for (const slot of frame.order) {
161
+ const plane = planes.get(slot.slot);
162
+ if (plane === void 0 || seen.has(slot.slot)) {
163
+ throw new ComposedTakeError("COMPOSED_SLOT_PARTITION", `unbound or repeated posed slot ${JSON.stringify(slot.slot)}`);
164
+ }
165
+ seen.add(slot.slot);
166
+ if (slot.clip) {
167
+ const owner = clipPlanes.get(slot.clip);
168
+ if (owner !== void 0 && owner !== plane) {
169
+ throw new ComposedTakeError("COMPOSED_CROSS_PLANE_CLIP", `one clip covers ${owner} and ${plane} at ${JSON.stringify(slot.slot)}`);
170
+ }
171
+ clipPlanes.set(slot.clip, plane);
172
+ }
173
+ if (plane === backdropPlane) backdrop.push(slot);
174
+ }
175
+ return backdrop;
176
+ }
177
+ function trackError(id, detail) {
178
+ return new ComposedTakeError("COMPOSED_PLATE_TRACK", `plane ${JSON.stringify(id)} ${detail}`);
179
+ }
180
+ function namedPlanes(assets, options) {
181
+ if (!options.planes) return void 0;
182
+ const read = assets.document;
183
+ const doc = underNoSkin(read.doc);
184
+ const skin = doc.skins.find((skin2) => skin2.name === "default");
185
+ const animation = doc.animations.find((animation2) => animation2.name === options.animation);
186
+ const setup = poseRawSetup(doc);
187
+ const setupFrame = frameOf(frameSource(doc, read.parsed), setup);
188
+ const bones = new Map(doc.bones.map((bone) => [bone.name, bone]));
189
+ const gains = /* @__PURE__ */ new Map();
190
+ const plates = [];
191
+ const figureSlots = /* @__PURE__ */ new Set();
192
+ const drivers = /* @__PURE__ */ new Set();
193
+ function checkStable(id, slot, chain, driver, { name, timelines }) {
194
+ if (timelines.bones.some((row) => chain.has(row.name) && row.name !== driver && row.timelines.length) || timelines.slots.some((row) => row.name === slot && row.timelines.some((timeline) => timeline.kind === "attachment")) || timelines.attachments.some((row) => row.slot === slot && row.sequence)) {
195
+ throw trackError(id, `has non-translation motion or an unstable attachment in ${JSON.stringify(name)}`);
196
+ }
197
+ }
198
+ for (const [id, { role, slots, gain, baked }] of Object.entries(options.planes)) {
199
+ if (gain !== void 0 && !Number.isFinite(gain)) {
200
+ throw new ComposedTakeError("COMPOSED_INVALID_DISPLACEMENT", `plane ${JSON.stringify(id)} needs a finite gain`);
201
+ }
202
+ if (role === "figure") {
203
+ if (baked !== void 0 || gain !== void 0 && gain !== 0) {
204
+ throw trackError(id, "must stay at focal gain 0 without a baked camera track");
205
+ }
206
+ gains.set(id, 0);
207
+ for (const slot2 of slots) figureSlots.add(slot2);
208
+ continue;
209
+ }
210
+ const slot = doc.slots.find((slot2) => slot2.name === slots[0]);
211
+ const region = setupFrame.order.find((drawn) => drawn.slot === slot.name);
212
+ if (region?.kind !== "region") {
213
+ throw new ComposedTakeError("COMPOSED_BACKDROP_COVERAGE", `plane ${JSON.stringify(id)} has no rigid setup quad (all edges)`);
214
+ }
215
+ const plate = { id, role, setup: region };
216
+ plates.push(plate);
217
+ if (gain !== void 0 || role === "backdrop") gains.set(id, gain ?? BACKDROP_GAIN);
218
+ if (role === "overlay" && baked === void 0) continue;
219
+ const attachment = slot.setup === null ? void 0 : skin?.attachments[slot.name]?.[slot.setup];
220
+ if (attachment?.kind !== "region" || (attachment.sequenceCount ?? 1) !== 1) {
221
+ throw trackError(id, "needs one stable setup region");
222
+ }
223
+ const chain = /* @__PURE__ */ new Set();
224
+ for (let bone = bones.get(slot.bone); bone; bone = bone.parent === void 0 ? void 0 : bones.get(bone.parent)) {
225
+ chain.add(bone.name);
226
+ }
227
+ const driver = baked?.bone;
228
+ checkStable(id, slot.name, chain, driver, animation);
229
+ for (const { record } of doc.constraints) {
230
+ if (!record) continue;
231
+ if (record.kind === "slider") {
232
+ checkStable(id, slot.name, chain, void 0, { name: record.animation, timelines: record.timelines });
233
+ } else if (record.kind === "physics" ? chain.has(record.bone) : record.bones.some((bone) => chain.has(bone))) {
234
+ throw trackError(id, `has a moving or constrained plate ancestry (${JSON.stringify(record.name)})`);
235
+ }
236
+ }
237
+ if (baked === void 0) continue;
238
+ const parentName = bones.get(slot.bone)?.parent;
239
+ const parent = setup.bones.find((bone) => bone.name === parentName);
240
+ if (driver !== slot.bone || !parent?.active || parent.parent !== null || drivers.has(driver)) {
241
+ throw trackError(id, "needs an independent translate track on its compiled slot’s direct root-child bone");
242
+ }
243
+ drivers.add(driver);
244
+ const rows = animation.timelines.bones.filter((row) => row.name === driver);
245
+ const timelines = rows[0]?.timelines;
246
+ const keys = timelines?.[0]?.keys;
247
+ const duration = animation.timelines.duration;
248
+ const isCenter = (key) => key.values[0] === 0 && key.values[1] === 0;
249
+ if (rows.length !== 1 || timelines?.length !== 1 || timelines[0].kind !== "translate" || !keys || keys.length < 2 || keys[0].time !== 0 || keys[keys.length - 1].time !== duration || !isCenter(keys[0]) || !isCenter(keys[keys.length - 1]) || keys.some((key, i) => key.curve !== "linear" || !Number.isFinite(key.time) || key.values.length !== 2 || !key.values.every(Number.isFinite) || i > 0 && key.time <= keys[i - 1].time)) {
250
+ throw trackError(id, "needs a finite linear translate loop with ordered keys and setup-center endpoints");
251
+ }
252
+ const range = { ...ZERO_RANGE };
253
+ let amplitudeX = 0;
254
+ let horizontal = parent.c === 0 && parent.a !== 0;
255
+ for (const { values: [x, y] } of keys) {
256
+ horizontal &&= y === 0;
257
+ amplitudeX = Math.max(amplitudeX, Math.abs(x));
258
+ const dx = parent.a * x + parent.b * y;
259
+ const dy = -(parent.c * x + parent.d * y);
260
+ range.minX = Math.min(range.minX, dx);
261
+ range.maxX = Math.max(range.maxX, dx);
262
+ range.minY = Math.min(range.minY, dy);
263
+ range.maxY = Math.max(range.maxY, dy);
264
+ }
265
+ if (!Object.values(range).every(Number.isFinite)) throw trackError(id, "has a non-finite world translation envelope");
266
+ plate.baked = { range, amplitudeX, horizontalRoot: horizontal ? parent.name : void 0, keys };
267
+ }
268
+ const backdrop = plates.find((plate) => plate.role === "backdrop");
269
+ const backdropGain = gains.get(backdrop.id);
270
+ const reference = backdrop.baked;
271
+ if (options.autoSweep && plates.some((plate) => plate.baked)) {
272
+ throw trackError(backdrop.id, "cannot combine a camera-only autoSweep with baked plate motion");
273
+ }
274
+ for (const { id, baked } of plates) {
275
+ if (gains.has(id)) continue;
276
+ const comparable = baked && reference && reference.horizontalRoot !== void 0 && baked.horizontalRoot === reference.horizontalRoot && reference.amplitudeX > 0 && baked.amplitudeX > 0 && baked.keys.length === reference.keys.length && baked.keys.every((key, i) => key.time === reference.keys[i].time && Math.sign(key.values[0]) === Math.sign(reference.keys[i].values[0]));
277
+ const gain = comparable ? backdropGain * (baked.amplitudeX / reference.amplitudeX) : NaN;
278
+ if (!Number.isFinite(gain)) {
279
+ throw trackError(id, `needs an explicit gain for motion relative to backdrop plane ${JSON.stringify(backdrop.id)}`);
280
+ }
281
+ gains.set(id, gain);
282
+ }
283
+ return { plates, backdrop: backdrop.id, figureSlots, gains };
284
+ }
285
+ function transformFrame(frame, shiftFor, { origin = NEUTRAL, scale = { x: 1, y: 1 }, centered, clipInStockSpace = false } = {}) {
286
+ const clips = /* @__PURE__ */ new Map();
287
+ const native = origin.x === 0 && origin.y === 0 && scale.x === 1 && scale.y === 1;
288
+ return { order: frame.order.map((slot) => {
289
+ const shift = shiftFor(slot);
290
+ const setup = centered?.get(slot.slot);
291
+ if (native && shift.x === 0 && shift.y === 0 && !setup) {
292
+ return clipInStockSpace && slot.clip ? rememberComposedClip({ ...slot }, slot, shift, origin, scale) : slot;
293
+ }
294
+ 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
+ let clip = slot.clip;
296
+ if (clip) {
297
+ const transformed = clips.get(clip) ?? { ...clip, polygon: transform(clip.polygon) };
298
+ clips.set(clip, transformed);
299
+ clip = transformed;
300
+ }
301
+ 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
+ if (!clipInStockSpace || !slot.clip) return positioned;
303
+ const source = slot.kind === "region" && setup ? { ...slot, corners: setup.corners.map((value, i) => i % 2 === 0 ? value - shift.x : value + shift.y) } : slot;
304
+ return rememberComposedClip(positioned, source, shift, origin, scale);
305
+ }) };
306
+ }
307
+ const stageTop = (stage) => stage.y + stage.height;
308
+ const edgeTolerance = (a, b) => Math.max(Math.abs(a), Math.abs(b), 1) * 2 ** -23;
309
+ function requireStage(stage) {
310
+ if (!stage || ![stage.x, stage.y, stage.width, stage.height, stage.x + stage.width, stageTop(stage)].every(Number.isFinite) || stage.x + stage.width <= stage.x || stageTop(stage) <= stage.y) {
311
+ throw new ComposedTakeError("COMPOSED_STAGE_REQUIRED", "the compiled model needs a positive stage with finite coordinates");
312
+ }
313
+ return stage;
314
+ }
315
+ function backdropAlphaAudit(renderer) {
316
+ let lastNonOpaque;
317
+ let renderFailure;
318
+ return (frame, viewport, pixelRatio = 1) => {
319
+ renderer.viewport = viewport;
320
+ renderer.pixelRatio = pixelRatio;
321
+ try {
322
+ renderer.render(frame);
323
+ } catch (error) {
324
+ renderFailure = { error };
325
+ lastNonOpaque = void 0;
326
+ throw error;
327
+ }
328
+ if (renderer.framesReused && renderFailure) throw renderFailure.error;
329
+ renderFailure = void 0;
330
+ if (!renderer.framesReused || lastNonOpaque === void 0) {
331
+ lastNonOpaque = void 0;
332
+ const ctx = renderer.canvas.getContext("2d");
333
+ if (!ctx) throw new Error("Canvas 2D readback is unavailable");
334
+ const { data } = ctx.getImageData(0, 0, renderer.canvas.width, renderer.canvas.height);
335
+ let count = 0;
336
+ for (let i = 3; i < data.length; i += 4) count += Number(data[i] !== 255);
337
+ lastNonOpaque = count;
338
+ }
339
+ return lastNonOpaque;
340
+ };
341
+ }
342
+ function backdropGuard(audit, stage) {
343
+ return (order, layout, mode) => {
344
+ if (mode === "fixed") return;
345
+ const shift = planeOffsets(layout.excursion, mode).background;
346
+ const requested = { x: Math.abs(shift.x), y: Math.abs(shift.y) };
347
+ const x = requested.x * stage.width / layout.cssWidth;
348
+ const y = requested.y * stage.height / layout.cssHeight;
349
+ const stageRight = stage.x + stage.width;
350
+ const topOfStage = stageTop(stage);
351
+ const bounds = { left: stage.x - x, right: stageRight + x, top: topOfStage + y, bottom: stage.y - y };
352
+ let left = Infinity, right = -Infinity, top = -Infinity, bottom = Infinity;
353
+ for (const slot of order) {
354
+ const points = slot.kind === "region" ? slot.corners : slot.vertices;
355
+ for (let i = 0; i < points.length; i += 2) {
356
+ left = Math.min(left, points[i]);
357
+ right = Math.max(right, points[i]);
358
+ bottom = Math.min(bottom, points[i + 1]);
359
+ top = Math.max(top, points[i + 1]);
360
+ }
361
+ }
362
+ const fail = (detail) => {
363
+ const cssPixels = (value) => Number.isFinite(value) ? String(Number(value.toFixed(3))) : "unavailable";
364
+ const available = (edge, stageEdge, sign, cssPerUnit) => {
365
+ if (!Number.isFinite(edge)) return "unavailable";
366
+ const margin = (edge - stageEdge) * sign;
367
+ return cssPixels(Math.abs(margin) <= edgeTolerance(edge, stageEdge) ? 0 : margin * cssPerUnit);
368
+ };
369
+ const cssPerX = layout.cssWidth / stage.width;
370
+ const cssPerY = layout.cssHeight / stage.height;
371
+ const horizontal = `left=${available(left, stage.x, -1, cssPerX)}, right=${available(right, stageRight, 1, cssPerX)}`;
372
+ const vertical = `top=${available(top, topOfStage, 1, cssPerY)}, bottom=${available(bottom, stage.y, -1, cssPerY)}`;
373
+ return new ComposedTakeError(
374
+ "COMPOSED_BACKDROP_COVERAGE",
375
+ `${mode} at ${cssPixels(layout.cssWidth)} × ${cssPixels(layout.cssHeight)} CSS px needs an opaque backdrop (camera excursion ${cssPixels(layout.excursion.x)} × ${cssPixels(layout.excursion.y)} CSS px); requested shift per edge X=${cssPixels(requested.x)}, Y=${cssPixels(requested.y)} CSS px; available geometric overscan ${horizontal}, ${vertical} CSS px; ${detail}`
376
+ );
377
+ };
378
+ if (!Object.values(bounds).every(Number.isFinite)) throw fail("the requested envelope has non-finite world bounds");
379
+ const outside = (edge, expected, sign) => !Number.isFinite(edge) || (edge - expected) * sign > edgeTolerance(edge, expected);
380
+ const uncovered = [
381
+ outside(left, bounds.left, 1) && "left",
382
+ outside(right, bounds.right, -1) && "right",
383
+ outside(top, bounds.top, -1) && "top",
384
+ outside(bottom, bounds.bottom, 1) && "bottom"
385
+ ].filter(Boolean);
386
+ if (uncovered.length) throw fail(`uncovered geometric edges ${uncovered.join(", ")}`);
387
+ const width = Math.ceil(layout.width + 2 * x * layout.width / stage.width);
388
+ const height = Math.ceil(layout.height + 2 * y * layout.height / stage.height);
389
+ const envelope = transformFrame({ order }, () => NEUTRAL, {
390
+ origin: { x: bounds.left, y: bounds.top },
391
+ scale: { x: width / (bounds.right - bounds.left), y: height / (bounds.top - bounds.bottom) }
392
+ });
393
+ let lastNonOpaque;
394
+ try {
395
+ lastNonOpaque = audit(envelope, { x: 0, y: -height, width, height });
396
+ } catch (error) {
397
+ throw fail(`backdrop alpha cannot be read (${String(error)})`);
398
+ }
399
+ if (lastNonOpaque) throw fail(`${lastNonOpaque} envelope pixels have alpha below 255`);
400
+ };
401
+ }
402
+ function plateCoverageError(id, mode, detail) {
403
+ return new ComposedTakeError("COMPOSED_BACKDROP_COVERAGE", `plane ${JSON.stringify(id)} in ${mode}: ${detail}`);
404
+ }
405
+ function livePlates(frame, named, mode) {
406
+ const slots = new Map(frame.order.map((slot) => [slot.slot, slot]));
407
+ return named.plates.map((plate) => {
408
+ const { id, role, setup, baked } = plate;
409
+ const slot = slots.get(setup.slot);
410
+ if (slot?.kind !== "region") throw plateCoverageError(id, mode, "missing live rigid quad (all edges)");
411
+ if (!baked && role === "overlay") return { plate, slot, live: NEUTRAL };
412
+ const { corners } = slot;
413
+ const x = corners[0] - setup.corners[0];
414
+ const y = setup.corners[1] - corners[1];
415
+ const range = baked?.range ?? ZERO_RANGE;
416
+ const tolerance = Math.max(...corners.map((value, i) => edgeTolerance(value, setup.corners[i])));
417
+ if (slot.region !== setup.region || slot.page !== setup.page || corners.length !== 8 || !corners.every((value, i) => Math.abs(value - (setup.corners[i] + (i % 2 === 0 ? x : -y))) <= tolerance) || x < range.minX - tolerance || x > range.maxX + tolerance || y < range.minY - tolerance || y > range.maxY + tolerance) {
418
+ throw plateCoverageError(id, mode, "live quad is outside its stable translation contract (all edges)");
419
+ }
420
+ return { plate, slot, live: { x, y } };
421
+ });
422
+ }
423
+ function plateEnvelope(baked, pointer, sweep, mode) {
424
+ if (mode === "fixed") return baked;
425
+ if (mode === "pan") return {
426
+ minX: baked.minX - pointer.x,
427
+ maxX: baked.maxX + pointer.x,
428
+ minY: baked.minY - pointer.y,
429
+ maxY: baked.maxY + pointer.y
430
+ };
431
+ const x = Math.max(pointer.x, sweep.x);
432
+ const y = Math.max(pointer.y, sweep.y);
433
+ return {
434
+ minX: Math.min(baked.minX, -x),
435
+ maxX: Math.max(baked.maxX, x),
436
+ minY: Math.min(baked.minY, -y),
437
+ maxY: Math.max(baked.maxY, y)
438
+ };
439
+ }
440
+ function checkPlateEnvelopes(stage, layout, mode, excursion, plates, gains, sweep) {
441
+ const backingX = layout.width / stage.width;
442
+ const backingY = layout.height / stage.height;
443
+ const cssToBacking = { x: layout.width / layout.cssWidth, y: layout.height / layout.cssHeight };
444
+ for (const { plate: { id, setup, baked, role }, slot } of plates) {
445
+ const stable = baked || role === "backdrop";
446
+ const gain = Math.abs(mode === "pan" ? 1 : gains.get(id));
447
+ const range = baked?.range ?? ZERO_RANGE;
448
+ const requested = plateEnvelope(
449
+ {
450
+ minX: range.minX * backingX,
451
+ maxX: range.maxX * backingX,
452
+ minY: range.minY * backingY,
453
+ maxY: range.maxY * backingY
454
+ },
455
+ { x: gain * excursion.x * cssToBacking.x, y: gain * excursion.y * cssToBacking.y },
456
+ { x: gain * sweep.x * cssToBacking.x, y: gain * sweep.y * cssToBacking.y },
457
+ mode
458
+ );
459
+ const left = -requested.maxX;
460
+ const right = layout.width - requested.minX;
461
+ const top = -requested.maxY;
462
+ const bottom = layout.height - requested.minY;
463
+ const corners = stable ? setup.corners : slot.corners;
464
+ const xs = [0, 2, 4, 6].map((i) => (corners[i] - stage.x) * backingX);
465
+ const ys = [1, 3, 5, 7].map((i) => (stageTop(stage) - corners[i]) * backingY);
466
+ const bounds = (numbers) => `[${numbers.map((n) => Number(n.toFixed(4))).join(", ")}]`;
467
+ const fail = (detail) => plateCoverageError(id, mode, `${detail}; at ${layout.width} × ${layout.height} backing px, swept stage X=${bounds([left, right])}, Y=${bounds([top, bottom])}, quad X=${bounds([Math.min(...xs), Math.max(...xs)])}, Y=${bounds([Math.min(...ys), Math.max(...ys)])}`);
468
+ if (corners.length !== 8 || ![left, right, top, bottom, ...xs, ...ys].every((value) => Number.isFinite(Math.fround(value)))) {
469
+ throw fail("non-finite swept quad bounds (all edges)");
470
+ }
471
+ if (!xs.every((x) => [requested.minX, requested.maxX].every((shift) => Number.isFinite(Math.fround(x + shift)))) || !ys.every((y) => [requested.minY, requested.maxY].every((shift) => Number.isFinite(Math.fround(y + shift))))) {
472
+ throw fail("swept quad exceeds finite backing coordinates (all edges)");
473
+ }
474
+ const edgeNames = ["left", "top", "right", "bottom"];
475
+ const distances = xs.map((x, i) => {
476
+ const next = (i + 1) % 4;
477
+ const dx = xs[next] - x;
478
+ const dy = ys[next] - ys[i];
479
+ const length = Math.hypot(dx, dy);
480
+ return (px, py) => (dx * (py - ys[i]) - dy * (px - x)) / length;
481
+ });
482
+ const winding = Math.sign(distances[0](xs[2], ys[2]));
483
+ const invalid = distances.findIndex((distance, i) => [2, 3].some((step) => {
484
+ const corner = (i + step) % 4;
485
+ return !(distance(xs[corner], ys[corner]) * winding > 0);
486
+ }));
487
+ if (invalid !== -1) throw fail(`invalid quad at ${edgeNames[invalid]} edge`);
488
+ if (role === "overlay") continue;
489
+ const tolerance = Math.max(1, ...xs.map(Math.abs), ...ys.map(Math.abs), Math.abs(right), Math.abs(bottom)) * 2 ** -23;
490
+ const uncovered = edgeNames.filter((_edge, i) => [left, right].some((x) => [top, bottom].some((y) => distances[i](x, y) * winding < -tolerance)));
491
+ if (uncovered.length) throw fail(`uncovered geometric edges ${uncovered.join(", ")}`);
492
+ }
493
+ }
494
+ async function mountComposedTake(root, options) {
495
+ const initial = options.camera ?? "fixed";
496
+ checkMode(initial);
497
+ if (options.loop !== true) throw new ComposedTakeError("COMPOSED_LOOP_REQUIRED", "declare the existing take as loop: true");
498
+ const override = options.maxDisplacement;
499
+ const validLimit = (limit) => limit && Number.isFinite(limit.x) && limit.x >= 0 && Number.isFinite(limit.y) && limit.y >= 0;
500
+ if (override !== void 0 && !validLimit(override)) {
501
+ throw new ComposedTakeError("COMPOSED_INVALID_DISPLACEMENT", "x and y must both be finite nonnegative CSS pixel excursions");
502
+ }
503
+ const explicit = override && { ...override };
504
+ const sweep = options.autoSweep;
505
+ if (sweep !== void 0 && (!sweep || !Number.isFinite(sweep.periodSeconds) || sweep.periodSeconds <= 0 || !validLimit(sweep.maxDisplacement))) {
506
+ throw new ComposedTakeError("COMPOSED_INVALID_DISPLACEMENT", "autoSweep needs a positive finite periodSeconds and finite nonnegative axis caps");
507
+ }
508
+ const sweepLimit = sweep ? { ...sweep.maxDisplacement } : NEUTRAL;
509
+ const sweepPeriod = sweep?.periodSeconds;
510
+ const transitionSeconds = (options.transitionMs === void 0 ? DEFAULT_TRANSITION_MS : options.transitionMs) / 1e3;
511
+ if (!Number.isFinite(options.transitionMs ?? DEFAULT_TRANSITION_MS) || !(transitionSeconds > 0)) {
512
+ throw new ComposedTakeError("COMPOSED_INVALID_DISPLACEMENT", "transitionMs must be positive and finite");
513
+ }
514
+ const assets = await loadModel({ modelUrl: options.modelUrl, regions: "none", setsUrl: null, crossOrigin: "anonymous" }).catch((error) => {
515
+ if (error instanceof Error && /(?:problem\(s\): |; )(?:stage[.: ]|section "stage" is missing(?=; | — |$))/.test(error.message)) {
516
+ throw new ComposedTakeError("COMPOSED_STAGE_REQUIRED", "the compiled model needs a valid stage", error);
517
+ }
518
+ throw error;
519
+ });
520
+ const doc = root.ownerDocument;
521
+ const surface = doc.createElement("div");
522
+ let player;
523
+ let audit;
524
+ try {
525
+ let syncTurn = function(next) {
526
+ if (!dials.length) return;
527
+ const weight = mode === "parallax" && next === mode ? handoff.weight : 0;
528
+ const pointer = weight === 0 ? NEUTRAL : handoff.pointer;
529
+ if (weight !== turnInput.weight || pointer.x !== turnInput.pointer.x || pointer.y !== turnInput.pointer.y) {
530
+ turnInput = { weight, pointer };
531
+ }
532
+ }, measure = function() {
533
+ const box = surface.getBoundingClientRect();
534
+ const cssWidth = box.width || stage.width;
535
+ const cssHeight = box.height || stage.height;
536
+ const dpr = window.devicePixelRatio;
537
+ if (layout?.cssWidth === cssWidth && layout.cssHeight === cssHeight && layout.dpr === dpr) return;
538
+ const width = Math.ceil(cssWidth * dpr);
539
+ const height = Math.ceil(cssHeight * dpr);
540
+ const pixelRatio = width / stage.width;
541
+ const native = [stage.x, stage.y, stage.width, stage.height].every(Number.isInteger) && stage.width * pixelRatio === width && stage.height * pixelRatio === height;
542
+ const excursion = explicit ?? cameraLimits(cssWidth, cssHeight);
543
+ 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;
546
+ }, cameraExcursionFor = function(next) {
547
+ const { excursion } = layout;
548
+ return next === "parallax" && dials.length ? { x: excursion.x, y: 0 } : excursion;
549
+ }, prepareFrame = function(frame, plates, next, excursion) {
550
+ const worldX = stage.width / layout.cssWidth;
551
+ const worldY = stage.height / layout.cssHeight;
552
+ const centered = /* @__PURE__ */ new Map();
553
+ const shifts = planeOffsets(cssTarget(camera, excursion), next);
554
+ let frameOffsets = shifts;
555
+ let namedShifts;
556
+ if (named) {
557
+ const liveByPlane = new Map(plates.map((plate) => [plate.plate.id, plate]));
558
+ const changingMode = mode !== next;
559
+ const weight = changingMode ? 0 : handoff.weight;
560
+ const pointer = cssTarget(changingMode ? NEUTRAL : next === "pan" ? camera : handoff.pointer, excursion);
561
+ const phase = sweepPeriod === void 0 ? 0 : Math.sin(2 * Math.PI * (poser.time % sweepPeriod / sweepPeriod));
562
+ const automatic = { x: sweepLimit.x * phase, y: sweepLimit.y * phase };
563
+ const liveOffsets = /* @__PURE__ */ new Map();
564
+ namedShifts = /* @__PURE__ */ new Map();
565
+ for (const [id, gain] of named.gains) {
566
+ const state = liveByPlane.get(id);
567
+ const live = state?.live ?? NEUTRAL;
568
+ const translated = planeShift(pointer, next === "pan" ? 1 : gain);
569
+ const baked = state?.plate.baked;
570
+ let correction = NEUTRAL;
571
+ let displayed = { x: live.x / worldX, y: live.y / worldY };
572
+ if (next === "pan") {
573
+ correction = translated;
574
+ displayed = { x: displayed.x + correction.x, y: displayed.y + correction.y };
575
+ } else if (next === "parallax") {
576
+ const auto = baked ? displayed : planeShift(automatic, gain);
577
+ displayed = {
578
+ x: (1 - weight) * auto.x + weight * translated.x,
579
+ y: (1 - weight) * auto.y + weight * translated.y
580
+ };
581
+ correction = baked ? { x: weight * (translated.x - auto.x), y: weight * (translated.y - auto.y) } : displayed;
582
+ if (baked && weight === 1 && pointer.x === 0 && pointer.y === 0) centered.set(state.plate.setup.slot, state.plate.setup);
583
+ }
584
+ liveOffsets.set(id, displayed);
585
+ namedShifts.set(id, correction);
586
+ }
587
+ frameOffsets = Object.fromEntries(liveOffsets);
588
+ }
589
+ const shiftFor = (slot) => {
590
+ const { x, y } = namedShifts?.get(planes.get(slot.slot)) ?? shifts[planes.get(slot.slot)];
591
+ return { x: x * stage.width / layout.cssWidth, y: y * stage.height / layout.cssHeight };
592
+ };
593
+ let positioned;
594
+ if (!layout.native) {
595
+ positioned = transformFrame(frame, shiftFor, {
596
+ origin,
597
+ scale: { x: layout.width / stage.width, y: layout.height / stage.height },
598
+ centered,
599
+ clipInStockSpace: true
600
+ });
601
+ } else if (!centered.size && (namedShifts ? [...namedShifts.values()] : Object.values(shifts)).every((shift) => shift.x === 0 && shift.y === 0)) {
602
+ positioned = frame;
603
+ if (frame.order.some((slot) => slot.clip)) {
604
+ positioned = transformFrame(frame, () => NEUTRAL, { clipInStockSpace: true });
605
+ const generation = Object.getOwnPropertyDescriptor(frame, "generation");
606
+ if (generation) Object.defineProperty(positioned, "generation", generation);
607
+ }
608
+ } else {
609
+ positioned = transformFrame(frame, shiftFor, { centered, clipInStockSpace: true });
610
+ }
611
+ return { frame: positioned, offsets: frameOffsets };
612
+ }, checkBackdropAlpha = function(frame, { figureSlots, backdrop }, next) {
613
+ const isFigure = (slot) => figureSlots.has(slot.slot);
614
+ const figures = frame.order.filter(isFigure);
615
+ const firstFigure = figures.length === figureSlots.size ? figures[0] : poser.slotIdentity().slots.find(isFigure);
616
+ const order = frame.order.filter((slot) => slot.z < (firstFigure?.z ?? Infinity));
617
+ coverage.backend = renderer.backend;
618
+ coverage.clipping = renderer.clipping;
619
+ coverage.meshSourceRect = renderer.meshSourceRect;
620
+ let nonOpaque;
621
+ try {
622
+ nonOpaque = auditBackdrop({ order }, renderer.viewport, renderer.pixelRatio);
623
+ } catch (error) {
624
+ throw plateCoverageError(backdrop, next, `backdrop alpha cannot be read (${String(error)})`);
625
+ }
626
+ if (nonOpaque) {
627
+ throw plateCoverageError(backdrop, next, `${nonOpaque} stage pixels have alpha below 255 at ${layout.width} × ${layout.height} backing px`);
628
+ }
629
+ }, currentFrame = function(next) {
630
+ syncTurn(next);
631
+ if (posedTurnInput !== turnInput) poser.repose();
632
+ 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) : [];
637
+ 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) {
644
+ camera = NEUTRAL;
645
+ handoff.reset();
646
+ if (next === "parallax" && hover !== void 0) handoff.enter();
647
+ }
648
+ mode = next;
649
+ if (!named && switching && mode === "fixed") camera = target = NEUTRAL;
650
+ offsets = prepared.offsets;
651
+ if (named && mode === "parallax") handoff.painted();
652
+ canvas.style.visibility = "";
653
+ Object.assign(canvas.style, { width: "100%", height: "100%", transform: "none", pointerEvents: "auto" });
654
+ }, select = function(next, switching, allowFallback) {
655
+ const { frame, backdrop } = currentFrame(next);
656
+ try {
657
+ drawMode(frame, backdrop, next, switching);
658
+ } catch (error) {
659
+ if (!(error instanceof ComposedTakeError) || error.code !== "COMPOSED_BACKDROP_COVERAGE" || next === "fixed" || !named && !allowFallback) throw error;
660
+ try {
661
+ const fixed = turnInput.weight === 0 ? { frame, backdrop } : currentFrame("fixed");
662
+ drawMode(fixed.frame, fixed.backdrop, "fixed", true);
663
+ } catch (fixedError) {
664
+ canvas.style.visibility = "hidden";
665
+ throw fixedError;
666
+ }
667
+ refusal = error;
668
+ if (!allowFallback) throw error;
669
+ }
670
+ }, renderCurrent = function() {
671
+ try {
672
+ select(mode, false, true);
673
+ } catch (error) {
674
+ if (error instanceof ComposedTakeError) refusal = error;
675
+ if (named) canvas.style.visibility = "hidden";
676
+ stopped = true;
677
+ if (frameId !== void 0) window.cancelAnimationFrame(frameId);
678
+ throw error;
679
+ }
680
+ }, setCamera = function(next) {
681
+ if (disposed || stopped) return;
682
+ try {
683
+ checkMode(next);
684
+ measure();
685
+ select(next, true, false);
686
+ refusal = null;
687
+ } catch (error) {
688
+ if (error instanceof ComposedTakeError) refusal = error;
689
+ if (named && next === "fixed") canvas.style.visibility = "hidden";
690
+ throw error;
691
+ }
692
+ }, advanceCamera = function(elapsed) {
693
+ if (!(elapsed > 0)) return;
694
+ if (named && mode === "parallax") handoff.advance(elapsed, target);
695
+ else camera = easeCamera(camera, target, elapsed);
696
+ }, syncCamera = function(now) {
697
+ const next = Math.max(lastCameraAt, now);
698
+ advanceCamera((next - lastCameraAt) / 1e3);
699
+ lastCameraAt = next;
700
+ }, advance = function(rigElapsed, cameraElapsed = rigElapsed) {
701
+ if (disposed || stopped) return;
702
+ advanceCamera(cameraElapsed);
703
+ syncTurn(mode);
704
+ poser.advance(rigElapsed);
705
+ }, render = function() {
706
+ if (disposed || stopped) return;
707
+ measure();
708
+ renderCurrent();
709
+ }, leave = function() {
710
+ if (hover === void 0 || stopped) return;
711
+ if (autoStart) syncCamera(window.performance.now());
712
+ hover = void 0;
713
+ target = NEUTRAL;
714
+ if (mode === "parallax") handoff.leave();
715
+ };
716
+ const stage = requireStage(assets.stage);
717
+ const take = assets.animations.find((animation) => animation.name === options.animation);
718
+ if (!take || !Number.isFinite(take.duration) || take.duration <= 0) {
719
+ throw new ComposedTakeError("COMPOSED_LOOP_REQUIRED", `no positive-duration animation named ${JSON.stringify(options.animation)}`);
720
+ }
721
+ const planes = bindSlots(assets, options);
722
+ const named = namedPlanes(assets, options);
723
+ const dials = named && options.pointerTurn !== false ? discoverTurnDials(assets.document.parsed, assets.animations) : [];
724
+ const handoff = createCameraHandoff(transitionSeconds);
725
+ let mode = initial;
726
+ let turnInput = { weight: 0, pointer: NEUTRAL };
727
+ let posedTurnInput = turnInput;
728
+ let turnValues = [];
729
+ const adjustTurn = (bones) => {
730
+ const { weight, pointer } = turnInput;
731
+ turnValues = dials.map((dial) => {
732
+ const { axis, bone, channel, min, max } = dial;
733
+ const locals = bones.bone(bone);
734
+ const baked = locals[channel];
735
+ const n = turnCoordinate(axis, pointer) / TURN_FULL_RANGE_AT_STAGE_EDGE;
736
+ const limited = normalizedDial(n, dial);
737
+ const value = weight === 0 ? baked : (1 - weight) * baked + weight * limited;
738
+ if (value !== baked) locals[channel] = value;
739
+ return { axis, min, max, baked, pointer: limited, value };
740
+ });
741
+ posedTurnInput = turnInput;
742
+ };
743
+ Object.assign(surface.style, {
744
+ position: "relative",
745
+ overflow: "hidden",
746
+ width: "100%",
747
+ height: "100%",
748
+ aspectRatio: `${stage.width} / ${stage.height}`
749
+ });
750
+ root.appendChild(surface);
751
+ const poser = player = new RigPlayer(surface, assets, { mode: "canvas", adjust: dials.length ? adjustTurn : null });
752
+ const renderer = poser.renderer;
753
+ const coverage = audit = new CanvasRenderer(doc.createElement("div"), assets.pageImages);
754
+ renderer.backend = coverage.backend = options.backend ?? "webgl";
755
+ const canvas = renderer.canvas;
756
+ poser.play(take.name, { loop: true });
757
+ let offsets = planeOffsets(NEUTRAL, "fixed");
758
+ let camera = NEUTRAL;
759
+ let target = NEUTRAL;
760
+ let hover;
761
+ let layout;
762
+ let refusal = null;
763
+ let stopped = false;
764
+ let disposed = false;
765
+ let frameId;
766
+ const window = doc.defaultView;
767
+ const auditBackdrop = backdropAlphaAudit(coverage);
768
+ const requireCoverage = backdropGuard(auditBackdrop, stage);
769
+ const origin = { x: stage.x, y: stageTop(stage) };
770
+ const autoStart = options.autoStart !== false;
771
+ let lastCameraAt = window.performance.now();
772
+ const cssTarget = (point, excursion) => ({ x: point.x * excursion.x, y: point.y * excursion.y });
773
+ measure();
774
+ select(initial, true, named !== void 0);
775
+ const boundaryEvent = (event) => event.target === root || event.bubbles;
776
+ const aim = (event) => {
777
+ if (!event.isPrimary || stopped) return;
778
+ if (named) {
779
+ if (event.pointerType === "touch" || event.type === "pointerenter" && !boundaryEvent(event) || hover !== void 0 && hover !== event.pointerId) return;
780
+ if (event.pointerType === "pen" && event.buttons !== 0) {
781
+ leave();
782
+ return;
783
+ }
784
+ }
785
+ if (!Number.isFinite(event.clientX) || !Number.isFinite(event.clientY)) return;
786
+ const box = surface.getBoundingClientRect();
787
+ 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();
791
+ hover = event.pointerId;
792
+ }
793
+ target = pointerTarget(event.clientX, event.clientY, box);
794
+ };
795
+ const recenter = (event) => {
796
+ if (!event.isPrimary) return;
797
+ if (!named) {
798
+ target = NEUTRAL;
799
+ return;
800
+ }
801
+ if (event.pointerType !== "touch" && hover === event.pointerId && (event.type !== "pointerleave" || boundaryEvent(event))) leave();
802
+ };
803
+ const contact = (event) => {
804
+ if (event.pointerType === "pen" && event.isPrimary && hover === event.pointerId) leave();
805
+ };
806
+ root.addEventListener("pointermove", aim, true);
807
+ root.addEventListener("pointerleave", recenter, true);
808
+ 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
+ }
815
+ const observer = new ResizeObserver(() => {
816
+ try {
817
+ render();
818
+ } catch (error) {
819
+ if (!(error instanceof ComposedTakeError)) throw error;
820
+ }
821
+ });
822
+ observer.observe(surface);
823
+ if (autoStart) {
824
+ let last = window.performance.now();
825
+ lastCameraAt = last;
826
+ frameId = window.requestAnimationFrame(function tick(now) {
827
+ if (disposed || stopped) return;
828
+ const elapsed = Math.max(0, (now - last) / 1e3);
829
+ last = now;
830
+ if (named) {
831
+ syncCamera(now);
832
+ advance(Math.min(elapsed, 1 / 15), 0);
833
+ } else {
834
+ advance(Math.min(elapsed, 1 / 15), elapsed);
835
+ }
836
+ if (named || layout.dpr !== window.devicePixelRatio) measure();
837
+ try {
838
+ renderCurrent();
839
+ } catch (error) {
840
+ if (!(error instanceof ComposedTakeError)) throw error;
841
+ }
842
+ if (!stopped) frameId = window.requestAnimationFrame(tick);
843
+ });
844
+ }
845
+ return {
846
+ canvas,
847
+ player: poser,
848
+ get mode() {
849
+ return mode;
850
+ },
851
+ get offsets() {
852
+ return offsets;
853
+ },
854
+ get cameraExcursion() {
855
+ return cameraExcursionFor(mode);
856
+ },
857
+ cameraExcursionFor,
858
+ get cameraTarget() {
859
+ return cssTarget(target, cameraExcursionFor(mode));
860
+ },
861
+ get turnReadouts() {
862
+ return turnValues.map((reading) => {
863
+ const n = turnCoordinate(reading.axis, target);
864
+ const clamped = mode === "parallax" && hover !== void 0 && (Math.abs(n) >= TURN_FULL_RANGE_AT_STAGE_EDGE || n < 0 && reading.min === 0 || n > 0 && reading.max === 0);
865
+ return { ...reading, clamped };
866
+ });
867
+ },
868
+ get refusal() {
869
+ return refusal;
870
+ },
871
+ setCamera,
872
+ advance,
873
+ render,
874
+ dispose() {
875
+ if (disposed) return;
876
+ disposed = true;
877
+ if (frameId !== void 0) window.cancelAnimationFrame(frameId);
878
+ observer.disconnect();
879
+ root.removeEventListener("pointermove", aim, true);
880
+ root.removeEventListener("pointerleave", recenter, true);
881
+ 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
+ }
888
+ poser.dispose();
889
+ coverage.dispose();
890
+ surface.remove();
891
+ assets.dispose();
892
+ }
893
+ };
894
+ } catch (error) {
895
+ player?.dispose();
896
+ audit?.dispose();
897
+ surface.remove();
898
+ assets.dispose();
899
+ throw error;
900
+ }
901
+ }
902
+ export {
903
+ ComposedTakeError,
904
+ mountComposedTake
905
+ };
906
+ //# sourceMappingURL=composed-take.js.map