rig-review 0.16.0 → 0.18.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,2439 @@
1
+ /**
2
+ * Picked-build Setup and Animate tools in a comparison session (#234).
3
+ *
4
+ * Mounts the existing Setup and Animate panel modules (`AnimationInspectionPanel`, `bindBonesPanel`, `bindRigFieldsPanel`,
5
+ * `bindCutsPanel`, `bindClothPanel`, `bindMeshPanel`, `bindDensityStrip`, `bindChestEditor`, `bindMeshEditor`,
6
+ * `bindWeightsView`, `bindRetargetPanel`, `bindPhysicsPanel`, `bindIdlePanel`, `bindReadingsPanel`,
7
+ * `bindRequirementsPanel`, `bindInspectorBlocks`) against the reviewer's picked build (`a` or `b`).
8
+ * Every producer route is scoped to `/api/compare/<side>/*` and `/compare-rebuild/<side>/:id/*`, and an Apply swaps
9
+ * only `players[pickedSide]`.
10
+ */
11
+ import type { BoneAdjust, ModelAssets, RigPlayer } from '@rig-c/play';
12
+ import type { CompareResponse } from '../src/compare.ts';
13
+ import type { CommentMode } from '../src/stage-comment.ts';
14
+ import { AnimationInspectionPanel } from './animation-inspection.ts';
15
+ import { partBounds, type PartExplorer } from './part-selection.ts';
16
+ import { bindInspectorBlocks, activeBlocksUI, restoreActiveBlocksUI, type InspectorBlocks } from './inspector-blocks.ts';
17
+ import { bindChestEditor, canvasToCrop, bustLabel, bustSides, LANDMARKS, landmarkInputId, rowCircle, type ChestEditor, type LandmarkKey } from './chest-editor.ts';
18
+ import { chestOverlayCircles, chestOverlayPolygons, chestRegionRows, chestRowId, evaluateChestForm } from './chest-regions-tool.ts';
19
+ import { chestRegionsBinding, cropWorldMapping, type CropWorldMapping } from '../src/chest-regions.ts';
20
+ import { bindMeshEditor, meshEditSource, sha256Hex, type MeshEditor } from './mesh-editor.ts';
21
+ import { meshEditBinding, meshEditText, type MeshEditDocument } from '../src/mesh-edit.ts';
22
+ import { bindWeightsView, setupPoseMesh, type WeightsView } from './weights-view.ts';
23
+ import { readSetupPose } from './setup-pose.ts';
24
+ import { bindBonesPanel, type BonesPanel, type BonesCheckView } from './bones-panel.ts';
25
+ import { bindCutsPanel, type CutsPanel } from './cuts-panel.ts';
26
+ import { bindClothPanel, type ClothPanel } from './cloth-panel.ts';
27
+ import { bindMeshPanel, type MeshPanel } from './mesh-panel.ts';
28
+ import { bindDensityStrip, type DensityStripPanel, type DensityStripViewLike } from './density-strip-panel.ts';
29
+ import { densityField, densityPath } from '../src/density-strip.ts';
30
+ import { assertMeshPatch, countsText, meshApplyOutcome, meshPatchOps, setEntryValue, triangleAgreement, type MeshEntry } from '../src/mesh-entry.ts';
31
+ import { bindPhysicsPanel, type PhysicsPanel } from './physics-panel.ts';
32
+ import { tuningRows, readoutRows, barLine, beforeLine, type InspectedCheckView } from '../src/physics-tuning.ts';
33
+ import { bindIdlePanel, type BoneSetup, type IdlePanel } from './idle-panel.ts';
34
+ import { IDLE_READOUT_BARS, type LocalChannel } from '../src/idle-tracks.ts';
35
+ import { bindRigFieldsPanel, type RigFieldsPanel } from './rig-fields-panel.ts';
36
+ import { assertRigFieldOps, RIG_FIELDS_READOUT_BARS, TURN_BONE } from '../src/rig-fields.ts';
37
+ import { bindReadingsPanel, type ReadingsJobView, type ReadingsPanel, type ReadingsRefusal } from './readings-panel.ts';
38
+ import { READINGS_SCHEMA, readingSeekTime, worstLine, type ReadingsContext } from '../src/readings.ts';
39
+ import { bindRequirementsPanel, type RequirementsCatalogView, type RequirementsJobView, type RequirementsPanel, type RequirementsRefusal } from './requirements-panel.ts';
40
+ import { bindRetargetPanel, type PoseMap, type RetargetPanel } from './retarget-panel.ts';
41
+ import type { RetargetFlags } from '../src/retarget.ts';
42
+ import {
43
+ historyRow, isPatchJob, recordFor, refusedText, retargetStage, undoControl,
44
+ appliedRecord, deltaAppliedRecord, deltaOutcomeLine, designatedRegions, handoffText,
45
+ landmarksRequest, seedLandmarks, makePatch, outcomeLine, patchAppliedRecord, patchOutcomeLine,
46
+ pickPart, runRebuild, seedFields, stageModel, retargetAppliedRecord, retargetOutcomeLine, stripPendingAfter,
47
+ type AppliedHistoryView, type UndoView, type AnyJobView, type AppliedDelta, type AppliedPatch,
48
+ type AppliedRecord, type AppliedRetarget, type DeltaJobView, type DeltaRequestBody, type ConfigPatch,
49
+ type PatchJobView, type RebuildJobView, type RebuildRefusal, type RebuildRequestBody, type RebuildStatusView,
50
+ type RetargetJobView, type RetargetRequestBody, type StageChange,
51
+ } from './rebuild-client.ts';
52
+ import { patchRoute } from '../src/retune-route.ts';
53
+ import type { CheckSummary } from '../src/applied-context.ts';
54
+ import { appliedBlockOps, recordBlock, staleReadouts } from '../src/applied-blocks.ts';
55
+ import { compareSeekStep } from '../src/compare-playhead.ts';
56
+ import { composeAdjust, PhysicsPreview } from './preview.ts';
57
+ import {
58
+ createWindModel, environmentFor, windReadout, RUNTIME_START_READOUT, joltPacket, dueJolts, dragMoved,
59
+ loadModelDocument, environmentContext, environmentJson, type JoltStep, type WindSnapshot, type WindState,
60
+ } from '../src/environment.ts';
61
+ import { environmentCheckRows, restartsWindClock, scheduleContext, worldExport, type ClipMove, type EnvironmentCheckView, type WorldExport } from './environment-world.ts';
62
+ import type { OverlayCircle, OverlayMarker, OverlayRegion, OverlaySnapshot } from './rig-overlays.ts';
63
+ import type { PatchOp } from '../src/config-patch.ts';
64
+
65
+ export type Side = 'a' | 'b';
66
+
67
+ interface StageWorld {
68
+ wind: WindState;
69
+ jolts: JoltStep[];
70
+ applied: boolean;
71
+ gravity: number;
72
+ }
73
+
74
+ interface SideBuildState {
75
+ inspectedModel: { url: string; prefix: string; sha256: string } | null;
76
+ stageSource: { url: string; prefix: string; hash: string } | null;
77
+ stageModelHash: string | null;
78
+ partModel: unknown | null;
79
+ inspectedDocument: unknown | null;
80
+ inspectedDocumentReason: string | null;
81
+ rebuildStatus: RebuildStatusView | null;
82
+ appliedOnStage: AppliedRecord | AppliedPatch | AppliedDelta | AppliedRetarget | null;
83
+ readoutStage: AppliedRecord | AppliedPatch | AppliedDelta | AppliedRetarget | null;
84
+ appliedHistory: AppliedHistoryView | null;
85
+ stageCheck: { lines: string[]; check: CheckSummary | null } | null;
86
+ chestInputs: Record<string, string> | null;
87
+ chestMapping: CropWorldMapping;
88
+ stripView: DensityStripViewLike | null;
89
+ stripPending: {
90
+ index: number;
91
+ id: string;
92
+ candidate: string;
93
+ back: {
94
+ url: string;
95
+ prefix: string;
96
+ hash: string;
97
+ applied: AppliedRecord | AppliedPatch | AppliedDelta | AppliedRetarget | null;
98
+ check: { lines: string[]; check: CheckSummary | null } | null;
99
+ };
100
+ } | null;
101
+ readingsJob: ReadingsJobView | null;
102
+ requirementsCatalog: RequirementsCatalogView | null;
103
+ lastOverlay: OverlaySnapshot | null;
104
+ }
105
+
106
+ function emptySideState(): SideBuildState {
107
+ return {
108
+ inspectedModel: null,
109
+ stageSource: null,
110
+ stageModelHash: null,
111
+ partModel: null,
112
+ inspectedDocument: null,
113
+ inspectedDocumentReason: null,
114
+ rebuildStatus: null,
115
+ appliedOnStage: null,
116
+ readoutStage: null,
117
+ appliedHistory: null,
118
+ stageCheck: null,
119
+ chestInputs: null,
120
+ chestMapping: { available: false, reason: 'CHEST_REGION_MAPPING_UNAVAILABLE: no compiled model drawn' },
121
+ stripView: null,
122
+ stripPending: null,
123
+ readingsJob: null,
124
+ requirementsCatalog: null,
125
+ lastOverlay: null,
126
+ };
127
+ }
128
+
129
+ export interface ComparePickedToolsHost {
130
+ data: () => CompareResponse;
131
+ readOnly: () => string | null;
132
+ players: Partial<Record<Side, RigPlayer>>;
133
+ assets: Partial<Record<Side, ModelAssets>>;
134
+ rigScales: Record<Side, number>;
135
+ layers: { images: boolean; mesh: boolean; bones: boolean; meshOpacity: number };
136
+ parts: () => PartExplorer | null;
137
+ time: () => number;
138
+ duration: () => number;
139
+ playing: () => boolean;
140
+ pause: () => void;
141
+ seekTo: (seconds: number) => Promise<void>;
142
+ api: <T>(path: string, init?: RequestInit) => Promise<T>;
143
+ route: (path: string) => string;
144
+ swapSideRig: (side: Side, modelUrl: string, prefix: string, sha256: string, clipName?: string) => Promise<void>;
145
+ redrawOverlays: (fresh: boolean) => void;
146
+ fit: () => void;
147
+ syncLayout: () => void;
148
+ saveDraft: () => void;
149
+ message: (value: string, error?: boolean) => void;
150
+ download: (filename: string, content: string, type: string) => void;
151
+ turnAdjustFor: (side: Side) => BoneAdjust | null;
152
+ syncFeedbackSide: (side: Side) => void;
153
+ }
154
+
155
+ export interface ComparePickedTools {
156
+ mode: () => CommentMode;
157
+ setMode: (mode: CommentMode, options?: { fromTab?: boolean }) => void;
158
+ onInspectorTabChanged: () => void;
159
+ pickedSide: () => Side;
160
+ setPickedSide: (side: Side) => void;
161
+ isSwitchingSide: () => boolean;
162
+ defaultStatusMessage: () => string;
163
+ registerSideModel: (side: Side, modelUrl: string, prefix: string, sha256: string, partModel: unknown | null) => void;
164
+ loadInitialSideStatuses: () => Promise<void>;
165
+ onPosePresented: () => void;
166
+ onPartSelected: (side: Side | null, slot: string | null) => void;
167
+ overlayInputFor: (side: Side) => {
168
+ regions: OverlayRegion[];
169
+ circles: OverlayCircle[];
170
+ markers: OverlayMarker[];
171
+ meshEdit: ReturnType<MeshEditor['overlay']>;
172
+ weights: ReturnType<WeightsView['overlay']>;
173
+ anchors: ReturnType<BonesPanel['overlay']>;
174
+ };
175
+ recordOverlaySnapshot: (side: Side, snapshot: OverlaySnapshot) => void;
176
+ uiState: () => Record<string, string | number | null>;
177
+ restoreUiState: (ui: Record<string, string | number | null>) => void;
178
+ commentRefusal: () => string | null;
179
+ shortcutBlocked: () => boolean;
180
+ busy: () => boolean;
181
+ appliedFor: (side: Side) => AppliedRecord | AppliedPatch | AppliedDelta | AppliedRetarget | null;
182
+ modelHashFor: (side: Side) => string | null;
183
+ seekMode: (target: number, continuing: boolean) => 'settle' | 'seek';
184
+ stepSide: (mode: 'present' | 'settle' | 'seek', side: Side, target: number) => void;
185
+ dispose: () => void;
186
+ }
187
+
188
+ const el = <T extends HTMLElement = HTMLElement>(id: string): T => {
189
+ const node = document.getElementById(id);
190
+ if (!node) throw new Error(`Missing compare UI element: ${id}`);
191
+ return node as T;
192
+ };
193
+ const input = (id: string) => el<HTMLInputElement>(id);
194
+ const select = (id: string) => el<HTMLSelectElement>(id);
195
+ const button = (id: string) => el<HTMLButtonElement>(id);
196
+ const text = (id: string, value: string) => { el(id).textContent = value; };
197
+ const option = (value: string, label: string) => { const o = document.createElement('option'); o.value = value; o.textContent = label; return o; };
198
+ const errorText = (error: unknown) => error instanceof Error ? error.message : String(error);
199
+
200
+ function boneSetup(document: unknown): BoneSetup {
201
+ const list = (document as { bones?: unknown })?.bones;
202
+ const map = new Map<string, Partial<Record<LocalChannel, number>>>();
203
+ for (const b of Array.isArray(list) ? list : []) {
204
+ if (!b || typeof (b as { name?: unknown }).name !== 'string') continue;
205
+ const o = b as Record<string, unknown>, v: Partial<Record<LocalChannel, number>> = {};
206
+ for (const c of ['rotation', 'x', 'y', 'scaleX', 'scaleY', 'shearX', 'shearY'] as const) {
207
+ if (typeof o[c] === 'number') v[c] = o[c] as number;
208
+ }
209
+ map.set(o.name as string, v);
210
+ }
211
+ return { names: [...map.keys()], get: bone => map.get(bone) };
212
+ }
213
+
214
+ /**
215
+ * Dynamic element proxy that forwards DOM queries/captures to the currently picked side's element
216
+ * (`a-<suffix>` or `b-<suffix>`) and attaches event listeners to both sides, firing only when the event
217
+ * originates on the currently picked side.
218
+ */
219
+ function sideElementProxy<T extends HTMLElement>(getSide: () => Side, suffix: 'pane' | 'viewport' | 'overlay'): T {
220
+ const targetFor = (side: Side) => el<T>(`${side}-${suffix}`);
221
+ const wrapped = new Map<EventListenerOrEventListenerObject, { a: EventListener; b: EventListener }>();
222
+ return new Proxy({} as T, {
223
+ get(_target, prop) {
224
+ const current = targetFor(getSide());
225
+ if (prop === 'addEventListener') {
226
+ return (type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions) => {
227
+ if (!listener) return;
228
+ const call = (side: Side) => (event: Event) => {
229
+ if (getSide() !== side) return;
230
+ if (typeof listener === 'function') listener.call(targetFor(side), event);
231
+ else listener.handleEvent(event);
232
+ };
233
+ const pair = { a: call('a'), b: call('b') };
234
+ wrapped.set(listener, pair);
235
+ targetFor('a').addEventListener(type, pair.a, options);
236
+ targetFor('b').addEventListener(type, pair.b, options);
237
+ };
238
+ }
239
+ if (prop === 'removeEventListener') {
240
+ return (type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | EventListenerOptions) => {
241
+ if (!listener) return;
242
+ const pair = wrapped.get(listener);
243
+ if (!pair) return;
244
+ targetFor('a').removeEventListener(type, pair.a, options);
245
+ targetFor('b').removeEventListener(type, pair.b, options);
246
+ wrapped.delete(listener);
247
+ };
248
+ }
249
+ const value = Reflect.get(current, prop, current);
250
+ return typeof value === 'function' ? value.bind(current) : value;
251
+ },
252
+ set(_target, prop, value) {
253
+ const current = targetFor(getSide());
254
+ return Reflect.set(current, prop, value, current);
255
+ },
256
+ });
257
+ }
258
+
259
+ export function mountComparePickedTools(host: ComparePickedToolsHost): ComparePickedTools {
260
+ let workspaceMode: CommentMode = 'compare';
261
+ let pickedSide: Side = 'a';
262
+ let switchingSide = false;
263
+ const sides: Record<Side, SideBuildState> = { a: emptySideState(), b: emptySideState() };
264
+ let rebuildBusy = false, densityBusy = false, readingsBusy = false, environmentCheckBusy = false;
265
+ let handoffTimer: ReturnType<typeof setTimeout> | null = null;
266
+ let lastMeshPatch: ConfigPatch | null = null;
267
+ const disposers: (() => void)[] = [];
268
+
269
+ const wind = createWindModel();
270
+ let joltQueue: JoltStep[] = [];
271
+ let environmentNote = '';
272
+ let steppedLive = false;
273
+ const physicsPreview = new PhysicsPreview();
274
+ let idleAdjust: BoneAdjust | null = null;
275
+ let dialAdjust: BoneAdjust | null = null;
276
+
277
+ let inspectorBlocks: InspectorBlocks | null = null;
278
+ let animationPanel: AnimationInspectionPanel | null = null;
279
+ let chestEditor: ChestEditor | null = null;
280
+ let meshEditor: MeshEditor | null = null;
281
+ let weightsView: WeightsView | null = null;
282
+ let bonesPanel: BonesPanel | null = null;
283
+ let cutsPanel: CutsPanel | null = null;
284
+ let clothPanel: ClothPanel | null = null;
285
+ let meshPanel: MeshPanel | null = null;
286
+ let densityStrip: DensityStripPanel | null = null;
287
+ let physicsPanel: PhysicsPanel | null = null;
288
+ let idlePanel: IdlePanel | null = null;
289
+ let rigFieldsPanel: RigFieldsPanel | null = null;
290
+ let readingsPanel: ReadingsPanel | null = null;
291
+ let requirementsPanel: RequirementsPanel | null = null;
292
+ let retargetPanel: RetargetPanel | null = null;
293
+
294
+ const currentState = (): SideBuildState => sides[pickedSide];
295
+ const currentPlayer = (): RigPlayer | undefined => host.players[pickedSide];
296
+ const currentAssets = (): ModelAssets | undefined => host.assets[pickedSide];
297
+ const currentSideData = () => host.data()[pickedSide];
298
+ const sideApiPrefix = (side: Side = pickedSide) => `/api/compare/${side}`;
299
+
300
+ function rigProject(side: Side = pickedSide) {
301
+ const root = el(`${side}-root`);
302
+ const scale = host.rigScales[side];
303
+ return (x: number, y: number) => ({
304
+ x: parseFloat(root.style.left || '0') + x * scale,
305
+ y: parseFloat(root.style.top || '0') - y * scale,
306
+ });
307
+ }
308
+
309
+ function currentInspector(): string {
310
+ return document.querySelector<HTMLElement>('[data-inspector][aria-selected="true"]')?.dataset.inspector ?? 'view';
311
+ }
312
+
313
+ function selectInspectorTab(name: 'view' | 'rig' | 'playback' | 'feedback'): void {
314
+ const tab = document.querySelector<HTMLButtonElement>(`[data-inspector="${name}"]`);
315
+ if (tab && tab.getAttribute('aria-selected') !== 'true') tab.click();
316
+ }
317
+
318
+ function defaultStatusMessage(): string {
319
+ if (workspaceMode === 'compare') return 'Inspecting both rigs at the actual reference video time.';
320
+ const d = host.data();
321
+ const title = d ? d[pickedSide].manifest.title : pickedSide.toUpperCase();
322
+ const sideUpper = pickedSide.toUpperCase();
323
+ const modeLabel = workspaceMode === 'setup' ? 'Setup' : 'Animate';
324
+ return `Inspecting Build ${sideUpper} (${title}) in ${modeLabel} mode at the actual reference video time; Apply rebuilds only Build ${sideUpper} in scratch.`;
325
+ }
326
+
327
+ function syncPickedBanner(): void {
328
+ const d = host.data();
329
+ const title = d ? d[pickedSide].manifest.title : pickedSide.toUpperCase();
330
+ const sideUpper = pickedSide.toUpperCase();
331
+ const modeLabel = workspaceMode === 'setup' ? 'Setup' : 'Animate';
332
+ const isCompare = workspaceMode === 'compare';
333
+ const label = document.getElementById('picked-build-label');
334
+ if (label) label.textContent = `Build ${sideUpper} — ${title}`;
335
+ for (const btn of document.querySelectorAll<HTMLButtonElement>('#mode-build-picker [data-build-side]')) {
336
+ const active = btn.dataset.buildSide === pickedSide;
337
+ btn.setAttribute('aria-pressed', String(active));
338
+ }
339
+ const picker = document.getElementById('mode-build-picker');
340
+ if (picker) picker.hidden = isCompare;
341
+ const stageLayout = document.getElementById('stage-layout');
342
+ if (stageLayout) {
343
+ stageLayout.dataset.workspaceMode = workspaceMode;
344
+ stageLayout.dataset.pickedSide = pickedSide;
345
+ }
346
+ for (const s of ['a', 'b'] as const) {
347
+ const pane = document.getElementById(`${s}-pane`);
348
+ if (pane) {
349
+ if (!isCompare && s === pickedSide) pane.dataset.picked = 'true';
350
+ else delete pane.dataset.picked;
351
+ }
352
+ }
353
+ host.parts()?.setVisibleSide(isCompare ? null : pickedSide);
354
+ host.parts()?.setStatusHint(
355
+ isCompare
356
+ ? null
357
+ : `Setup and Animate tools target Build ${sideUpper} (${title}): Apply rebuilds only Build ${sideUpper} in scratch; supplied source art and compiled packages on disk are never modified.`,
358
+ );
359
+ const toolbarHint = document.getElementById('toolbar-mode-hint');
360
+ if (toolbarHint) {
361
+ toolbarHint.textContent = isCompare
362
+ ? 'Inspect A and B at the reference video time'
363
+ : `Inspect Build ${sideUpper} (${title}) in ${modeLabel} mode at the reference video time`;
364
+ }
365
+ const inputsHint = document.querySelector<HTMLElement>('#workspace-left .workspace-sources > p.hint, #workspace-left > p.hint');
366
+ if (inputsHint) {
367
+ inputsHint.textContent = isCompare
368
+ ? 'A and B retain their fixed source bindings. The reference video and shared animation are named above the stage.'
369
+ : `Editing Build ${sideUpper} (${title}) in ${modeLabel} mode; Apply writes to scratch while A and B retain their fixed on-disk source bindings.`;
370
+ }
371
+ const rigHint = document.getElementById('rig-inspector-hint');
372
+ if (rigHint) {
373
+ rigHint.textContent = isCompare
374
+ ? 'These controls show actual images, last-drawn mesh edges and named bone points. Both builds use the fixed animation named above. This inspector does not author geometry or motion.'
375
+ : `These controls show actual images, last-drawn mesh edges and named bone points for Build ${sideUpper} (${title}). Setup tools apply changes only to Build ${sideUpper} in a scratch build; on-disk packages stay immutable.`;
376
+ }
377
+ const playbackHint = document.getElementById('playback-inspector-hint');
378
+ if (playbackHint) {
379
+ playbackHint.textContent = isCompare
380
+ ? 'Motion is read only. The reference video FPS is not used to infer the pose frame clock.'
381
+ : `Inspecting Build ${sideUpper} (${title}) in ${modeLabel} mode: Animate tools apply motion changes only to Build ${sideUpper} in a scratch build. The reference video FPS is not used to infer the pose frame clock.`;
382
+ }
383
+ const msgNode = document.getElementById('message');
384
+ if (msgNode && !msgNode.classList.contains('error')) {
385
+ host.message(defaultStatusMessage());
386
+ }
387
+ host.syncLayout();
388
+ }
389
+
390
+ function moveStageHandlesToPickedSide(): void {
391
+ const viewport = document.getElementById(`${pickedSide}-viewport`);
392
+ if (!viewport) return;
393
+ const empty = document.getElementById(`${pickedSide}-empty`);
394
+ for (const id of ['idle-handles', 'rig-fields-stage']) {
395
+ const node = document.getElementById(id);
396
+ if (node && node.parentElement !== viewport) {
397
+ if (empty && empty.parentElement === viewport) viewport.insertBefore(node, empty);
398
+ else viewport.append(node);
399
+ }
400
+ }
401
+ const picks = document.querySelector<HTMLElement>('.animation-stage-picks');
402
+ if (picks && picks.parentElement !== viewport) viewport.append(picks);
403
+ }
404
+
405
+ function setAdjust(side: Side = pickedSide): void {
406
+ const player = host.players[side];
407
+ if (!player) return;
408
+ const baseTurn = host.turnAdjustFor(side);
409
+ player.adjust = side === pickedSide ? composeAdjust(baseTurn, composeAdjust(idleAdjust, dialAdjust)) : baseTurn;
410
+ if (player.current && !host.playing()) {
411
+ player.repose();
412
+ player.draw();
413
+ host.parts()?.present(side);
414
+ host.redrawOverlays(true);
415
+ }
416
+ }
417
+
418
+ function syncModeButtons(): void {
419
+ const expected = workspaceMode === 'setup' ? 'rig' : workspaceMode === 'animate' ? 'playback' : 'compare';
420
+ for (const btn of document.querySelectorAll<HTMLButtonElement>('.mode-switch [data-mode]')) {
421
+ btn.setAttribute('aria-pressed', String(btn.dataset.mode === expected));
422
+ }
423
+ }
424
+
425
+ function setMode(nextMode: CommentMode, options: { fromTab?: boolean } = {}): void {
426
+ workspaceMode = nextMode;
427
+ const currentPart = host.parts()?.value();
428
+ if (nextMode !== 'compare' && (currentPart?.side === 'a' || currentPart?.side === 'b') && currentPart.side !== pickedSide) {
429
+ setPickedSide(currentPart.side);
430
+ }
431
+ if (nextMode !== 'compare') {
432
+ host.syncFeedbackSide(pickedSide);
433
+ }
434
+ syncModeButtons();
435
+ syncPickedBanner();
436
+ if (!options.fromTab) {
437
+ if (nextMode === 'setup') selectInspectorTab('rig');
438
+ else if (nextMode === 'animate') selectInspectorTab('playback');
439
+ else if (currentInspector() === 'rig' || currentInspector() === 'playback') selectInspectorTab('view');
440
+ }
441
+ refreshAnimationInspection();
442
+ inspectorBlocks?.refresh();
443
+ host.redrawOverlays(false);
444
+ host.saveDraft();
445
+ }
446
+
447
+ function setPickedSide(nextSide: Side): void {
448
+ if (pickedSide === nextSide) {
449
+ if (workspaceMode !== 'compare') host.syncFeedbackSide(pickedSide);
450
+ syncPickedBanner();
451
+ moveStageHandlesToPickedSide();
452
+ return;
453
+ }
454
+ const prevSide = pickedSide;
455
+ if (sides[prevSide].chestInputs !== null) {
456
+ sides[prevSide].chestInputs = snapshotChestInputs();
457
+ }
458
+ physicsPanel?.clearPreview();
459
+ idleAdjust = null;
460
+ dialAdjust = null;
461
+ setAdjust(prevSide);
462
+ const prevPlayer = host.players[prevSide];
463
+ if (prevPlayer) {
464
+ prevPlayer.environment(null);
465
+ if (prevPlayer.current && !host.playing()) {
466
+ prevPlayer.seek(host.time());
467
+ prevPlayer.draw();
468
+ host.parts()?.present(prevSide);
469
+ }
470
+ }
471
+ pickedSide = nextSide;
472
+ steppedLive = false;
473
+ if (workspaceMode !== 'compare') host.syncFeedbackSide(pickedSide);
474
+ applyEnvironment();
475
+ const nextPlayer = currentPlayer();
476
+ if (nextPlayer?.current && !host.playing()) {
477
+ nextPlayer.repose();
478
+ nextPlayer.draw();
479
+ host.parts()?.present(pickedSide);
480
+ }
481
+ syncPickedBanner();
482
+ moveStageHandlesToPickedSide();
483
+ const currentPart = host.parts()?.value();
484
+ if (currentPart && currentPart.side !== nextSide) {
485
+ const nextSlots = host.data()[nextSide].feedbackCatalog.slots ?? [];
486
+ switchingSide = true;
487
+ try {
488
+ if (nextSlots.includes(currentPart.slot)) {
489
+ host.parts()?.select({ side: nextSide, slot: currentPart.slot, mode: currentPart.mode });
490
+ } else {
491
+ host.parts()?.select(null);
492
+ }
493
+ } finally {
494
+ switchingSide = false;
495
+ }
496
+ }
497
+ switchingSide = true;
498
+ try {
499
+ clearChestInputs();
500
+ populateChestBones();
501
+ applySideStateToPanels();
502
+ updateChestMapping();
503
+ } finally {
504
+ switchingSide = false;
505
+ }
506
+ host.redrawOverlays(true);
507
+ host.saveDraft();
508
+ }
509
+
510
+ function chestInputIds(): string[] {
511
+ return [
512
+ ...chestRegionRows.flatMap(row => ['name', 'bone', 'cx', 'cy', 'r', 'band', 'ring', 'poly'].map(f => chestRowId(row, f as 'name'))),
513
+ ...LANDMARKS.flatMap(({ key }) => [landmarkInputId(key, 'x'), landmarkInputId(key, 'y')]),
514
+ 'lm-bone-r',
515
+ 'lm-bone-l',
516
+ ];
517
+ }
518
+
519
+ function snapshotChestInputs(): Record<string, string> {
520
+ const out: Record<string, string> = {};
521
+ for (const id of chestInputIds()) {
522
+ const node = document.getElementById(id) as HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement | null;
523
+ if (!node) continue;
524
+ out[id] = node instanceof HTMLInputElement && node.type === 'checkbox' ? String(node.checked) : node.value;
525
+ }
526
+ return out;
527
+ }
528
+
529
+ function clearChestInputs(): void {
530
+ for (const id of chestInputIds()) {
531
+ const node = document.getElementById(id) as HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement | null;
532
+ if (!node) continue;
533
+ if (node instanceof HTMLInputElement && node.type === 'checkbox') node.checked = false;
534
+ else node.value = '';
535
+ }
536
+ }
537
+
538
+ function writeChestInputs(values: Record<string, string>): void {
539
+ for (const [id, value] of Object.entries(values)) {
540
+ const node = document.getElementById(id) as HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement | null;
541
+ if (!node) continue;
542
+ if (node instanceof HTMLInputElement && node.type === 'checkbox') node.checked = value === 'true';
543
+ else node.value = value;
544
+ }
545
+ }
546
+
547
+ function populateChestBones(): void {
548
+ const bones = currentSideData()?.feedbackCatalog.bones ?? null;
549
+ const list = document.getElementById('lm-bones');
550
+ if (list) {
551
+ list.replaceChildren();
552
+ for (const name of bones ?? []) list.append(option(name, name));
553
+ }
554
+ for (const row of chestRegionRows) {
555
+ const node = document.getElementById(chestRowId(row, 'bone')) as HTMLSelectElement | null;
556
+ if (!node) continue;
557
+ node.replaceChildren(option('', bones ? 'Select bone' : 'No model bones'));
558
+ for (const name of bones ?? []) node.append(option(name, name));
559
+ node.disabled = !bones;
560
+ }
561
+ }
562
+
563
+ function chestField(id: string) {
564
+ const node = document.getElementById(id) as HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement | null;
565
+ return node ? { value: node.value, ...(node instanceof HTMLInputElement && node.type === 'checkbox' ? { checked: node.checked } : {}) } : undefined;
566
+ }
567
+
568
+ function chestEvaluation() {
569
+ return evaluateChestForm(chestField, currentState().chestMapping, currentSideData()?.feedbackCatalog.bones);
570
+ }
571
+
572
+ function updateChestMapping(side: Side = pickedSide): void {
573
+ const state = sides[side];
574
+ const player = host.players[side], sideAssets = host.assets[side];
575
+ const root = host.data()[side]?.feedbackCatalog.bones?.[0];
576
+ let at: { x: number; y: number } | null = null;
577
+ if (player && root) {
578
+ try { const bone = player.bone(root); at = { x: bone.x, y: bone.y }; } catch { at = null; }
579
+ }
580
+ state.chestMapping = player ? cropWorldMapping(sideAssets?.stage, at) : { available: false, reason: 'CHEST_REGION_MAPPING_UNAVAILABLE: no compiled model drawn' };
581
+ if (side === pickedSide) renderChest();
582
+ }
583
+
584
+ function renderChest(): void {
585
+ const mapping = currentState().chestMapping;
586
+ for (const id of ['chest-crop-w', 'chest-crop-h']) {
587
+ const node = document.getElementById(id) as HTMLInputElement | null;
588
+ if (!node) continue;
589
+ node.readOnly = mapping.available;
590
+ if (mapping.available) node.value = String(id === 'chest-crop-w' ? mapping.crop.w : mapping.crop.h);
591
+ }
592
+ const mapNode = document.getElementById('chest-mapping');
593
+ if (mapNode) {
594
+ mapNode.textContent = mapping.available ? `Crop → rig world from the model: ${mapping.basis}.` : `${mapping.reason}. No overlay is drawn; enter the crop size to export.`;
595
+ mapNode.classList.toggle('error', !mapping.available);
596
+ }
597
+ const value = chestEvaluation();
598
+ const statusNode = document.getElementById('chest-status');
599
+ if (statusNode) {
600
+ statusNode.textContent = value.ok ? `${value.document.mesh.value.contour.regions.map(r => `${r.name} → ${r.bone}`).join(' · ')} · valid for export` : value.error;
601
+ statusNode.classList.toggle('error', !value.ok);
602
+ }
603
+ if (!switchingSide && currentState().chestInputs !== null) {
604
+ currentState().chestInputs = snapshotChestInputs();
605
+ }
606
+ chestEditor?.sync(); meshEditor?.sync(); weightsView?.sync(); bonesPanel?.sync(); cutsPanel?.sync(); clothPanel?.sync();
607
+ host.redrawOverlays(false);
608
+ }
609
+
610
+ function chestRegions(): OverlayRegion[] {
611
+ const style = getComputedStyle(document.documentElement), token = (name: string) => style.getPropertyValue(name).trim();
612
+ return chestOverlayPolygons(chestEvaluation(), currentState().chestMapping).map((region, i) => ({
613
+ ...region,
614
+ stroke: token(i ? '--rv-region-b' : '--rv-region-a'),
615
+ fill: token(i ? '--rv-region-b-fill' : '--rv-region-a-fill'),
616
+ }));
617
+ }
618
+
619
+ function chestCircles(): OverlayCircle[] {
620
+ const mapping = currentState().chestMapping;
621
+ if (!mapping.available) return [];
622
+ const style = getComputedStyle(document.documentElement), token = (name: string) => style.getPropertyValue(name).trim();
623
+ const colors = (row: number, overlap: boolean) => ({
624
+ stroke: token(overlap ? '--rv-bust-overlap' : row ? '--rv-bust-l' : '--rv-bust-r'),
625
+ fill: token(overlap ? '--rv-bust-overlap-fill' : row ? '--rv-bust-l-fill' : '--rv-bust-r-fill'),
626
+ handle: token('--rv-bust-handle'),
627
+ ink: token('--rv-bust-ink'),
628
+ labelBg: token('--rv-bust-label-bg'),
629
+ flash: token('--rv-bust-flash'),
630
+ });
631
+ if (chestEditor?.active() && chestEditor.mode() === 'landmarks') {
632
+ const read = chestEditor.landmarks();
633
+ if (!('derived' in read)) return [];
634
+ const refused = !!read.derived.refusal;
635
+ return read.derived.regions.filter(r => r.r > 0 && r.band >= 0).map((r, row) => ({
636
+ center: mapping.toWorld(r.cx, r.cy), r: r.r, band: r.band, label: `${r.name} r:${r.r} b:${r.band}`, labelRow: row, handles: false, colors: colors(row, refused),
637
+ }));
638
+ }
639
+ if (chestEditor?.active()) {
640
+ const rows = bustSides.map(({ side, row }) => ({ side, row, circle: rowCircle(chestField, row) })), [r, l] = [rows[0]!.circle, rows[1]!.circle];
641
+ const overlap = !!r && !!l && r.r + l.r > Math.hypot(l.cx - r.cx, l.cy - r.cy);
642
+ return rows.flatMap(({ side, row, circle }) => circle ? [{
643
+ center: mapping.toWorld(circle.cx, circle.cy), r: circle.r, band: circle.band, label: bustLabel(side, circle), labelRow: row, handles: true, flash: chestEditor!.flashing(side), colors: colors(row, overlap),
644
+ }] : []);
645
+ }
646
+ return chestOverlayCircles(chestEvaluation(), mapping).map(c => ({ center: c.center, r: c.r, band: c.band, handles: false, colors: colors(c.row, false) }));
647
+ }
648
+
649
+ function chestMarkers(): OverlayMarker[] {
650
+ const mapping = currentState().chestMapping;
651
+ if (!mapping.available || !chestEditor?.active() || chestEditor.mode() !== 'landmarks') return [];
652
+ const style = getComputedStyle(document.documentElement), token = (name: string) => style.getPropertyValue(name).trim(), armed = chestEditor.armed();
653
+ const at = (key: LandmarkKey) => {
654
+ const x = Number(input(landmarkInputId(key, 'x')).value.trim() || NaN), y = Number(input(landmarkInputId(key, 'y')).value.trim() || NaN);
655
+ return Number.isFinite(x) && Number.isFinite(y) ? mapping.toWorld(x, y) : null;
656
+ };
657
+ const apexes = [at('apex_r'), at('apex_l')].filter((p): p is { x: number; y: number } => !!p);
658
+ return LANDMARKS.flatMap(({ key, tag }) => {
659
+ const p = at(key); if (!p) return [];
660
+ const stroke = token(key === 'apex_r' ? '--rv-bust-r' : key === 'apex_l' ? '--rv-bust-l' : '--rv-landmark');
661
+ return [{ at: p, tag, active: armed === key, colors: { stroke, fill: stroke, ink: token('--rv-landmark-ink'), labelBg: token('--rv-bust-label-bg') }, ...(key === 'cleavage' ? { guideTo: apexes } : {}) }];
662
+ });
663
+ }
664
+
665
+ async function exportChest(): Promise<void> {
666
+ const value = chestEvaluation();
667
+ if (!value.ok) { host.message(`Chest regions not exported: ${value.error}`, true); return; }
668
+ const digest = await sha256Hex(value.text);
669
+ const sideData = currentSideData();
670
+ const mapping = currentState().chestMapping;
671
+ const binding = chestRegionsBinding({
672
+ fileSha256: digest,
673
+ sourceHash: sideData.sourceHash,
674
+ reviewedSource: sideData.reviewedSource,
675
+ exportedAt: new Date().toISOString(),
676
+ mapping: mapping.available ? mapping.basis : mapping.reason,
677
+ });
678
+ host.download('chest-regions.json', value.text, 'application/json');
679
+ host.download('chest-regions.binding.json', JSON.stringify(binding, null, 2) + '\n', 'application/json');
680
+ host.message(`Downloaded chest-regions.json and chest-regions.binding.json for Build ${pickedSide.toUpperCase()}.`);
681
+ }
682
+
683
+ function meshSource() {
684
+ const state = currentState(), sideData = currentSideData(), sideAssets = currentAssets();
685
+ if (sideData.manifest.model && !state.partModel) return { ok: false as const, code: 'MESH_EDIT_RIG_UNAVAILABLE: the compiled model document is still loading' };
686
+ const selectedPart = host.parts()?.value();
687
+ const slot = selectedPart?.side === pickedSide ? selectedPart.slot : null;
688
+ return meshEditSource({
689
+ slot,
690
+ model: sideData.manifest.model ? state.partModel : null,
691
+ pose: s => sideAssets ? readSetupPose(sideAssets, s, document.createElement('div')) : null,
692
+ mapping: state.chestMapping,
693
+ });
694
+ }
695
+
696
+ async function exportMesh(doc: MeshEditDocument): Promise<void> {
697
+ const raw = meshEditText(doc), digest = await sha256Hex(raw);
698
+ const sideData = currentSideData(), mapping = currentState().chestMapping;
699
+ const binding = meshEditBinding({
700
+ fileSha256: digest,
701
+ sourceHash: sideData.sourceHash,
702
+ reviewedSource: sideData.reviewedSource,
703
+ exportedAt: new Date().toISOString(),
704
+ mapping: mapping.available ? mapping.basis : mapping.reason,
705
+ attachment: { slot: doc.slot, skin: doc.skin, name: doc.attachment, sha256: doc.source.hash },
706
+ });
707
+ host.download('mesh-edit.json', raw, 'application/json');
708
+ host.download('mesh-edit.binding.json', JSON.stringify(binding, null, 2) + '\n', 'application/json');
709
+ host.message(`Downloaded mesh-edit.json (${doc.ops.length} ops) and mesh-edit.binding.json for Build ${pickedSide.toUpperCase()}.`);
710
+ }
711
+
712
+ function refreshAnimationInspection(): void {
713
+ if (!animationPanel) return;
714
+ const state = currentState(), player = currentPlayer();
715
+ if (state.partModel) {
716
+ animationPanel.model(state.partModel, player?.current ?? host.data().animation);
717
+ animationPanel.update(host.time(), host.duration());
718
+ if (player) animationPanel.capture(player, host.parts()?.frame(pickedSide));
719
+ } else if (state.inspectedDocumentReason) {
720
+ animationPanel.unavailable(state.inspectedDocumentReason);
721
+ }
722
+ animationPanel.redraw(host.layers.bones);
723
+ }
724
+
725
+ function refreshPhysics(): void {
726
+ if (!physicsPanel) return;
727
+ const state = currentState();
728
+ if (state.inspectedDocumentReason) { physicsPanel.load({ available: false, reason: state.inspectedDocumentReason }, []); return; }
729
+ if (!state.inspectedDocument) return;
730
+ if (!state.rebuildStatus) { text('physics-panel-state', 'Reading the producer handoff…'); return; }
731
+ if (!state.rebuildStatus.inputs || !state.rebuildStatus.producer) {
732
+ physicsPanel.load({ available: false, reason: state.rebuildStatus.reason ?? 'PHYSICS_TUNING_UNAVAILABLE: no producer handoff' }, []);
733
+ return;
734
+ }
735
+ const bones = (state.inspectedDocument as { bones?: unknown }).bones;
736
+ const list = Array.isArray(bones) ? bones.filter((b): b is { name: string; parent?: string } => !!b && typeof (b as { name?: unknown }).name === 'string') : [];
737
+ physicsPanel.load(tuningRows(state.rebuildStatus.constraints ?? null, state.inspectedDocument), list);
738
+ refreshIdle();
739
+ }
740
+
741
+ function refreshIdle(): void {
742
+ const state = currentState();
743
+ if (!idlePanel || !state.rebuildStatus) return;
744
+ idlePanel.load(state.rebuildStatus.idle ?? null, state.rebuildStatus.inputs ? null : state.rebuildStatus.reason ?? 'IDLE_TRACKS_UNAVAILABLE: no producer handoff');
745
+ if (state.inspectedDocument) idlePanel.model(boneSetup(state.inspectedDocument));
746
+ }
747
+
748
+ function renderHandoff(status: RebuildStatusView): void {
749
+ const line = el('handoff-line'), shown = handoffText(status);
750
+ line.textContent = shown.text; line.title = shown.text; line.classList.toggle('error', shown.error);
751
+ if (handoffTimer) clearTimeout(handoffTimer); handoffTimer = null;
752
+ const side = pickedSide;
753
+ if (status.baseline?.status === 'running') {
754
+ handoffTimer = setTimeout(() => {
755
+ void host.api<RebuildStatusView>(`${sideApiPrefix(side)}/rebuild`).then(next => {
756
+ sides[side].rebuildStatus = next;
757
+ if (pickedSide === side) renderHandoff(next);
758
+ }).catch(() => {});
759
+ }, 2000);
760
+ }
761
+ }
762
+
763
+ function renderAppliedBlocks(): void {
764
+ const state = currentState();
765
+ const on = appliedBlockOps(state.appliedOnStage);
766
+ cutsPanel?.applied(on.cuts); clothPanel?.applied(on.cloth);
767
+ for (const block of staleReadouts(state.readoutStage, state.appliedOnStage)) {
768
+ (block === 'cuts' ? cutsPanel : clothPanel)?.shown(null);
769
+ }
770
+ state.readoutStage = state.appliedOnStage;
771
+ }
772
+
773
+ function renderApplied(): void {
774
+ renderAppliedBlocks();
775
+ const section = document.getElementById('applied-records');
776
+ if (!section) return;
777
+ const state = currentState(), h = state.appliedHistory;
778
+ section.hidden = !h || h.depth === 0;
779
+ const list = el('applied-list');
780
+ list.replaceChildren(...(h?.records ?? []).map((r, i) => {
781
+ const li = document.createElement('li');
782
+ li.textContent = historyRow(h!, i);
783
+ li.dataset.buildId = r.id;
784
+ li.classList.toggle('on-stage', i === h!.records.length - 1 && state.appliedOnStage?.buildId === r.id);
785
+ return li;
786
+ }));
787
+ const control = undoControl(h, state.appliedOnStage?.buildId ?? null, rebuildBusy || !!host.readOnly());
788
+ const undo = button('applied-undo');
789
+ undo.textContent = control.label; undo.disabled = !control.enabled; undo.title = control.title;
790
+ }
791
+
792
+ async function refreshApplied(side: Side = pickedSide): Promise<void> {
793
+ if (!sides[side].inspectedModel) return;
794
+ try { sides[side].appliedHistory = await host.api<AppliedHistoryView>(`${sideApiPrefix(side)}/rebuild/history`); } catch { return; }
795
+ if (side === pickedSide) renderApplied();
796
+ }
797
+
798
+ function rebuildState(): void {
799
+ const state = currentState();
800
+ chestEditor?.rebuildState({ busy: rebuildBusy, applied: !!state.appliedOnStage });
801
+ renderApplied();
802
+ if (!rebuildBusy) void refreshApplied(pickedSide);
803
+ }
804
+
805
+ function applySideStateToPanels(): void {
806
+ const state = currentState(), sideData = currentSideData();
807
+ const selectedPart = host.parts()?.value();
808
+ const currentSlot = selectedPart?.side === pickedSide ? selectedPart.slot : null;
809
+ readingsPanel?.catalog(sideData?.feedbackCatalog.slots ?? [], sideData?.feedbackCatalog.bones ?? []);
810
+ readingsPanel?.status('Pick readings, then Run: each runs on the picked build and on its latest scratch build.', false);
811
+ const status = state.rebuildStatus;
812
+ if (status) {
813
+ if (state.chestInputs !== null) {
814
+ writeChestInputs(state.chestInputs);
815
+ } else {
816
+ clearChestInputs();
817
+ const seed = { ...(seedFields(status, chestField) ?? {}), ...(seedLandmarks(status, chestField) ?? {}) };
818
+ if (Object.keys(seed).length) {
819
+ writeChestInputs(seed);
820
+ }
821
+ state.chestInputs = snapshotChestInputs();
822
+ }
823
+ el('chest-regions').dispatchEvent(new Event('input', { bubbles: true }));
824
+ if (!status.available) chestEditor?.notify(status.reason, true);
825
+ else chestEditor?.notify('', false);
826
+ renderHandoff(status);
827
+ retargetPanel?.load(status.retarget ?? null, status.reason);
828
+ bonesPanel?.load(status.inputs ? status.bones ?? [] : null, status.inputs ? null : status.reason ?? 'BONES_UNAVAILABLE: no producer handoff');
829
+ rigFieldsPanel?.load(status.inputs ? status.fields ?? {} : null, status.inputs ? null : status.reason ?? 'RIG_FIELDS_UNAVAILABLE: no producer handoff');
830
+ clothPanel?.load(status.inputs ? status.cloth ?? null : null, status.inputs ? null : status.reason ?? 'CLOTH_UNAVAILABLE: no producer handoff');
831
+ cutsPanel?.load(status.inputs && status.cuts ? status.cuts.config : null, status.bones ?? [], status.inputs ? null : status.reason ?? 'CUTS_UNAVAILABLE: no producer handoff', status.cuts?.build ?? null);
832
+ meshPanel?.load(status.inputs ? status.meshes ?? {} : null, status.inputs ? null : status.reason ?? 'MESH_PANEL_UNAVAILABLE: no producer handoff');
833
+ meshPanel?.select(currentSlot);
834
+ }
835
+ if (state.requirementsCatalog) {
836
+ requirementsPanel?.load(state.requirementsCatalog, state.requirementsCatalog.reason);
837
+ }
838
+ refreshPhysics();
839
+ refreshAnimationInspection();
840
+ weightsView?.refresh();
841
+ meshEditor?.selectionChanged();
842
+ renderApplied();
843
+ renderStrip();
844
+ const draft = el<HTMLTextAreaElement>('rebuild-applied');
845
+ draft.value = state.appliedOnStage ? JSON.stringify(state.appliedOnStage) : '';
846
+ }
847
+
848
+ async function loadRebuildStatus(side: Side = pickedSide): Promise<RebuildStatusView | null> {
849
+ try {
850
+ sides[side].rebuildStatus = await host.api<RebuildStatusView>(`${sideApiPrefix(side)}/rebuild`);
851
+ } catch (error) {
852
+ sides[side].rebuildStatus = null;
853
+ if (side === pickedSide) chestEditor?.notify(`REBUILD_STATUS_UNAVAILABLE: ${errorText(error)}`, true);
854
+ return null;
855
+ }
856
+ if (side === pickedSide) applySideStateToPanels();
857
+ return sides[side].rebuildStatus;
858
+ }
859
+
860
+ async function loadRequirements(side: Side = pickedSide): Promise<void> {
861
+ try {
862
+ const catalog = await host.api<RequirementsCatalogView>(`${sideApiPrefix(side)}/requirements`);
863
+ sides[side].requirementsCatalog = catalog;
864
+ if (side === pickedSide) requirementsPanel?.load(catalog, catalog.reason);
865
+ } catch (error) {
866
+ if (side === pickedSide) requirementsPanel?.load(null, `REQUIREMENTS_UNAVAILABLE: ${errorText(error)}`);
867
+ }
868
+ }
869
+
870
+ function environmentApplied(): boolean {
871
+ return input('environment-applied').checked;
872
+ }
873
+
874
+ function gravityValue(): number {
875
+ return Number(input('gravity').value);
876
+ }
877
+
878
+ function stageWorld(): StageWorld {
879
+ return { wind: wind.state(), jolts: joltQueue.map(step => ({ ...step })), applied: environmentApplied(), gravity: gravityValue() };
880
+ }
881
+
882
+ function useWorld(): boolean {
883
+ return input('environment-use').checked && environmentApplied();
884
+ }
885
+
886
+ function checkAnimation(side: Side = pickedSide): string {
887
+ const sideAssets = host.assets[side];
888
+ return sideAssets?.animations.some(item => item.name === 'idle') ? 'idle' : host.data().animation;
889
+ }
890
+
891
+ function clipDuration(name: string, side: Side = pickedSide): number {
892
+ return host.assets[side]?.animations.find(item => item.name === name)?.duration ?? host.duration();
893
+ }
894
+
895
+ function worldFor(name: string, side: Side = pickedSide): WorldExport | { error: string } {
896
+ return worldExport(wind.snapshot(), gravityValue(), environmentApplied(), name, clipDuration(name, side));
897
+ }
898
+
899
+ function stepEnvironment(dt: number): void {
900
+ const player = currentPlayer();
901
+ if (!player) return;
902
+ wind.advance(dt);
903
+ const { due, pending } = dueJolts(joltQueue, wind.read().time);
904
+ joltQueue = pending;
905
+ for (const step of due) player.moved({ x: step.x, y: step.y });
906
+ if (environmentApplied()) player.environment(environmentFor(wind.read(), gravityValue()));
907
+ renderEnvironment();
908
+ }
909
+
910
+ function applyEnvironment(): void {
911
+ for (const s of ['a', 'b'] as const) {
912
+ const p = host.players[s];
913
+ if (!p) continue;
914
+ if (s === pickedSide && environmentApplied()) {
915
+ p.environment(environmentFor(wind.read(), gravityValue()));
916
+ } else {
917
+ p.environment(null);
918
+ }
919
+ }
920
+ renderEnvironment();
921
+ }
922
+
923
+ function renderSchedule(): void {
924
+ const animation = host.data().animation, check = checkAnimation(pickedSide);
925
+ const world = worldFor(animation, pickedSide), checked = check !== animation ? worldFor(check, pickedSide) : null;
926
+ const shown = 'error' in world
927
+ ? world.error
928
+ : `${world.summary}${useWorld() ? ' · used for readings and Apply' : ''}${checked && !('error' in checked) && checked.sha256 !== world.sha256 ? ` · check reads ${check}'s: ${checked.summary}` : ''}`;
929
+ text('environment-schedule', shown);
930
+ }
931
+
932
+ function renderEnvironment(): void {
933
+ if (!currentPlayer()) return;
934
+ const reading = wind.read(), g = gravityValue();
935
+ text('wind-readout', (environmentApplied() ? windReadout(reading, g) : RUNTIME_START_READOUT) + environmentNote);
936
+ const gust = button('wind-gust');
937
+ gust.disabled = reading.gusting;
938
+ gust.setAttribute('aria-pressed', String(reading.gusting));
939
+ gust.textContent = reading.gusting ? 'Gusting…' : 'Gust';
940
+ text('wind-base-label', input('wind-base').value);
941
+ text('gravity-label', g.toFixed(2));
942
+ renderSchedule();
943
+ }
944
+
945
+ function restartWindClock(): void {
946
+ const now = wind.read().time;
947
+ wind.restore(wind.snapshot());
948
+ joltQueue = joltQueue.map(step => ({ ...step, at: Math.max(0, step.at - now) }));
949
+ }
950
+
951
+ function clipMoved(move: ClipMove): void {
952
+ if (currentPlayer() && restartsWindClock(move, useWorld())) {
953
+ restartWindClock();
954
+ applyEnvironment();
955
+ }
956
+ }
957
+
958
+ function syncEnvironmentInputs(): void {
959
+ const s = wind.snapshot();
960
+ input('wind-base').value = String(s.base);
961
+ input('wind-breeze').checked = s.breeze;
962
+ input('wind-repeat').checked = s.repeat;
963
+ input('wind-gust-peak').value = String(s.gustPeak);
964
+ input('wind-gust-duration').value = String(s.gustDuration);
965
+ renderEnvironment();
966
+ }
967
+
968
+ function resetPhysics(): void {
969
+ const p = currentPlayer();
970
+ if (!p) return;
971
+ joltQueue = [];
972
+ steppedLive = false;
973
+ wind.restore(null);
974
+ input('environment-applied').checked = false;
975
+ input('gravity').value = '1';
976
+ syncEnvironmentInputs();
977
+ try {
978
+ p.environment(null);
979
+ if (p.current) {
980
+ p.seek(host.time());
981
+ p.draw();
982
+ host.parts()?.present(pickedSide);
983
+ host.redrawOverlays(true);
984
+ }
985
+ environmentNote = ` · physics history cleared; re-posed from ${host.time().toFixed(3)} s`;
986
+ } catch (error) {
987
+ environmentNote = '';
988
+ host.message(`Physics reset refused: ${errorText(error)}`, true);
989
+ }
990
+ renderEnvironment();
991
+ host.saveDraft();
992
+ }
993
+
994
+ function restoreEnvironment(): void {
995
+ const snapshot: WindSnapshot = {
996
+ version: 1,
997
+ base: Number(input('wind-base').value),
998
+ breeze: input('wind-breeze').checked,
999
+ repeat: input('wind-repeat').checked,
1000
+ gustPeak: Number(input('wind-gust-peak').value),
1001
+ gustDuration: Number(input('wind-gust-duration').value),
1002
+ };
1003
+ try {
1004
+ wind.restore(snapshot);
1005
+ environmentFor(wind.read(), gravityValue());
1006
+ } catch (error) {
1007
+ wind.restore(null);
1008
+ input('environment-applied').checked = false;
1009
+ input('gravity').value = '1';
1010
+ host.message(`Saved environment not restored: ${errorText(error)}`, true);
1011
+ }
1012
+ syncEnvironmentInputs();
1013
+ applyEnvironment();
1014
+ }
1015
+
1016
+ function seekEndTime(time: number): number {
1017
+ const steps = Math.floor(time / compareSeekStep);
1018
+ let t = 0;
1019
+ for (let i = 0; i < steps; i++) t += compareSeekStep;
1020
+ const rest = time - t;
1021
+ if (rest > 0) t += rest;
1022
+ return t;
1023
+ }
1024
+
1025
+ function seekMode(target: number, continuing: boolean): 'settle' | 'seek' {
1026
+ const p = currentPlayer();
1027
+ if (!continuing && steppedLive && p && target >= p.time - 1e-9 && target - p.time <= 0.25) {
1028
+ steppedLive = false;
1029
+ return 'settle';
1030
+ }
1031
+ steppedLive = false;
1032
+ clipMoved(continuing ? { kind: 'replay' } : { kind: 'seek', to: target });
1033
+ return 'seek';
1034
+ }
1035
+
1036
+ function stepSide(mode: 'present' | 'settle' | 'seek', side: Side, target: number): void {
1037
+ const player = host.players[side];
1038
+ if (!player) return;
1039
+ if (side !== pickedSide) {
1040
+ player.environment(null);
1041
+ player.seek(target);
1042
+ return;
1043
+ }
1044
+ const end = seekEndTime(target);
1045
+ if ((mode === 'settle' || (mode === 'present' && (environmentApplied() || joltQueue.length > 0 || steppedLive))) && end >= player.time - 1e-9) {
1046
+ if (mode === 'present') steppedLive = true;
1047
+ player.resume();
1048
+ try {
1049
+ const step = compareSeekStep;
1050
+ while (player.time + step < end) {
1051
+ stepEnvironment(step);
1052
+ player.advance(step);
1053
+ }
1054
+ while (player.time > 0 && player.time < end / 2) {
1055
+ const d = Math.min(step, end / 2);
1056
+ stepEnvironment(d);
1057
+ player.advance(d);
1058
+ }
1059
+ const rest = end - player.time;
1060
+ if (rest > 0) {
1061
+ stepEnvironment(rest);
1062
+ player.advance(rest);
1063
+ }
1064
+ } finally {
1065
+ player.pause();
1066
+ }
1067
+ return;
1068
+ }
1069
+ steppedLive = false;
1070
+ if (environmentApplied()) {
1071
+ player.environment(environmentFor(wind.read(), gravityValue()));
1072
+ } else {
1073
+ player.environment(null);
1074
+ }
1075
+ player.seek(target);
1076
+ }
1077
+
1078
+ function stageChanged(side: Side, change: StageChange<NonNullable<SideBuildState['stripPending']>>): void {
1079
+ const state = sides[side];
1080
+ const next = stripPendingAfter(state.stripPending, change);
1081
+ if (next === state.stripPending) return;
1082
+ state.stripPending = next;
1083
+ void refreshDensityStrip(side);
1084
+ }
1085
+
1086
+ async function swapPickedSide(side: Side, modelUrl: string, prefix: string, sha256: string, clipName?: string): Promise<void> {
1087
+ await host.swapSideRig(side, modelUrl, prefix, sha256, clipName);
1088
+ applyEnvironment();
1089
+ }
1090
+
1091
+ async function applyRebuild(): Promise<void> {
1092
+ if (rebuildBusy) return;
1093
+ const ro = host.readOnly();
1094
+ if (ro) { chestEditor?.notify(ro, true); return; }
1095
+ const side = pickedSide, state = sides[side];
1096
+ const status = state.rebuildStatus ?? await loadRebuildStatus(side);
1097
+ if (!status || !status.available || !status.inputs) {
1098
+ const reason = status?.reason ?? 'REBUILD_STATUS_UNAVAILABLE';
1099
+ chestEditor?.notify(reason, true, [reason]); host.message(reason, true); return;
1100
+ }
1101
+ let part: string, body: RebuildRequestBody;
1102
+ const lines: string[] = [];
1103
+ if (chestEditor?.mode() === 'landmarks') {
1104
+ const request = landmarksRequest(status, chestEditor.landmarks());
1105
+ if ('error' in request) { chestEditor.notify(request.error, true, [request.error]); host.message(request.error, true); return; }
1106
+ ({ part, body } = request);
1107
+ } else {
1108
+ const designated = designatedRegions(chestField);
1109
+ if ('error' in designated) { chestEditor?.notify(designated.error, true); return; }
1110
+ const picked = pickPart(status, designated.regions);
1111
+ if (!picked) { chestEditor?.notify(`REBUILD_PART_AMBIGUOUS: the config states ${status.parts.length} contour meshes and the designated bones name none of them alone`, true); return; }
1112
+ part = picked; body = { part, regions: designated.regions, configHash: status.inputs.configHash };
1113
+ }
1114
+ rebuildBusy = true; rebuildState();
1115
+ chestEditor?.notify(`Rebuilding ${part} on Build ${side.toUpperCase()} with ${status.producer?.package} ${status.producer?.version}…`, false, []);
1116
+ try {
1117
+ const result = await runRebuild(body, {
1118
+ post: value => host.api<RebuildJobView | RebuildRefusal>(`${sideApiPrefix(side)}/rebuild`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(value) }),
1119
+ get: id => host.api<RebuildJobView>(`${sideApiPrefix(side)}/rebuild/${id}`),
1120
+ sleep: ms => new Promise(resolve => setTimeout(resolve, ms)),
1121
+ onLine: line => { lines.push(line); chestEditor?.notify(line.trim() || '…', false, lines.slice(-6)); },
1122
+ });
1123
+ const outcome = outcomeLine(result);
1124
+ if (!('id' in result) || result.status !== 'built' || !result.build) {
1125
+ chestEditor?.notify(outcome.text, true, [...lines.slice(-5), outcome.text]);
1126
+ host.message(outcome.text, true);
1127
+ return;
1128
+ }
1129
+ await swapPickedSide(side, new URL(host.route(result.build.modelUrl), location.href).href, host.route(`/compare-rebuild/${side}/${result.id}/`), result.build.modelHash);
1130
+ state.appliedOnStage = appliedRecord(result); state.stageCheck = null; stageChanged(side, { kind: 'apply', via: 'regions' });
1131
+ const draft = el<HTMLTextAreaElement>('rebuild-applied'); draft.value = JSON.stringify(state.appliedOnStage); draft.dispatchEvent(new Event('input', { bubbles: true }));
1132
+ chestEditor?.notify(outcome.text, false, []); host.message(outcome.text);
1133
+ } catch (error) {
1134
+ chestEditor?.notify(`REBUILD_FAILED: ${errorText(error)}`, true);
1135
+ host.message(`REBUILD_FAILED: ${errorText(error)}`, true);
1136
+ } finally {
1137
+ rebuildBusy = false; rebuildState();
1138
+ }
1139
+ }
1140
+
1141
+ async function applyPatch(patch: ConfigPatch, _world: StageWorld | null = null): Promise<PatchJobView | RebuildRefusal> {
1142
+ if (rebuildBusy) return { status: 'refused', error: 'REBUILD_BUSY: an Apply is still running', producerLine: null };
1143
+ const ro = host.readOnly();
1144
+ if (ro) { chestEditor?.notify(ro, true); return { status: 'refused', error: ro, producerLine: null }; }
1145
+ const side = pickedSide, state = sides[side];
1146
+ const lines: string[] = [];
1147
+ rebuildBusy = true; rebuildState();
1148
+ chestEditor?.notify(`Applying patch on Build ${side.toUpperCase()} (${patch.op.cmd}, ${patch.ops.length} op(s))…`, false, []);
1149
+ try {
1150
+ const scheduled = useWorld() ? worldFor(checkAnimation(side), side) : null;
1151
+ if (scheduled && 'error' in scheduled) {
1152
+ chestEditor?.notify(scheduled.error, true); host.message(scheduled.error, true);
1153
+ return { status: 'refused', error: scheduled.error, producerLine: scheduled.error };
1154
+ }
1155
+ const result = await runRebuild<{ patch: ConfigPatch; environment?: WorldExport['schedule'] }, PatchJobView>(
1156
+ { patch, ...(scheduled ? { environment: scheduled.schedule } : {}) },
1157
+ {
1158
+ post: value => host.api<PatchJobView | RebuildRefusal>(`${sideApiPrefix(side)}/rebuild`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(value) }),
1159
+ get: id => host.api<PatchJobView>(`${sideApiPrefix(side)}/rebuild/${id}`),
1160
+ sleep: ms => new Promise(resolve => setTimeout(resolve, ms)),
1161
+ onLine: line => { lines.push(line); chestEditor?.notify(line.trim() || '…', false, lines.slice(-6)); },
1162
+ },
1163
+ );
1164
+ const outcome = patchOutcomeLine(result), next = stageModel(result, { url: '', hash: state.stageModelHash ?? '' });
1165
+ if (next.id === null || !('id' in result)) {
1166
+ chestEditor?.notify(outcome.text, true, [...lines.slice(-5), outcome.text]);
1167
+ host.message(outcome.text, true);
1168
+ return result;
1169
+ }
1170
+ await swapPickedSide(side, new URL(host.route(next.url), location.href).href, host.route(`/compare-rebuild/${side}/${next.id}/`), next.hash);
1171
+ state.appliedOnStage = patchAppliedRecord(result);
1172
+ state.stageCheck = { lines: [...result.lines], check: result.check };
1173
+ stageChanged(side, { kind: 'apply', via: 'patch' });
1174
+ const draft = el<HTMLTextAreaElement>('rebuild-applied'); draft.value = JSON.stringify(state.appliedOnStage); draft.dispatchEvent(new Event('input', { bubbles: true }));
1175
+ chestEditor?.notify(outcome.text, outcome.error, []); host.message(outcome.text, outcome.error);
1176
+ return result;
1177
+ } catch (error) {
1178
+ const textMsg = `REBUILD_FAILED: ${errorText(error)}`;
1179
+ chestEditor?.notify(textMsg, true); host.message(textMsg, true);
1180
+ return { status: 'refused', error: textMsg, producerLine: null };
1181
+ } finally {
1182
+ rebuildBusy = false; rebuildState();
1183
+ }
1184
+ }
1185
+
1186
+ async function applyMeshDelta(doc: MeshEditDocument, line: (text: string) => void): Promise<{ built: boolean; text: string; error: boolean }> {
1187
+ if (rebuildBusy) return { built: false, text: 'REBUILD_BUSY: an Apply is still running', error: true };
1188
+ const ro = host.readOnly();
1189
+ if (ro) return { built: false, text: ro, error: true };
1190
+ const side = pickedSide, state = sides[side];
1191
+ const status = state.rebuildStatus ?? await loadRebuildStatus(side);
1192
+ if (!status?.inputs) return { built: false, text: status?.reason ?? 'REBUILD_STATUS_UNAVAILABLE', error: true };
1193
+ const body: DeltaRequestBody = { part: doc.slot, delta: doc, configHash: status.inputs.configHash };
1194
+ rebuildBusy = true; rebuildState();
1195
+ try {
1196
+ const result = await runRebuild<DeltaRequestBody, DeltaJobView>(body, {
1197
+ post: value => host.api<DeltaJobView | RebuildRefusal>(`${sideApiPrefix(side)}/rebuild`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(value) }),
1198
+ get: id => host.api<DeltaJobView>(`${sideApiPrefix(side)}/rebuild/${id}`),
1199
+ sleep: ms => new Promise(resolve => setTimeout(resolve, ms)),
1200
+ onLine: textLine => line(textLine),
1201
+ });
1202
+ const outcome = deltaOutcomeLine(result), next = stageModel(result, { url: '', hash: state.stageModelHash ?? '' });
1203
+ if (next.id === null || !('id' in result)) { host.message(outcome.text, true); return { built: false, text: outcome.text, error: true }; }
1204
+ await swapPickedSide(side, new URL(host.route(next.url), location.href).href, host.route(`/compare-rebuild/${side}/${next.id}/`), next.hash);
1205
+ state.appliedOnStage = deltaAppliedRecord(result); state.stageCheck = null; stageChanged(side, { kind: 'apply', via: 'delta' });
1206
+ const draft = el<HTMLTextAreaElement>('rebuild-applied'); draft.value = JSON.stringify(state.appliedOnStage); draft.dispatchEvent(new Event('input', { bubbles: true }));
1207
+ host.message(outcome.text);
1208
+ return { built: true, text: outcome.text, error: false };
1209
+ } catch (error) {
1210
+ const textMsg = `REBUILD_FAILED: ${errorText(error)}`; host.message(textMsg, true);
1211
+ return { built: false, text: textMsg, error: true };
1212
+ } finally {
1213
+ rebuildBusy = false; rebuildState();
1214
+ }
1215
+ }
1216
+
1217
+ async function applyRetarget(body: { sequence: string; map: PoseMap; flags: RetargetFlags }): Promise<RetargetJobView | RebuildRefusal | null> {
1218
+ if (rebuildBusy) { retargetPanel?.status('REBUILD_BUSY: an Apply is still running', true); return null; }
1219
+ const ro = host.readOnly();
1220
+ if (ro) { retargetPanel?.status(ro, true); return null; }
1221
+ const side = pickedSide, state = sides[side];
1222
+ const status = state.rebuildStatus ?? await loadRebuildStatus(side);
1223
+ if (!status?.inputs) { retargetPanel?.status(status?.reason ?? 'REBUILD_STATUS_UNAVAILABLE', true); return null; }
1224
+ const request: RetargetRequestBody = { retarget: { ...body, configHash: status.inputs.configHash } };
1225
+ rebuildBusy = true; rebuildState(); retargetPanel?.busy(true); retargetPanel?.result(null);
1226
+ retargetPanel?.status(`Retargeting ${body.sequence} as "${body.flags.animation}" on Build ${side.toUpperCase()}…`, false);
1227
+ try {
1228
+ const result = await runRebuild<RetargetRequestBody, RetargetJobView>(request, {
1229
+ post: value => host.api<RetargetJobView | RebuildRefusal>(`${sideApiPrefix(side)}/rebuild`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(value) }),
1230
+ get: id => host.api<RetargetJobView>(`${sideApiPrefix(side)}/rebuild/${id}`),
1231
+ sleep: ms => new Promise(resolve => setTimeout(resolve, ms)),
1232
+ onLine: textLine => retargetPanel?.line(textLine),
1233
+ });
1234
+ const outcome = retargetOutcomeLine(result), next = stageModel(result, { url: '', hash: state.stageModelHash ?? '' });
1235
+ retargetPanel?.result(result); retargetPanel?.status(outcome.text, outcome.error);
1236
+ if (next.id === null || !('id' in result)) { host.message(outcome.text, true); return result; }
1237
+ await swapPickedSide(side, new URL(host.route(next.url), location.href).href, host.route(`/compare-rebuild/${side}/${next.id}/`), next.hash, result.request.record.flags.animation);
1238
+ state.appliedOnStage = retargetAppliedRecord(result); state.stageCheck = null; stageChanged(side, { kind: 'apply', via: 'retarget' });
1239
+ const draft = el<HTMLTextAreaElement>('rebuild-applied'); draft.value = JSON.stringify(state.appliedOnStage); draft.dispatchEvent(new Event('input', { bubbles: true }));
1240
+ host.message(outcome.text, outcome.error);
1241
+ return result;
1242
+ } catch (error) {
1243
+ const textMsg = `REBUILD_FAILED: ${errorText(error)}`; retargetPanel?.status(textMsg, true); host.message(textMsg, true);
1244
+ return { status: 'refused', error: textMsg, producerLine: null };
1245
+ } finally {
1246
+ rebuildBusy = false; rebuildState(); retargetPanel?.busy(false);
1247
+ }
1248
+ }
1249
+
1250
+ async function resetRebuild(_world: StageWorld | null = null): Promise<void> {
1251
+ const side = pickedSide, state = sides[side];
1252
+ if (rebuildBusy || (!state.appliedOnStage && !state.stripPending) || !state.inspectedModel) return;
1253
+ rebuildBusy = true; rebuildState();
1254
+ try {
1255
+ await swapPickedSide(side, state.inspectedModel.url, state.inspectedModel.prefix, state.inspectedModel.sha256);
1256
+ state.appliedOnStage = null; state.stageCheck = null; stageChanged(side, { kind: 'reset' });
1257
+ chestEditor?.notify(`Reset: Build ${side.toUpperCase()} is back on its inspected build.`, false);
1258
+ host.message(`Reset Build ${side.toUpperCase()} to its inspected build.`);
1259
+ } catch (error) {
1260
+ chestEditor?.notify(`REBUILD_RESET_FAILED: ${errorText(error)}`, true);
1261
+ } finally {
1262
+ rebuildBusy = false; rebuildState();
1263
+ }
1264
+ }
1265
+
1266
+ function appliedStatus(msg: string, error = false): void {
1267
+ const node = el('applied-status'); node.textContent = msg; node.classList.toggle('error', error);
1268
+ }
1269
+
1270
+ async function undoApply(): Promise<UndoView | null> {
1271
+ const side = pickedSide, state = sides[side];
1272
+ const from = state.appliedOnStage?.buildId;
1273
+ if (rebuildBusy || host.readOnly() || !from || !state.inspectedModel) return null;
1274
+ rebuildBusy = true; rebuildState(); appliedStatus('Undoing the last Apply…');
1275
+ try {
1276
+ let result = await host.api<UndoView>(`${sideApiPrefix(side)}/rebuild/undo`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ from }) });
1277
+ if (result.status === 'running') {
1278
+ let job = result.job as AnyJobView; const undone = result.undone; let seen = 0;
1279
+ while (job.status === 'running') {
1280
+ await new Promise(resolve => setTimeout(resolve, 700));
1281
+ job = await host.api<AnyJobView>(`${sideApiPrefix(side)}/rebuild/${job.id}`);
1282
+ for (; seen < job.lines.length; seen++) appliedStatus(job.lines[seen]!.trim() || '…');
1283
+ }
1284
+ if (job.status !== 'built') {
1285
+ const textMsg = refusedText(job); appliedStatus(textMsg, true); host.message(textMsg, true);
1286
+ return { status: 'refused', error: textMsg, producerLine: job.producerLine };
1287
+ }
1288
+ result = { status: 'built', undone, job, history: await host.api<AppliedHistoryView>(`${sideApiPrefix(side)}/rebuild/history`) };
1289
+ }
1290
+ if (result.status === 'refused') { appliedStatus(result.error, true); host.message(result.error, true); return result; }
1291
+ let ops: PatchOp[] | null = null;
1292
+ if (result.status === 'inspected') {
1293
+ await swapPickedSide(side, state.inspectedModel.url, state.inspectedModel.prefix, state.inspectedModel.sha256);
1294
+ state.appliedOnStage = null; state.stageCheck = null;
1295
+ } else {
1296
+ const job = result.job; if (!job.build) throw new Error('the restored job carries no build');
1297
+ await swapPickedSide(side, new URL(host.route(job.build.modelUrl), location.href).href, host.route(`/compare-rebuild/${side}/${job.id}/`), job.build.modelHash);
1298
+ state.appliedOnStage = recordFor(job);
1299
+ state.stageCheck = (job as PatchJobView).kind === 'patch' ? { lines: [...job.lines], check: (job as PatchJobView).check } : null;
1300
+ if ((job as PatchJobView).kind === 'patch') ops = (job as PatchJobView).request.patch.ops;
1301
+ }
1302
+ stageChanged(side, { kind: 'undo' });
1303
+ physicsPanel?.applied(ops); idlePanel?.applied(ops); rigFieldsPanel?.applied(ops); bonesPanel?.applied(ops);
1304
+ const restored = result.status === 'built' && isPatchJob(result.job) ? result.job : null, block = recordBlock(state.appliedOnStage);
1305
+ cutsPanel?.shown(block === 'cuts' ? restored : null); clothPanel?.shown(block === 'cloth' ? restored : null);
1306
+ const draft = el<HTMLTextAreaElement>('rebuild-applied'); draft.value = state.appliedOnStage ? JSON.stringify(state.appliedOnStage) : ''; draft.dispatchEvent(new Event('input', { bubbles: true }));
1307
+ state.appliedHistory = result.history;
1308
+ const textMsg = `Undid ${result.undone.slice(0, 12)}… on Build ${side.toUpperCase()} · ${result.history.depth} applied record(s) left`;
1309
+ appliedStatus(textMsg); host.message(textMsg); host.redrawOverlays(true);
1310
+ return result;
1311
+ } catch (error) {
1312
+ const textMsg = `UNDO_FAILED: ${errorText(error)}`; appliedStatus(textMsg, true); host.message(textMsg, true);
1313
+ return { status: 'refused', error: textMsg, producerLine: null };
1314
+ } finally {
1315
+ rebuildBusy = false; rebuildState();
1316
+ }
1317
+ }
1318
+
1319
+ function inspectedCheckView(side: Side = pickedSide): InspectedCheckView | null {
1320
+ return sides[side].rebuildStatus?.inspectedCheck ?? null;
1321
+ }
1322
+
1323
+ async function followInspectedCheck(show: () => void, side: Side = pickedSide): Promise<void> {
1324
+ for (let i = 0; i < 120 && (!sides[side].rebuildStatus?.inspectedCheck || sides[side].rebuildStatus?.inspectedCheck?.status === 'running'); i++) {
1325
+ try { sides[side].rebuildStatus = await host.api<RebuildStatusView>(`${sideApiPrefix(side)}/rebuild`); } catch { return; }
1326
+ if (side === pickedSide) show();
1327
+ if (sides[side].rebuildStatus?.inspectedCheck && sides[side].rebuildStatus?.inspectedCheck?.status !== 'running') return;
1328
+ if (!sides[side].rebuildStatus?.inspectedCheck && sides[side].rebuildStatus?.baseline?.status !== 'running') return;
1329
+ await new Promise(resolve => setTimeout(resolve, 3000));
1330
+ }
1331
+ }
1332
+
1333
+ async function applyPhysics(ops: PatchOp[]): Promise<PatchJobView | RebuildRefusal | null> {
1334
+ const side = pickedSide, state = sides[side];
1335
+ const status = state.rebuildStatus ?? await loadRebuildStatus(side);
1336
+ const patch = status && ops.length ? makePatch(status, ops, { cmd: 'rig' }) : null;
1337
+ if (!patch) { const reason = !ops.length ? 'PHYSICS_NOTHING_PENDING: no pending ops' : status?.reason ?? 'REBUILD_STATUS_UNAVAILABLE'; physicsPanel?.status(reason, true); return null; }
1338
+ physicsPanel?.clearPreview();
1339
+ const world = stageWorld(), before = state.stageCheck;
1340
+ physicsPanel?.busy(true); physicsPanel?.status(`Applying ${ops.length} op(s) on Build ${side.toUpperCase()}…`, false);
1341
+ try {
1342
+ const result = await applyPatch(patch, world);
1343
+ const outcome = patchOutcomeLine(result); physicsPanel?.status(outcome.text, outcome.error);
1344
+ if ('id' in result && result.status === 'built') {
1345
+ physicsPanel?.applied(result.request.patch.ops);
1346
+ const after = { lines: [...result.lines], check: result.check };
1347
+ const show = () => physicsPanel?.readout(readoutRows(before, before ? null : inspectedCheckView(side), after));
1348
+ show(); if (!before) void followInspectedCheck(show, side);
1349
+ }
1350
+ return result;
1351
+ } finally { physicsPanel?.busy(false); }
1352
+ }
1353
+
1354
+ async function resetPhysicsBuild(): Promise<void> {
1355
+ physicsPanel?.clear(); physicsPanel?.applied(null); physicsPanel?.readout([]);
1356
+ if (currentState().appliedOnStage) { physicsPanel?.busy(true); try { await resetRebuild(stageWorld()); } finally { physicsPanel?.busy(false); } }
1357
+ physicsPanel?.status('Reset: the inspected build is on the stage; no pending ops.', false);
1358
+ }
1359
+
1360
+ async function applyIdle(ops: PatchOp[], keys: 'ctl' | 'direct' | null): Promise<PatchJobView | RebuildRefusal | null> {
1361
+ const side = pickedSide, state = sides[side];
1362
+ const status = state.rebuildStatus ?? await loadRebuildStatus(side);
1363
+ const patch = status && ops.length ? makePatch(status, ops, { cmd: 'rig', args: keys ? ['--idle-keys', keys] : [] }) : null;
1364
+ if (!patch) { const reason = !ops.length ? 'IDLE_NOTHING_PENDING: no pending ops' : status?.reason ?? 'REBUILD_STATUS_UNAVAILABLE'; idlePanel?.status(reason, true); return null; }
1365
+ const world = stageWorld(), before = state.stageCheck;
1366
+ idlePanel?.busy(true); idlePanel?.status(`Applying ${ops.length} op(s) on Build ${side.toUpperCase()}…`, false);
1367
+ try {
1368
+ const result = await applyPatch(patch, world);
1369
+ const outcome = patchOutcomeLine(result); idlePanel?.status(outcome.text, outcome.error);
1370
+ if ('id' in result && result.status === 'built') {
1371
+ idlePanel?.applied(result.request.patch.ops);
1372
+ const after = { lines: [...result.lines], check: result.check };
1373
+ const show = () => idlePanel?.readout(readoutRows(before, before ? null : inspectedCheckView(side), after, IDLE_READOUT_BARS));
1374
+ show(); if (!before) void followInspectedCheck(show, side);
1375
+ }
1376
+ return result;
1377
+ } finally { idlePanel?.busy(false); }
1378
+ }
1379
+
1380
+ async function resetIdleBuild(): Promise<void> {
1381
+ idlePanel?.clear(); idlePanel?.applied(null); idlePanel?.readout([]);
1382
+ if (currentState().appliedOnStage) { idlePanel?.busy(true); try { await resetRebuild(stageWorld()); } finally { idlePanel?.busy(false); } }
1383
+ idlePanel?.status('Reset: the inspected build is on the stage; no pending ops; the preview is cleared.', false);
1384
+ }
1385
+
1386
+ async function checkBones(ops: PatchOp[]): Promise<BonesCheckView> {
1387
+ const side = pickedSide, status = sides[side].rebuildStatus ?? await loadRebuildStatus(side);
1388
+ if (!status?.inputs) return { status: 'refused', error: status?.reason ?? 'REBUILD_STATUS_UNAVAILABLE' };
1389
+ try { return await host.api<BonesCheckView>(`${sideApiPrefix(side)}/bones-check`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ops, configHash: status.inputs.configHash }) }); }
1390
+ catch (error) { const raw = errorText(error).replace(/^\d+: /, ''); try { return { status: 'refused', error: (JSON.parse(raw) as { error?: string }).error ?? raw }; } catch { return { status: 'refused', error: raw }; } }
1391
+ }
1392
+
1393
+ async function applyBones(ops: PatchOp[]): Promise<PatchJobView | RebuildRefusal | null> {
1394
+ const side = pickedSide, status = sides[side].rebuildStatus ?? await loadRebuildStatus(side);
1395
+ const patch = status && ops.length ? makePatch(status, ops, { cmd: 'rig' }) : null;
1396
+ if (!patch) { const reason = !ops.length ? 'BONES_NOTHING_PENDING: no pending ops' : status?.reason ?? 'REBUILD_STATUS_UNAVAILABLE'; bonesPanel?.status(reason, true); return null; }
1397
+ bonesPanel?.busy(true); bonesPanel?.status(`Applying ${ops.length} op(s) on Build ${side.toUpperCase()}…`, false);
1398
+ try {
1399
+ const result = await applyPatch(patch, stageWorld());
1400
+ const outcome = patchOutcomeLine(result); bonesPanel?.status(outcome.text, outcome.error);
1401
+ if ('id' in result && result.status === 'built') { bonesPanel?.applied(result.request.patch.ops); host.redrawOverlays(true); }
1402
+ return result;
1403
+ } finally { bonesPanel?.busy(false); }
1404
+ }
1405
+
1406
+ async function resetBonesBuild(): Promise<void> {
1407
+ bonesPanel?.clear(); bonesPanel?.applied(null);
1408
+ if (currentState().appliedOnStage) { bonesPanel?.busy(true); try { await resetRebuild(stageWorld()); } finally { bonesPanel?.busy(false); } }
1409
+ bonesPanel?.status('Reset: the inspected build is on the stage; no pending ops.', false);
1410
+ }
1411
+
1412
+ async function applyCuts(ops: PatchOp[]): Promise<PatchJobView | RebuildRefusal | null> {
1413
+ const side = pickedSide, status = sides[side].rebuildStatus ?? await loadRebuildStatus(side);
1414
+ const patch = status && ops.length ? makePatch(status, ops, { cmd: 'rig' }) : null;
1415
+ if (!patch) { const reason = !ops.length ? 'CUTS_NOTHING_PENDING: no pending ops' : status?.reason ?? 'REBUILD_STATUS_UNAVAILABLE'; cutsPanel?.status(reason, true); return null; }
1416
+ cutsPanel?.busy(true); cutsPanel?.status(`Applying ${ops.length} op(s) on Build ${side.toUpperCase()}…`, false);
1417
+ try {
1418
+ const result = await applyPatch(patch, stageWorld());
1419
+ const outcome = patchOutcomeLine(result); cutsPanel?.status(outcome.text, outcome.error);
1420
+ if ('id' in result && result.status === 'built') host.redrawOverlays(true);
1421
+ return result;
1422
+ } finally { cutsPanel?.busy(false); }
1423
+ }
1424
+
1425
+ async function resetCutsBuild(): Promise<void> {
1426
+ cutsPanel?.clear(); cutsPanel?.shown(null);
1427
+ if (currentState().appliedOnStage) { cutsPanel?.busy(true); try { await resetRebuild(stageWorld()); } finally { cutsPanel?.busy(false); } }
1428
+ cutsPanel?.status('Reset: the inspected build is on the stage; no pending ops.', false);
1429
+ }
1430
+
1431
+ async function applyCloth(ops: PatchOp[]): Promise<PatchJobView | RebuildRefusal | null> {
1432
+ const side = pickedSide, status = sides[side].rebuildStatus ?? await loadRebuildStatus(side);
1433
+ const patch = status && ops.length ? makePatch(status, ops, { cmd: 'rig' }) : null;
1434
+ if (!patch) { const reason = !ops.length ? 'CLOTH_NOTHING_PENDING: no pending ops' : status?.reason ?? 'REBUILD_STATUS_UNAVAILABLE'; clothPanel?.status(reason, true); return null; }
1435
+ clothPanel?.busy(true); clothPanel?.status(`Applying ${ops.length} op(s) on Build ${side.toUpperCase()}…`, false);
1436
+ try {
1437
+ const result = await applyPatch(patch, stageWorld());
1438
+ const outcome = patchOutcomeLine(result); clothPanel?.status(outcome.text, outcome.error);
1439
+ if ('id' in result && result.status === 'built') host.redrawOverlays(true);
1440
+ return result;
1441
+ } finally { clothPanel?.busy(false); }
1442
+ }
1443
+
1444
+ async function resetClothBuild(): Promise<void> {
1445
+ clothPanel?.clear(); clothPanel?.shown(null);
1446
+ if (currentState().appliedOnStage) { clothPanel?.busy(true); try { await resetRebuild(stageWorld()); } finally { clothPanel?.busy(false); } }
1447
+ clothPanel?.status('Reset: the inspected build is on the stage; no pending ops.', false);
1448
+ }
1449
+
1450
+ async function applyRigFields(ops: PatchOp[]): Promise<PatchJobView | RebuildRefusal | null> {
1451
+ const side = pickedSide, state = sides[side], status = state.rebuildStatus ?? await loadRebuildStatus(side);
1452
+ try { assertRigFieldOps(ops); } catch (error) { rigFieldsPanel?.status(errorText(error), true); return null; }
1453
+ const patch = status && ops.length ? makePatch(status, ops, { cmd: 'rig' }) : null;
1454
+ if (!patch) { const reason = !ops.length ? 'RIG_FIELDS_NOTHING_PENDING: no pending ops' : status?.reason ?? 'REBUILD_STATUS_UNAVAILABLE'; rigFieldsPanel?.status(reason, true); return null; }
1455
+ const world = stageWorld(), before = state.stageCheck;
1456
+ rigFieldsPanel?.busy(true); rigFieldsPanel?.status(`Applying ${ops.length} op(s) on Build ${side.toUpperCase()}…`, false);
1457
+ try {
1458
+ const result = await applyPatch(patch, world);
1459
+ const outcome = patchOutcomeLine(result); rigFieldsPanel?.status(outcome.text, outcome.error);
1460
+ if ('id' in result && result.status === 'built') {
1461
+ rigFieldsPanel?.applied(result.request.patch.ops);
1462
+ const after = { lines: [...result.lines], check: result.check };
1463
+ const show = () => rigFieldsPanel?.readout(readoutRows(before, before ? null : inspectedCheckView(side), after, RIG_FIELDS_READOUT_BARS));
1464
+ show(); if (!before) void followInspectedCheck(show, side);
1465
+ }
1466
+ return result;
1467
+ } finally { rigFieldsPanel?.busy(false); }
1468
+ }
1469
+
1470
+ async function resetRigFieldsBuild(): Promise<void> {
1471
+ rigFieldsPanel?.setDial(0); rigFieldsPanel?.clear(); rigFieldsPanel?.applied(null); rigFieldsPanel?.readout([]);
1472
+ if (currentState().appliedOnStage) { rigFieldsPanel?.busy(true); try { await resetRebuild(stageWorld()); } finally { rigFieldsPanel?.busy(false); } }
1473
+ rigFieldsPanel?.status('Reset: the inspected build is on the stage; no pending ops; the dial is at 0.', false);
1474
+ }
1475
+
1476
+ async function applyMesh(part: string, entry: MeshEntry): Promise<PatchJobView | RebuildRefusal | null> {
1477
+ const side = pickedSide, state = sides[side], status = state.rebuildStatus ?? await loadRebuildStatus(side);
1478
+ const problems = meshPanel?.precheck() ?? [];
1479
+ if (problems.length) { meshPanel?.status(`${problems[0]} (review pre-check; nothing sent)`, true); return null; }
1480
+ const patch = status ? makePatch(status, meshPatchOps(part, entry), { cmd: 'remesh', args: ['--part', part] }) : null;
1481
+ if (!patch) { meshPanel?.status(status?.reason ?? 'REBUILD_STATUS_UNAVAILABLE', true); return null; }
1482
+ try { assertMeshPatch(patch, part); } catch (error) { meshPanel?.status(errorText(error), true); return null; }
1483
+ lastMeshPatch = patch;
1484
+ const world = stageWorld(), before = state.stageCheck;
1485
+ meshPanel?.busy(true); meshPanel?.status(`Applying meshes.${part} on Build ${side.toUpperCase()} with ${patch.producer.name} ${patch.producer.version}: remesh --mesh, compile, check…`, false);
1486
+ try {
1487
+ const result = await applyPatch(patch, world);
1488
+ const outcome = meshApplyOutcome(result as Parameters<typeof meshApplyOutcome>[0]);
1489
+ meshPanel?.status(outcome.text, outcome.error);
1490
+ if ('id' in result && result.status === 'built') {
1491
+ if (!host.layers.mesh) { host.layers.mesh = true; input('layer-mesh').checked = true; }
1492
+ const player = host.players[side];
1493
+ if (player) { player.draw(); host.parts()?.present(side); }
1494
+ host.redrawOverlays(true);
1495
+ const counts = result.remesh ?? null, overlay = state.lastOverlay?.meshTriangles[part] ?? null;
1496
+ const agree = triangleAgreement(counts, counts?.modelTriangles ?? null, overlay);
1497
+ meshPanel?.counts([
1498
+ ...(counts ? [{ label: 'BEFORE', text: `${counts.part} ${countsText(counts.before)} (remesh.json)` }, { label: 'AFTER', text: `${counts.part} ${countsText(counts.after)} (remesh.json)` }] : []),
1499
+ { label: agree.ok ? 'AGREE' : 'DIFFER', text: agree.line, error: !agree.ok },
1500
+ ]);
1501
+ const after = { lines: [...result.lines], check: result.check };
1502
+ const show = () => meshPanel?.readout(readoutRows(before, before ? null : inspectedCheckView(side), after, ['TEXTURE_STRETCH']));
1503
+ show(); if (!before) void followInspectedCheck(show, side);
1504
+ }
1505
+ return result;
1506
+ } finally { meshPanel?.busy(false); }
1507
+ }
1508
+
1509
+ async function resetMeshBuild(): Promise<void> {
1510
+ meshPanel?.counts([]); meshPanel?.readout([]);
1511
+ if (currentState().appliedOnStage || currentState().stripPending) {
1512
+ meshPanel?.busy(true); try { await resetRebuild(stageWorld()); } finally { meshPanel?.busy(false); }
1513
+ }
1514
+ meshPanel?.status('Reset: the inspected build is on the stage; the pending entry is the config\'s.', false);
1515
+ }
1516
+
1517
+ const densityLine = (msg: string, error = false) => { densityStrip?.status(msg, error); if (error) host.message(msg, true); };
1518
+ const renderStrip = () => {
1519
+ const state = currentState();
1520
+ densityStrip?.show(state.stripView, state.stripPending && state.stripView?.id === state.stripPending.id ? state.stripPending.index : null, densityBusy || rebuildBusy || !!host.readOnly());
1521
+ };
1522
+
1523
+ async function refreshDensityStrip(side: Side = pickedSide): Promise<void> {
1524
+ try { const r = await host.api<{ strip: DensityStripViewLike | null }>(`${sideApiPrefix(side)}/density-strip`); sides[side].stripView = r.strip; } catch { /* keep */ }
1525
+ if (side === pickedSide) renderStrip();
1526
+ }
1527
+
1528
+ async function buildDensityStrip(values: number[]): Promise<DensityStripViewLike | { error: string }> {
1529
+ if (densityBusy) return { error: 'DENSITY_STRIP_BUSY: a strip is still building' };
1530
+ const ro = host.readOnly();
1531
+ if (ro) { densityLine(ro, true); return { error: ro }; }
1532
+ const side = pickedSide, state = sides[side];
1533
+ const status = state.rebuildStatus ?? await loadRebuildStatus(side), part = meshPanel?.part() ?? null, entry = meshPanel?.entry() ?? null;
1534
+ if (!status || !part || !entry) { const t = status?.reason ?? 'MESH_PANEL_NO_PART: select a mesh part'; densityLine(t, true); return { error: t }; }
1535
+ const problems = meshPanel?.precheck() ?? [];
1536
+ if (problems.length) { const t = `${problems[0]} (review pre-check; nothing sent)`; densityLine(t, true); return { error: t }; }
1537
+ let patches: ConfigPatch[];
1538
+ try {
1539
+ const field = densityField(entry, part);
1540
+ patches = values.map(v => {
1541
+ const patch = makePatch(status, meshPatchOps(part, setEntryValue(entry, densityPath(field), v)), { cmd: 'remesh', args: ['--part', part] });
1542
+ if (!patch) throw new Error(status.reason ?? 'REBUILD_STATUS_UNAVAILABLE');
1543
+ assertMeshPatch(patch, part);
1544
+ return patch;
1545
+ });
1546
+ } catch (error) { const t = errorText(error); densityLine(t, true); return { error: t }; }
1547
+ if (state.stripPending) await stripBack();
1548
+ densityBusy = true; renderStrip();
1549
+ densityLine(`Building a strip of ${values.length} on ${part} (Build ${side.toUpperCase()}): ${values.join(', ')}…`);
1550
+ const t0 = performance.now();
1551
+ try {
1552
+ let view: DensityStripViewLike | { status: string; error: string };
1553
+ try { view = await host.api<DensityStripViewLike | { status: string; error: string }>(`${sideApiPrefix(side)}/density-strip`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ patches }) }); }
1554
+ catch (error) { const t = errorText(error); densityLine(t, true); return { error: t }; }
1555
+ if ('error' in view) { densityLine(view.error, true); return { error: view.error }; }
1556
+ state.stripView = view; renderStrip();
1557
+ while (state.stripView.status === 'running') {
1558
+ await new Promise(resolve => setTimeout(resolve, 1500));
1559
+ state.stripView = await host.api<DensityStripViewLike>(`${sideApiPrefix(side)}/density-strip/${state.stripView.id}`);
1560
+ renderStrip();
1561
+ const settled = state.stripView.rows.filter(r => r.status !== 'running').length;
1562
+ densityLine(`Strip ${state.stripView.id.slice(0, 12)}…: ${settled} of ${state.stripView.rows.length} settled · ${((performance.now() - t0) / 1000).toFixed(0)} s`);
1563
+ }
1564
+ const passing = state.stripView.rows.filter(r => r.verdict === 'PASS').length;
1565
+ densityLine(`Strip of ${state.stripView.rows.length} on ${state.stripView.part} settled: ${passing} passing.`);
1566
+ return state.stripView;
1567
+ } finally { densityBusy = false; renderStrip(); }
1568
+ }
1569
+
1570
+ async function loadStripRow(index: number): Promise<{ line: string; ok: boolean } | { error: string }> {
1571
+ const side = pickedSide, state = sides[side];
1572
+ const view = state.stripView, row = view?.rows[index];
1573
+ if (!view || !row) return { error: 'DENSITY_STRIP_NOT_FOUND' };
1574
+ if (!row.modelUrl || !row.modelHash) { const t = `DENSITY_STRIP_ROW_NOT_LOADABLE: ${row.value} — ${row.applied ? 'applied already' : row.verdict}`; densityLine(t, true); return { error: t }; }
1575
+ if (rebuildBusy || densityBusy) return { error: 'REBUILD_BUSY' };
1576
+ const back = state.stripPending?.back ?? {
1577
+ url: state.stageSource?.url ?? state.inspectedModel!.url,
1578
+ prefix: state.stageSource?.prefix ?? state.inspectedModel!.prefix,
1579
+ hash: state.stageSource?.hash ?? state.inspectedModel!.sha256,
1580
+ applied: state.appliedOnStage,
1581
+ check: state.stageCheck,
1582
+ };
1583
+ rebuildBusy = true; rebuildState();
1584
+ try {
1585
+ await swapPickedSide(side, new URL(host.route(row.modelUrl), location.href).href, host.route(`/compare-density-strip/${side}/${view.id}/${row.id}/`), row.modelHash);
1586
+ state.stripPending = { index, id: view.id, candidate: row.id, back };
1587
+ state.appliedOnStage = null; state.stageCheck = null;
1588
+ const draft = el<HTMLTextAreaElement>('rebuild-applied'); draft.value = ''; draft.dispatchEvent(new Event('input', { bubbles: true }));
1589
+ meshPanel?.setEntry(row.entry as MeshEntry);
1590
+ if (!host.layers.mesh) { host.layers.mesh = true; input('layer-mesh').checked = true; }
1591
+ host.redrawOverlays(true);
1592
+ const c = row.counts ? { vertices: row.counts.vertices, triangles: row.counts.triangles, hull: 0 } : null;
1593
+ const agree = triangleAgreement(c ? { part: view.part, before: c, after: c } : null, row.modelTriangles, state.lastOverlay?.meshTriangles[view.part] ?? null);
1594
+ meshPanel?.counts([{ label: 'PENDING', text: `${view.field} ${row.value} — not applied` }, { label: agree.ok ? 'AGREE' : 'DIFFER', text: agree.line, error: !agree.ok }]);
1595
+ densityLine(`Pending on Build ${side.toUpperCase()}: ${view.part} ${view.field} ${row.value} (strip row ${index + 1}) — not applied.`, !agree.ok);
1596
+ return { line: agree.line, ok: agree.ok };
1597
+ } catch (error) { const t = `DENSITY_STRIP_LOAD_FAILED: ${errorText(error)}`; densityLine(t, true); return { error: t }; }
1598
+ finally { rebuildBusy = false; rebuildState(); renderStrip(); }
1599
+ }
1600
+
1601
+ async function stripBack(): Promise<void> {
1602
+ const side = pickedSide, state = sides[side], pending = state.stripPending;
1603
+ if (!pending || rebuildBusy) return;
1604
+ rebuildBusy = true; rebuildState();
1605
+ try {
1606
+ await swapPickedSide(side, pending.back.url, pending.back.prefix, pending.back.hash);
1607
+ state.appliedOnStage = pending.back.applied; state.stageCheck = pending.back.check; state.stripPending = null;
1608
+ const draft = el<HTMLTextAreaElement>('rebuild-applied'); draft.value = state.appliedOnStage ? JSON.stringify(state.appliedOnStage) : ''; draft.dispatchEvent(new Event('input', { bubbles: true }));
1609
+ meshPanel?.counts([]); host.redrawOverlays(true);
1610
+ densityLine(`Back: Build ${side.toUpperCase()} shows ${state.appliedOnStage ? 'the last applied record' : 'the inspected build'}.`);
1611
+ } catch (error) { densityLine(`DENSITY_STRIP_BACK_FAILED: ${errorText(error)}`, true); }
1612
+ finally { rebuildBusy = false; rebuildState(); renderStrip(); }
1613
+ }
1614
+
1615
+ async function closeDensityStrip(): Promise<{ status: string; error?: string }> {
1616
+ const side = pickedSide, state = sides[side], view = state.stripView;
1617
+ if (!view) return { status: 'closed' };
1618
+ if (state.stripPending && state.stripPending.id === view.id) await stripBack();
1619
+ try {
1620
+ const r = await host.api<{ status: string; error?: string }>(`${sideApiPrefix(side)}/density-strip/close`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id: view.id }) });
1621
+ if (r.status !== 'closed') { densityLine(r.error ?? 'DENSITY_STRIP_CLOSE_REFUSED', true); return r; }
1622
+ state.stripView = null; renderStrip(); densityLine('Strip closed; its scratch is removed.'); return r;
1623
+ } catch (error) { const t = errorText(error); densityLine(t, true); return { status: 'refused', error: t }; }
1624
+ }
1625
+
1626
+ async function runReadings(override?: { readings: import('../src/readings.ts').ReadingRequest[] }): Promise<ReadingsJobView | ReadingsRefusal | null> {
1627
+ if (!readingsPanel || readingsBusy) return null;
1628
+ const chosen = override ?? readingsPanel.requests();
1629
+ if ('error' in chosen) { readingsPanel.status(chosen.error, true); return { status: 'refused', error: chosen.error }; }
1630
+ const side = pickedSide, animation = host.data().animation;
1631
+ let environment: ReturnType<typeof environmentFor> | WorldExport['schedule'] | null = currentPlayer() && input('environment-applied').checked ? environmentFor(wind.read(), Number(input('gravity').value)) : null;
1632
+ if (environment && useWorld()) {
1633
+ const world = worldFor(animation, side);
1634
+ if ('error' in world) { readingsPanel.status(world.error, true); return { status: 'refused', error: world.error }; }
1635
+ environment = world.schedule;
1636
+ }
1637
+ const body = { animation, readings: chosen.readings, environment };
1638
+ readingsBusy = true; readingsPanel.busy(true); readingsPanel.status(`Running ${chosen.readings.length} reading(s) of ${animation} on Build ${side.toUpperCase()}…`, false);
1639
+ const started = performance.now();
1640
+ try {
1641
+ let job = await host.api<ReadingsJobView | ReadingsRefusal>(`${sideApiPrefix(side)}/readings`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }).catch(error => ({ status: 'refused' as const, error: errorText(error).replace(/^\d+: /, '') }));
1642
+ if (!('id' in job)) {
1643
+ const textMsg = (() => { try { return (JSON.parse(job.error) as { error?: string }).error ?? job.error; } catch { return job.error; } })();
1644
+ readingsPanel.status(textMsg, true); return { status: 'refused', error: textMsg };
1645
+ }
1646
+ while (job.status === 'running') {
1647
+ await new Promise(resolve => setTimeout(resolve, 800));
1648
+ job = await host.api<ReadingsJobView>(`${sideApiPrefix(side)}/readings/${job.id}`);
1649
+ }
1650
+ if (job.status === 'failed') { readingsPanel.status(job.error ?? 'READINGS_FAILED', true); return job; }
1651
+ sides[side].readingsJob = job; readingsPanel.lines(job);
1652
+ const ticks = job.runs.map(r => `${r.build} ${r.results.reduce((n, x) => n + x.frames.length, 0)} tick(s)`).join(' · ');
1653
+ const refused = job.runs.flatMap(r => r.results).find(r => r.status !== 'read');
1654
+ readingsPanel.status(`${refused ? `${refused.refusal} · ` : ''}Readings of ${job.request.animation}: ${ticks} · ${((performance.now() - started) / 1000).toFixed(1)} s`, !!refused);
1655
+ return job;
1656
+ } catch (error) { readingsPanel.status(`READINGS_FAILED: ${errorText(error)}`, true); return null; }
1657
+ finally { readingsBusy = false; readingsPanel.busy(false); }
1658
+ }
1659
+
1660
+ function readingsContext(): ReadingsContext | null {
1661
+ const job = currentState().readingsJob;
1662
+ if (!job) return null;
1663
+ const ticks = (build: 'inspected' | 'scratch') => {
1664
+ const run = job.runs.find(r => r.build === build);
1665
+ return run ? run.results.reduce((n, r) => n + r.frames.length, 0) : null;
1666
+ };
1667
+ return {
1668
+ schema: READINGS_SCHEMA,
1669
+ animation: job.request.animation,
1670
+ requests: job.request.readings,
1671
+ environment: job.request.environment,
1672
+ environmentPassed: job.environment.passed,
1673
+ builds: { inspected: job.runs.find(r => r.build === 'inspected')?.modelHash ?? '', scratch: job.runs.find(r => r.build === 'scratch')?.id ?? null },
1674
+ compiler: job.compiler,
1675
+ ticks: { inspected: ticks('inspected') ?? 0, scratch: ticks('scratch') },
1676
+ };
1677
+ }
1678
+
1679
+ async function meshFolds(): Promise<string[]> {
1680
+ const animation = host.data().animation;
1681
+ meshPanel?.status(`Running the folds reading of ${animation}…`, false);
1682
+ const job = await runReadings({ readings: [{ kind: 'folds' }] });
1683
+ if (!job || !('runs' in job)) {
1684
+ const textMsg = job && 'error' in job && job.error ? job.error : 'READINGS_UNAVAILABLE: no reading ran';
1685
+ meshPanel?.status(textMsg, true); return [textMsg];
1686
+ }
1687
+ const lines = job.runs.map(run => { const r = run.results[0]; return r ? worstLine(run.build, r) : `${run.build} · folds: not run`; });
1688
+ if (job.runs.length < 2) lines.push('scratch · folds: no scratch build yet (Apply builds one)');
1689
+ meshPanel?.status(lines.join(' | '), job.runs.some(run => run.results.some(r => r.status !== 'read')));
1690
+ return lines;
1691
+ }
1692
+
1693
+ async function runRequirements(body: { fps: number; build: 'inspected' | 'scratch'; requirements: Record<string, unknown>[] }): Promise<RequirementsJobView | RequirementsRefusal | null> {
1694
+ const side = pickedSide;
1695
+ const unwrap = (error: unknown) => { const raw = errorText(error).replace(/^\d+: /, ''); try { return (JSON.parse(raw) as { error?: string }).error ?? raw; } catch { return raw; } };
1696
+ try {
1697
+ let job = await host.api<RequirementsJobView | RequirementsRefusal>(`${sideApiPrefix(side)}/requirements`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
1698
+ while ('id' in job && job.status === 'running') {
1699
+ await new Promise(resolve => setTimeout(resolve, 800));
1700
+ job = await host.api<RequirementsJobView>(`${sideApiPrefix(side)}/requirements/${job.id}`);
1701
+ }
1702
+ return job;
1703
+ } catch (error) { return { status: 'refused', error: unwrap(error) }; }
1704
+ finally { void loadRequirements(side); }
1705
+ }
1706
+
1707
+ async function runEnvironmentCheck(): Promise<EnvironmentCheckView | { status: 'refused'; error: string } | null> {
1708
+ if (environmentCheckBusy) return null;
1709
+ const side = pickedSide, state = sides[side];
1710
+ const out = el('environment-check-lines');
1711
+ const show = (rows: { kind: string; text: string }[]) => {
1712
+ out.replaceChildren(...rows.map(row => { const line = document.createElement('div'); line.className = `env-${row.kind}`; line.textContent = row.text; return line; }));
1713
+ };
1714
+ const name = checkAnimation(side), world = worldFor(name, side);
1715
+ if ('error' in world) { show([{ kind: 'error', text: world.error }]); return { status: 'refused', error: world.error }; }
1716
+ const build = state.appliedOnStage ? 'scratch' : 'inspected', before = state.stageCheck;
1717
+ environmentCheckBusy = true; button('environment-check').disabled = true;
1718
+ show([{ kind: 'label', text: `Checking Build ${side.toUpperCase()} (${build}) under ${name}'s schedule…` }]);
1719
+ try {
1720
+ let job = await host.api<EnvironmentCheckView | { status: 'refused'; error: string }>(`${sideApiPrefix(side)}/environment-check`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ build, schedule: world.schedule }) }).catch(error => ({ status: 'refused' as const, error: errorText(error).replace(/^\d+: /, '') }));
1721
+ if (!('id' in job)) {
1722
+ const textMsg = (() => { try { return (JSON.parse(job.error) as { error?: string }).error ?? job.error; } catch { return job.error; } })();
1723
+ show([{ kind: 'error', text: textMsg }]); return { status: 'refused', error: textMsg };
1724
+ }
1725
+ while (job.status === 'running') {
1726
+ await new Promise(resolve => setTimeout(resolve, 1500));
1727
+ job = await host.api<EnvironmentCheckView>(`${sideApiPrefix(side)}/environment-check/${job.id}`);
1728
+ }
1729
+ const checked = job;
1730
+ const label = build === 'inspected' ? 'default world (the inspected build\'s own check)' : 'the scratch build\'s Apply check';
1731
+ const baseline = state.rebuildStatus?.baseline, noDefault = build === 'inspected' && !inspectedCheckView(side) && baseline && baseline.status !== 'running' && baseline.status !== 'reproduced';
1732
+ const draw = () => show(environmentCheckRows(checked, barName => noDefault ? `${barName}: no default-world check — ${baseline!.line}` : build === 'inspected' ? beforeLine(barName, null, inspectedCheckView(side)) : barLine(barName, before?.lines ?? null, before?.check ?? null), label));
1733
+ draw(); if (build === 'inspected' && inspectedCheckView(side)?.status !== 'checked') void followInspectedCheck(draw, side);
1734
+ return job;
1735
+ } catch (error) { show([{ kind: 'error', text: `ENVIRONMENT_CHECK_FAILED: ${errorText(error)}` }]); return null; }
1736
+ finally { environmentCheckBusy = false; button('environment-check').disabled = !currentPlayer(); }
1737
+ }
1738
+
1739
+ function seekReading(clip: string, frame: number, exact: number | null, label: string): void {
1740
+ if (exact === null) { host.message(`${label}: F${frame} has no time; no seek was performed.`, true); return; }
1741
+ const at = readingSeekTime(exact, clipDuration(clip));
1742
+ void host.seekTo(Math.min(at, host.duration())).then(() => host.message(`Reading · ${label} → F${frame} · ${exact.toFixed(4)} s`));
1743
+ }
1744
+
1745
+ function sampleLocals(bone: string, dt: number, n: number) {
1746
+ const p = currentPlayer();
1747
+ if (!p?.current || !(dt > 0) || !Number.isInteger(n) || n < 0) return null;
1748
+ const inner = p.adjust;
1749
+ const rows = new Map<number, { t: number; rotation: number; x: number; y: number; scaleX: number; scaleY: number; shearX: number; shearY: number }>();
1750
+ let recording = false;
1751
+ const read: BoneAdjust = (bones, ctx) => {
1752
+ inner?.(bones, ctx);
1753
+ if (!recording) return;
1754
+ const l = bones.bone(bone);
1755
+ rows.set(ctx.trackTime ?? 0, { t: ctx.trackTime ?? 0, rotation: l.rotation, x: l.x, y: l.y, scaleX: l.scaleX, scaleY: l.scaleY, shearX: l.shearX, shearY: l.shearY });
1756
+ };
1757
+ host.pause(); p.adjust = read;
1758
+ try { p.seek(0); recording = true; p.repose(); p.resume(); for (let k = 1; k <= n; k++) p.frame(dt); }
1759
+ finally { recording = false; p.pause(); p.adjust = inner; p.seek(host.time()); p.draw(); host.parts()?.present(pickedSide); }
1760
+ return [...rows.values()].sort((a, b) => a.t - b.t);
1761
+ }
1762
+
1763
+ function bindEnvironmentControls(): void {
1764
+ const environmentInputs = ['wind-base', 'wind-breeze', 'wind-gust', 'wind-repeat', 'wind-gust-peak', 'wind-gust-duration', 'gravity', 'jolt', 'drag-trail', 'physics-reset', 'environment-use', 'environment-export', 'environment-check'];
1765
+ for (const id of environmentInputs) {
1766
+ const node = document.getElementById(id) as HTMLInputElement | HTMLButtonElement | null;
1767
+ if (node) node.disabled = false;
1768
+ }
1769
+ const engage = (change: () => void) => {
1770
+ try {
1771
+ change(); input('environment-applied').checked = true; environmentNote = '';
1772
+ applyEnvironment();
1773
+ const p = currentPlayer();
1774
+ if (p?.current && !host.playing()) {
1775
+ p.repose(); p.draw(); host.parts()?.present(pickedSide); host.redrawOverlays(true);
1776
+ }
1777
+ host.saveDraft();
1778
+ } catch (error) {
1779
+ host.message(`Environment unchanged: ${errorText(error)}`, true);
1780
+ syncEnvironmentInputs();
1781
+ }
1782
+ };
1783
+ input('wind-base').oninput = () => engage(() => wind.setBase(Number(input('wind-base').value)));
1784
+ input('wind-breeze').onchange = () => engage(() => wind.setBreeze(input('wind-breeze').checked));
1785
+ input('wind-repeat').onchange = () => engage(() => wind.setRepeat(input('wind-repeat').checked));
1786
+ input('wind-gust-peak').onchange = () => engage(() => wind.setGustPeak(Number(input('wind-gust-peak').value)));
1787
+ input('wind-gust-duration').onchange = () => engage(() => wind.setGustDuration(Number(input('wind-gust-duration').value)));
1788
+ input('gravity').oninput = () => engage(() => { environmentFor(wind.read(), gravityValue()); });
1789
+ button('wind-gust').onclick = () => engage(() => wind.triggerGust());
1790
+ button('jolt').onclick = () => {
1791
+ if (!currentPlayer()) return;
1792
+ joltQueue.push(...joltPacket(wind.read().time));
1793
+ if (!host.playing()) host.message('Jolt queued · it reaches the physics on the next steps; press Play.');
1794
+ };
1795
+ button('physics-reset').onclick = resetPhysics;
1796
+ button('applied-undo').onclick = () => { void undoApply(); };
1797
+ input('environment-use').onchange = () => {
1798
+ if (!input('environment-use').checked) {
1799
+ host.message("Use for readings is off: readings send the standing wind and gravity, Apply's check reads the default world.");
1800
+ renderSchedule();
1801
+ return;
1802
+ }
1803
+ const world = worldFor(host.data().animation, pickedSide);
1804
+ if ('error' in world) {
1805
+ input('environment-use').checked = false;
1806
+ host.message(world.error, true);
1807
+ renderSchedule();
1808
+ return;
1809
+ }
1810
+ restartWindClock();
1811
+ void host.seekTo(0);
1812
+ applyEnvironment();
1813
+ host.message(`Use for readings: ${world.summary} · the wind clock restarts with the clip.`);
1814
+ };
1815
+ button('environment-export').onclick = () => {
1816
+ const w = worldFor(host.data().animation, pickedSide);
1817
+ if ('error' in w) { host.message(w.error, true); return; }
1818
+ host.download('rigc-environment.json', w.text, 'application/json');
1819
+ host.message(`Exported ${w.summary}. The download is the bytes readings, Apply and feedback carry; the package is unchanged.`);
1820
+ };
1821
+ button('environment-check').onclick = () => { void runEnvironmentCheck(); };
1822
+ input('drag-trail').onchange = () => {
1823
+ for (const s of ['a', 'b'] as const) el(`${s}-viewport`).dataset.trail = String(s === pickedSide && input('drag-trail').checked);
1824
+ };
1825
+ }
1826
+
1827
+ function onInspectorTabChanged(): void {
1828
+ const which = currentInspector();
1829
+ if (which === 'rig') {
1830
+ if (workspaceMode !== 'setup') setMode('setup', { fromTab: true });
1831
+ else syncModeButtons();
1832
+ } else if (which === 'playback') {
1833
+ if (workspaceMode !== 'animate') setMode('animate', { fromTab: true });
1834
+ else syncModeButtons();
1835
+ } else if (which === 'view') {
1836
+ if (workspaceMode !== 'compare') setMode('compare', { fromTab: true });
1837
+ else syncModeButtons();
1838
+ } else {
1839
+ syncModeButtons();
1840
+ }
1841
+ }
1842
+
1843
+ // Wire top mode switch and picked-build switch.
1844
+ for (const btn of document.querySelectorAll<HTMLButtonElement>('.mode-switch [data-mode]')) {
1845
+ btn.onclick = () => {
1846
+ const raw = btn.dataset.mode;
1847
+ const next: CommentMode = raw === 'rig' ? 'setup' : raw === 'playback' ? 'animate' : 'compare';
1848
+ setMode(next);
1849
+ };
1850
+ }
1851
+ for (const btn of document.querySelectorAll<HTMLButtonElement>('#mode-build-picker [data-build-side]')) {
1852
+ btn.onclick = () => {
1853
+ const side = btn.dataset.buildSide;
1854
+ if (side === 'a' || side === 'b') setPickedSide(side);
1855
+ };
1856
+ }
1857
+ syncModeButtons();
1858
+ syncPickedBanner();
1859
+ moveStageHandlesToPickedSide();
1860
+
1861
+ button('chest-export').onclick = () => { void exportChest(); };
1862
+ for (const event of ['input', 'change']) el('chest-regions').addEventListener(event, renderChest);
1863
+ bindEnvironmentControls();
1864
+
1865
+ const paneProxy = sideElementProxy(() => pickedSide, 'pane');
1866
+ const viewportProxy = sideElementProxy(() => pickedSide, 'viewport');
1867
+ const overlayProxy = sideElementProxy<HTMLCanvasElement>(() => pickedSide, 'overlay');
1868
+ const token = (name: string) => getComputedStyle(document.documentElement).getPropertyValue(name).trim();
1869
+
1870
+ inspectorBlocks = bindInspectorBlocks({
1871
+ sections: [el('inspector-rig'), el('inspector-playback')],
1872
+ changed: () => host.saveDraft(),
1873
+ });
1874
+ disposers.push(() => inspectorBlocks?.dispose());
1875
+
1876
+ animationPanel = new AnimationInspectionPanel({
1877
+ host: el('animation-inspection'),
1878
+ stage: viewportProxy,
1879
+ project: (x, y) => rigProject()(x, y),
1880
+ enabled: () => !!currentState().partModel && currentInspector() === 'playback',
1881
+ seek: exact => {
1882
+ if (!Number.isFinite(exact) || exact < 0 || exact > host.duration()) {
1883
+ host.message('KEY_TIME_OUT_OF_DOMAIN: no substitute time was used.', true);
1884
+ return;
1885
+ }
1886
+ void host.seekTo(exact);
1887
+ },
1888
+ select: value => {
1889
+ const slot = value?.kind === 'slot' ? value.name : null;
1890
+ const cur = host.parts()?.value();
1891
+ if ((cur?.side === pickedSide ? cur.slot : null) !== slot) {
1892
+ host.parts()?.select(slot ? { side: pickedSide, slot, mode: cur?.mode ?? 'context' } : null);
1893
+ }
1894
+ host.parts()?.highlightBone(value?.kind === 'bone' ? value.name : null);
1895
+ host.redrawOverlays(false);
1896
+ },
1897
+ });
1898
+ disposers.push(() => animationPanel?.dispose());
1899
+
1900
+ chestEditor = bindChestEditor({
1901
+ pane: paneProxy,
1902
+ canvas: overlayProxy,
1903
+ project: () => currentPlayer() ? rigProject() : null,
1904
+ mapping: () => currentState().chestMapping,
1905
+ changed: renderChest,
1906
+ download: () => { void exportChest(); },
1907
+ apply: () => { void applyRebuild(); },
1908
+ reset: () => { void resetRebuild(); },
1909
+ message: host.message,
1910
+ inspector: currentInspector,
1911
+ });
1912
+ disposers.push(() => chestEditor?.dispose());
1913
+
1914
+ meshEditor = bindMeshEditor({
1915
+ pane: paneProxy,
1916
+ canvas: overlayProxy,
1917
+ project: () => currentPlayer() ? rigProject() : null,
1918
+ mapping: () => currentState().chestMapping,
1919
+ inspector: currentInspector,
1920
+ source: meshSource,
1921
+ pause: host.pause,
1922
+ changed: () => host.redrawOverlays(false),
1923
+ download: doc => { void exportMesh(doc); },
1924
+ apply: (doc, line) => applyMeshDelta(doc, line),
1925
+ applied: () => currentState().appliedOnStage?.schema === 'rig-review-applied/3',
1926
+ resetBuild: () => resetRebuild(stageWorld()),
1927
+ message: host.message,
1928
+ confirm: msg => window.confirm(msg),
1929
+ token,
1930
+ });
1931
+ disposers.push(() => meshEditor?.dispose());
1932
+
1933
+ weightsView = bindWeightsView({
1934
+ pane: paneProxy,
1935
+ canvas: overlayProxy,
1936
+ project: () => currentPlayer() ? rigProject() : null,
1937
+ inspector: currentInspector,
1938
+ slot: () => { const p = host.parts()?.value(); return p?.side === pickedSide ? p.slot : null; },
1939
+ model: () => currentSideData()?.manifest.model ? currentState().partModel ?? undefined : null,
1940
+ setup: slot => { const a = currentAssets(); return a ? setupPoseMesh(a, currentState().partModel, slot, document.createElement('div')) : null; },
1941
+ changed: () => host.redrawOverlays(false),
1942
+ token,
1943
+ });
1944
+ disposers.push(() => weightsView?.dispose());
1945
+
1946
+ bonesPanel = bindBonesPanel({
1947
+ pane: paneProxy,
1948
+ canvas: overlayProxy,
1949
+ project: () => currentPlayer() ? rigProject() : null,
1950
+ mapping: () => currentState().chestMapping,
1951
+ inspector: currentInspector,
1952
+ pause: host.pause,
1953
+ changed: () => host.redrawOverlays(false),
1954
+ saved: () => host.saveDraft(),
1955
+ check: checkBones,
1956
+ apply: async ops => { await applyBones(ops); },
1957
+ reset: resetBonesBuild,
1958
+ token,
1959
+ });
1960
+ disposers.push(() => bonesPanel?.dispose());
1961
+
1962
+ cutsPanel = bindCutsPanel({
1963
+ pane: paneProxy,
1964
+ canvas: overlayProxy,
1965
+ project: () => currentPlayer() ? rigProject() : null,
1966
+ mapping: () => currentState().chestMapping,
1967
+ inspector: currentInspector,
1968
+ pause: host.pause,
1969
+ changed: () => host.redrawOverlays(false),
1970
+ saved: () => host.saveDraft(),
1971
+ apply: applyCuts,
1972
+ reset: resetCutsBuild,
1973
+ token,
1974
+ route: path => host.route(path),
1975
+ });
1976
+ disposers.push(() => cutsPanel?.dispose());
1977
+
1978
+ clothPanel = bindClothPanel({
1979
+ project: () => currentPlayer() ? rigProject() : null,
1980
+ mapping: () => currentState().chestMapping,
1981
+ inspector: currentInspector,
1982
+ pause: host.pause,
1983
+ changed: () => host.redrawOverlays(false),
1984
+ saved: () => host.saveDraft(),
1985
+ apply: applyCloth,
1986
+ reset: resetClothBuild,
1987
+ token,
1988
+ });
1989
+ disposers.push(() => clothPanel?.dispose());
1990
+
1991
+ physicsPanel = bindPhysicsPanel({
1992
+ preview: edits => {
1993
+ const player = currentPlayer();
1994
+ const before = JSON.stringify(physicsPreview.read()), next = physicsPreview.sync(player ?? null, edits);
1995
+ if (player?.current && !host.playing() && before !== JSON.stringify(next)) {
1996
+ player.repose(); player.draw(); host.parts()?.present(pickedSide); host.redrawOverlays(true);
1997
+ }
1998
+ return physicsPreview.read();
1999
+ },
2000
+ previewRead: () => physicsPreview.read(),
2001
+ apply: async ops => { await applyPhysics(ops); },
2002
+ reset: resetPhysicsBuild,
2003
+ pane: paneProxy,
2004
+ saved: () => host.saveDraft(),
2005
+ bonePoints: bones => {
2006
+ const player = currentPlayer(); if (!player) return null;
2007
+ const project = rigProject(), pane = el(`${pickedSide}-pane`).getBoundingClientRect(), view = el(`${pickedSide}-root`).parentElement!.getBoundingClientRect();
2008
+ const out = new Map<string, { x: number; y: number }>();
2009
+ for (const name of bones) {
2010
+ try { const b = player.bone(name), p = project(b.x, b.y); out.set(name, { x: p.x + view.left - pane.left, y: p.y + view.top - pane.top }); } catch { /* absent */ }
2011
+ }
2012
+ return out;
2013
+ },
2014
+ });
2015
+ disposers.push(() => physicsPanel?.dispose());
2016
+
2017
+ meshPanel = bindMeshPanel({
2018
+ pane: paneProxy,
2019
+ project: () => currentPlayer() ? rigProject() : null,
2020
+ mapping: () => currentState().chestMapping,
2021
+ bones: () => currentSideData()?.feedbackCatalog.bones ?? [],
2022
+ apply: async (part, entry) => { await applyMesh(part, entry); },
2023
+ reset: resetMeshBuild,
2024
+ folds: async () => { await meshFolds(); },
2025
+ changed: () => { host.redrawOverlays(false); densityStrip?.changed(); },
2026
+ saved: () => host.saveDraft(),
2027
+ token,
2028
+ });
2029
+ disposers.push(() => meshPanel?.dispose());
2030
+
2031
+ densityStrip = bindDensityStrip({
2032
+ part: () => meshPanel?.part() ?? null,
2033
+ entry: () => meshPanel?.entry() ?? null,
2034
+ build: async values => { await buildDensityStrip(values); },
2035
+ load: async i => { await loadStripRow(i); },
2036
+ back: async () => { await stripBack(); },
2037
+ close: async () => { await closeDensityStrip(); },
2038
+ });
2039
+
2040
+ idlePanel = bindIdlePanel({
2041
+ apply: async (ops, keys) => { await applyIdle(ops, keys); },
2042
+ reset: resetIdleBuild,
2043
+ pane: paneProxy,
2044
+ saved: () => host.saveDraft(),
2045
+ preview: fn => { idleAdjust = fn; setAdjust(); },
2046
+ bonePoints: bones => {
2047
+ const player = currentPlayer(); if (!player) return null;
2048
+ const project = rigProject(), out = new Map<string, { x: number; y: number }>();
2049
+ for (const name of bones) { try { const b = player.bone(name); out.set(name, project(b.x, b.y)); } catch { /* absent */ } }
2050
+ return out;
2051
+ },
2052
+ });
2053
+ disposers.push(() => idlePanel?.dispose());
2054
+
2055
+ rigFieldsPanel = bindRigFieldsPanel({
2056
+ apply: async ops => { await applyRigFields(ops); },
2057
+ reset: resetRigFieldsBuild,
2058
+ reading: async (bone, relative) => { await runReadings({ readings: [{ kind: 'angle-range', bone, relative }] }); },
2059
+ part: () => { const p = host.parts()?.value(); return p?.side === pickedSide ? p.slot : null; },
2060
+ inspector: currentInspector,
2061
+ pause: host.pause,
2062
+ saved: () => host.saveDraft(),
2063
+ toPane: (x, y) => {
2064
+ const mapping = currentState().chestMapping;
2065
+ if (!currentPlayer() || !mapping.available) return null;
2066
+ const w = mapping.toWorld(x, y); return rigProject()(w.x, w.y);
2067
+ },
2068
+ toRig: (x, y) => {
2069
+ const mapping = currentState().chestMapping;
2070
+ return currentPlayer() && mapping.available ? canvasToCrop(rigProject(), mapping.toWorld, { x, y }) : null;
2071
+ },
2072
+ slotBox: slot => {
2073
+ const frame = currentPlayer()?.posedFrame(); if (!frame) return null;
2074
+ try {
2075
+ const b = partBounds(frame, slot); if (!b) return null;
2076
+ const project = rigProject(), a = project(b.x, b.y), c = project(b.x + b.width, b.y + b.height);
2077
+ return { left: Math.min(a.x, c.x), right: Math.max(a.x, c.x), top: Math.min(a.y, c.y), bottom: Math.max(a.y, c.y) };
2078
+ } catch { return null; }
2079
+ },
2080
+ dial: fn => { dialAdjust = fn as BoneAdjust | null; setAdjust(); },
2081
+ hasTurn: () => {
2082
+ const p = currentPlayer(); if (!p) return false;
2083
+ try { p.bone(TURN_BONE); return true; } catch { return false; }
2084
+ },
2085
+ });
2086
+ disposers.push(() => rigFieldsPanel?.dispose());
2087
+
2088
+ readingsPanel = bindReadingsPanel({ run: () => { void runReadings(); }, seek: seekReading });
2089
+ retargetPanel = bindRetargetPanel({ apply: body => applyRetarget(body), reset: () => { void resetRebuild(stageWorld()); }, seek: seekReading });
2090
+ requirementsPanel = bindRequirementsPanel({
2091
+ check: runRequirements,
2092
+ seek: seekReading,
2093
+ animation: () => host.data().animation,
2094
+ slot: () => { const p = host.parts()?.value(); return p?.side === pickedSide ? p.slot : null; },
2095
+ hash: sha256Hex,
2096
+ });
2097
+
2098
+ // Expose automation surface on window.rigReviewEditor for the picked build.
2099
+ (window as unknown as { rigReviewEditor: unknown }).rigReviewEditor = {
2100
+ mode: () => workspaceMode,
2101
+ setMode: (m: CommentMode) => setMode(m),
2102
+ pickedSide: () => pickedSide,
2103
+ pickSide: (s: Side) => setPickedSide(s),
2104
+ applyPatch,
2105
+ reset: () => resetRebuild(),
2106
+ undo: () => undoApply(),
2107
+ history: () => currentState().appliedHistory ? JSON.parse(JSON.stringify(currentState().appliedHistory)) : null,
2108
+ status: async () => currentState().rebuildStatus ?? await loadRebuildStatus(pickedSide),
2109
+ physics: {
2110
+ rows: () => physicsPanel?.rows() ?? [],
2111
+ chains: () => physicsPanel?.chains() ?? [],
2112
+ edits: () => physicsPanel?.edits() ?? [],
2113
+ preview: () => physicsPreview.read(),
2114
+ clearPreview: () => physicsPanel?.clearPreview(),
2115
+ set: (name: string, field: Parameters<PhysicsPanel['set']>[1], value: number) => physicsPanel?.set(name, field, value),
2116
+ ramp: (id: string, field: Parameters<PhysicsPanel['set']>[1], root: number, tip: number) => physicsPanel?.ramp(id, field, root, tip),
2117
+ select: (name: string) => physicsPanel?.select(name),
2118
+ apply: () => applyPhysics(physicsPanel?.edits().map(e => ({ op: e.op, path: e.path, value: e.value, name: e.name })) ?? []),
2119
+ reset: () => resetPhysicsBuild(),
2120
+ },
2121
+ posed: (slot: string) => {
2122
+ const frame = currentPlayer()?.posedFrame();
2123
+ const found = frame?.order.find(item => item.slot === slot);
2124
+ return found ? JSON.parse(JSON.stringify(found, (key, value) => key === 'bitmap' || key === 'image' || key === 'page' ? undefined : value)) : null;
2125
+ },
2126
+ bone: (name: string, side: Side = pickedSide) => host.players[side] ? JSON.parse(JSON.stringify(host.players[side]!.bone(name))) : null,
2127
+ meshEdit: () => {
2128
+ const sSession = meshEditor?.session(), overlay = meshEditor?.overlay();
2129
+ if (!sSession || !overlay) return null;
2130
+ const s = sSession.source, project = rigProject(), view = el(`${pickedSide}-root`).parentElement!.getBoundingClientRect();
2131
+ return {
2132
+ slot: s.slot, skin: s.skin, attachment: s.attachment, hash: s.hash, hull: s.hull,
2133
+ triangles: s.triangles.length / 3, vertices: s.vertices, ops: sSession.ops(),
2134
+ drawn: overlay.vertices.map(v => { const p = project(v.at.x, v.at.y); return { x: p.x + view.left, y: p.y + view.top, state: v.state }; }),
2135
+ };
2136
+ },
2137
+ screen: (x: number, y: number) => {
2138
+ const p = rigProject()(x, y), view = el(`${pickedSide}-root`).parentElement!.getBoundingClientRect();
2139
+ return { x: p.x + view.left, y: p.y + view.top };
2140
+ },
2141
+ readings: {
2142
+ run: (readings?: import('../src/readings.ts').ReadingRequest[]) => runReadings(readings ? { readings } : undefined),
2143
+ job: () => currentState().readingsJob ? JSON.parse(JSON.stringify(currentState().readingsJob)) : null,
2144
+ lines: () => readingsPanel?.shownLines() ?? [],
2145
+ context: () => readingsContext(),
2146
+ },
2147
+ idle: {
2148
+ state: () => idlePanel?.state() ?? null,
2149
+ ops: () => idlePanel?.ops() ?? [],
2150
+ source: () => idlePanel?.source() ?? null,
2151
+ keying: () => idlePanel?.keying() ?? null,
2152
+ refusals: () => idlePanel?.refusals() ?? [],
2153
+ select: (key: string) => idlePanel?.select(key),
2154
+ field: (key: string, field: Parameters<IdlePanel['field']>[1], value: number | null) => idlePanel?.field(key, field, value),
2155
+ linkAmp: (key: string, link: number, value: number) => idlePanel?.linkAmp(key, link, value),
2156
+ add: (spec: Parameters<IdlePanel['add']>[0]) => idlePanel?.add(spec),
2157
+ remove: (key: string) => idlePanel?.remove(key),
2158
+ blink: (field: Parameters<IdlePanel['blink']>[0], value: number) => idlePanel?.blink(field, value),
2159
+ preview: () => idlePanel?.previewing() ?? null,
2160
+ setPreview: (on: boolean) => idlePanel?.setPreview(on),
2161
+ apply: () => applyIdle(idlePanel?.ops() ?? [], idlePanel?.keying()?.keys ?? null),
2162
+ reset: () => resetIdleBuild(),
2163
+ sample: (bone: string, dt: number, n: number) => sampleLocals(bone, dt, n),
2164
+ adjustSet: () => !!currentPlayer()?.adjust,
2165
+ },
2166
+ mesh: {
2167
+ part: () => meshPanel?.part() ?? null,
2168
+ select: (part: string) => meshPanel?.select(part),
2169
+ entry: () => meshPanel?.entry() ?? null,
2170
+ configEntry: () => meshPanel?.configEntry() ?? null,
2171
+ set: (path: string[], value: import('../src/config-patch.ts').JsonValue | undefined) => meshPanel?.set(path, value),
2172
+ setEntry: (entry: MeshEntry) => meshPanel?.setEntry(entry),
2173
+ regions: () => meshPanel?.regions.list() ?? [],
2174
+ addRegion: (region: import('../src/mesh-entry.ts').MeshRegion) => meshPanel?.regions.add(region),
2175
+ moveRegion: (region: number, vertex: number, to: [number, number]) => meshPanel?.regions.move(region, vertex, to),
2176
+ drawRegions: (on: boolean) => meshPanel?.regions.draw(on),
2177
+ placing: () => meshPanel?.regions.placing() ?? null,
2178
+ precheck: () => meshPanel?.precheck() ?? [],
2179
+ apply: () => { const part = meshPanel?.part(), entry = meshPanel?.entry(); return part && entry ? applyMesh(part, entry) : Promise.resolve(null); },
2180
+ reset: () => resetMeshBuild(),
2181
+ folds: () => meshFolds(),
2182
+ overlayTriangles: (slot: string) => currentState().lastOverlay?.meshTriangles[slot] ?? null,
2183
+ status: () => el('mesh-status').textContent,
2184
+ counts: () => [...document.querySelectorAll('#mesh-counts code')].map(c => c.textContent),
2185
+ readout: () => [...document.querySelectorAll('#mesh-readout code')].map(c => c.textContent),
2186
+ pending: () => input('mesh-pending').value,
2187
+ lastPatch: () => lastMeshPatch ? JSON.parse(JSON.stringify(lastMeshPatch)) : null,
2188
+ strip: {
2189
+ build: (values: number[]) => buildDensityStrip(values),
2190
+ view: () => currentState().stripView ? JSON.parse(JSON.stringify(currentState().stripView)) : null,
2191
+ load: (i: number) => loadStripRow(i),
2192
+ back: () => stripBack(),
2193
+ close: () => closeDensityStrip(),
2194
+ pending: () => currentState().stripPending ? { index: currentState().stripPending!.index, candidate: currentState().stripPending!.candidate } : null,
2195
+ applied: () => currentState().appliedOnStage ? JSON.parse(JSON.stringify(currentState().appliedOnStage)) : null,
2196
+ stageHash: () => currentState().stageModelHash,
2197
+ },
2198
+ },
2199
+ cuts: {
2200
+ source: () => cutsPanel?.source() ?? null,
2201
+ ops: () => cutsPanel?.ops() ?? [],
2202
+ handles: () => cutsPanel?.handles() ?? [],
2203
+ active: () => cutsPanel?.active() ?? false,
2204
+ setActive: (on: boolean) => cutsPanel?.setActive(on),
2205
+ setVertex: (cut: number, k: number, value: [number, number]) => cutsPanel?.setVertex(cut, k, value),
2206
+ setBox: (i: number, value: [number, number, number, number]) => cutsPanel?.setBox(i, value),
2207
+ setRange: (limb: string, k: number, value: [number, number] | null) => cutsPanel?.setRange(limb, k, value),
2208
+ apply: () => cutsPanel?.apply() ?? Promise.resolve(null),
2209
+ reset: () => resetCutsBuild(),
2210
+ applied: () => cutsPanel?.appliedItems() ?? [],
2211
+ },
2212
+ cloth: {
2213
+ tag: () => clothPanel?.tag() ?? '',
2214
+ select: (tag: string) => clothPanel?.select(tag),
2215
+ values: (tag?: string) => clothPanel?.values(tag) ?? {},
2216
+ set: (key: string, val: string, tag?: string) => clothPanel?.set(key, val, tag),
2217
+ declare: (on: boolean, tag?: string) => clothPanel?.declare(on, tag),
2218
+ ops: () => clothPanel?.ops() ?? [],
2219
+ links: () => clothPanel?.links() ?? null,
2220
+ active: () => clothPanel?.active() ?? false,
2221
+ setActive: (on: boolean) => clothPanel?.setActive(on),
2222
+ apply: () => clothPanel?.apply() ?? Promise.resolve(null),
2223
+ reset: () => resetClothBuild(),
2224
+ applied: () => clothPanel?.appliedItems() ?? [],
2225
+ status: () => el('cloth-status').textContent,
2226
+ readout: () => [...document.querySelectorAll('#cloth-readout code')].map(c => c.textContent),
2227
+ },
2228
+ bones: {
2229
+ anchors: () => bonesPanel?.anchors() ?? [],
2230
+ edits: () => bonesPanel?.edits() ?? [],
2231
+ set: (path: string, value: [number, number]) => bonesPanel?.set(path, value),
2232
+ select: (name: string | null) => bonesPanel?.select(name),
2233
+ active: () => bonesPanel?.active() ?? false,
2234
+ setActive: (on: boolean) => bonesPanel?.setActive(on),
2235
+ handles: () => bonesPanel?.handles() ?? [],
2236
+ check: () => bonesPanel?.check() ?? Promise.resolve(null),
2237
+ apply: () => applyBones((bonesPanel?.edits() ?? []).map(e => ({ op: 'replace' as const, path: e.path, value: [...e.value], name: e.name }))),
2238
+ reset: () => resetBonesBuild(),
2239
+ status: () => el('bones-status').textContent,
2240
+ lines: () => [...document.querySelectorAll('#bones-lint code, #bones-lint summary')].map(c => c.textContent),
2241
+ compare: () => [...document.querySelectorAll('#bones-compare code')].map(c => c.textContent),
2242
+ pending: () => input('bones-pending').value,
2243
+ },
2244
+ fields: {
2245
+ source: () => rigFieldsPanel?.source() ?? null,
2246
+ edits: () => rigFieldsPanel?.edits() ?? [],
2247
+ ops: () => rigFieldsPanel?.ops() ?? [],
2248
+ region: (part: string, bone: string) => rigFieldsPanel?.region(part, bone),
2249
+ still: (part: string, entry: { row: number; bone: string } | null) => rigFieldsPanel?.still(part, entry),
2250
+ stop: (index: number, bounds: { inward?: number; outward?: number }) => rigFieldsPanel?.stop(index, bounds),
2251
+ inherit: (index: number, mode: string | null, link?: string) => rigFieldsPanel?.inherit(index, mode, link),
2252
+ turn: (target: { pivot: number } | { part: string; depth: number }) => rigFieldsPanel?.turn(target),
2253
+ select: (kind: 'part' | 'still' | 'stop' | 'bone', value: string | number | null) => rigFieldsPanel?.select(kind, value),
2254
+ setDial: (x: number) => rigFieldsPanel?.setDial(x),
2255
+ dial: () => rigFieldsPanel?.dialState() ?? null,
2256
+ handles: () => rigFieldsPanel?.handles() ?? [],
2257
+ apply: () => applyRigFields(rigFieldsPanel?.ops() ?? []),
2258
+ reset: () => resetRigFieldsBuild(),
2259
+ status: () => el('rig-fields-status').textContent,
2260
+ readout: () => [...document.querySelectorAll('#rig-fields-readout code')].map(c => c.textContent),
2261
+ pending: () => input('rig-fields-pending').value,
2262
+ },
2263
+ retarget: {
2264
+ map: () => retargetPanel?.map() ?? null,
2265
+ setMap: (map: PoseMap) => retargetPanel?.setMap(map),
2266
+ include: (chain: string, on: boolean) => retargetPanel?.include(chain, on),
2267
+ pick: (chain: string, index: number, bone: string) => retargetPanel?.pick(chain, index, bone),
2268
+ flags: () => retargetPanel?.flags() ?? null,
2269
+ setFlags: (flags: Partial<RetargetFlags>) => retargetPanel?.setFlags(flags),
2270
+ apply: () => { const b = document.getElementById('retarget-apply') as HTMLButtonElement | null; b?.click(); },
2271
+ status: () => el('retarget-status').textContent,
2272
+ lines: () => retargetPanel?.shownLines() ?? [],
2273
+ refusals: () => [...document.querySelectorAll('#retarget-refusals code')].map(c => c.textContent),
2274
+ },
2275
+ stage: (side: Side = pickedSide) => ({
2276
+ side,
2277
+ modelHash: sides[side].stageModelHash,
2278
+ inspectedHash: sides[side].inspectedModel?.sha256 ?? null,
2279
+ applied: sides[side].appliedOnStage ? JSON.parse(JSON.stringify(sides[side].appliedOnStage)) : null,
2280
+ animation: host.data()?.animation ?? null,
2281
+ time: host.time(),
2282
+ playing: host.playing(),
2283
+ busy: rebuildBusy,
2284
+ }),
2285
+ };
2286
+
2287
+ return {
2288
+ mode: () => workspaceMode,
2289
+ setMode,
2290
+ onInspectorTabChanged,
2291
+ pickedSide: () => pickedSide,
2292
+ setPickedSide,
2293
+ isSwitchingSide: () => switchingSide,
2294
+ defaultStatusMessage,
2295
+ registerSideModel: (side, modelUrl, prefix, sha256, partModel) => {
2296
+ const st = sides[side];
2297
+ if (!st.inspectedModel) st.inspectedModel = { url: modelUrl, prefix, sha256 };
2298
+ st.stageSource = { url: modelUrl, prefix, hash: sha256 };
2299
+ st.stageModelHash = sha256;
2300
+ st.partModel = partModel;
2301
+ void loadModelDocument(modelUrl, sha256).then(loaded => {
2302
+ if (loaded.ok) {
2303
+ st.inspectedDocument = loaded.document;
2304
+ st.inspectedDocumentReason = null;
2305
+ if (side === pickedSide && st.stageModelHash === sha256) {
2306
+ idlePanel?.model(boneSetup(loaded.document));
2307
+ }
2308
+ } else {
2309
+ st.inspectedDocumentReason = `PHYSICS_TUNING_UNAVAILABLE: ${loaded.reason}`;
2310
+ }
2311
+ if (side === pickedSide) refreshPhysics();
2312
+ }, error => {
2313
+ st.inspectedDocumentReason = `PHYSICS_TUNING_UNAVAILABLE: ${errorText(error)}`;
2314
+ if (side === pickedSide) refreshPhysics();
2315
+ });
2316
+ updateChestMapping(side);
2317
+ if (side === pickedSide) {
2318
+ populateChestBones();
2319
+ refreshAnimationInspection();
2320
+ weightsView?.refresh();
2321
+ }
2322
+ },
2323
+ loadInitialSideStatuses: async () => {
2324
+ syncPickedBanner();
2325
+ moveStageHandlesToPickedSide();
2326
+ await Promise.all([
2327
+ loadRebuildStatus('a'),
2328
+ loadRebuildStatus('b'),
2329
+ loadRequirements('a'),
2330
+ loadRequirements('b'),
2331
+ refreshApplied('a'),
2332
+ refreshApplied('b'),
2333
+ refreshDensityStrip('a'),
2334
+ refreshDensityStrip('b'),
2335
+ ]);
2336
+ applySideStateToPanels();
2337
+ renderChest();
2338
+ physicsPanel?.restore();
2339
+ bonesPanel?.restore();
2340
+ cutsPanel?.restore();
2341
+ clothPanel?.restore();
2342
+ idlePanel?.restore();
2343
+ rigFieldsPanel?.restore();
2344
+ meshPanel?.restore();
2345
+ },
2346
+ onPosePresented: () => {
2347
+ if (!animationPanel) return;
2348
+ animationPanel.update(host.time(), host.duration());
2349
+ const player = currentPlayer();
2350
+ if (player && currentState().partModel) {
2351
+ animationPanel.capture(player, host.parts()?.frame(pickedSide));
2352
+ }
2353
+ },
2354
+ onPartSelected: (side, slot) => {
2355
+ if (side && side !== pickedSide && workspaceMode !== 'compare') {
2356
+ setPickedSide(side);
2357
+ }
2358
+ const activeSlot = (side ?? pickedSide) === pickedSide ? slot : null;
2359
+ const player = currentPlayer();
2360
+ if (player && currentState().partModel) animationPanel?.capture(player, host.parts()?.frame(pickedSide));
2361
+ weightsView?.refresh();
2362
+ meshEditor?.selectionChanged();
2363
+ animationPanel?.fromParts(activeSlot);
2364
+ meshPanel?.select(activeSlot);
2365
+ requirementsPanel?.selectionChanged();
2366
+ },
2367
+ overlayInputFor: side => {
2368
+ animationPanel?.redraw(host.layers.bones);
2369
+ if (side !== pickedSide) {
2370
+ return { regions: [], circles: [], markers: [], meshEdit: null, weights: null, anchors: null };
2371
+ }
2372
+ idlePanel?.place(host.duration());
2373
+ rigFieldsPanel?.place();
2374
+ return {
2375
+ regions: [
2376
+ ...chestRegions(),
2377
+ ...(meshPanel?.overlayRegions() ?? []),
2378
+ ...(cutsPanel?.overlayRegions() ?? []),
2379
+ ...(clothPanel?.overlayRegions() ?? []),
2380
+ ],
2381
+ circles: [
2382
+ ...chestCircles(),
2383
+ ...(meshPanel?.overlayCircles() ?? []),
2384
+ ],
2385
+ markers: [
2386
+ ...chestMarkers(),
2387
+ ...(cutsPanel?.overlayMarkers() ?? []),
2388
+ ],
2389
+ meshEdit: meshEditor?.overlay() ?? null,
2390
+ weights: weightsView?.overlay() ?? null,
2391
+ anchors: bonesPanel?.overlay() ?? null,
2392
+ };
2393
+ },
2394
+ recordOverlaySnapshot: (side, snapshot) => {
2395
+ sides[side].lastOverlay = snapshot;
2396
+ },
2397
+ uiState: () => ({
2398
+ workspaceMode,
2399
+ pickedSide,
2400
+ ...(inspectorBlocks ? activeBlocksUI(inspectorBlocks.state()) : {}),
2401
+ }),
2402
+ restoreUiState: ui => {
2403
+ if (ui.pickedSide === 'a' || ui.pickedSide === 'b') setPickedSide(ui.pickedSide);
2404
+ if (ui.workspaceMode === 'setup' || ui.workspaceMode === 'animate' || ui.workspaceMode === 'compare') {
2405
+ setMode(ui.workspaceMode);
2406
+ }
2407
+ restoreEnvironment();
2408
+ inspectorBlocks?.restore(restoreActiveBlocksUI(ui));
2409
+ },
2410
+ commentRefusal: () => {
2411
+ if (sides.a.appliedOnStage || sides.b.appliedOnStage) {
2412
+ return 'COMMENT_APPLIED_BUILD_UNSUPPORTED: return to the inspected source before commenting on this applied scratch build';
2413
+ }
2414
+ if (rebuildBusy) {
2415
+ return 'COMMENT_SOURCE_BUSY: wait for the rebuild or candidate model replacement before commenting';
2416
+ }
2417
+ const preview = idleAdjust ? 'Idle tracks' : dialAdjust ? 'Rig fields turn dial' : physicsPreview.read().length ? 'Physics live overrides' :
2418
+ (sides.a.stripPending || sides.b.stripPending) ? 'Density strip candidate' :
2419
+ meshEditor?.overlay() ? 'Edit Mesh' : bonesPanel?.overlay() ? 'Bones anchors' :
2420
+ cutsPanel && (cutsPanel.overlayRegions().length || cutsPanel.overlayMarkers().length) ? 'Cuts/patches/joints' :
2421
+ clothPanel?.overlayRegions().length ? 'Cloth links' :
2422
+ meshPanel && (meshPanel.overlayRegions().length || meshPanel.overlayCircles().length) ? 'Mesh regions' :
2423
+ chestEditor?.active() ? 'Chest regions/landmarks' :
2424
+ rigFieldsPanel?.handles().length ? 'Rig fields stage handles' : null;
2425
+ return preview ? `COMMENT_UNAPPLIED_PREVIEW: ${preview} is active; leave or disable that preview before commenting (nothing is cleared or applied automatically)` : null;
2426
+ },
2427
+ shortcutBlocked: () => !!meshEditor?.active(),
2428
+ busy: () => rebuildBusy || densityBusy,
2429
+ appliedFor: side => sides[side].appliedOnStage,
2430
+ modelHashFor: side => sides[side].stageModelHash,
2431
+ seekMode,
2432
+ stepSide,
2433
+ dispose: () => {
2434
+ if (handoffTimer) clearTimeout(handoffTimer);
2435
+ for (const dispose of disposers) dispose();
2436
+ disposers.length = 0;
2437
+ },
2438
+ };
2439
+ }