rig-review 1.1.1 → 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.
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,10 +821,10 @@ 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(); };
@@ -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),
@@ -1167,7 +1171,7 @@ async function applyInspection(bookmark:InspectionBookmark,signal:AbortSignal,pr
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
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))),
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);}});
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';
@@ -1,6 +1,6 @@
1
1
  /** Inspection graphics from the last successfully drawn public player pose. */
2
2
  import {partBounds} from './part-selection.ts';
3
- import {placeLabels} from './label-placement.ts';
3
+ import {boxesIntersect,placeLabels,type LabelBox} from './label-placement.ts';
4
4
  import type {BoneWorld,PosedFrame,RigPlayer} from '@rig-c/play';
5
5
 
6
6
  export interface OverlayPoint {x:number;y:number}
@@ -27,7 +27,7 @@ export interface OverlayRegion {name:string;points:OverlayPoint[];stroke:string;
27
27
  * outer circle at r + band. With handles it is the chest editor's drawing (centre, core edge on the right, band on
28
28
  * top, a label under the outer circle). Colours are theme token values.
29
29
  */
30
- export interface OverlayCircle {center:OverlayPoint;r:number;band:number;label?:string;/** Label rows below the outer circle, so two labels never overlap. */labelRow?:number;handles:boolean;flash?:boolean;colors:{stroke:string;fill:string;handle:string;ink:string;labelBg:string;flash:string}}
30
+ export interface OverlayCircle {center:OverlayPoint;r:number;band:number;/** #315: an ellipse row's vertical semi-axis (world px); absent for a circle. */ry?:number;/** #315: a clipped ellipse's medial clip x (world px). */clipX?:number;label?:string;/** Label rows below the outer circle, so two labels never overlap. */labelRow?:number;handles:boolean;flash?:boolean;colors:{stroke:string;fill:string;handle:string;ink:string;labelBg:string;flash:string}}
31
31
  /**
32
32
  * Mesh edit preview in rig world coordinates: the selected slot's original triangles (cut out of the veil that dims the
33
33
  * rest of the rig), the edges after the delta by kind, moved-vertex ghosts and the vertices as handles. A box is in
@@ -70,11 +70,33 @@ export interface OverlayAnchors {
70
70
  }
71
71
  export interface OverlayView {project:OverlayProject;settings:RigOverlaySettings;dpr?:number;regions?:readonly OverlayRegion[];circles?:readonly OverlayCircle[];markers?:readonly OverlayMarker[];meshEdit?:OverlayMeshEdit|null;weights?:OverlayWeights|null;anchors?:OverlayAnchors|null}
72
72
  /** Canvas-pixel geometry of a circle designation, the same numbers the editor hit-tests against. */
73
- export function projectCircle(project:OverlayProject,circle:Pick<OverlayCircle,'center'|'r'|'band'>):{center:OverlayPoint;pxR:number;pxBand:number}|null {
74
- const {x,y}=circle.center,center=project(x,y),edge=project(x+circle.r,y),top=project(x,y+circle.r+circle.band);
73
+ export function projectCircle(project:OverlayProject,circle:Pick<OverlayCircle,'center'|'r'|'band'|'ry'>):{center:OverlayPoint;pxR:number;pxBand:number;pxRy?:number}|null {
74
+ const {x,y}=circle.center,ry=circle.ry??circle.r,center=project(x,y),edge=project(x+circle.r,y),top=project(x,y+ry+circle.band);
75
75
  if(![center,edge,top].every(finite))return null;
76
76
  const pxR=Math.max(2,Math.hypot(edge.x-center.x,edge.y-center.y));
77
- return {center,pxR,pxBand:Math.max(pxR+2,Math.hypot(top.x-center.x,top.y-center.y))};
77
+ if(circle.ry===undefined)return {center,pxR,pxBand:Math.max(pxR+2,Math.hypot(top.x-center.x,top.y-center.y))};
78
+ // #315: an ellipse row — pxRy is its vertical core; pxBand stays the distance to the band's top, where its handle sits.
79
+ const low=project(x,y+ry);if(!finite(low))return null;
80
+ const pxRy=Math.max(2,Math.hypot(low.x-center.x,low.y-center.y));
81
+ return {center,pxR,pxRy,pxBand:Math.max(pxRy+2,Math.hypot(top.x-center.x,top.y-center.y))};
82
+ }
83
+ export interface CircleLabelInput {center:OverlayPoint;pxBand:number;width:number;height?:number;row?:number}
84
+ /**
85
+ * Circle coordinate label rects (#307): R (row 0 / image-left) anchors below-left of its outer ring, L (row 1 / image-right)
86
+ * anchors below-right of its outer ring, away from the other circle. If two rects would still intersect, the later one
87
+ * stacks vertically below the earlier one.
88
+ */
89
+ export function circleLabelRects(items:readonly CircleLabelInput[]):LabelBox[] {
90
+ const out:LabelBox[]=[];
91
+ for(let i=0;i<items.length;i++){
92
+ const item=items[i]!,w=item.width,h=item.height??15,other=items.length===2?items[1-i]:undefined;
93
+ const leftSide=item.row!==undefined?item.row===0:other?item.center.x<=other.center.x:true;
94
+ const x=items.length===1&&item.row===undefined?item.center.x-w/2:leftSide?item.center.x-w:item.center.x;
95
+ let box:LabelBox={x,y:item.center.y+item.pxBand+3,w,h};
96
+ while(out.some(p=>boxesIntersect(box,p))){const hit=out.find(p=>boxesIntersect(box,p))!;box={...box,y:hit.y+hit.h+2};}
97
+ out.push(box);
98
+ }
99
+ return out;
78
100
  }
79
101
  export interface OverlayRefresh extends OverlayView {player:OverlayPlayer|null;bones:readonly BoneOverlaySpec[];frame?:PosedFrame;selectedSlot?:string|null}
80
102
  const point=(x:number,y:number):OverlayPoint=>({x,y});
@@ -208,18 +230,32 @@ export class RigOverlays {
208
230
  if(region.name){ctx.font='600 11px ui-monospace, monospace';const width=ctx.measureText(region.name).width+8;ctx.fillStyle=c.labelBg;ctx.fillRect(top!.x-width/2,top!.y-24,width,15);ctx.fillStyle=region.stroke;ctx.fillText(region.name,top!.x-width/2+4,top!.y-13);}
209
231
  }
210
232
  }
