@rig-c/review 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,12 @@
1
- /** Inspector block row: the sticky row of buttons at the top of each Inspector section (index.html
2
- * `.block-row`). A button scrolls its block into view inside the section (the section is the Inspector's
3
- * scroll container) and marks it `aria-current`; the active block then follows scrolling. The active block
4
- * per section is the only thing this adds to the inspection draft (its `ui` record, key `inspectorBlocks`);
5
- * the scroll offset itself stays with the Inspector scroll memory. */
1
+ /** Inspector block row: the sticky row at the top of each Inspector section (index.html `.block-row`) is a WAI-ARIA
2
+ * tablist. Each `role=tab` button owns the `role=tabpanel` block its `aria-controls` names; selecting it shows that
3
+ * block alone and hides the others with `hidden`, so one block is on screen at a time and nothing scrolls between them.
4
+ * A tab may carry blocks that belong to its group (`data-block-includes`, e.g. Transport's Angle block): those keep
5
+ * their own `hidden` for their own reasons and are hidden with the group by `data-block-hidden` instead. Arrow keys,
6
+ * Home and End move between tabs and select as they go (the pattern compare.html's Inspector tabs follow).
7
+ * Hiding writes nothing inside a block, so a hidden block keeps whatever it held. Each block keeps its own scroll
8
+ * offset for the session; the section's saved offset stays with the Inspector scroll memory. The active tab per
9
+ * section is the only thing this adds to the inspection draft (its `ui` record, key `inspectorBlocks`). */
6
10
  export const inspectorBlocksKey='inspectorBlocks';
7
11
  export type ActiveBlocks=Record<string,string>;
8
12
  type DraftUI=Record<string,string|number|null>;
