rig-review 1.5.3 → 1.6.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/docs/PANELS.md CHANGED
@@ -35,6 +35,8 @@ Animate plays in fixed 1/60 s steps taken from wall-clock time
35
35
  any display refresh rate; a frame with less than one step's worth of time draws
36
36
  nothing new. A repeating clip wraps without a seek, so physics carries across
37
37
  the loop seam; only **Reset physics**, a seek or choosing a clip restarts it.
38
+ While paused, physics continues in fixed `PLAYBACK_STEP` (1/60 s) steps,
39
+ independent of display refresh.
38
40
 
39
41
  **Settings** (`#workspace-settings`) stores workspace-level preferences across
40
42
  tabs under `rig-review.workspace.v1` (`web/workspace-preferences.ts`):
@@ -261,7 +263,7 @@ The pinned published `@rig-c/play`1.14.0 supplies `slotIdentity()` and frame gen
261
263
 
262
264
  Source-bound links/drafts and explicit feedback preserve that side/slot plus exact attachment/owning skin/set/active skin/null reason. A restored explicit target is checked after restoring its animation/time/set and drawing; `PART_IDENTITY_MISMATCH` rolls back rather than silently substituting another key. Older slot-only links remain readable and resolve from the current authoritative snapshot. Runtime generation is current observation/feedback evidence, never a persistent identity. Named vertex weights and original source alpha remain unavailable in this inspection; packed pages are not original part images.
263
265
 