211
- if(this.playerAvailable)for(const circle of circles){
212
- const at=projectCircle(project,circle);if(!at)continue;const {center,pxR,pxBand}=at,c=circle.colors;
213
- ctx.globalAlpha=.95;
214
- ctx.beginPath();ctx.setLineDash([5,4]);ctx.strokeStyle=c.stroke;ctx.lineWidth=1.6;ctx.arc(center.x,center.y,pxBand,0,Math.PI*2);ctx.stroke();
215
- ctx.beginPath();ctx.setLineDash([]);ctx.fillStyle=c.fill;ctx.lineWidth=2.2;ctx.arc(center.x,center.y,pxR,0,Math.PI*2);ctx.fill();ctx.stroke();
216
- if(!circle.handles)continue;
217
- ctx.globalAlpha=1;
218
- ctx.beginPath();ctx.moveTo(center.x-7,center.y);ctx.lineTo(center.x+7,center.y);ctx.moveTo(center.x,center.y-7);ctx.lineTo(center.x,center.y+7);ctx.stroke();
219
- for(const [x,y,fill,stroke] of [[center.x,center.y,c.handle,c.stroke],[center.x+pxR,center.y,c.stroke,c.ink],[center.x,center.y-pxBand,c.ink,c.stroke]] as const){ctx.beginPath();ctx.fillStyle=fill;ctx.strokeStyle=stroke;ctx.lineWidth=2;ctx.arc(x,y,4.5,0,Math.PI*2);ctx.fill();ctx.stroke();}
220
- if(circle.label){
221
- ctx.font='600 11px ui-monospace, monospace';const width=ctx.measureText(circle.label).width+8,lx=center.x-width/2,ly=center.y+pxBand+14+(circle.labelRow??0)*17;
222
- ctx.fillStyle=circle.flash?c.flash:c.labelBg;ctx.fillRect(lx,ly-11,width,15);ctx.fillStyle=circle.flash?c.ink:c.stroke;ctx.fillText(circle.label,lx+4,ly);
233
+ if(this.playerAvailable){
234
+ const drawnCircles=circles.flatMap(circle=>{const at=projectCircle(project,circle);return at?[{circle,at}]:[];});
235
+ for(const {circle,at} of drawnCircles){
236
+ const {center,pxR,pxBand}=at,pxRy=at.pxRy??pxR,c=circle.colors,ring=pxBand-pxRy;
237
+ ctx.globalAlpha=.95;
238
+ // #315: an ellipse row draws its own core and band ring; a clipped one is cut at its medial clip line.
239
+ const clipPx=circle.clipX===undefined?null:project(circle.clipX,circle.center.y).x;
240
+ ctx.save();
241
+ if(clipPx!==null&&Number.isFinite(clipPx)){ctx.beginPath();if(clipPx>center.x)ctx.rect(center.x-pxR-ring-4,center.y-pxBand-4,clipPx-(center.x-pxR-ring-4),2*pxBand+8);else ctx.rect(clipPx,center.y-pxBand-4,center.x+pxR+ring+4-clipPx,2*pxBand+8);ctx.clip();}
242
+ ctx.beginPath();ctx.setLineDash([5,4]);ctx.strokeStyle=c.stroke;ctx.lineWidth=1.6;ctx.ellipse(center.x,center.y,pxR+ring,pxBand,0,0,Math.PI*2);ctx.stroke();
243
+ ctx.beginPath();ctx.setLineDash([]);ctx.fillStyle=c.fill;ctx.lineWidth=2.2;ctx.ellipse(center.x,center.y,pxR,pxRy,0,0,Math.PI*2);ctx.fill();ctx.stroke();
244
+ ctx.restore();ctx.strokeStyle=c.stroke;ctx.lineWidth=2.2;ctx.setLineDash([]);
245
+ if(!circle.handles)continue;
246
+ ctx.globalAlpha=1;
247
+ ctx.beginPath();ctx.moveTo(center.x-7,center.y);ctx.lineTo(center.x+7,center.y);ctx.moveTo(center.x,center.y-7);ctx.lineTo(center.x,center.y+7);ctx.stroke();
248
+ for(const [x,y,fill,stroke] of [[center.x,center.y,c.handle,c.stroke],[center.x+pxR,center.y,c.stroke,c.ink],[center.x,center.y-pxBand,c.ink,c.stroke]] as const){ctx.beginPath();ctx.fillStyle=fill;ctx.strokeStyle=stroke;ctx.lineWidth=2;ctx.arc(x,y,4.5,0,Math.PI*2);ctx.fill();ctx.stroke();}
249
+ }
250
+ const labelled=drawnCircles.filter(({circle})=>circle.handles&&!!circle.label);
251
+ if(labelled.length){
252
+ ctx.globalAlpha=1;ctx.font='600 11px ui-monospace, monospace';
253
+ const rects=circleLabelRects(labelled.map(({circle,at})=>({center:at.center,pxBand:at.pxBand,width:ctx.measureText(circle.label!).width+8,row:circle.labelRow})));
254
+ labelled.forEach(({circle},i)=>{
255
+ const box=rects[i]!,c=circle.colors;
256
+ ctx.fillStyle=circle.flash?c.flash:c.labelBg;ctx.fillRect(box.x,box.y,box.w,box.h);
257
+ ctx.fillStyle=circle.flash?c.ink:c.stroke;ctx.fillText(circle.label!,box.x+4,box.y+11);
258
+ });
223
259
  }
224
260
  }
225
261
  if(this.playerAvailable){
package/web/styles.css CHANGED
@@ -249,7 +249,7 @@ footer.status-bar{flex-wrap:nowrap}
249
249
  .idle-panel .idle-add-row input[type=text]{flex:1;min-width:90px;width:auto;padding:4px 6px;font:11px var(--font-mono)}.idle-preview-label{margin-left:auto;padding:2px 7px;border:1px solid var(--warn);border-radius:4px;color:var(--warn);font-size:11px;overflow-wrap:anywhere}.idle-preview-label.refused{border-style:dashed}.idle-preview-toggle{display:inline-flex;align-items:center;gap:4px;color:var(--fg-muted)}.idle-table tr.pending td,.idle-panel p.pending{color:var(--warn)}.idle-blink{margin:10px 0}.idle-blink .eyebrow{margin:0 0 6px}.idle-period select{width:100%;min-width:0}.idle-precheck{display:flex;flex-direction:column;gap:4px;margin-bottom:9px}.idle-precheck code{font:11px var(--font-mono);overflow-wrap:anywhere}.idle-precheck .idle-note{color:var(--fg-muted)}.transport.has-idle-blink{padding-top:22px}.idle-blink-strip{position:absolute;height:12px;pointer-events:none}.idle-blink-marker{position:absolute;top:0;width:14px;height:12px;margin-left:-7px;padding:0;border:0;background:transparent;color:var(--link);font-size:10px;line-height:12px;pointer-events:auto;cursor:ew-resize;touch-action:none}.idle-blink-marker.pending{color:var(--warn)}.idle-handles{position:absolute;inset:0;pointer-events:none;z-index:3}.idle-handle{position:absolute;width:14px;height:14px;margin:-7px 0 0 -7px;padding:0;border:2px solid var(--rv-tick-scratch);border-radius:50%;background:var(--rv-pane-label-bg);pointer-events:auto;cursor:ns-resize;touch-action:none}.idle-handle span{position:absolute;left:16px;top:-3px;white-space:nowrap;padding:1px 4px;border-radius:3px;background:var(--rv-pane-label-bg);color:var(--rv-stage-fg);font:10px var(--font-mono);pointer-events:none}
250
250
  .mesh-params{margin:0 0 10px}.mesh-param{grid-template-columns:78px minmax(0,1fr) 72px 18px auto}.mesh-param select{max-width:140px}.mesh-param-toggle{margin-top:2px}.mesh-tools{display:flex;align-items:center;flex-wrap:wrap;gap:6px}.mesh-tools .eyebrow{margin:0 6px 0 0}.mesh-tools button[aria-pressed=true]{background:var(--rv-pressed-bg);border-color:var(--rv-pressed-border);color:var(--rv-pressed-fg)}.mesh-regions{display:flex;flex-direction:column;gap:6px;margin:0 0 10px}.mesh-region{display:flex;flex-wrap:wrap;align-items:center;gap:4px 8px;margin:0;padding:6px 8px;border:1px solid var(--border);border-radius:6px}.mesh-region.selected{border-color:var(--rv-mesh-region)}.mesh-region legend{padding:0 4px;font:600 11px var(--font-mono);color:var(--rv-mesh-region)}.mesh-region label{display:flex;align-items:center;gap:4px;color:var(--fg-muted)}.mesh-region input[type=number]{width:62px}.mesh-region input[type=text]{width:96px;padding:3px 5px;font-size:11px}.mesh-segments li{display:flex;flex-wrap:wrap;align-items:center;gap:6px}.mesh-ribs{display:inline-flex;align-items:center;gap:4px;color:var(--fg-muted)}.mesh-ribs input{width:64px}.mesh-precheck{margin:0 0 9px;padding-left:18px}.mesh-precheck li{color:var(--fail);overflow-wrap:anywhere}#mesh-counts code.error,#mesh-status.error{color:var(--fail)}
251
251
  /* Inspector block row (#124): sticky at the top of each section's scroll (the section pads 12px 15px), one line that scrolls sideways when narrow. */
252
- .block-row{position:sticky;top:-12px;z-index:3;display:flex;flex-wrap:nowrap;gap:4px;margin:-12px -15px 10px;padding:6px 15px;overflow-x:auto;overscroll-behavior-x:contain;background:var(--rv-panel);border-bottom:1px solid var(--border)}.block-row button{flex:none;padding:3px 9px;font-size:11px;white-space:nowrap;color:var(--fg-muted);background:transparent;border-color:transparent}.block-row button:hover{color:var(--fg-strong);background:var(--rv-control-hover)}.block-row button[aria-current=true]{color:var(--rv-pressed-fg);background:var(--rv-pressed-bg);border-color:var(--rv-pressed-border)}.block-row button:focus-visible{outline:2px solid var(--rv-focus);outline-offset:-2px}
252
+ .block-row{position:sticky;top:-12px;z-index:3;display:flex;flex-wrap:nowrap;gap:4px;margin:-12px -15px 10px;padding:6px 15px;overflow-x:auto;overscroll-behavior-x:contain;background:var(--rv-panel);border-bottom:1px solid var(--border)}.block-row button{flex:none;padding:3px 9px;font-size:11px;white-space:nowrap;color:var(--fg-muted);background:transparent;border-color:transparent}.block-row button:hover{color:var(--fg-strong);background:var(--rv-control-hover)}.block-row button[aria-selected=true]{color:var(--rv-pressed-fg);background:var(--rv-pressed-bg);border-color:var(--rv-pressed-border)}.block-row button:focus-visible{outline:2px solid var(--rv-focus);outline-offset:-2px}[data-block-hidden]{display:none!important}
253
253
  /* Setup · Weights (#107): the weight ramp (low → half → high) and max influence's bone colours. Drawn on the stage, which stays dark, so both schemes carry the same values. */
254
254
  :root{--rv-weight-0:#3d1a78;--rv-weight-half:#e0573a;--rv-weight-1:#fcef6c;--rv-weight-bone-1:#00e5ff;--rv-weight-bone-2:#ff7ae0;--rv-weight-bone-3:#52ff88;--rv-weight-bone-4:#ffb020;--rv-weight-bone-5:#a98bff;--rv-weight-bone-6:#ff5252}
255
255
  :root[data-theme=light]{--rv-weight-0:#3d1a78;--rv-weight-half:#e0573a;--rv-weight-1:#fcef6c;--rv-weight-bone-1:#00e5ff;--rv-weight-bone-2:#ff7ae0;--rv-weight-bone-3:#52ff88;--rv-weight-bone-4:#ffb020;--rv-weight-bone-5:#a98bff;--rv-weight-bone-6:#ff5252}