@@ -19,65 +23,72 @@ export function activeBlocksUI(state:ActiveBlocks):DraftUI {return {[inspectorBl
19
23
  /** The active blocks read back from a draft `ui` record. */
20
24
  export function restoreActiveBlocksUI(ui:DraftUI):ActiveBlocks {return parseActiveBlocks(ui[inspectorBlocksKey]);}
21
25
 
22
- export interface BlockObserver {observe(target:Element):void;disconnect():void}
23
26
  export interface InspectorBlocksOptions {
24
- /** Sections carrying `data-inspector-panel`, each with a `.block-row` first child. */
27
+ /** Sections carrying `data-inspector-panel`, each with a `.block-row` first child (or a child panel that has one). */
25
28
  sections:HTMLElement[];
26
- /** Creates the scroll-follow observer for one section; defaults to IntersectionObserver rooted at the section. */
27
- observer?:(root:HTMLElement,changed:()=>void)=>BlockObserver|null;
28
- /** Called when a click or scrolling changes a section's active block. */
29
+ /** Called when a click or a key changes a section's active tab. */
29
30
  changed?:()=>void;
30
- reducedMotion?:()=>boolean;now?:()=>number;
31
31
  }
32
- export interface InspectorBlocks {state():ActiveBlocks;restore(state:ActiveBlocks):void;select(section:string,id:string):void;refresh():void;dispose():void}
33
- /** Gap kept between the sticky row and a block scrolled under it, in CSS pixels. */
34
- export const blockScrollGap=6;
35
- /** How long a programmatic scroll (click or restore) holds the chosen block against scroll-follow, unless the user scrolls first. */
36
- const holdMs=1200;
32
+ export interface InspectorBlocks {state():ActiveBlocks;restore(state:ActiveBlocks):void;select(section:string,id:string):void;dispose():void}
33
+
34
+ interface Tab {button:HTMLButtonElement;id:string;panel:HTMLElement;included:HTMLElement[]}
35
+ interface Row {scrollRoot:HTMLElement;row:HTMLElement;tabs:Tab[];scrolls:Map<string,number>}
36
+ const isRow=(node:Element)=>node.classList.contains('block-row');
37
37
 
38
38
  export function bindInspectorBlocks(options:InspectorBlocksOptions):InspectorBlocks {
39
- const now=options.now??(()=>Date.now()),reduced=options.reducedMotion??(()=>typeof matchMedia==='function'&&matchMedia('(prefers-reduced-motion: reduce)').matches);
40
- const makeObserver=options.observer??((root,changed)=>typeof IntersectionObserver==='function'?new IntersectionObserver(changed,{root,threshold:[0,.25,.5,.75,1]}):null);
41
- let ready=false;const disposers:(()=>void)[]=[],state:ActiveBlocks={},rows=new Map<string,{section:HTMLElement;scrollRoot:HTMLElement;row:HTMLElement;buttons:HTMLButtonElement[];hold:number;follow:()=>void}>();
42
- const targetOf=(scrollRoot:HTMLElement,button:HTMLButtonElement)=>{const id=button.dataset.blockTarget??'';const node=id?scrollRoot.ownerDocument.getElementById(id):null;return node&&scrollRoot.contains(node)?node:null;};
43
- const resolveId=(entry:{buttons:HTMLButtonElement[]},id:string)=>entry.buttons.some(b=>b.dataset.blockTarget===id)?id:(id==='transport'&&entry.buttons.some(b=>b.dataset.blockTarget==='motion-tools')?'motion-tools':id);
44
- const mark=(name:string,rawId:string)=>{const entry=rows.get(name);if(!entry)return false;const id=resolveId(entry,rawId);if(!entry.buttons.some(button=>button.dataset.blockTarget===id))return false;for(const button of entry.buttons){if(button.dataset.blockTarget===id)button.setAttribute('aria-current','true');else button.removeAttribute('aria-current');}const before=state[name];state[name]=id;if(before!==id&&ready)options.changed?.();return true;};
39
+ const disposers:(()=>void)[]=[],state:ActiveBlocks={},rows=new Map<string,Row>();
40
+ // A saved id from before #258 named the Transport block by its old id.
41
+ const resolve=(entry:Row,id:string)=>entry.tabs.find(tab=>tab.id===id)??(id==='transport'?entry.tabs.find(tab=>tab.id==='motion-tools'):undefined);
42
+ /** Show one tab's panel and hide the rest. Writes only visibility and tab state, and only what changes. */
43
+ const show=(entry:Row,active:Tab)=>{
44
+ for(const tab of entry.tabs){
45
+ const on=tab===active;
46
+ if(tab.button.getAttribute('aria-selected')!==String(on))tab.button.setAttribute('aria-selected',String(on));
47
+ if(tab.button.tabIndex!==(on?0:-1))tab.button.tabIndex=on?0:-1;
48
+ if(tab.panel.hidden===on)tab.panel.hidden=!on;
49
+ for(const node of tab.included)if(node.hasAttribute('data-block-hidden')===on)node.toggleAttribute('data-block-hidden',!on);
50
+ }
51
+ };
52
+ /** Select a tab. A user's selection also swaps the scroll offset: the panel left keeps where it was, the one shown opens where it was left. */
53
+ const choose=(name:string,rawId:string,user:boolean)=>{
54
+ const entry=rows.get(name);if(!entry)return false;const tab=resolve(entry,rawId);if(!tab)return false;
55
+ const before=state[name];if(before===tab.id)return true;
56
+ if(user&&before!==undefined){entry.scrolls.set(before,entry.scrollRoot.scrollTop);const next=entry.scrolls.get(tab.id)??0;show(entry,tab);if(entry.scrollRoot.scrollTop!==next)entry.scrollRoot.scrollTop=next;}
57
+ else show(entry,tab);
58
+ state[name]=tab.id;if(before!==undefined)options.changed?.();return true;
59
+ };
45
60
  for(const section of options.sections){
46
61
  const name=section.dataset.inspectorPanel??'';if(!name)continue;
47
- const directRow=[...section.children].find(node=>(node as HTMLElement).classList.contains('block-row')) as HTMLElement|undefined;
48
- const nestedRoot=directRow?undefined:[...section.children].find(node=>[...((node as HTMLElement).children??[])].some(c=>(c as HTMLElement).classList.contains('block-row'))) as HTMLElement|undefined;
49
- const scrollRoot=nestedRoot??section;
50
- const row=directRow??([...(nestedRoot?.children??[])].find(node=>(node as HTMLElement).classList.contains('block-row')) as HTMLElement|undefined);
51
- if(!row)continue;
52
- const buttons=[...row.querySelectorAll<HTMLButtonElement>('button[data-block-target]')].filter(button=>targetOf(scrollRoot,button));if(!buttons.length)continue;
53
- const entry={section,scrollRoot,row,buttons,hold:0,follow:()=>{}};rows.set(name,entry);
54
- // Scroll-follow: the active block is the last one whose top has reached the row; at the end of the
55
- // section it is the last visible one, so a short closing block can still become active.
56
- entry.follow=()=>{
57
- if(entry.hold>now()||section.hidden)return;const top=scrollRoot.getBoundingClientRect().top+row.getBoundingClientRect().height+blockScrollGap*4;
58
- const visible=buttons.map(button=>({button,node:targetOf(scrollRoot,button)})).filter((item):item is {button:HTMLButtonElement;node:HTMLElement}=>!!item.node&&!item.node.hidden);if(!visible.length)return;
59
- let current=visible[0]!;for(const item of visible)if(item.node.getBoundingClientRect().top<=top)current=item;
60
- if(scrollRoot.scrollHeight-scrollRoot.clientHeight>0&&scrollRoot.scrollTop>=scrollRoot.scrollHeight-scrollRoot.clientHeight-2){const bottom=scrollRoot.getBoundingClientRect().bottom;for(const item of visible)if(item.node.getBoundingClientRect().top<bottom)current=item;}
61
- mark(name,current.button.dataset.blockTarget!);
62
+ // In Animate the row heads the blocks panel beside the timeline; that panel is what scrolls.
63
+ const children=[...section.children],directRow=children.find(isRow) as HTMLElement|undefined;
64
+ const scrollRoot=directRow?section:children.find(node=>[...node.children].some(isRow)) as HTMLElement|undefined;if(!scrollRoot)continue;
65
+ const row=directRow??[...scrollRoot.children].find(isRow) as HTMLElement;
66
+ const doc=section.ownerDocument,inside=(id:string)=>{const node=id?doc.getElementById(id):null;return node&&scrollRoot.contains(node)?node:null;};
67
+ const tabs:Tab[]=[];
68
+ for(const button of row.querySelectorAll<HTMLButtonElement>('button[data-block-target]')){
69
+ const id=button.dataset.blockTarget??'',panel=inside(id);if(!panel)continue;
70
+ const included=(button.dataset.blockIncludes??'').split(' ').map(inside).filter((node):node is HTMLElement=>!!node);
71
+ tabs.push({button,id,panel,included});
72
+ }
73
+ if(!tabs.length)continue;
74
+ const entry:Row={scrollRoot,row,tabs,scrolls:new Map()};rows.set(name,entry);
75
+ const tabOf=(event:Event)=>{const button=(event.target as Element|null)?.closest?.('button[data-block-target]');return tabs.find(tab=>tab.button===button);};
76
+ const click=(event:Event)=>{const tab=tabOf(event);if(tab)choose(name,tab.id,true);};
77
+ const key=(event:KeyboardEvent)=>{
78
+ const tab=tabOf(event);if(!tab)return;const index=tabs.indexOf(tab);
79
+ const next=event.key==='ArrowRight'?(index+1)%tabs.length:event.key==='ArrowLeft'?(index+tabs.length-1)%tabs.length:event.key==='Home'?0:event.key==='End'?tabs.length-1:null;
80
+ if(next===null)return;event.preventDefault();const target=tabs[next]!;choose(name,target.id,true);target.button.focus();
62
81
  };
63
- const click=(event:Event)=>{const button=(event.target as Element|null)?.closest?.('button[data-block-target]') as HTMLButtonElement|null;if(!button||!buttons.includes(button))return;select(name,button.dataset.blockTarget!);};
64
- const release=()=>{entry.hold=0;};const intent=(event:Event)=>{if(!row.contains(event.target as Node))release();};
65
- row.addEventListener('click',click);for(const type of ['wheel','touchstart','keydown','pointerdown'])scrollRoot.addEventListener(type,intent,{passive:true});scrollRoot.addEventListener('scrollend',release);
66
- const observer=makeObserver(scrollRoot,()=>entry.follow());if(observer)for(const button of buttons)observer.observe(targetOf(scrollRoot,button)!);
67
- disposers.push(()=>{row.removeEventListener('click',click);for(const type of ['wheel','touchstart','keydown','pointerdown'])scrollRoot.removeEventListener(type,intent);scrollRoot.removeEventListener('scrollend',release);observer?.disconnect();});
68
- mark(name,buttons[0]!.dataset.blockTarget!);
69
- }
70
- ready=true;
71
- /** Scroll the block so its top sits just under the sticky row, then mark it. */
72
- function select(name:string,rawId:string):void {
73
- const entry=rows.get(name);if(!entry)return;const id=resolveId(entry,rawId);const button=entry.buttons.find(b=>b.dataset.blockTarget===id);const node=button&&targetOf(entry.scrollRoot,button);if(!node)return;
74
- const {scrollRoot,row}=entry,offset=node.getBoundingClientRect().top-scrollRoot.getBoundingClientRect().top-row.getBoundingClientRect().height-blockScrollGap,top=Math.max(0,scrollRoot.scrollTop+offset);
75
- entry.hold=now()+holdMs;scrollRoot.scrollTop=top;scrollRoot.scrollTo({top,behavior:reduced()?'auto':'smooth'});if(typeof scrollRoot.dispatchEvent==='function')scrollRoot.dispatchEvent(new Event('scroll'));mark(name,id);
82
+ row.addEventListener('click',click);row.addEventListener('keydown',key as EventListener);
83
+ disposers.push(()=>{row.removeEventListener('click',click);row.removeEventListener('keydown',key as EventListener);});
84
+ // The markup ships its first tab selected; binding makes the DOM agree with it whatever the markup said.
85
+ const first=tabs.find(tab=>tab.button.getAttribute('aria-selected')==='true')??tabs[0]!;show(entry,first);state[name]=first.id;
76
86
  }
77
87
  return {
78
- state:()=>({...state}),select,
79
- restore(saved){for(const [name,id]of Object.entries(saved)){const entry=rows.get(name);if(entry&&mark(name,id))entry.hold=now()+holdMs;}},
80
- refresh(){for(const entry of rows.values())entry.follow();},
88
+ state:()=>({...state}),
89
+ select:(name,id)=>{choose(name,id,true);},
90
+ /** Restore saved tabs. The section's scroll offset is the workspace scroll memory's, so this does not touch it. */
91
+ restore(saved){for(const [name,id]of Object.entries(saved))choose(name,id,false);},
81
92
  dispose(){for(const dispose of disposers)dispose();disposers.length=0;rows.clear();},
82
93
  };
83
94
  }
package/web/main.ts CHANGED
@@ -6,7 +6,7 @@ import {PartExplorer,loadPartModel,partBounds} from './part-selection.ts';
6
6
  import {AnimationInspectionPanel} from './animation-inspection.ts';
7
7
  import {PartThumbnails,pageRegionTable} from './part-thumbnails.ts';
8
8
  import { CanvasRenderer, loadModel, RigPlayer, type BoneAdjust, type ModelAssets, type PoseBounds } from '@rig-c/play';
9
- import {cameraFrame,cameraSignature,cameraFromSignature,assertCameraView,boundsFitSignature,dragSignature,zoomSignature,type CameraFrame,type CameraSignature} from './camera-view.ts';
9
+ import {cameraFrame,cameraSignature,cameraFromSignature,assertCameraView,boundsFitSignature,dragSignature,zoomSignature,type CameraFrame,type CameraPoint,type CameraSignature} from './camera-view.ts';
10
10
  import {rendererStatus} from './renderer-status.ts';
11
11
  import {bindAppearance,bindPan,bindStageLayout,syncStageLayout,bindInspectorTabs,idleAvailable,initialIdleAnimation,automaticIdlePreview,bindLayerShortcuts,describeLayerToggles,type ViewPoint} from './view-controls.ts';
12
12
  import {RigOverlays,type OverlayCircle,type OverlayMarker,type OverlayRegion,type OverlaySnapshot} from './rig-overlays.ts';
@@ -16,7 +16,7 @@ import {densityField,densityPath} from '../src/density-strip.ts';
16
16
  import {assertMeshPatch,countsText,meshApplyOutcome,meshPatchOps,setEntryValue,triangleAgreement,type MeshEntry} from '../src/mesh-entry.ts';
17
17
  import {worstLine} from '../src/readings.ts';
18
18
  import {chestOverlayCircles,chestOverlayPolygons,chestRegionRows,chestRowId,evaluateChestForm} from './chest-regions-tool.ts';
19
- import {bindChestEditor,canvasToCrop,bustLabel,bustSides,LANDMARKS,landmarkInputId,rowCircle,type ChestEditor,type LandmarkKey} from './chest-editor.ts';
19
+ import {bindChestEditor,canvasToCrop,bustLabel,bustSides,chestPoseOffset,LANDMARKS,landmarkInputId,posedChestMapping,rowShape,type ChestEditor,type LandmarkKey} from './chest-editor.ts';
20
20
  import {bindMeshEditor,meshEditSource,sha256Hex,type MeshEditor} from './mesh-editor.ts';
21
21
  import {bindWeightsView,setupPoseMesh,type WeightsView} from './weights-view.ts';
22
22
  import {readSetupPose} from './setup-pose.ts';
@@ -26,7 +26,7 @@ import {bindClothPanel,type ClothPanel} from './cloth-panel.ts';
26
26
  import {animationAppliedRecord,animationOutcomeLine,retargetAppliedRecord,retargetOutcomeLine,stripPendingAfter,type AnimationJobView,type AnimationRequestBody,type AnimationSourceOp,type StageChange,type AppliedAnimation,type AppliedRetarget,type RetargetJobView,type RetargetRequestBody} from './rebuild-client.ts';
27
27
  import {bindRetargetPanel,type PoseMap,type RetargetPanel} from './retarget-panel.ts';
28
28
  import type {RetargetFlags} from '../src/retarget.ts';
29
- import {historyRow,isPatchJob,recordFor,refusedText,restoredOutcomeForJob,retargetStage,undoControl,type AppliedHistoryView,type UndoView,type AnyJobView,appliedRecord,deltaAppliedRecord,deltaOutcomeLine,designatedRegions,handoffText,landmarksRequest,seedLandmarks,makePatch,outcomeLine,patchAppliedRecord,patchOutcomeLine,pickBustPart,pickPart,runRebuild,seedFields,stageModel,type AppliedDelta,type AppliedPatch,type AppliedRecord,type DeltaJobView,type DeltaRequestBody,type ConfigPatch,type PatchJobView,type RebuildJobView,type RebuildRefusal,type RebuildRequestBody,type RebuildStatusView} from './rebuild-client.ts';
29
+ import {historyRow,isPatchJob,recordFor,refusedText,restoredOutcomeForJob,retargetStage,undoControl,type AppliedHistoryView,type UndoView,type AnyJobView,appliedRecord,deltaAppliedRecord,deltaOutcomeLine,chestSeed,designatedRegions,handoffText,landmarksRequest,seedLandmarks,makePatch,outcomeLine,patchAppliedRecord,patchOutcomeLine,pickBustPart,pickPart,runRebuild,seedFields,stageModel,type AppliedDelta,type AppliedPatch,type AppliedRecord,type DeltaJobView,type DeltaRequestBody,type ConfigPatch,type PatchJobView,type RebuildJobView,type RebuildRefusal,type RebuildRequestBody,type RebuildStatusView} from './rebuild-client.ts';
30
30
  import {meshEditBinding,meshEditText,type MeshEditDocument} from '../src/mesh-edit.ts';
31
31
  import {chestRegionsBinding,cropWorldMapping,type CropWorldMapping} from '../src/chest-regions.ts';
32
32
  import {bindWorkspaceUI,selectedInspector,type WorkspaceUI} from './workspace-ui.ts';
@@ -141,6 +141,9 @@ let controlDispose:(()=>void)|null=null;
141
141
  const viewDisposers:(()=>void)[]=[];
142
142
  const layers={images:true,mesh:false,bones:false,meshOpacity:.65};
143
143
  let chestMapping:CropWorldMapping={available:false,reason:'CHEST_REGION_MAPPING_UNAVAILABLE: no compiled model drawn'};
144
+ let setupChestWorld:{x:number;y:number}|null=null;
145
+ const readSetupChest=(p:RigPlayer|null):{x:number;y:number}|null=>{if(!p)return null;try{const b=p.bone('chest');return b&&Number.isFinite(b.x)&&Number.isFinite(b.y)?{x:b.x,y:b.y}:null;}catch{return null;}};
146
+ const activeChestMapping=():CropWorldMapping=>posedChestMapping(chestMapping,chestPoseOffset(player,setupChestWorld));
144
147
  let referenceSize: { width: number; height: number } | null = null;
145
148
  let video: HTMLVideoElement | null = null;
146
149
  let controlledVideoSample:{media:HTMLVideoElement;position:number;time:number}|null=null;
@@ -671,6 +674,7 @@ async function initPlayer(initialCheckpoint?:Checkpoint): Promise<void> {
671
674
  const target = new URL(name, url); if (target.origin !== location.origin || !target.pathname.startsWith(access.route('/assets/'))) throw new Error(`Model page escapes local package: ${name}`); return target.href;
672
675
  } });
673
676
  player = new RigPlayer(el('rig-root'), assets);
677
+ setupChestWorld = readSetupChest(player);
674
678
  // Parts inspection is an add-on: a catalog refusal is shown in the explorer and never aborts the rig.
675
679
  try{const catalog=await loadPartModel(modelUrl,data.reviewedSource.rig!.sha256,data.feedbackCatalog.slots??[]);inspectionSourceState='ready';partModel=catalog.model;configureTurnPad(catalog.model);refreshAnimationInspection();weightsView?.refresh();parts?.register('single',catalog.entries,player,new PartThumbnails(pageRegionTable(catalog.model),assets.pageImages));}catch(error){inspectionSourceState='failed';partModel=null;refreshAnimationInspection();parts?.refuseCatalog('single',error);}
676
680
  player.on('event', event => { text('event-log', `Runtime event: ${event.name} · ${event.time.toFixed(2)} s`); });
@@ -817,17 +821,17 @@ function updateCamera(target:CameraTarget,value:CameraSignature):void {
817
821
  for(const other of ['rig','reference'] as const){const update=updates[other];if(update)writeCamera(other,update);}activeCamera=target;
818
822
  fitCamera();renderCameraControls();
819
823
  }
820
- function zoomCamera(factor:number,target=availableCamera()):void {if(!target)return;const frame=paneFrame(target);if(frame)updateCamera(target,zoomSignature(cameraSignature(paneCamera(target),frame),factor));}
824
+ function zoomCamera(factor:number,target=availableCamera(),point?:CameraPoint|null):void {if(!target)return;const frame=paneFrame(target);if(frame)updateCamera(target,zoomSignature(cameraSignature(paneCamera(target),frame),factor,frame,point));}
821
825
  function panCamera(target:CameraTarget,dx:number,dy:number):void {const frame=paneFrame(target);if(frame)updateCamera(target,dragSignature(cameraSignature(paneCamera(target),frame),frame,dx,dy));}
822
826
  function fitActiveCamera(target=availableCamera()):void {if(!target)return;const part=parts?.value();if(target==='rig'&&part){const box=parts?.bounds(),frame=paneFrame(target);if(!box||!frame){message('PART_FIT_UNAVAILABLE: selected slot has no positive drawn bounds.',true);return;}updateCamera(target,boundsFitSignature(box,frame,28,58));message('Selected slot fitted.');}else{if(!paneFrame(target))return;updateCamera(target,{zoom:1,pan:{x:0,y:0}});message('View fitted.');}}
823
- function zoomViewport(target:CameraTarget,deltaY:number):void {zoomCamera(deltaY<0?1.1:1/1.1,target);}
827
+ function zoomViewport(target:CameraTarget,deltaY:number,point?:CameraPoint|null):void {zoomCamera(deltaY<0?1.1:1/1.1,target,point);}
824
828
 
825
829
  function bind(): void {
826
830
  button('strip-export').onclick = () => { void exportStrip(); };
827
831
  button('chest-export').onclick = () => { void exportChest(); };
828
832
  for (const event of ['input', 'change']) el('chest-regions').addEventListener(event, renderChest);
829
833
  // A discarded local draft restores the form after its button's own handler; re-read the tool then.
830
- el('draft-recovery').addEventListener('click', () => { renderChest(); restoreEnvironment(); physicsPanel?.restore(); bonesPanel?.restore(); cutsPanel?.restore(); clothPanel?.restore(); idlePanel?.restore(); rigFieldsPanel?.restore(); });
834
+ for (const id of ['draft-recovery', 'review-draft-recovery']) el(id).addEventListener('click', () => { renderChest(); restoreEnvironment(); physicsPanel?.restore(); bonesPanel?.restore(); cutsPanel?.restore(); clothPanel?.restore(); idlePanel?.restore(); rigFieldsPanel?.restore(); });
831
835
  for (const id of ['strip-scope', 'strip-reference', 'strip-format']) select(id).onchange = () => stripStatus('Selection changed. Check the ranges, animation and reference video before downloading.');
832
836
  for (const item of document.querySelectorAll<HTMLButtonElement>('[data-view]')) item.onclick = () => {setView(item.dataset.view as typeof view);const menu=document.getElementById('view-menu') as HTMLDetailsElement|null;if(menu)menu.open=false;};
833
837
  for (const item of document.querySelectorAll<HTMLButtonElement>('[data-proposal]')) item.onclick = () => propose(item.dataset.proposal ?? '');
@@ -839,7 +843,7 @@ function bind(): void {
839
843
  button('zoom-in').onclick=()=>cameraAction(()=>zoomCamera(1.25));button('zoom-out').onclick=()=>cameraAction(()=>zoomCamera(1/1.25));button('fit').onclick=()=>cameraAction(()=>fitActiveCamera());
840
844
  input('camera-sync').onchange=()=>cameraAction(()=>setCameraSync(input('camera-sync').checked));
841
845
  for(const target of ['rig','reference'] as const)for(const event of ['pointerdown','focusin'] as const)el(target+'-viewport').addEventListener(event,()=>activateCamera(target));
842
- for (const id of ['reference-viewport', 'rig-viewport']) el(id).addEventListener('wheel', event => { event.preventDefault(); cameraAction(()=>zoomViewport(id==='rig-viewport'?'rig':'reference',event.deltaY)); }, { passive: false });
846
+ for (const id of ['reference-viewport', 'rig-viewport']) el(id).addEventListener('wheel', event => { event.preventDefault(); const rect=el(id).getBoundingClientRect(); cameraAction(()=>zoomViewport(id==='rig-viewport'?'rig':'reference',event.deltaY,{x:event.clientX-rect.left,y:event.clientY-rect.top})); }, { passive: false });
843
847
  input('scrub').oninput = () => { pause(); seek(Number(input('scrub').value)); };
844
848
  input('frame-number').onfocus = pause;
845
849
  input('frame-number').onkeydown = event => { if (event.key === 'Enter') { event.preventDefault(); const value = input('frame-number').value.trim(); seekFrame(value ? Number(value) : NaN); } };
@@ -910,7 +914,7 @@ function bind(): void {
910
914
  appearance=bindAppearance(select('settings-theme'),workspace.defaults().theme);
911
915
  inspectorBlocks=bindInspectorBlocks({sections:[el('inspector-rig'),el('inspector-playback')],changed:()=>persistence?.save()});
912
916
  overlays=new RigOverlays({canvas:el<HTMLCanvasElement>('rig-overlay'),rigRoot:el('rig-root')});
913
- chestEditor=bindChestEditor({pane:el('rig-pane'),canvas:el('rig-overlay'),project:()=>player?rigProject():null,mapping:()=>chestMapping,changed:renderChest,download:()=>{void exportChest();},apply:()=>{void applyRebuild();},reset:()=>{void resetRebuild();},message,inspector:()=>selectedInspector()});viewDisposers.push(()=>chestEditor?.dispose());
917
+ chestEditor=bindChestEditor({pane:el('rig-pane'),canvas:el('rig-overlay'),project:()=>player?rigProject():null,mapping:()=>activeChestMapping(),changed:renderChest,download:()=>{void exportChest();},apply:()=>{void applyRebuild();},reset:()=>{void resetRebuild();},message,inspector:()=>selectedInspector()});viewDisposers.push(()=>chestEditor?.dispose());
914
918
  meshEditor=bindMeshEditor({pane:el('rig-pane'),canvas:el('rig-overlay'),project:()=>player?rigProject():null,mapping:()=>chestMapping,inspector:()=>selectedInspector(),source:meshSource,pause,changed:()=>redrawOverlay(false),download:doc=>{void exportMesh(doc);},apply:(doc,line)=>applyMeshDelta(doc,line),applied:()=>appliedOnStage?.schema==='rig-review-applied/3',resetBuild:()=>resetRebuild(stageWorld()),message,confirm:text=>window.confirm(tr(text)),token:name=>getComputedStyle(document.documentElement).getPropertyValue(name).trim()});viewDisposers.push(()=>meshEditor?.dispose());
915
919
  weightsView=bindWeightsView({pane:el('rig-pane'),canvas:el('rig-overlay'),project:()=>player?rigProject():null,inspector:()=>selectedInspector(),slot:()=>parts?.value()?.slot??null,
916
920
  model:()=>data.manifest.model?partModel??undefined:null,setup:slot=>assets?setupPoseMesh(assets,partModel,slot,document.createElement('div')):null,changed:()=>redrawOverlay(false),
@@ -1166,8 +1170,8 @@ async function applyInspection(bookmark:InspectionBookmark,signal:AbortSignal,pr
1166
1170
  }
1167
1171
  async function waitReferenceMetadata(media:HTMLVideoElement,signal:AbortSignal):Promise<void> {if(media.readyState>=1)return;await new Promise<void>((resolve,reject)=>{const clean=()=>{clearTimeout(timer);media.removeEventListener('loadedmetadata',ready);media.removeEventListener('error',fail);signal.removeEventListener('abort',fail);};const ready=()=>{clean();resolve();},fail=()=>{clean();reject(new Error('Saved reference metadata unavailable'));};const timer=setTimeout(fail,10000);media.addEventListener('loadedmetadata',ready,{once:true});media.addEventListener('error',fail,{once:true});signal.addEventListener('abort',fail,{once:true});});}
1168
1172
  async function setupPersistence():Promise<boolean> {
1169
- persistence=await connectInspectionPersistence({scope:'single:'+data.manifest.id+':'+data.sourceHash,binding:inspectionBinding(),baseline:submittedBaseline!,session:()=>session,reviewDirty:()=>dirty,restoreSession:(value,isDirty)=>{session=value;dirty=isDirty;select('review-status').value=session.status;renderProposals();renderCheckpoint();renderCheckpoints();updateSavedState();},bookmark:inspectionBookmark,restoreBookmark:(b,s)=>restoreInspection(b,s,session.feedback.some(f=>isTimeOnlyFeedback(f)&&JSON.stringify((f.context as any).comment.bookmark)===JSON.stringify(b))),
1170
- ui:()=>({inspectorScroll:workspace?.scroll()??'{}',...(inspectorBlocks?activeBlocksUI(inspectorBlocks.state()):{}),reportCategory:select('report-category').value,reportPage,reportEvent:selectedReportEvent?.id??null,reportTime:selectedReportTime??null,reportTarget:selectedReportTarget??null}),restoreUI:value=>{if(typeof value.reportCategory==='string'&&[...select('report-category').options].some(o=>o.value===value.reportCategory))select('report-category').value=value.reportCategory;if(typeof value.reportPage==='number'&&Number.isSafeInteger(value.reportPage)&&value.reportPage>=0)reportPage=value.reportPage;selectedReportEvent=typeof value.reportEvent==='string'?data.report?.categories.flatMap(c=>c.events).find(e=>e.id===value.reportEvent)??null:null;selectedReportTime=typeof value.reportTime==='number'?value.reportTime:undefined;selectedReportTarget=typeof value.reportTarget==='number'?value.reportTarget:undefined;renderReportEvents();renderReportSelection();workspace?.restoreScroll(value.inspectorScroll);inspectorBlocks?.restore(restoreActiveBlocksUI(value));},afterInputs:()=>{const target=input('feedback-target-name').value;renderFeedbackTargets(true);if(select('feedback-target-kind').value!=='rig')input('feedback-target-name').value=target;renderFeedbackRange();text('audio-volume-label',`${Math.round(Number(input('audio-volume').value)*100)}%`);},onConflict:value=>{draftConflict=value;updateSavedState();},onStatus:value=>{text('draft-state',value);el('draft-state').title=value;text('review-draft-state',value);}});
1173
+ persistence=await connectInspectionPersistence({scope:'single:'+data.manifest.id+':'+data.sourceHash,binding:inspectionBinding(),baseline:submittedBaseline!,session:()=>session,reviewDirty:()=>dirty,restoreSession:(value,isDirty)=>{session=value;dirty=isDirty;select('review-status').value=session.status;renderProposals();renderCheckpoint();renderCheckpoints();renderProvenance();updateSavedState();},bookmark:inspectionBookmark,restoreBookmark:(b,s)=>restoreInspection(b,s,session.feedback.some(f=>isTimeOnlyFeedback(f)&&JSON.stringify((f.context as any).comment.bookmark)===JSON.stringify(b))),
1174
+ ui:()=>({inspectorScroll:workspace?.scroll()??'{}',...(inspectorBlocks?activeBlocksUI(inspectorBlocks.state()):{}),reportCategory:select('report-category').value,reportPage,reportEvent:selectedReportEvent?.id??null,reportTime:selectedReportTime??null,reportTarget:selectedReportTarget??null}),restoreUI:value=>{if(typeof value.reportCategory==='string'&&[...select('report-category').options].some(o=>o.value===value.reportCategory))select('report-category').value=value.reportCategory;if(typeof value.reportPage==='number'&&Number.isSafeInteger(value.reportPage)&&value.reportPage>=0)reportPage=value.reportPage;selectedReportEvent=typeof value.reportEvent==='string'?data.report?.categories.flatMap(c=>c.events).find(e=>e.id===value.reportEvent)??null:null;selectedReportTime=typeof value.reportTime==='number'?value.reportTime:undefined;selectedReportTarget=typeof value.reportTarget==='number'?value.reportTarget:undefined;renderReportEvents();renderReportSelection();inspectorBlocks?.restore(restoreActiveBlocksUI(value));workspace?.restoreScroll(value.inspectorScroll);},afterInputs:()=>{const target=input('feedback-target-name').value;renderFeedbackTargets(true);if(select('feedback-target-kind').value!=='rig')input('feedback-target-name').value=target;renderFeedbackRange();text('audio-volume-label',`${Math.round(Number(input('audio-volume').value)*100)}%`);},onConflict:value=>{draftConflict=value;updateSavedState();},onStatus:value=>{text('draft-state',value);el('draft-state').title=value;text('review-draft-state',value);}});
1171
1175
  return persistence.restored;
1172
1176
  }
1173
1177
  /** Setup's Chest regions tool: designation values, an overlay and a two-file client download. Nothing reaches the session's feedback or the package. */
@@ -1175,11 +1179,11 @@ function chestField(id:string){const node=document.getElementById(id) as HTMLInp
1175
1179
  function chestEvaluation(){return evaluateChestForm(chestField,chestMapping,data.feedbackCatalog.bones);}
1176
1180
  function chestRegions():OverlayRegion[]{
1177
1181
  const style=getComputedStyle(document.documentElement),token=(name:string)=>style.getPropertyValue(name).trim();
1178
- return chestOverlayPolygons(chestEvaluation(),chestMapping).map((region,i)=>({...region,stroke:token(i?'--rv-region-b':'--rv-region-a'),fill:token(i?'--rv-region-b-fill':'--rv-region-a-fill')}));
1182
+ return chestOverlayPolygons(chestEvaluation(),activeChestMapping()).map((region,i)=>({...region,stroke:token(i?'--rv-region-b':'--rv-region-a'),fill:token(i?'--rv-region-b-fill':'--rv-region-a-fill')}));
1179
1183
  }
1180
1184
  /** Circle regions: in edit mode the editor's circles straight from the fields (handles and labels), else the valid designation's. */
1181
1185
  function chestCircles():OverlayCircle[]{
1182
- const mapping=chestMapping;if(!mapping.available)return [];
1186
+ const mapping=activeChestMapping();if(!mapping.available)return [];
1183
1187
  const style=getComputedStyle(document.documentElement),token=(name:string)=>style.getPropertyValue(name).trim();
1184
1188
  const colors=(row:number,overlap:boolean)=>({stroke:token(overlap?'--rv-bust-overlap':row?'--rv-bust-l':'--rv-bust-r'),fill:token(overlap?'--rv-bust-overlap-fill':row?'--rv-bust-l-fill':'--rv-bust-r-fill'),handle:token('--rv-bust-handle'),ink:token('--rv-bust-ink'),labelBg:token('--rv-bust-label-bg'),flash:token('--rv-bust-flash')});
1185
1189
  if(chestEditor?.active()&&chestEditor.mode()==='landmarks'){
@@ -1189,16 +1193,16 @@ function chestCircles():OverlayCircle[]{
1189
1193
  return read.derived.regions.filter(r=>r.r>0&&r.band>=0).map((r,row)=>({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)}));
1190
1194
  }
1191
1195
  if(chestEditor?.active()){
1192
- const rows=bustSides.map(({side,row})=>({side,row,circle:rowCircle(chestField,row)})),[r,l]=[rows[0]!.circle,rows[1]!.circle];
1196
+ const rows=bustSides.map(({side,row})=>({side,row,circle:rowShape(chestField,row)})),[r,l]=[rows[0]!.circle,rows[1]!.circle];
1193
1197
  // As in the example, overlapping cores turn both circles to the overlap colour.
1194
1198
  const overlap=!!r&&!!l&&r.r+l.r>Math.hypot(l.cx-r.cx,l.cy-r.cy);
1195
- return rows.flatMap(({side,row,circle})=>circle?[{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)}]:[]);
1199
+ return rows.flatMap(({side,row,circle})=>circle?[{center:mapping.toWorld(circle.cx,circle.cy),r:circle.r,...(circle.ry===undefined?{}:{ry:circle.ry}),...(circle.clip===undefined?{}:{clipX:mapping.toWorld(circle.clip,circle.cy).x}),band:circle.band,label:bustLabel(side,circle),labelRow:row,handles:true,flash:chestEditor!.flashing(side),colors:colors(row,overlap)}]:[]);
1196
1200
  }
1197
1201
  return chestOverlayCircles(chestEvaluation(),mapping).map(c=>({center:c.center,r:c.r,band:c.band,handles:false,colors:colors(c.row,false)}));
1198
1202
  }
1199
1203
  /** Landmark markers (#105) in Landmarks mode: apexes in the R / L colours, the cleavage with guides to both apexes. */
1200
1204
  function chestMarkers():OverlayMarker[]{
1201
- const mapping=chestMapping;if(!mapping.available||!chestEditor?.active()||chestEditor.mode()!=='landmarks')return [];
1205
+ const mapping=activeChestMapping();if(!mapping.available||!chestEditor?.active()||chestEditor.mode()!=='landmarks')return [];
1202
1206
  const style=getComputedStyle(document.documentElement),token=(name:string)=>style.getPropertyValue(name).trim(),armed=chestEditor.armed();
1203
1207
  const at=(key:LandmarkKey)=>{const x=Number(input(landmarkInputId(key,'x')).value.trim()||NaN),y=Number(input(landmarkInputId(key,'y')).value.trim()||NaN);return Number.isFinite(x)&&Number.isFinite(y)?mapping.toWorld(x,y):null;};
1204
1208
  const apexes=[at('apex_r'),at('apex_l')].filter((p):p is {x:number;y:number}=>!!p);
@@ -1379,7 +1383,7 @@ function refreshPhysics():void {
1379
1383
  if(inspectedDocumentReason){physicsPanel.load({available:false,reason:inspectedDocumentReason},[]);return;}
1380
1384
  if(!inspectedDocument)return;
1381
1385
  if(!rebuildStatus){text('physics-panel-state','Reading the producer handoff…');text('idle-tracks-state','Reading the producer handoff…');return;}
1382
- if(!rebuildStatus.inputs||!rebuildStatus.producer){physicsPanel.load({available:false,reason:rebuildStatus.reason??'PHYSICS_TUNING_UNAVAILABLE: no producer handoff'},[]);return;}
1386
+ if(!rebuildStatus.inputs||!rebuildStatus.producer){physicsPanel.load({available:false,reason:rebuildStatus.reason??'PHYSICS_TUNING_UNAVAILABLE: no producer handoff'},[]);refreshIdle();return;}
1383
1387
  const bones=(inspectedDocument as {bones?:unknown}).bones,list=Array.isArray(bones)?bones.filter((b):b is {name:string;parent?:string}=>!!b&&typeof (b as {name?:unknown}).name==='string'):[];
1384
1388
  physicsPanel.load(tuningRows(rebuildStatus.constraints??null,inspectedDocument),list);
1385
1389
  refreshIdle();
@@ -1473,7 +1477,9 @@ async function loadRebuildStatus():Promise<RebuildStatusView|null> {
1473
1477
  try{rebuildStatus=await api<RebuildStatusView>('/api/rebuild');}catch(error){rebuildStatus=null;const reason=`REBUILD_STATUS_UNAVAILABLE: ${errorText(error)}`;chestEditor?.notify(reason,true);animationPanel?.loadSource(null,reason);return null;}
1474
1478
  const seed={...(seedFields(rebuildStatus,chestField)??{}),...(seedLandmarks(rebuildStatus,chestField)??{})};
1475
1479
  if(Object.keys(seed).length){for(const [id,value] of Object.entries(seed)){const node=document.getElementById(id) as HTMLInputElement|HTMLSelectElement|HTMLTextAreaElement|null;if(!node)continue;if(node instanceof HTMLInputElement&&node.type==='checkbox')node.checked=value==='true';else node.value=value;}el('chest-regions').dispatchEvent(new Event('input',{bubbles:true}));}
1476
- if(!rebuildStatus.available)chestEditor?.notify(rebuildStatus.reason,true);
1480
+ // #315: a config polygon the editor cannot read as an ellipse is named, never shown as an empty row.
1481
+ const refused=chestSeed(rebuildStatus).refusals;if(refused.length)chestEditor?.notify(refused.join(' · '),true,refused);
1482
+ if(!rebuildStatus.available)chestEditor?.notify(rebuildStatus.reason,!rebuildStatus.viewOnly);
1477
1483
  renderHandoff(rebuildStatus);refreshPhysics();
1478
1484
  retargetPanel?.load(rebuildStatus.retarget??null,rebuildStatus.reason);
1479
1485
  bonesPanel?.load(rebuildStatus.inputs?rebuildStatus.bones??[]:null,rebuildStatus.inputs?null:rebuildStatus.reason??'BONES_UNAVAILABLE: no producer handoff');
@@ -1506,7 +1512,7 @@ function chestPartForNotice():string|null {
1506
1512
  const read=chestEditor.landmarks();
1507
1513
  return 'derived' in read?pickBustPart(rebuildStatus,read.derived.regions):pickBustPart(rebuildStatus,[]);
1508
1514
  }
1509
- const designated=designatedRegions(chestField);
1515
+ const designated=designatedRegions(chestField,rebuildStatus?chestSeed(rebuildStatus):null);
1510
1516
  return 'regions' in designated?pickPart(rebuildStatus,designated.regions):rebuildStatus.parts.length===1?rebuildStatus.parts[0]!.name:null;
1511
1517
  }
1512
1518
  function renderDropNotices():void {
@@ -1649,7 +1655,7 @@ async function applyRebuild():Promise<void> {
1649
1655
  const request=landmarksRequest(status,chestEditor.landmarks());if('error' in request){chestEditor.notify(request.error,true,[request.error]);message(request.error,true);return;}
1650
1656
  ({part,body}=request);
1651
1657
  }else{
1652
- const designated=designatedRegions(chestField);if('error' in designated){chestEditor?.notify(designated.error,true);return;}
1658
+ const designated=designatedRegions(chestField,chestSeed(status));if('error' in designated){chestEditor?.notify(designated.error,true);return;}
1653
1659
  const picked=pickPart(status,designated.regions);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;}
1654
1660
  part=picked;body={part,regions:designated.regions,configHash:status.inputs.configHash};
1655
1661
  }
@@ -2141,7 +2147,7 @@ async function swapRig(modelUrl:string,prefix:string,sha256:string,world:StageWo
2141
2147
  inspectionSourceState='pending';partModel=null;pause();refreshAnimationInspection();
2142
2148
  const next=await loadModel({modelUrl,setsUrl:null,resolvePage:(name,url)=>{const target=new URL(name,url);if(target.origin!==location.origin||!target.pathname.startsWith(prefix))throw new Error(`Model page escapes its build: ${name}`);return target.href;}}).catch(error=>{inspectionSourceState='failed';refreshAnimationInspection();throw error;});
2143
2149
  physicsPanel?.clearPreview();
2144
- pause();player?.dispose();assets?.dispose();assets=next;player=new RigPlayer(el('rig-root'),assets);stageModelHash=sha256;stageSource={url:modelUrl,prefix,hash:sha256};
2150
+ pause();player?.dispose();assets?.dispose();assets=next;player=new RigPlayer(el('rig-root'),assets);setupChestWorld=readSetupChest(player);stageModelHash=sha256;stageSource={url:modelUrl,prefix,hash:sha256};
2145
2151
  // A scratch build may hold another set of animations (a retarget adds one, #114): the picker lists what this build has.
2146
2152
  {const animations=select('animation-select');animations.replaceChildren(...assets.animations.map(item=>option(item.name,data.manifest.animations.find(a=>a.id===item.name)?.label??item.name)));animations.disabled=assets.animations.length===0;}
2147
2153
  player.on('event',event=>{text('event-log',`Runtime event: ${event.name} · ${event.time.toFixed(2)} s`);});
@@ -3,8 +3,8 @@
3
3
  * goes to `/api/rebuild`, the job's lines stream back by polling, and the applied state is recorded. No DOM here
4
4
  * (main.ts owns the elements and the player); the server owns every path and the producer's flags.
5
5
  */
6
- import {ellipsePolygon} from '../src/chest-regions.ts';
7
- import type {BustSpec} from '../src/chest-landmarks.ts';
6
+ import {ellipsePolygon,fitChestEllipse,CHEST_ELLIPSE_MIN_POINTS} from '../src/chest-regions.ts';
7
+ import {deriveBust,parseBustSpec,type BustSpec} from '../src/chest-landmarks.ts';
8
8
  import {CONFIG_PATCH_SCHEMA,type ConfigPatch,type PatchCmd,type PatchOp} from '../src/config-patch.ts';
9
9
  import {APPLIED_ANIMATION_SCHEMA,APPLIED_DELTA_SCHEMA,APPLIED_PATCH_SCHEMA,APPLIED_RETARGET_SCHEMA,filesDiffText,type AppliedAnimation,type AppliedAssembled,type AppliedDelta,type AppliedPatch,type AppliedRetarget,type CheckSummary,type FilesDiff} from '../src/applied-context.ts';
10
10
  import {appliedBuildOwner,type RestoredPanelOutcome} from '../src/applied-blocks.ts';
@@ -12,7 +12,7 @@ import {meshApplyOutcome} from '../src/mesh-entry.ts';
12
12
  import type {AnimationSourceOp} from '../src/animation-ops.ts';
13
13
  import type {MotionSummary,RetargetFlags,RetargetLine,RetargetRecord} from '../src/retarget.ts';
14
14
  export type {ConfigPatch,PatchOp,AppliedPatch,AppliedDelta,AppliedRetarget,AppliedAnimation,AnimationSourceOp,CheckSummary,BustSpec};
15
- import {chestContourFields,chestRegionRows,chestRowId,type ChestFieldReader} from './chest-regions-tool.ts';
15
+ import {chestContourFields,chestRegionFields,chestRegionRows,chestRowId,type ChestFieldReader} from './chest-regions-tool.ts';
16
16
  import type {InspectedCheckView} from '../src/physics-tuning.ts';
17
17
  import {samplesClock,type StageClock} from '../src/frame-clock.ts';
18
18
 
@@ -24,7 +24,7 @@ export interface HandoffView {how:'declared'|'discovered';via:string;outside:boo
24
24
  export interface BaselineView {status:'running'|'reproduced'|'not-reproduced'|'refused'|'failed';firstDifference:string|null;hashes:{baseline:{rigJson:string|null;tree:string};inspected:{rigJson:string|null;tree:string}}|null;line:string;wallMs:number|null}
25
25
  export interface RetargetStatusView {available:boolean;reason:string|null;producer:{package:string;version:string}|null;compiler:{package:string;version:string}|null;rig:string|null;sequences:{id:string;label:string;path:string;cleaned:boolean;frames:number;people:string[]}[];bones:string[];animations:string[]}
26
26
  export type AnimationSourceView=import('../src/rebuild.ts').AnimationSourceStatus;
27
- export interface RebuildStatusView {retarget?:RetargetStatusView;animations?:AnimationSourceView|null;available:boolean;handoff:HandoffView|null;baseline:BaselineView|null;inputs:{config:string;parts:string|null;rig:string|null;configHash:string}|null;parts:{name:string;regions:unknown[]}[];contour:Record<string,Record<string,unknown>>;meshes?:Record<string,unknown>;constraints?:unknown[]|null;bones?:unknown[]|null;fields?:Record<string,unknown>|null;cuts?:{config:Record<string,unknown>;build:string|null}|null;inspectedCheck?:InspectedCheckView|null;idle?:import('../src/idle-tracks.ts').IdleStatus|null;cloth?:ClothStatusView|null;producer:{package:string;version:string}|null;compiler:{package:string;version:string}|null;reason:string|null}
27
+ export interface RebuildStatusView {retarget?:RetargetStatusView;animations?:AnimationSourceView|null;available:boolean;viewOnly?:boolean;handoff:HandoffView|null;baseline:BaselineView|null;inputs:{config:string;parts:string|null;rig:string|null;configHash:string}|null;parts:{name:string;regions:unknown[]}[];contour:Record<string,Record<string,unknown>>;meshes?:Record<string,unknown>;constraints?:unknown[]|null;bones?:unknown[]|null;fields?:Record<string,unknown>|null;cuts?:{config:Record<string,unknown>;build:string|null}|null;inspectedCheck?:InspectedCheckView|null;idle?:import('../src/idle-tracks.ts').IdleStatus|null;cloth?:ClothStatusView|null;producer:{package:string;version:string}|null;compiler:{package:string;version:string}|null;reason:string|null}
28
28
  /** #111: the cloth recipe form's status — the reader's tags, the recipes as written, each tag's parts and chains, the keypoints, the route and why Apply cannot run. */
29
29
  export interface ClothStatusView {targets:string[];targetsRead:boolean;recipes:Record<string,unknown>|null;tags:import('../src/cloth-recipe.ts').ClothTagView[];keypoints:{path:string;sha256:string}|null;route:'build'|'rig';reason:string|null}
30
30
  export interface RebuildJobView {id:string;status:'running'|'built'|'refused'|'failed';reused:boolean;lines:string[];producerLine:string|null;hint?:string;exitCode:number|null;wallMs:{remesh:number|null;compile:number|null};build:{modelUrl:string;modelHash:string;files:Record<string,string>}|null;request:{part:string;regions:RegionEntry[];configHash:string;entrySha256:string;bust?:BustSpec};producer:{package:string;version:string};compiler:{package:string;version:string}}
@@ -36,11 +36,19 @@ export interface AppliedRecord {schema:'rig-review-applied/1';buildId:string;par
36
36
 
37
37
  const number=(read:ChestFieldReader,id:string)=>{const raw=(read(id)?.value??'').trim();if(!raw)return null;const value=Number(raw);return Number.isFinite(value)?value:Number.NaN;};
38
38
 
39
- /** Rows with a centre x are designated; a row with equal semi-axes and no clip is the config's circle, else the 32-sample polygon. */
40
- export function designatedRegions(read:ChestFieldReader):{regions:RegionEntry[]}|{error:string} {
39
+ /**
40
+ * Rows with a centre x are designated; a row with equal semi-axes and no clip is the config's circle, else the 32-sample
41
+ * polygon. With the config's seed (#315), a row whose fields still equal what the config seeded sends the config's own
42
+ * polygon verbatim (an untouched Apply rebuilds the inspected rig), and a refused row left empty keeps its region as written.
43
+ * #317: the regions the rows do not show (`seed.kept`) follow as written, in their config order; one that cannot be sent
44
+ * back as written, a row left empty over such a region, or two regions of one name refuse Apply by name.
45
+ */
46
+ export function designatedRegions(read:ChestFieldReader,seed:ChestSeed|null=null):{regions:RegionEntry[]}|{error:string} {
41
47
  const regions:RegionEntry[]=[];
42
48
  for(const row of chestRegionRows){
43
- if(number(read,chestRowId(row,'cx'))===null)continue;
49
+ const seeded=seed?.rows.find(r=>r.row===row);
50
+ if(number(read,chestRowId(row,'cx'))===null){if(seeded?.refusal){if(seeded.unsendable)return {error:seeded.refusal};regions.push(seeded.region);}continue;}
51
+ if(seeded&&!seeded.refusal&&seeded.region.shape==='polygon'&&chestRegionFields.every(f=>(read(chestRowId(row,f))?.value??'').trim()===(seeded.fields[chestRowId(row,f)]??''))){regions.push(seeded.region);continue;}
44
52
  const name=(read(chestRowId(row,'name'))?.value??'').trim(),bone=(read(chestRowId(row,'bone'))?.value??'').trim(),tag=`row ${row+1}`;
45
53
  if(!name)return {error:`REBUILD_REGION_INCOMPLETE: ${tag} name`};if(!bone)return {error:`REBUILD_REGION_INCOMPLETE: ${name} bone`};
46
54
  const values:Record<string,number|null>={};
@@ -50,13 +58,30 @@ export function designatedRegions(read:ChestFieldReader):{regions:RegionEntry[]}
50
58
  if(ax===ay&&values.clip===null)regions.push({name,shape:'circle',cx,cy,r:ax,bone,spacing,band});
51
59
  else regions.push({name,bone,shape:'polygon',points:ellipsePolygon([cx,cy],[ax,ay],32,values.clip===null?undefined:clip),spacing,band});
52
60
  }
53
- return regions.length?{regions}:{error:'REBUILD_REGION_INCOMPLETE: no region has a centre'};
61
+ if(!regions.length)return {error:'REBUILD_REGION_INCOMPLETE: no region has a centre'};
62
+ for(const kept of seed?.kept??[]){if(kept.refusal)return {error:kept.refusal};keptRegions.add(kept.region);regions.push(kept.region);}
63
+ const names=new Set<string>();for(const r of regions){if(names.has(r.name))return {error:`REBUILD_REGION_DUPLICATE: ${r.name} (two regions of the chest part carry this name)`};names.add(r.name);}
64
+ return {regions};
54
65
  }
55
66
 
56
- /** The contour part to rebuild: the one whose regions name the first designated bone, else the only one, else none. */
57
- export function pickPart(status:Pick<RebuildStatusView,'parts'>,regions:readonly RegionEntry[]):string|null {
58
- const bones=new Set(regions.map(r=>r.bone));
59
- const named=status.parts.filter(p=>p.regions.some(r=>!!r&&typeof r==='object'&&bones.has(String((r as {bone?:unknown}).bone))));
67
+ /** #320: the config regions `designatedRegions` appended as kept (#317), by identity; they never name the part to rebuild. */
68
+ const keptRegions=new WeakSet<object>();
69
+ /** #314: the two circles the producer derives from a contour's `contour.bust`, or none when it states none or one the loader would refuse. */
70
+ function derivedBust(contour:unknown):readonly RegionEntry[] {
71
+ const bust=contour&&typeof contour==='object'?(contour as Record<string,unknown>).bust:undefined;
72
+ if(!bust||typeof bust!=='object')return [];
73
+ try{return deriveBust(parseBustSpec(bust)).regions;}catch{return [];}
74
+ }
75
+ /** #314: a part's regions as the producer reads them: the regions it writes, then the two it derives from `contour.bust`. */
76
+ const producerRegions=(status:Partial<Pick<RebuildStatusView,'contour'>>,part:{name:string;regions:unknown[]}):readonly unknown[]=>[...part.regions,...derivedBust(status.contour?.[part.name]?.contour)];
77
+ /**
78
+ * The contour part to rebuild: the one whose regions name the designated bones, else the only one, else none. A part's
79
+ * regions are the producer's reading of them, so the circles derived from `contour.bust` count (#314). Only the rows
80
+ * count on the designation side: a region carried back as kept (#317, #320) takes no part in the inference.
81
+ */
82
+ export function pickPart(status:Pick<RebuildStatusView,'parts'>&Partial<Pick<RebuildStatusView,'contour'>>,regions:readonly RegionEntry[]):string|null {
83
+ const bones=new Set(regions.filter(r=>!keptRegions.has(r)).map(r=>r.bone));
84
+ const named=status.parts.filter(p=>producerRegions(status,p).some(r=>!!r&&typeof r==='object'&&bones.has(String((r as {bone?:unknown}).bone))));
60
85
  if(named.length===1)return named[0]!.name;
61
86
  return status.parts.length===1?status.parts[0]!.name:null;
62
87
  }
@@ -81,18 +106,75 @@ export function landmarksRequest(status:Pick<RebuildStatusView,'parts'|'contour'
81
106
  return {part,body:{part,bust:read.spec,configHash:status.inputs.configHash}};
82
107
  }
83
108
 
109
+ /** #315: one config region as a chest row: its field values, the region as the producer reads it, or the refusal that names it. */
110
+ export interface ChestSeedRow {row:number;fields:Record<string,string>;region:RegionEntry;refusal:string|null;unsendable?:true}
111
+ /** #317: a config region beyond the editor's rows: sent back as written, or the refusal that names why it cannot be. */
112
+ export interface ChestKeptRegion {region:RegionEntry;refusal:string|null}
113
+ /** #315: what the config seeds the chest editor with: the chest part, its rows, every region refused by name, and (#317) the regions the rows do not show. */
114
+ export interface ChestSeed {part:string|null;rows:ChestSeedRow[];refusals:string[];kept:ChestKeptRegion[]}
115
+ const REGION_KEYS={circle:'band,bone,cx,cy,name,r,shape,spacing',polygon:'band,bone,name,points,shape,spacing'} as const;
116
+ /** #317: why a config region cannot go back to the producer as written (the server's key and shape rule), or null. */
117
+ function notSendable(value:unknown,index:number):string|null {
118
+ const v=value as Record<string,unknown>,named=!!v&&typeof v==='object'&&typeof v.name==='string'&&v.name?v.name:`regions[${index}]`;
119
+ if(!v||typeof v!=='object'||Array.isArray(v))return `CHEST_REGION_NOT_KEPT: ${named} (not an object; Apply would drop it)`;
120
+ const shape=v.shape,keys=Object.keys(v).sort().join(',');
121
+ if(shape!=='circle'&&shape!=='polygon')return `CHEST_REGION_NOT_KEPT: ${named} (shape ${JSON.stringify(shape??null)}; Apply sends back circle and polygon regions only)`;
122
+ if(keys!==REGION_KEYS[shape])return `CHEST_REGION_NOT_KEPT: ${named} (${shape} with keys ${keys}; Apply sends back ${REGION_KEYS[shape]} only)`;
123
+ return null;
124
+ }
125
+ const readable=(r:unknown)=>{const v=r as Record<string,unknown>;return !!v&&typeof v==='object'&&(v.shape==='circle'||(v.shape==='polygon'&&Array.isArray(v.points)&&fitChestEllipse(v.points as [number,number][]).ok));};
126
+ /**
127
+ * The chest part (#315): the contour part stating `contour.bust` (#314: it names the chest in the producer's own words,
128
+ * so another part's readable circles do not displace it), else the first with a region the editor can read (a circle or
129
+ * an axis-aligned ellipse polygon), else the first with any region (whose polygons are then refused by name).
130
+ */
131
+ function chestPart(status:Pick<RebuildStatusView,'parts'|'contour'>){
132
+ const bust=(p:{name:string})=>{const c=status.contour[p.name]?.contour;return !!c&&typeof c==='object'&&'bust' in (c as Record<string,unknown>);};
133
+ return status.parts.find(bust)??status.parts.find(p=>p.regions.some(readable))??status.parts.find(p=>p.regions.length);
134
+ }
135
+ /** The config's regions as chest rows (at most two), read by measurement, never by point count. Pure: Apply recomputes it. */
136
+ export function chestSeed(status:Pick<RebuildStatusView,'parts'|'contour'>):ChestSeed {
137
+ const part=chestPart(status),entry=part?status.contour[part.name]:undefined;if(!part||!entry)return {part:null,rows:[],refusals:[],kept:[]};
138
+ const contour=(entry.contour??{}) as Record<string,unknown>;
139
+ // An invalid bust spec leaves the rows empty.
140
+ const regions:readonly unknown[]=part.regions.length?part.regions:derivedBust(contour);
141
+ const rows:ChestSeedRow[]=[];
142
+ regions.slice(0,chestRegionRows.length).forEach((value,row)=>{
143
+ const r=value as Record<string,unknown>,fields:Record<string,string>={},id=(f:typeof chestRegionFields[number])=>chestRowId(row,f);
144
+ for(const [field,key] of [['name','name'],['bone','bone'],['spacing','spacing'],['band','band']] as const)if(r[key]!==undefined)fields[id(field)]=String(r[key]);
145
+ if(r.shape==='circle'){
146
+ for(const [field,key] of [['cx','cx'],['cy','cy'],['ax','r'],['ay','r']] as const)if(r[key]!==undefined)fields[id(field)]=String(r[key]);
147
+ rows.push({row,fields,region:r as unknown as RegionEntry,refusal:null});return;
148
+ }
149
+ if(r.shape!=='polygon'||!Array.isArray(r.points)){rows.push({row,fields:{},region:value as RegionEntry,refusal:notSendable(value,row)??`CHEST_REGION_NOT_KEPT: ${String(r?.name??`regions[${row}]`)} (polygon without points)`,unsendable:true});return;}
150
+ const points=r.points as [number,number][],region:RegionEntry={name:String(r.name),bone:String(r.bone),shape:'polygon',points,spacing:r.spacing as number,band:r.band as number};
151
+ const fit=fitChestEllipse(points);
152
+ if(!fit.ok){
153
+ const name=String(r.name),count=points.length;
154
+ const refusal=fit.points<CHEST_ELLIPSE_MIN_POINTS?`CHEST_REGION_NOT_ELLIPSE: ${name} (polygon, ${count} points, below the ${CHEST_ELLIPSE_MIN_POINTS} a fit needs)`
155
+ :fit.maxOff===null?`CHEST_REGION_NOT_ELLIPSE: ${name} (polygon, ${count} points, no ellipse fits)`
156
+ :`CHEST_REGION_NOT_ELLIPSE: ${name} (polygon, ${count} points, max off-ellipse ${fit.maxOff.toFixed(1)} px)`;
157
+ rows.push({row,fields:{},region,refusal});return;
158
+ }
159
+ fields[id('cx')]=String(fit.cx);fields[id('cy')]=String(fit.cy);fields[id('ax')]=String(fit.ax);fields[id('ay')]=String(fit.ay);
160
+ if(fit.clip!==undefined)fields[id('clip')]=String(fit.clip);
161
+ rows.push({row,fields,region,refusal:null});
162
+ });
163
+ // #317: only regions the config writes are kept; regions derived from contour.bust are never sent back.
164
+ const kept:ChestKeptRegion[]=regions===part.regions?regions.slice(chestRegionRows.length).map((value,i)=>({region:value as RegionEntry,refusal:notSendable(value,chestRegionRows.length+i)})):[];
165
+ return {part:part.name,rows,refusals:[...rows,...kept].flatMap(r=>r.refusal?[r.refusal]:[]),kept};
166
+ }
167
+
84
168
  /**
85
- * Field values that start the editor from the producer config: the first contour part's circle regions (at most two
86
- * rows) and its contour numbers. Only for an untouched editor — `null` once any row has a centre.
169
+ * Field values that start the editor from the producer config: the chest part's circle and ellipse-polygon regions (at
170
+ * most two rows, #315) and its contour numbers. Only for an untouched editor — `null` once any row has a centre. A
171
+ * refused polygon leaves its row empty; `chestSeed(status).refusals` names it.
87
172
  */
88
173
  export function seedFields(status:Pick<RebuildStatusView,'parts'|'contour'>,read:ChestFieldReader):Record<string,string>|null {
89
174
  if(chestRegionRows.some(row=>(read(chestRowId(row,'cx'))?.value??'').trim()))return null;
90
- const part=status.parts.find(p=>p.regions.length),entry=part?status.contour[part.name]:undefined;if(!part||!entry)return null;
175
+ const part=chestPart(status),entry=part?status.contour[part.name]:undefined;if(!part||!entry)return null;
91
176
  const out:Record<string,string>={},contour=(entry.contour??{}) as Record<string,unknown>;
92
- part.regions.slice(0,chestRegionRows.length).forEach((value,row)=>{
93
- const r=value as Record<string,unknown>;if(r.shape!=='circle')return;
94
- for(const [field,key] of [['name','name'],['bone','bone'],['cx','cx'],['cy','cy'],['ax','r'],['ay','r'],['spacing','spacing'],['band','band']] as const)if(r[key]!==undefined)out[chestRowId(row,field)]=String(r[key]);
95
- });
177
+ for(const row of chestSeed(status).rows)Object.assign(out,row.fields);
96
178
  for(const [key,id] of chestContourFields)if(typeof contour[key]==='number')out[id]=String(contour[key]);
97
179
  if(typeof contour.bridges==='boolean')out['chest-bridges']=String(contour.bridges);
98
180
  if(typeof entry.r==='number')out['chest-r']=String(entry.r);
@@ -237,9 +319,9 @@ export function outcomeLine(result:RebuildJobView|RebuildRefusal):{text:string;e
237
319
  * outside the opened folder when it is the `../config.json` beside an opened out/), its path and hash, then the
238
320
  * baseline. Without a handoff it is the refusal naming where it was looked for and how to declare it.
239
321
  */
240
- export function handoffText(status:Pick<RebuildStatusView,'handoff'|'baseline'|'reason'>):{text:string;error:boolean} {
322
+ export function handoffText(status:Pick<RebuildStatusView,'handoff'|'baseline'|'reason'|'viewOnly'>):{text:string;error:boolean} {
241
323
  const h=status.handoff;
242
- if(!h)return {text:status.reason??'MODELING_HANDOFF_MISSING',error:true};
324
+ if(!h)return status.viewOnly?{text:status.reason??'view only, no producer handoff',error:false}:{text:status.reason??'MODELING_HANDOFF_MISSING',error:true};
243
325
  const how=h.how==='declared'?`declared (${h.via})`:h.outside?'discovered outside the opened folder':'discovered';
244
326
  const parts=h.parts?` · parts ${h.parts==='.'?'(the opened folder)':h.parts}`:'';
245
327
  const base=status.baseline?` · ${status.baseline.wallMs!==null&&status.baseline.status!=='running'?`${status.baseline.line} (${(status.baseline.wallMs/1000).toFixed(1)} s)`:status.baseline.line}`:' · baseline: waits for the producer';