264
- **A drag on the rig view moves the physics.** A plain drag on the rig pane pans the camera and, on the same move, tells the rig's player it was carried, so hair and cloth trail the way they do in the Family viewer (rig-c/examples `family/viewer/index.html`, whose tuning this takes as written): each pointer move of `dx`, `dy` page px at root scale `s` calls `player.moved({x: clamp(dx/s × 0.25, ±8), y: clamp(−dy/s × 0.25, ±6)})`. A press is a click until it travels more than 3 px from where it went down (`CLICK_SLOP_PX` in `web/stage-pick.ts`, the one line both the pick and the drag read); a click selects a part as below and moves nothing, and a press that once passed the line is a drag even if it is released where it started. The first impulse carries the whole travel since the press. A press made with **Space** held pans only, a press an editor handle or comment mode takes is unchanged, and the reference pane pans without an impulse. On the compare page a drag on either build carries both, each by its own root scale, so A and B take the same stimulus. `player.moved` applies on the player's next step, so on a paused rig nothing swings until it steps. It is inspection only: nothing is recorded in drafts, feedback or exports. The earlier **Drag to trail** toggle, which moved the physics with the camera held, is retired (#331): the default drag covers it and **Jolt** gives an impulse without moving the camera.
266
+ **A drag on the rig view moves the physics.** A plain drag on the rig pane pans the camera and, on the same move, tells the rig's player it was carried, so hair and cloth trail the way they do in the Family viewer (rig-c/examples `family/viewer/index.html`, whose tuning this takes as written): each pointer move of `dx`, `dy` page px at root scale `s` calls `player.moved({x: clamp(dx/s × 0.25, ±8), y: clamp(−dy/s × 0.25, ±6)})`. A press is a click until it travels more than 3 px from where it went down (`CLICK_SLOP_PX` in `web/stage-pick.ts`, the one line both the pick and the drag read); a click selects a part as below and moves nothing, and a press that once passed the line is a drag even if it is released where it started. The first impulse carries the whole travel since the press. A press made with **Space** held pans only, a press an editor handle or comment mode takes is unchanged, and the reference pane pans without an impulse. On the compare page a drag on either build carries both, each by its own root scale, so A and B take the same stimulus. `player.moved` applies on the player's next step, so dragging a paused rig in single-review Animate swings its physics on the continuing held steps. It is inspection only: nothing is recorded in drafts, feedback or exports. The earlier **Drag to trail** toggle, which moved the physics with the camera held, is retired (#331): the default drag covers it and **Jolt** gives an impulse without moving the camera.
265
267
 
266
268
  **Hover preview on the stage.** In **Animate**, where a click on drawn part geometry selects its slot, resting the mouse over the rig view previews that click: the part a click at that point would select gets a solid white outline (dark halo) over a faint light tint, and its slot name sits beside the pointer. It is distinct from the selection's dashed amber box. The preview and the click are one hit test (`web/stage-pick.ts` `pickAt`: the held drawn primitives with their resolved clip, the last drawn on top, only a slot the inspection lists); where a click would select nothing — empty stage, Setup, a button or handle under the pointer, Space held — nothing is shown. It is hidden while a button is pressed (a pan or a drag), while comment mode or an editor handle owns the press, and when the pointer leaves the view. It repaints only when what it would draw changes, so a still pointer over a paused rig paints nothing. Touch and keyboard show no preview, and tap and keyboard selection are unchanged. On the compare page it follows the picked build's own rig. The preview is never recorded: sessions, drafts, feedback and exports are unchanged.
267
269
 
@@ -10,7 +10,7 @@ npx rig-review parts <out>/rig # the same package, named directly
10
10
  npx rig-review parts <out>/check # a built rig's atlas (any review package with a compiled model)
11
11
  ```
12
12
 
13
- Options: `--mesh-report <file>`, `--check <file>` (producer flags; see below), `--verdict <file>` (where the sign-off
13
+ Options: `--rig <file>` (mesh geometry), `--mesh-report <file>`, `--check <file>` (producer flags; see below), `--verdict <file>` (where the sign-off
14
14
  is written), `--port <n>`. Like `review`, it serves in the foreground and exits 3 s after its last tab closes.
15
15
 
16
16
  ## Inputs
@@ -73,6 +73,14 @@ Refusals, by name: `PARTS_VERDICT_MISSING_PART`, `PARTS_VERDICT_UNKNOWN_PART`, `
73
73
  `PARTS_VERDICT_NOT_CLEAN`, `PARTS_VERDICT_NOTHING_FLAGGED`, `PARTS_VERDICT_INVALID`, and `PARTS_VIEW_SOURCE_CHANGED`
74
74
  when a file changed after the view opened.
75
75
 
76
+ A verdict destination matching a protected part, producer report, rig/package input, model or atlas image is
77
+ refused as `PARTS_VERDICT_INPUT_COLLISION`, including normalized paths, symbolic links and filesystem aliases.
78
+ Choose a separate verdict file; saving an existing verdict again remains supported.
79
+
80
+ Sign-off JSON requests are limited to 4 MiB (4,194,304 bytes) of UTF-8 while streaming. An over-limit body is
81
+ cancelled before its remainder is read; a valid request exactly at the byte limit is accepted. Same-origin and
82
+ write-capability requirements remain unchanged.
83
+
76
84
  On reopen, a saved sign-off is offered only when both `source.sha256` and `source.flags` match the files on disk. When
77
85
  only the producer flags differ, the page says the saved sign-off is for different producer flags and starts fresh.
78
86
  Consumers that gate on the sign-off (rig-c/create) check `source.sha256`.
@@ -83,3 +91,60 @@ as `PARTS_IMAGE_OUTSIDE` / `PARTS_FILE_OUTSIDE`, and a discovered `mesh_report.j
83
91
  (`--mesh-report`, `--check`) is read where it is.
84
92
 
85
93
  Editing parts is out of scope: repairs go through the producer's source ladder, never the browser.
94
+
95
+ ## Mesh geometry
96
+
97
+ In parts mode, a `rig.json` beside `parts.json` supplies optional mesh geometry;
98
+ `--rig <file>` selects an explicit input instead. The per-part **mesh from
99
+ rig.json UVs** toggle starts off. It draws edges and vertices over the sentinel
100
+ background, and tints nontransparent art pixels pink when their centres lie
101
+ outside every nondegenerate triangle (triangle boundaries count as covered).
102
+ The mesh outcome has its own Pending / Clean / Flagged states and note; Flagged
103
+ requires a note. Approval requires both part and mesh outcomes to be Clean.
104
+ A part without a mesh has no mesh controls or outcome.
105
+
106
+ Image-space positions are `(u × width, v × height)` from each attachment's own
107
+ UVs and dimensions, never reconstructed through bones or weights. The mesh's raster
108
+ is the rig image; the parts PNG is located inside it by pixel equality. The
109
+ attachment's literal `image` under the rig spec's literal `images` directory must
110
+ be a local PNG of exactly the declared dimensions. Its centred window must match
111
+ the parts PNG RGBA exactly, and every pixel outside must have alpha zero. The
112
+ window offset `((W-w)/2,(H-h)/2)` is subtracted from mesh positions. Fractional
113
+ or negative offsets refuse; no padding constant is assumed. Border vertices
114
+ are allowed and drawn clipped. The rig raster is hashed in `source.files`. The producer
115
+ rounds UVs to six decimals: the coordinate error is at most `0.5e-6 × dimension`
116
+ pixels on each axis (for a 598×465 image, at most 0.000299 and 0.0002325 px).
117
+ The overlay cannot show this subpixel error, and coverage tint works at whole
118
+ pixels, so it cannot move a tinted pixel unless a triangle edge lies within that
119
+ rounding distance of a pixel centre. Coverage describes these derived triangles,
120
+ not an exact recovery of the producer's original unrounded positions.
121
+
122
+ Mode, vertex count, triangle count, `art_coverage` and `stray_cleared` are copied
123
+ from the part's `mesh_report.json` row without recomputing them. Absent fields
124
+ say **not reported**; faint islands remain in Producer flags. A report count may
125
+ differ from the loaded geometry; it is the producer's reading. The verdict's
126
+ `parts[name].mesh` contains `{outcome,note}` only for a mesh-bearing part.
127
+ `rig.json` and the loaded mesh report enter `source.files`, and the mesh report
128
+ also remains in `source.flags`. Changes invalidate the saved sign-off. No rig
129
+ means the existing parts view and verdict format remain unchanged.
130
+
131
+ | Refusal | Found / required |
132
+ | --- | --- |
133
+ | `PARTS_MESH_UNKNOWN_PART` | An attachment name not in parts.json / a known part |
134
+ | `PARTS_MESH_UV` | Invalid coordinate pairs or UV outside [0,1] / finite UV pairs in [0,1] |
135
+ | `PARTS_MESH_TRIANGLE` | Invalid triples or index / integer indices within the vertex array |
136
+ | `PARTS_MESH_SIZE` | Invalid declared dimensions / positive integer dimensions and image |
137
+ | `PARTS_MESH_IMAGE_SIZE` | Raster size / attachment dimensions |
138
+ | `PARTS_MESH_IMAGE_MISMATCH` | First differing RGBA pixel, nontransparent border or incompatible crop / exact centred window and transparent border |
139
+ | `PARTS_MESH_IMAGE_PATH` | Unsafe or missing rig raster / literal inside path |
140
+ | `PARTS_MESH_IMAGE_FORMAT` | Undecodable raster / PNG |
141
+ | `PARTS_MESH_AMBIGUOUS` | Multiple mesh attachments for one name / one mesh |
142
+ | `PARTS_MESH_REPORT_AMBIGUOUS` | Multiple report rows for a mesh part / at most one |
143
+ | `PARTS_MESH_MALFORMED` | Missing skins object / a rig spec with skins |
144
+ | `PARTS_MESH_OUTSIDE` | A discovered rig symlink escaping the package / an inside file |
145
+ | `PARTS_MESH_OUTCOME` | Missing or invalid mesh outcome or oversized note / a valid outcome and bounded note |
146
+ | `PARTS_MESH_OUTCOME_UNAVAILABLE` | Mesh outcome on a part without a mesh / no mesh outcome |
147
+
148
+ Explicit CLI file paths are the user's designation, as with `--mesh-report`;
149
+ discovered paths cannot escape the package. This view never writes geometry,
150
+ bones, weights or source images. Repairs remain producer config changes.
@@ -589,7 +589,7 @@ Browser players retain play's default DOM mode and default mesh backend. Rigid
589
589
  parts remain DOM images; a WebGL mesh label does not claim full-frame GL drawing.
590
590
  WebGL is requested by the published default, with Canvas2D as the supported mesh
591
591
  fallback. Accurate public actual-flush telemetry requires play 1.11.1 or later;
592
- this checkout consumes pinned 1.22.3. The consumer does not probe GL or inspect
592
+ this checkout consumes pinned 1.23.0. The consumer does not probe GL or inspect
593
593
  private renderer state. The separate Node strip exporter remains Canvas2D.
594
594
 
595
595
  The backend badge is sampled only after successful draw/frame calls. Fresh mesh
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rig-review",
3
- "version": "1.5.3",
3
+ "version": "1.6.0",
4
4
  "type": "module",
5
5
  "description": "Local human rig inspection and structured feedback export",
6
6
  "license": "MIT",
@@ -19,10 +19,12 @@
19
19
  },
20
20
  "dependencies": {
21
21
  "@napi-rs/canvas": "1.0.11",
22
- "@rig-c/play": "1.22.3"
22
+ "@rig-c/play": "1.23.0",
23
+ "pngjs": "7.0.0"
23
24
  },
24
25
  "devDependencies": {
25
26
  "@types/bun": "^1.3.0",
27
+ "@types/pngjs": "6.0.5",
26
28
  "typescript": "^5.9.3"
27
29
  },
28
30
  "engines": {
package/src/cli.ts CHANGED
@@ -22,7 +22,7 @@ import { readCompareSession } from './compare-session.ts';
22
22
  import { exportReviewStrip, exportCompareStrip, stripJson, writeStripOutput, validateStripOutput } from './strip-export.ts';
23
23
  import type { StripInterval, StripRequest } from './strip.ts';
24
24
  const handoffUsage='[--config <path> [--parts <dir>] [--source <png> --full <dir> [--head <dir>]] [--keypoints <file>]]';
25
- const usage='Usage: rig-review open <dir> [--reference <video>] [--compare <dir>] [--animation <name>] [--control] [--direct] [--view-only] '+handoffUsage+'\n --config declares the producer handoff (wins over the review.json "producer" block and discovery of config.json, rig/config.json, ../config.json beside an opened out/); feedback and control take the same flags; --view-only opens without a producer handoff.\n open is managed by default: one loopback front at 127.0.0.1:4318 (RIG_REVIEW_FRONT_PORT overrides) serves /instances/<key>/; --direct serves the worker on its own port.\n rig-review control <dir> [--reference <video>] [--compare <dir>] [--animation <name>] '+handoffUsage+' [--page <id> --expected-revision <n> --command <JSON> --wait-ms <n>]\n rig-review feedback <dir> [--reference <video>] [--compare <dir>] [--animation <name>] '+handoffUsage+' [--format json|issue]\n Usage: bun run review -- <review.json|output-directory> [--port 4317] [--checkpoint ID] [--view-only]\n bun run check -- <review.json|output-directory>\n bun run feedback -- <review.json|output-directory>\n bun run review -- compare <a> <b> --reference <video> --animation <name> [--port 4317]\n bun run check -- compare <a> <b> --reference <video> --animation <name>\n bun run feedback -- compare <a> <b> --reference <video> --animation <name>\n rig-review parts <build root | parts dir | review package> [--mesh-report <file>] [--check <file>] [--verdict <file>] [--port <n>]\n rig-review --version';
25
+ const usage='Usage: rig-review open <dir> [--reference <video>] [--compare <dir>] [--animation <name>] [--control] [--direct] [--view-only] '+handoffUsage+'\n --config declares the producer handoff (wins over the review.json "producer" block and discovery of config.json, rig/config.json, ../config.json beside an opened out/); feedback and control take the same flags; --view-only opens without a producer handoff.\n open is managed by default: one loopback front at 127.0.0.1:4318 (RIG_REVIEW_FRONT_PORT overrides) serves /instances/<key>/; --direct serves the worker on its own port.\n rig-review control <dir> [--reference <video>] [--compare <dir>] [--animation <name>] '+handoffUsage+' [--page <id> --expected-revision <n> --command <JSON> --wait-ms <n>]\n rig-review feedback <dir> [--reference <video>] [--compare <dir>] [--animation <name>] '+handoffUsage+' [--format json|issue]\n Usage: bun run review -- <review.json|output-directory> [--port 4317] [--checkpoint ID] [--view-only]\n bun run check -- <review.json|output-directory>\n bun run feedback -- <review.json|output-directory>\n bun run review -- compare <a> <b> --reference <video> --animation <name> [--port 4317]\n bun run check -- compare <a> <b> --reference <video> --animation <name>\n bun run feedback -- compare <a> <b> --reference <video> --animation <name>\n rig-review parts <build root | parts dir | review package> [--rig <file>] [--mesh-report <file>] [--check <file>] [--verdict <file>] [--port <n>]\n rig-review --version';
26
26
  async function stripCommand(args:string[],options:{stateDir?:string}){
27
27
  const compare=args[0]==='compare';if(compare)args.shift();const a=args.shift(),b=compare?args.shift():undefined;if(!a||compare&&!b)throw new Error('strip: expected package input(s)');
28
28
  let reference:string|undefined,referenceVideo:string|undefined,animation:string|undefined,basis:'a'|'b'|undefined,range:string|undefined,output:string|undefined,jsonOnly=false,all=false;
@@ -95,13 +95,13 @@ function commandHelpRequested(args:readonly string[],command:'open'|'review'|'ch
95
95
  }
96
96
  return false;
97
97
  }
98
- const partsUsage='Usage: rig-review parts <build root | parts dir | review package> [--mesh-report <file>] [--check <file>] [--verdict <file>] [--port <n>]\n A directory holding parts.json (or a build root whose rig/ holds it) opens in parts mode, before rigging; a review package or check/ folder opens its atlas.\n The sign-off is written to parts-review.json beside parts.json (or the model), or to --verdict.';
98
+ const partsUsage='Usage: rig-review parts <build root | parts dir | review package> [--rig <file>] [--mesh-report <file>] [--check <file>] [--verdict <file>] [--port <n>]\n A directory holding parts.json (or a build root whose rig/ holds it) opens in parts mode, before rigging; a review package or check/ folder opens its atlas.\n The sign-off is written to parts-review.json beside parts.json (or the model), or to --verdict.';
99
99
  /** `rig-review parts` (#348): the parts and atlas view, served in the foreground; exits when its last tab closes. */
100
100
  async function partsCommand(args:string[]){
101
101
  const input=args.shift();if(!input||input==='--help'||input==='-h'){console.log(partsUsage);return;}
102
102
  const options:PartsViewOptions={};let port=4317;const seen=new Set<string>();
103
103
  while(args.length){const flag=args.shift()!;if(flag==='--help'||flag==='-h'){console.log(partsUsage);return;}if(seen.has(flag))throw new Error(`parts: duplicate option ${flag}`);seen.add(flag);const value=args.shift();if(!value)throw new Error(`Missing value for ${flag}`);
104
- if(flag==='--mesh-report')options.meshReport=value;else if(flag==='--check')options.check=value;else if(flag==='--verdict')options.verdict=value;
104
+ if(flag==='--rig')options.rig=value;else if(flag==='--mesh-report')options.meshReport=value;else if(flag==='--check')options.check=value;else if(flag==='--verdict')options.verdict=value;
105
105
  else if(flag==='--port'){port=Number(value);if(!Number.isInteger(port)||port<0||port>65535)throw new Error('--port: expected integer 0..65535');}
106
106
  else throw new Error(`Unknown option ${flag}\n${partsUsage}`);}
107
107
  const pkg=await loadPartsView(input,options);
@@ -11,9 +11,26 @@ const BODY_LIMIT = 4 * 1024 * 1024;
11
11
 
12
12
  async function bodyJson(req: Request): Promise<unknown> {
13
13
  if (!/^application\/json(?:\s*;|$)/i.test(req.headers.get('content-type') ?? '')) throw new Error('Expected application/json');
14
- const text = await req.text();
15
- if (text.length > BODY_LIMIT) throw new Error('Verdict payload exceeds 4 MiB');
16
- return JSON.parse(text);
14
+ const reader = req.body?.getReader();
15
+ if (!reader) return JSON.parse('');
16
+ const chunks: Uint8Array[] = [];
17
+ let bytes = 0;
18
+ try {
19
+ for (;;) {
20
+ const { value, done } = await reader.read();
21
+ if (done) break;
22
+ bytes += value.byteLength;
23
+ if (bytes > BODY_LIMIT) {
24
+ await reader.cancel().catch(() => {});
25
+ throw new Error('Verdict payload exceeds 4 MiB');
26
+ }
27
+ chunks.push(value);
28
+ }
29
+ } finally { reader.releaseLock(); }
30
+ const body = new Uint8Array(bytes);
31
+ let offset = 0;
32
+ for (const chunk of chunks) { body.set(chunk, offset); offset += chunk.byteLength; }
33
+ return JSON.parse(new TextDecoder().decode(body));
17
34
  }
18
35
 
19
36
  export interface PartsServerOptions { port?: number; capability?: string; exitOnClose?: boolean; graceMs?: number; unopenedTimeoutMs?: number; onClose?: (info: LiveExitInfo) => void | Promise<void>; log?: (line: string) => void }
package/src/parts-view.ts CHANGED
@@ -16,9 +16,10 @@
16
16
  */
17
17
  import { createHash } from 'node:crypto';
18
18
  import { existsSync } from 'node:fs';
19
- import { mkdir, readFile, realpath, rename, stat, writeFile } from 'node:fs/promises';
19
+ import { mkdir, readFile, realpath, rename, rm, stat, writeFile } from 'node:fs/promises';
20
20
  import { basename, dirname, isAbsolute, join, posix, relative, resolve, sep } from 'node:path';
21
- import { loadReview, safeFile } from './manifest.ts';
21
+ import { PNG } from 'pngjs';
22
+ import { loadReview, safeFile, packagePath } from './manifest.ts';
22
23
 
23
24
  export const PARTS_VERDICT_SCHEMA = 'rig-review-parts-verdict/1';
24
25
  export const PARTS_VERDICT_FILE = 'parts-review.json';
@@ -32,7 +33,9 @@ export interface HashedFile { path: string; bytes: number; sha256: string }
32
33
  interface LocalFile { abs: string; bytes: number; sha256: string }
33
34
 
34
35
  /** A part (parts mode) or a named region (atlas mode). Boxes are rig px (parts) or page px (atlas). */
36
+ export interface PartMesh { vertices: number[]; triangles: number[]; figures: Record<string, unknown>; width: number; height: number; image: string }
35
37
  export interface ViewItem {
38
+ mesh?: PartMesh;
36
39
  name: string;
37
40
  /** Draw order, back first (parts mode); the region's place in the atlas file (atlas mode). */
38
41
  index: number;
@@ -65,13 +68,15 @@ export interface PartsViewPackage {
65
68
  flagFiles: LocalFile[];
66
69
  /** Where flags were looked for and not found, said in words. */
67
70
  flagNotes: string[];
71
+ /** Additional package/producer inputs protected from verdict writes, without changing verdict identity. */
72
+ protectedPaths?: string[];
68
73
  verdictPath: string;
69
74
  /** Absolute paths, served by index. */
70
75
  imagePaths: string[];
71
76
  pagePaths: string[];
72
77
  }
73
78
 
74
- export interface PartsViewOptions { meshReport?: string; check?: string; verdict?: string }
79
+ export interface PartsViewOptions { rig?: string; meshReport?: string; check?: string; verdict?: string }
75
80
 
76
81
  const record = (v: unknown): Record<string, unknown> | null => v && typeof v === 'object' && !Array.isArray(v) ? v as Record<string, unknown> : null;
77
82
  const finite = (v: unknown, min: number): v is number => typeof v === 'number' && Number.isFinite(v) && v >= min;
@@ -196,6 +201,70 @@ async function producerFlags(rigDir: string | null, buildRoot: string | null, na
196
201
  return { flags, files, notes };
197
202
  }
198
203
 
204
+ /** Exact attachment identity and UV-derived geometry; never reconstruct through weights. */
205
+ export function readPartMeshes(raw: unknown, items: ViewItem[], reports: unknown): void {
206
+ const skins = record(record(raw)?.skins);
207
+ if (!skins) refuse('PARTS_MESH_MALFORMED', 'rig.json requires skins object');
208
+ const byName = new Map(items.map(i => [i.name, i]));
209
+ for (const slots of Object.values(skins!)) for (const attachments of Object.values(record(slots) ?? {})) {
210
+ for (const [name, value] of Object.entries(record(attachments) ?? {})) {
211
+ const a = record(value);
212
+ if (a?.type !== 'mesh') continue;
213
+ const item = byName.get(name);
214
+ if (!item) refuse('PARTS_MESH_UNKNOWN_PART', `${name}: found mesh; required a part in parts.json`);
215
+ if (item!.mesh) refuse('PARTS_MESH_AMBIGUOUS', `${name}: found multiple meshes; required one attachment`);
216
+ if (!finite(a.width, 1) || !Number.isInteger(a.width) || !finite(a.height, 1) || !Number.isInteger(a.height) || typeof a.image !== 'string') refuse('PARTS_MESH_SIZE', `${name}: found invalid raster declaration; required image and positive integer dimensions`);
217
+ const uv = a.uvs, triangles = a.triangles;
218
+ if (!Array.isArray(uv) || !uv.length || uv.length % 2) refuse('PARTS_MESH_UV', `${name}: found invalid uvs; required nonempty coordinate pairs in [0,1]`);
219
+ for (const v of uv as unknown[]) if (!finite(v, 0) || v > 1) refuse('PARTS_MESH_UV', `${name}: found ${String(v)}; required UV in [0,1]`);
220
+ const count = (uv as number[]).length / 2;
221
+ if (!Array.isArray(triangles) || !triangles.length || triangles.length % 3) refuse('PARTS_MESH_TRIANGLE', `${name}: found invalid triangles; required nonempty index triples`);
222
+ for (const v of triangles as unknown[]) if (typeof v !== 'number' || !Number.isInteger(v) || v < 0 || v >= count) refuse('PARTS_MESH_TRIANGLE', `${name}: found ${String(v)}; required integer index in [0,${count - 1}]`);
223
+ const rows = Array.isArray(reports) ? reports.filter(r => record(r)?.part === name) : [];
224
+ if (rows.length > 1) refuse('PARTS_MESH_REPORT_AMBIGUOUS', `${name}: found ${rows.length} report rows; required at most one`);
225
+ const row = record(rows[0]) ?? {}, figures: Record<string, unknown> = {};
226
+ for (const field of ['mode', 'vertices', 'triangles', 'art_coverage', 'stray_cleared']) if (Object.hasOwn(row, field)) figures[field] = row[field];
227
+ item!.mesh = { vertices: (uv as number[]).map((v, i) => v * (i % 2 ? a.height as number : a.width as number)), triangles: triangles as number[], figures, width: a.width as number, height: a.height as number, image: a.image as string };
228
+ }
229
+ }
230
+ }
231
+
232
+ /** Prove the crop window in the mesh raster byte-for-byte; accept no inferred producer padding. */
233
+ async function locateMeshRasters(rig: unknown, root: string, items: ViewItem[], images: string[], files: LocalFile[]): Promise<void> {
234
+ const directory = record(rig)?.images;
235
+ for (const item of items) {
236
+ const mesh = item.mesh; if (!mesh) continue;
237
+ let path: string;
238
+ try {
239
+ // Validate both literal components before joining: normalization must not hide traversal.
240
+ path = await safeFile(root, `${packagePath(directory, 'rig.images')}/${packagePath(mesh.image, 'mesh.image')}`);
241
+ } catch { return refuse('PARTS_MESH_IMAGE_PATH', `${item.name}: found unavailable or unsafe rig image; required a literal local raster inside the rig directory`); }
242
+ const bytes = await readFile(path);
243
+ let image: ReturnType<typeof PNG.sync.read>, part: ReturnType<typeof PNG.sync.read>;
244
+ try {
245
+ const partBytes = await readFile(images[item.index]!);
246
+ image = PNG.sync.read(bytes); part = PNG.sync.read(partBytes);
247
+ // Retain all sixteen bits where present; 8-bit downsampling would hide a differing sample.
248
+ if (image.depth === 16) image = PNG.sync.read(bytes, { skipRescale: true });
249
+ if (part.depth === 16) part = PNG.sync.read(partBytes, { skipRescale: true });
250
+ }
251
+ catch { return refuse('PARTS_MESH_IMAGE_FORMAT', `${item.name}: found undecodable PNG; required PNG raster`); }
252
+ if (image.width !== mesh.width || image.height !== mesh.height) refuse('PARTS_MESH_IMAGE_SIZE', `${item.name}: found ${image.width}×${image.height}; required ${mesh.width}×${mesh.height}`);
253
+ const ox = (mesh.width - part.width) / 2, oy = (mesh.height - part.height) / 2;
254
+ if (part.width !== item.w || part.height !== item.h || ox < 0 || oy < 0 || !Number.isInteger(ox) || !Number.isInteger(oy)) refuse('PARTS_MESH_IMAGE_MISMATCH', `${item.name}: found incompatible raster window ${ox},${oy}; required a centred integer window of ${item.w}×${item.h}`);
255
+ const raster = image.data, original = part.data;
256
+ const rasterScale = image.depth === 16 ? 1 : 257, partScale = part.depth === 16 ? 1 : 257;
257
+ for (let y = 0; y < image.height; y++) for (let x = 0; x < image.width; x++) {
258
+ const i = (y * image.width + x) * 4;
259
+ const inside = x >= ox && x < ox + part.width && y >= oy && y < oy + part.height;
260
+ const j = ((y - oy) * part.width + x - ox) * 4;
261
+ if (inside ? [0, 1, 2, 3].some(c => raster[i + c]! * rasterScale !== original[j + c]! * partScale) : raster[i + 3] !== 0) refuse('PARTS_MESH_IMAGE_MISMATCH', `${item.name}: first differing rig pixel (${x},${y}) found RGBA [${[...raster.slice(i, i + 4)]}]; required ${inside ? `RGBA [${[...original.slice(j, j + 4)]}]` : 'border alpha 0'}`);
262
+ }
263
+ mesh.vertices = mesh.vertices.map((v, i) => v - (i % 2 ? oy : ox));
264
+ files.push({ abs: path, bytes: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') });
265
+ }
266
+ }
267
+
199
268
  async function loadPartsMode(root: string, options: PartsViewOptions): Promise<PartsViewPackage> {
200
269
  const partsJson = await insideRoot(root, join(root, 'parts.json'), 'PARTS_FILE_OUTSIDE', 'parts.json');
201
270
  const doc = record(await readJson(partsJson, 'parts.json'));
@@ -220,7 +289,25 @@ async function loadPartsMode(root: string, options: PartsViewOptions): Promise<P
220
289
  items.push({ name: part.name, index, x: part.x, y: part.y, w: part.w, h: part.h, image: true });
221
290
  }
222
291
  const { flags, files: flagFiles, notes } = await producerFlags(root, null, seen, options);
223
- return { mode: 'parts', root, title: basename(root) === 'rig' ? basename(dirname(root)) : basename(root), rigSize, items, pages: [], flags, files, flagFiles, flagNotes: notes, verdictPath: options.verdict ? resolve(options.verdict) : join(root, PARTS_VERDICT_FILE), imagePaths, pagePaths: [] };
292
+ const protectedPaths = [join(root, 'rig.json'), join(root, 'config.json'), join(root, 'review.json'), join(root, 'report.json')];
293
+ if (basename(root) === 'rig') protectedPaths.push(...['parts.json', 'config.json', 'review.json', 'report.json'].map(name => join(dirname(root), name)));
294
+ if (options.rig !== undefined) protectedPaths.push(resolve(options.rig));
295
+ const verdictPath = options.verdict ? resolve(options.verdict) : join(root, PARTS_VERDICT_FILE);
296
+ await assertVerdictDestination({ files, flagFiles, protectedPaths, verdictPath });
297
+ const rigPath = options.rig !== undefined ? resolve(options.rig) : existsSync(join(root, 'rig.json')) ? await insideRoot(root, join(root, 'rig.json'), 'PARTS_MESH_OUTSIDE', 'rig.json') : null;
298
+ if (rigPath) {
299
+ const report = notes.includes('mesh_report.json') ? undefined : flagFiles[0];
300
+ const rigBytes = await readFile(rigPath);
301
+ let rig: unknown;
302
+ try { rig = JSON.parse(rigBytes.toString('utf8')); }
303
+ catch (e) { return refuse('PARTS_MESH_MALFORMED', `rig.json: ${e instanceof Error ? e.message : String(e)}`); }
304
+ readPartMeshes(rig, items, report ? await readJson(report.abs, 'mesh_report.json') : null);
305
+ await locateMeshRasters(rig, dirname(rigPath), items, imagePaths, files);
306
+ // Bind exactly the bytes parsed above, even if the path is replaced during raster checks.
307
+ files.push({ abs: rigPath, bytes: rigBytes.length, sha256: createHash('sha256').update(rigBytes).digest('hex') });
308
+ if (report) files.push(report);
309
+ }
310
+ return { mode: 'parts', root, title: basename(root) === 'rig' ? basename(dirname(root)) : basename(root), rigSize, items, pages: [], flags, files, flagFiles, flagNotes: notes, protectedPaths, verdictPath, imagePaths, pagePaths: [] };
224
311
  }
225
312
 
226
313
  async function loadAtlasMode(input: string, options: PartsViewOptions): Promise<PartsViewPackage> {
@@ -251,7 +338,11 @@ async function loadAtlasMode(input: string, options: PartsViewOptions): Promise<
251
338
  // A build root opens as its check package (#149); its own rig/ and check/ hold the flags.
252
339
  const buildRoot = p.buildRoot ?? null;
253
340
  const { flags, files: flagFiles, notes } = await producerFlags(null, buildRoot, names, options);
254
- return { mode: 'atlas', root: p.root, title: p.manifest.title, rigSize: null, items, pages, flags, files, flagFiles, flagNotes: notes, verdictPath: options.verdict ? resolve(options.verdict) : join(dirname(modelAbs), PARTS_VERDICT_FILE), imagePaths: [], pagePaths };
341
+ const protectedPaths = [...p.files].map(path => resolve(p.root, path));
342
+ protectedPaths.push(...['rig.json', 'config.json', 'report.json', 'review.json'].map(name => join(p.root, name)));
343
+ if (p.handoff) protectedPaths.push(...p.handoff.record.files.map(file => resolve(p.root, file.path)));
344
+ if (buildRoot) protectedPaths.push(...['parts.json', 'config.json', 'rig/rig.json', 'rig/parts.json'].map(name => join(buildRoot, name)));
345
+ return { mode: 'atlas', root: p.root, title: p.manifest.title, rigSize: null, items, pages, flags, files, flagFiles, flagNotes: notes, protectedPaths, verdictPath: options.verdict ? resolve(options.verdict) : join(dirname(modelAbs), PARTS_VERDICT_FILE), imagePaths: [], pagePaths };
255
346
  }
256
347
 
257
348
  /**
@@ -261,10 +352,30 @@ async function loadAtlasMode(input: string, options: PartsViewOptions): Promise<
261
352
  export async function loadPartsView(input: string, options: PartsViewOptions = {}): Promise<PartsViewPackage> {
262
353
  const abs = await realpath(resolve(input)).catch(() => refuse('PARTS_VIEW_INPUT_MISSING', `${input} does not exist`));
263
354
  if ((await stat(abs)).isDirectory()) {
264
- if (existsSync(join(abs, 'parts.json'))) return loadPartsMode(abs, options);
265
- if (existsSync(join(abs, 'rig', 'parts.json')) && !existsSync(join(abs, 'review.json'))) return loadPartsMode(join(abs, 'rig'), options);
355
+ if (existsSync(join(abs, 'parts.json'))) return checkedVerdict(await loadPartsMode(abs, options));
356
+ if (existsSync(join(abs, 'rig', 'parts.json')) && !existsSync(join(abs, 'review.json'))) return checkedVerdict(await loadPartsMode(join(abs, 'rig'), options));
357
+ }
358
+ return checkedVerdict(await loadAtlasMode(input, options));
359
+ }
360
+
361
+ /** Compare names, real paths (including parent links), and filesystem identities before creating output. */
362
+ async function assertVerdictDestination(pkg: Pick<PartsViewPackage, 'files' | 'flagFiles' | 'protectedPaths' | 'verdictPath'>): Promise<void> {
363
+ const target = resolve(pkg.verdictPath);
364
+ const targetReal = await realpath(target).catch((e: NodeJS.ErrnoException) => { if (e.code !== 'ENOENT') throw e; return null; });
365
+ const targetStat = await stat(target, { bigint: true }).catch((e: NodeJS.ErrnoException) => { if (e.code !== 'ENOENT') throw e; return null; });
366
+ const parent = await realpath(dirname(target)).catch((e: NodeJS.ErrnoException) => { if (e.code !== 'ENOENT') throw e; return null; });
367
+ for (const path of [...pkg.files, ...pkg.flagFiles].map(file => file.abs).concat(pkg.protectedPaths ?? [])) {
368
+ const input = resolve(path);
369
+ const real = await realpath(input).catch((e: NodeJS.ErrnoException) => { if (e.code !== 'ENOENT') throw e; return null; });
370
+ const sameName = target === input || (real !== null && (targetReal === real || (parent !== null && join(parent, basename(target)) === real)));
371
+ const identity = targetStat && real ? await stat(real, { bigint: true }) : null;
372
+ if (sameName || (targetStat && identity && targetStat.dev === identity.dev && targetStat.ino === identity.ino)) refuse('PARTS_VERDICT_INPUT_COLLISION', `${basename(target)} is a protected input; choose a separate verdict file`);
266
373
  }
267
- return loadAtlasMode(input, options);
374
+ }
375
+
376
+ async function checkedVerdict(pkg: PartsViewPackage): Promise<PartsViewPackage> {
377
+ await assertVerdictDestination(pkg);
378
+ return pkg;
268
379
  }
269
380
 
270
381
  /** The hashed files as the verdict records them: relative to the verdict file's directory. */
@@ -280,7 +391,7 @@ export interface PartsVerdict {
280
391
  tool: { name: '@rig-c/review'; version: string };
281
392
  source: ReturnType<typeof verdictSource>;
282
393
  status: VerdictStatus;
283
- parts: Record<string, { outcome: PartOutcome; note: string; flags: string[] }>;
394
+ parts: Record<string, { outcome: PartOutcome; note: string; flags: string[]; mesh?: { outcome: PartOutcome; note: string } }>;
284
395
  updatedAt: string;
285
396
  }
286
397
 
@@ -309,9 +420,20 @@ export function buildVerdict(pkg: Pick<PartsViewPackage, 'mode' | 'items' | 'fla
309
420
  const note = entry.note === undefined ? '' : entry.note;
310
421
  if (typeof note !== 'string' || note.length > PARTS_NOTE_LIMIT) return refuse('PARTS_VERDICT_INVALID', `${name}.note is a string of at most ${PARTS_NOTE_LIMIT} characters`);
311
422
  if (outcome === 'flagged' && !note.trim()) return refuse('PARTS_VERDICT_NOTE_REQUIRED', `${name} is flagged and has no note saying what is wrong`);
312
- parts[name] = { outcome, note, flags: [...new Set(pkg.flags.filter(f => f.item === name).map(f => f.id))] };
423
+ const meshInput = record(entry.mesh);
424
+ const hasMesh = pkg.items.some(i => i.name === name && i.mesh);
425
+ if (!hasMesh && entry.mesh !== undefined) refuse('PARTS_MESH_OUTCOME_UNAVAILABLE', `${name}: no mesh; required no mesh outcome`);
426
+ let mesh: { outcome: PartOutcome; note: string } | undefined;
427
+ if (hasMesh) {
428
+ if (!meshInput || !['pending', 'clean', 'flagged'].includes(String(meshInput.outcome))) refuse('PARTS_MESH_OUTCOME', `${name}: required mesh outcome pending, clean or flagged`);
429
+ const meshNote = meshInput!.note ?? '';
430
+ if (typeof meshNote !== 'string' || meshNote.length > PARTS_NOTE_LIMIT) refuse('PARTS_MESH_OUTCOME', `${name}: required mesh note up to ${PARTS_NOTE_LIMIT} characters`);
431
+ if (meshInput!.outcome === 'flagged' && !(meshNote as string).trim()) refuse('PARTS_VERDICT_NOTE_REQUIRED', `${name}.mesh is flagged and has no note`);
432
+ mesh = { outcome: meshInput!.outcome as PartOutcome, note: meshNote as string };
433
+ }
434
+ parts[name] = { ...(mesh ? { mesh } : {}), outcome, note, flags: [...new Set(pkg.flags.filter(f => f.item === name).map(f => f.id))] };
313
435
  }
314
- const outcomes = Object.values(parts).map(p => p.outcome);
436
+ const outcomes = Object.values(parts).flatMap(p => p.mesh ? [p.outcome, p.mesh.outcome] : [p.outcome]);
315
437
  if (status === 'approved' && outcomes.some(o => o !== 'clean')) refuse('PARTS_VERDICT_NOT_CLEAN', `approved needs every part clean; ${outcomes.filter(o => o !== 'clean').length} are not`);
316
438
  if (status === 'changes-requested' && !outcomes.includes('flagged')) refuse('PARTS_VERDICT_NOTHING_FLAGGED', 'changes-requested needs at least one flagged part');
317
439
  return { schema: PARTS_VERDICT_SCHEMA, mode: pkg.mode, tool: { name: '@rig-c/review', version }, source: verdictSource(pkg), status, parts, updatedAt: now.toISOString() };
@@ -331,12 +453,16 @@ async function packageVersion(): Promise<string> {
331
453
 
332
454
  /** Writes the verdict atomically beside its sources. */
333
455
  export async function saveVerdict(pkg: PartsViewPackage, input: unknown): Promise<PartsVerdict> {
456
+ await assertVerdictDestination(pkg);
334
457
  await assertPartsUnchanged(pkg);
335
458
  const verdict = buildVerdict(pkg, input, await packageVersion());
336
459
  await mkdir(dirname(pkg.verdictPath), { recursive: true });
337
460
  const tmp = `${pkg.verdictPath}.${crypto.randomUUID()}.tmp`;
338
- await writeFile(tmp, JSON.stringify(verdict, null, 2) + '\n');
339
- await rename(tmp, pkg.verdictPath);
461
+ try {
462
+ await writeFile(tmp, JSON.stringify(verdict, null, 2) + '\n', { flag: 'wx' });
463
+ await assertVerdictDestination(pkg);
464
+ await rename(tmp, pkg.verdictPath);
465
+ } finally { await rm(tmp, { force: true }); }
340
466
  return verdict;
341
467
  }
342
468
 
package/web/catalog-en.ts CHANGED
@@ -3085,4 +3085,10 @@ export const enCatalog: Readonly<Record<string, string>> = {
3085
3085
  "Page {name}: {width}×{height} px, 1 region. The background shows through padding; a region box is the packer's, and pixels outside it are bleed.": "Page {name}: {width}×{height} px, 1 region. The background shows through padding; a region box is the packer's, and pixels outside it are bleed.",
3086
3086
  "Tinted: the footprint of the part drawn in front ({names}).": "Tinted: the footprint of the part drawn in front ({names}).",
3087
3087
  "The saved sign-off is for different producer flags; this review starts fresh.": "The saved sign-off is for different producer flags; this review starts fresh.",
3088
+ "mesh from rig.json UVs": "mesh from rig.json UVs",
3089
+ "Mesh geometry": "Mesh geometry",
3090
+ "not reported": "not reported",
3091
+ "Pink: art pixels outside every triangle.": "Pink: art pixels outside every triangle.",
3092
+ "Mesh outcome": "Mesh outcome",
3093
+ "Mesh note": "Mesh note",
3088
3094
  };
package/web/catalog-ko.ts CHANGED
@@ -3085,4 +3085,10 @@ export const koCatalog: Readonly<Record<string, string>> = {
3085
3085
  "Page {name}: {width}×{height} px, 1 region. The background shows through padding; a region box is the packer's, and pixels outside it are bleed.": "페이지 {name}: {width}×{height} px, 영역 1개. 패딩에는 배경이 비쳐 보이고, 영역 상자는 패커가 정한 것이며 상자 밖의 픽셀은 블리드입니다.",
3086
3086
  "Tinted: the footprint of the part drawn in front ({names}).": "색칠된 부분: 앞에 그려지는 파츠의 풋프린트({names}).",
3087
3087
  "The saved sign-off is for different producer flags; this review starts fresh.": "저장된 승인은 다른 프로듀서 플래그에 대해 내려진 것이라, 이번 검수는 처음부터 시작합니다.",
3088
+ "mesh from rig.json UVs": "rig.json UV로 계산한 메시",
3089
+ "Mesh geometry": "메시 형상",
3090
+ "not reported": "보고되지 않음",
3091
+ "Pink: art pixels outside every triangle.": "분홍색: 모든 삼각형 밖의 원화 픽셀.",
3092
+ "Mesh outcome": "메시 판정",
3093
+ "Mesh note": "메시 메모",
3088
3094
  };
package/web/main.ts CHANGED
@@ -101,6 +101,7 @@ let assets: ModelAssets | null = null;
101
101
  let player: RigPlayer | null = null;
102
102
  let animation = '';
103
103
  let playing = false;
104
+ let heldPhysicsFailed = false;
104
105
  let time = 0;
105
106
  /** The clock a scratch build on the stage states for its own animation (a retarget's report frameTimes, #164). */
106
107
  let stageClock: StageClock | null = null;
@@ -524,7 +525,7 @@ function seek(value: number, move?: ClipMove): void {
524
525
  }
525
526
 
526
527
  function stopAudio(): void { for (const audio of audioPlaying) audio.pause(); audioPlaying.clear(); }
527
- function pause(): void { ++playbackIntent;desiredPlay=false;suspendedPreview=false;idleHeld=true; playing = false; lastFrame = 0; playbackCarry = 0; player?.pause(); video?.pause(); stopAudio(); button('play').textContent = '▶'; button('play').setAttribute('aria-label', 'Play'); }
528
+ function pause(): void { ++playbackIntent;desiredPlay=false;suspendedPreview=false;idleHeld=true; heldPhysicsFailed=false; playing = false; lastFrame = 0; playbackCarry = 0; player?.hold(true); player?.resume(); video?.pause(); stopAudio(); button('play').textContent = '▶'; button('play').setAttribute('aria-label', 'Play'); }
528
529
 
529
530
  async function audition(clipId: string): Promise<void> {
530
531
  const clip = data.manifest.audio.clips.find(item => item.id === clipId); if (!clip) return;
@@ -651,9 +652,23 @@ function seekReading(clip: string, frame: number, exact: number | null, label: s
651
652
  function tick(now: number): void {
652
653
  // #356: the scrub box is read before this frame writes anything (a read after the writes forces a layout).
653
654
  if (playing) try { holdScrubBox(input('scrub')); tickPlaying(now); } finally { releaseScrubBox(); }
655
+ else tickHeldPhysics(now);
654
656
  requestAnimationFrame(tick);
655
657
  }
656
658
 
659
+ /** Animate steps held physics under the standing environment; wind time and queued jolts stay frozen. */
660
+ function tickHeldPhysics(now:number):void {
661
+ const elapsed=lastFrame?Math.min((now-lastFrame)/1000,.1):0;lastFrame=now;
662
+ if(heldPhysicsFailed||!player?.current||document.hidden||selectedInspector(document)!=='playback'||seekingControl){playbackCarry=0;return;}
663
+ const next=advancePlayback({time,duration,carry:playbackCarry,elapsed,repeat:false,held:true});
664
+ playbackCarry=next.carry;
665
+ if(!next.steps.length)return;
666
+ try{
667
+ player.hold(true);player.resume();
668
+ drawRig(()=>{for(const step of next.steps)player!.advance(step);player!.draw();});
669
+ }catch(error){heldPhysicsFailed=true;player.pause();playbackCarry=0;message(errorText(error),true);}
670
+ }
671
+
657
672
  function tickPlaying(now: number): void {
658
673
  const dt = lastFrame ? Math.min((now - lastFrame) / 1000, .1) : 0;
659
674
  // #346: fixed PLAYBACK_STEP steps from wall-clock time; a repeating clip wraps here with no seek, so physics carries across the loop.
@@ -1058,7 +1073,7 @@ async function playPreview():Promise<void> {
1058
1073
  if((!player&&!video&&!sequence)||duration<=0)return;
1059
1074
  const intent=++playbackIntent;desiredPlay=true;idleHeld=false;syncPlayerLoop();if(time>=duration)seek(0,{kind:'replay'});
1060
1075
  if(video&&referenceInput.state==='loaded'){try{await video.play();}catch(error){pause();message(`Playback is paused: ${errorText(error)}. Use Play to retry.`,true);return;}}
1061
- if(intent!==playbackIntent||!desiredPlay){if(!desiredPlay)video?.pause();return;}playing=true;lastFrame=0;player?.resume();button('play').textContent='Ⅱ';button('play').setAttribute('aria-label','Pause');
1076
+ if(intent!==playbackIntent||!desiredPlay){if(!desiredPlay)video?.pause();return;}playing=true;lastFrame=0;player?.hold(false);player?.resume();button('play').textContent='Ⅱ';button('play').setAttribute('aria-label','Pause');
1062
1077
  }
1063
1078
  function localDraft():boolean{return !!comments?.draft()||dirty||!!input('feedback-summary').value.trim()||!!input('feedback-start').value.trim()||!!input('feedback-end').value.trim()||!!select('feedback-category').value||!!input('feedback-target-name').value.trim()&&input('feedback-target-name').value!==data.manifest.id;}
1064
1079
  function controlState():ControlInspection {
@@ -1742,8 +1757,8 @@ async function applyPatch(patch:ConfigPatch,world:StageWorld|null=null):Promise<
1742
1757
  replay:(t:number,dt:number,steps:readonly {t:number;wind?:[number,number];gravity?:[number,number]}[]=[])=>{
1743
1758
  if(!player?.current||!(dt>0)||!(t>=0))return null;
1744
1759
  const at=(k:number)=>{for(const step of steps)if(Math.max(0,Math.ceil(step.t/dt-1e-9))===k)player!.environment({...(step.wind?{wind:step.wind}:{}),...(step.gravity?{gravity:step.gravity}:{})});};
1745
- pause();if(steps.length)player.environment(null);at(0);player.seek(0);player.resume();
1746
- try{for(let k=1,n=Math.round(t/dt);k<=n;k++){at(k);player.frame(dt);}}finally{player.pause();}
1760
+ pause();if(steps.length)player.environment(null);at(0);player.seek(0);player.hold(false);player.resume();
1761
+ try{for(let k=1,n=Math.round(t/dt);k<=n;k++){at(k);player.frame(dt);}}finally{player.hold(true);player.pause();}
1747
1762
  drawRig(()=>player!.draw());time=player.time;renderTransport();
1748
1763
  const posedTime=player.time;if(steps.length){if(environmentApplied())player.environment(environmentFor(wind.read(),gravityValue()));else player.environment(null);}
1749
1764
  return posedTime;},
@@ -2138,8 +2153,8 @@ function sampleLocals(bone:string,dt:number,n:number):{t:number;rotation:number;
2138
2153
  let recording=false;
2139
2154
  const read:BoneAdjust=(bones,ctx)=>{inner?.(bones,ctx);if(!recording)return;const l=bones.bone(bone);rows.set(ctx.trackTime??0,{t:ctx.trackTime??0,rotation:l.rotation,x:l.x,y:l.y,scaleX:l.scaleX,scaleY:l.scaleY,shearX:l.shearX,shearY:l.shearY});};
2140
2155
  pause();p.adjust=read;
2141
- try{p.seek(0);recording=true;p.repose();p.resume();for(let k=1;k<=n;k++)p.frame(dt);}
2142
- finally{recording=false;p.pause();p.adjust=inner;drawRig(()=>p.draw());time=p.time;renderTransport();}
2156
+ try{p.seek(0);recording=true;p.repose();p.hold(false);p.resume();for(let k=1;k<=n;k++)p.frame(dt);}
2157
+ finally{recording=false;p.hold(true);p.pause();p.adjust=inner;drawRig(()=>p.draw());time=p.time;renderTransport();}
2143
2158
  return [...rows.values()].sort((a,b)=>a.t-b.t);
2144
2159
  }
2145
2160
  async function resetRebuild(world:StageWorld|null=null):Promise<void> {
@@ -55,3 +55,41 @@ export function paintPart(ctx: Ctx, item: Box, image: Source, options: { bg: str
55
55
  ctx.drawImage(mask, 0, 0);
56
56
  ctx.globalAlpha = 1;
57
57
  }
58
+
59
+ export interface MeshGeometry { vertices: readonly number[]; triangles: readonly number[] }
60
+ /** Closed triangle union at pixel centres. Degenerate triangles cover no area. */
61
+ export function meshCoverage(w: number, h: number, mesh: MeshGeometry): Uint8Array {
62
+ const mask = new Uint8Array(w * h), v = mesh.vertices;
63
+ const cross = (ax: number, ay: number, bx: number, by: number, x: number, y: number) => (bx - ax) * (y - ay) - (by - ay) * (x - ax);
64
+ for (let i = 0; i < mesh.triangles.length; i += 3) {
65
+ const a = mesh.triangles[i]! * 2, b = mesh.triangles[i + 1]! * 2, c = mesh.triangles[i + 2]! * 2;
66
+ const ax = v[a]!, ay = v[a + 1]!, bx = v[b]!, by = v[b + 1]!, cx = v[c]!, cy = v[c + 1]!;
67
+ if (cross(ax, ay, bx, by, cx, cy) === 0) continue;
68
+ for (let y = Math.max(0, Math.ceil(Math.min(ay, by, cy) - .5)); y <= Math.min(h - 1, Math.floor(Math.max(ay, by, cy) - .5)); y++) {
69
+ for (let x = Math.max(0, Math.ceil(Math.min(ax, bx, cx) - .5)); x <= Math.min(w - 1, Math.floor(Math.max(ax, bx, cx) - .5)); x++) {
70
+ const p = cross(ax, ay, bx, by, x + .5, y + .5), q = cross(bx, by, cx, cy, x + .5, y + .5), r = cross(cx, cy, ax, ay, x + .5, y + .5);
71
+ if ((p >= 0 && q >= 0 && r >= 0) || (p <= 0 && q <= 0 && r <= 0)) mask[y * w + x] = 1;
72
+ }
73
+ }
74
+ }
75
+ return mask;
76
+ }
77
+ /** Tint only nontransparent source-art pixels outside the triangle union, before drawing diagnostic edges. */
78
+ export function paintMesh(ctx: Ctx, source: Source, w: number, h: number, mesh: MeshGeometry, makeCanvas: (w: number, h: number) => HTMLCanvasElement): void {
79
+ const scratch = makeCanvas(w, h), s = scratch.getContext('2d')!;
80
+ s.drawImage(source, 0, 0);
81
+ const art = s.getImageData(0, 0, w, h), tint = s.createImageData(w, h), mask = meshCoverage(w, h, mesh);
82
+ for (let i = 0; i < mask.length; i++) if (!mask[i] && art.data[i * 4 + 3]) {
83
+ tint.data[i * 4] = 255; tint.data[i * 4 + 2] = 80; tint.data[i * 4 + 3] = 160;
84
+ }
85
+ s.putImageData(tint, 0, 0); ctx.drawImage(scratch, 0, 0);
86
+ ctx.strokeStyle = '#00bfff'; ctx.fillStyle = '#ffffff'; ctx.lineWidth = .5;
87
+ ctx.beginPath();
88
+ const v = mesh.vertices;
89
+ for (let i = 0; i < mesh.triangles.length; i += 3) {
90
+ for (let j = 0; j < 3; j++) { const a = mesh.triangles[i + j]! * 2; if (!j) ctx.moveTo(v[a]!, v[a + 1]!); else ctx.lineTo(v[a]!, v[a + 1]!); }
91
+ ctx.closePath();
92
+ }
93
+ ctx.stroke();
94
+ for (let i = 0; i < v.length; i += 2) { ctx.beginPath(); ctx.arc(v[i]!, v[i + 1]!, .8, 0, Math.PI * 2); ctx.fill(); }
95
+ }
package/web/parts.css CHANGED
@@ -49,3 +49,10 @@ h2{font-size:11px;letter-spacing:.06em;color:var(--muted);margin:4px 0 8px}
49
49
  textarea,select{font:inherit;color:inherit;background:var(--bg);border:1px solid var(--line);border-radius:5px;padding:4px}
50
50
  .pv-primary{background:var(--accent);color:#fff;border:0;border-radius:6px;padding:6px 10px;cursor:pointer;font:inherit}
51
51
  @media (max-width:900px){.pv-layout{grid-template-columns:1fr}.pv-list,.pv-side{max-height:30vh}}
52
+
53
+ #pv-mesh-panel{margin-top:16px;display:flex;flex-direction:column;gap:6px}
54
+ #pv-mesh-panel dl{display:grid;grid-template-columns:1fr 1fr;gap:3px 8px;margin:0}
55
+ #pv-mesh-panel dd{margin:0;overflow-wrap:anywhere}
56
+ #pv-mesh-panel p{margin:4px 0}
57
+ #pv-mesh-panel label{display:flex;flex-direction:column;gap:4px}
58
+ #pv-mesh-panel textarea{height:48px;resize:vertical}
package/web/parts.ts CHANGED
@@ -11,10 +11,12 @@ import { bindDomI18n, onLanguageChange, t } from './i18n.ts';
11
11
  import { pageInstanceAccess } from './instance-access.ts';
12
12
  import { connectLiveWindow } from './live-connection.ts';
13
13
  import { flagLabel } from './parts-flags.ts';
14
- import { frontParts, paintAlphaOnly, paintBackground, paintPart } from './parts-render.ts';
14
+ import { frontParts, paintAlphaOnly, paintBackground, paintPart, paintMesh } from './parts-render.ts';
15
15
 
16
16
  type Outcome = 'pending' | 'clean' | 'flagged';
17
- interface Item { name: string; index: number; x: number; y: number; w: number; h: number; page?: string; degrees?: number; image?: boolean }
17
+ interface Mesh { vertices: number[]; triangles: number[]; figures: Record<string, unknown> }
18
+ interface Entry { outcome: Outcome; note: string; mesh?: { outcome: Outcome; note: string } }
19
+ interface Item { mesh?: Mesh; name: string; index: number; x: number; y: number; w: number; h: number; page?: string; degrees?: number; image?: boolean }
18
20
  interface Page { name: string; width: number; height: number; index: number }
19
21
  type Flag =
20
22
  | { id: string; item: string; source: 'mesh_report'; kind: 'faint'; art: number; maxAlpha: number; box: [number, number, number, number] }
@@ -22,7 +24,7 @@ type Flag =
22
24
  interface ViewData {
23
25
  mode: 'parts' | 'atlas'; title: string; rigSize: [number, number] | null; items: Item[]; pages: Page[]; flags: Flag[];
24
26
  flagSources: string[]; flagMissing: string[]; verdictFile: string;
25
- verdict: { status: string; parts: Record<string, { outcome: Outcome; note: string }> } | null; verdictStale: 'files' | 'flags' | null;
27
+ verdict: { status: string; parts: Record<string, Entry> } | null; verdictStale: 'files' | 'flags' | null;
26
28
  }
27
29
 
28
30
  /** Page pixels shown around a region in its own view, so the packer's bleed and padding are visible. */
@@ -30,7 +32,7 @@ export const REGION_MARGIN = 4;
30
32
 
31
33
  const $ = <T extends HTMLElement>(id: string) => document.getElementById(id) as T;
32
34
  const access = pageInstanceAccess();
33
- const state = { data: null as ViewData | null, selected: 0, zoom: 1, bg: 'green', alpha: false, footprints: false, view: 'item' as 'item' | 'page', page: 0, verdict: new Map<string, { outcome: Outcome; note: string }>() };
35
+ const state = { data: null as ViewData | null, selected: 0, zoom: 1, bg: 'green', alpha: false, footprints: false, view: 'item' as 'item' | 'page', page: 0, meshShown: new Set<string>(), verdict: new Map<string, Entry>() };
34
36
  const images = new Map<string, HTMLImageElement>();
35
37
 
36
38
  function load(src: string): Promise<HTMLImageElement> {
@@ -108,6 +110,7 @@ async function paint(): Promise<void> {
108
110
  if (token !== paintToken) return;
109
111
  const ctx = setCanvas(canvas, item.w, item.h);
110
112
  paintPart(ctx, item, img, { bg: state.bg, alpha: state.alpha, fronts: fronts.map(f => ({ box: f.o, image: f.img })), makeCanvas: (w, h) => Object.assign(document.createElement('canvas'), { width: w, height: h }) });
113
+ if (item.mesh && state.meshShown.has(item.name)) paintMesh(ctx, img, item.w, item.h, item.mesh, (w, h) => Object.assign(document.createElement('canvas'), { width: w, height: h }));
111
114
  overlay.replaceChildren(...data.flags.filter((f): f is Extract<Flag, { kind: 'faint' }> => f.item === item.name && f.kind === 'faint').map(f => {
112
115
  const box = overlayBox(f.box[0], f.box[1], f.box[2], f.box[3]);
113
116
  box.dataset.flag = f.id;
@@ -169,12 +172,43 @@ function renderVerdict(): void {
169
172
  $<HTMLTextAreaElement>('pv-note').value = entry.note;
170
173
  }
171
174
 
175
+ function renderMesh(): void {
176
+ document.getElementById('pv-mesh-panel')?.remove();
177
+ document.getElementById('pv-mesh-control')?.remove();
178
+ const item = state.data!.items[state.selected]!;
179
+ if (!item.mesh) return;
180
+ const control = document.createElement('label'); control.id = 'pv-mesh-control'; control.className = 'pv-field';
181
+ const toggle = document.createElement('input'); toggle.type = 'checkbox'; toggle.checked = state.meshShown.has(item.name);
182
+ toggle.onchange = () => { if (toggle.checked) state.meshShown.add(item.name); else state.meshShown.delete(item.name); void paint(); };
183
+ control.append(toggle, t('mesh from rig.json UVs')); document.querySelector('.pv-toolbar')!.append(control);
184
+ const panel = document.createElement('section'); panel.id = 'pv-mesh-panel';
185
+ const heading = document.createElement('h2'); heading.textContent = t('Mesh geometry'); panel.append(heading);
186
+ const figures = document.createElement('dl');
187
+ for (const key of ['mode', 'vertices', 'triangles', 'art_coverage', 'stray_cleared']) {
188
+ const dt = document.createElement('dt'), dd = document.createElement('dd'); dt.textContent = key;
189
+ dd.textContent = Object.hasOwn(item.mesh.figures, key) ? JSON.stringify(item.mesh.figures[key]) : t('not reported');
190
+ dd.dataset.meshFigure = key; figures.append(dt, dd);
191
+ }
192
+ panel.append(figures);
193
+ const help = document.createElement('p'); help.textContent = t('Pink: art pixels outside every triangle.'); panel.append(help);
194
+ const entry = state.verdict.get(item.name)!;
195
+ const select = document.createElement('select'); select.setAttribute('aria-label', t('Mesh outcome'));
196
+ for (const [value, label] of [['pending', 'Pending'], ['clean', 'Clean'], ['flagged', 'Flagged']]) { const option = document.createElement('option'); option.value = value!; option.textContent = t(label!); select.append(option); }
197
+ select.value = entry.mesh!.outcome;
198
+ const note = document.createElement('textarea'); note.maxLength = 10000; note.value = entry.mesh!.note; note.setAttribute('aria-label', t('Mesh note'));
199
+ select.onchange = () => { entry.mesh!.outcome = select.value as Outcome; };
200
+ note.oninput = () => { entry.mesh!.note = note.value; };
201
+ const outcomeLabel = document.createElement('label'), noteLabel = document.createElement('label');
202
+ outcomeLabel.append(t('Mesh outcome'), select); noteLabel.append(t('Mesh note'), note);
203
+ panel.append(outcomeLabel, noteLabel); document.querySelector('.pv-verdict')!.before(panel);
204
+ }
205
+
172
206
  function select(index: number): void {
173
207
  const data = state.data!;
174
208
  state.selected = index;
175
209
  const item = data.items[index]!;
176
210
  if (item.page !== undefined) state.page = data.pages.findIndex(p => p.name === item.page);
177
- renderList(); renderFlags(); renderVerdict(); void paint();
211
+ renderList(); renderFlags(); renderVerdict(); renderMesh(); void paint();
178
212
  }
179
213
 
180
214
  function setView(view: 'item' | 'page'): void {
@@ -206,8 +240,8 @@ async function boot(): Promise<void> {
206
240
  const data = await res.json() as ViewData & { error?: string };
207
241
  if (!res.ok) { $('pv-load').textContent = data.error ?? t('Load failed.'); return; }
208
242
  state.data = data;
209
- for (const item of data.items) state.verdict.set(item.name, { outcome: 'pending', note: '' });
210
- if (data.verdict) { for (const [name, v] of Object.entries(data.verdict.parts)) if (state.verdict.has(name)) state.verdict.set(name, { outcome: v.outcome, note: v.note ?? '' }); $<HTMLSelectElement>('pv-overall').value = data.verdict.status; }
243
+ for (const item of data.items) state.verdict.set(item.name, { outcome: 'pending', note: '', ...(item.mesh ? { mesh: { outcome: 'pending' as Outcome, note: '' } } : {}) });
244
+ if (data.verdict) { for (const [name, v] of Object.entries(data.verdict.parts)) if (state.verdict.has(name)) state.verdict.set(name, { outcome: v.outcome, note: v.note ?? '', ...(v.mesh ? { mesh: v.mesh } : {}) }); $<HTMLSelectElement>('pv-overall').value = data.verdict.status; }
211
245
  document.title = data.title;
212
246
  $('pv-title').textContent = data.title;
213
247
  $('pv-mode').textContent = data.mode === 'parts' ? t('Parts package, before rigging') : t('Atlas of a built rig');
@@ -17,6 +17,8 @@ export interface PlaybackInput {
17
17
  /** Wall-clock seconds since the previous frame. */
18
18
  elapsed: number;
19
19
  repeat: boolean;
20
+ /** Keep the clip time fixed while supplying wall-clock physics steps. */
21
+ held?: boolean;
20
22
  step?: number;
21
23
  }
22
24
  export interface PlaybackAdvance {
@@ -33,16 +35,16 @@ export interface PlaybackAdvance {
33
35
  export function advancePlayback(input: PlaybackInput): PlaybackAdvance {
34
36
  const step = input.step ?? PLAYBACK_STEP, duration = input.duration, steps: number[] = [];
35
37
  let time = input.time, carry = input.carry + Math.max(0, input.elapsed), wrapped = false, ended = false;
36
- if (!(duration > 0)) return { steps, time, carry: 0, wrapped, ended };
38
+ if (!input.held && !(duration > 0)) return { steps, time, carry: 0, wrapped, ended };
37
39
  while (carry >= step - STEP_SLACK) {
38
- if (!input.repeat && time + step >= duration) {
40
+ if (!input.held && !input.repeat && time + step >= duration) {
39
41
  const last = duration - time;
40
42
  if (last > 0) steps.push(last);
41
43
  time = duration; carry = 0; ended = true;
42
44
  break;
43
45
  }
44
- steps.push(step); carry = Math.max(0, carry - step); time += step;
45
- if (input.repeat) while (time >= duration) { time -= duration; wrapped = true; }
46
+ steps.push(step); carry = Math.max(0, carry - step); if (!input.held) time += step;
47
+ if (!input.held && input.repeat) while (time >= duration) { time -= duration; wrapped = true; }
46
48
  }
47
49
  return { steps, time, carry, wrapped, ended };
48
50
  }