vibedgames 0.10.1 → 0.10.2
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/assets/rebuild-object/.cache/spec-search/core_3d.json +1 -0
- package/assets/rebuild-object/.cache/spec-search/cs2.json +1 -0
- package/assets/rebuild-object/LICENSE +201 -0
- package/assets/rebuild-object/NOTICE +7 -0
- package/assets/rebuild-object/docs/materials/material-reference.json +2324 -0
- package/assets/rebuild-object/docs/specs/render-profile.v2.example.json +63 -0
- package/assets/rebuild-object/docs/specs/render-profile.v2.schema.json +56 -0
- package/assets/rebuild-object/docs/specs/vocabulary/README.md +86 -0
- package/assets/rebuild-object/docs/specs/vocabulary/core_3d.jsonl +12 -0
- package/assets/rebuild-object/docs/specs/vocabulary/core_3d_reconstruction.jsonl +37 -0
- package/assets/rebuild-object/docs/specs/vocabulary/cs2.jsonl +8 -0
- package/assets/rebuild-object/docs/specs/vocabulary/cs2_reconstruction.jsonl +62 -0
- package/assets/rebuild-object/forge/_shared/artifact_cache.py +54 -0
- package/assets/rebuild-object/forge/_shared/chirality.py +272 -0
- package/assets/rebuild-object/forge/_shared/color_metrics.py +107 -0
- package/assets/rebuild-object/forge/_shared/feature_acceptance_policy.py +113 -0
- package/assets/rebuild-object/forge/_shared/image_hash.py +113 -0
- package/assets/rebuild-object/forge/_shared/jpeg.py +448 -0
- package/assets/rebuild-object/forge/_shared/material_physics.py +253 -0
- package/assets/rebuild-object/forge/_shared/pipeline_routing.py +177 -0
- package/assets/rebuild-object/forge/_shared/scalp_field.py +302 -0
- package/assets/rebuild-object/forge/_shared/sdf_primitives.py +172 -0
- package/assets/rebuild-object/forge/_shared/spec_search.py +1792 -0
- package/assets/rebuild-object/forge/_shared/spec_search_profiles.json +58 -0
- package/assets/rebuild-object/forge/_shared/status_banner.py +35 -0
- package/assets/rebuild-object/forge/_shared/subdivision.py +232 -0
- package/assets/rebuild-object/forge/_shared/vertex_paint.py +236 -0
- package/assets/rebuild-object/forge/_shared/workflow_state.py +406 -0
- package/assets/rebuild-object/forge/materials/__init__.py +17 -0
- package/assets/rebuild-object/forge/materials/compatibility.py +106 -0
- package/assets/rebuild-object/forge/materials/reference.py +240 -0
- package/assets/rebuild-object/forge/next.py +116 -0
- package/assets/rebuild-object/forge/report.py +38 -0
- package/assets/rebuild-object/forge/requirements.txt +6 -0
- package/assets/rebuild-object/forge/stage1_intake/analyze_texture.py +255 -0
- package/assets/rebuild-object/forge/stage1_intake/bind_detail_properties.py +99 -0
- package/assets/rebuild-object/forge/stage1_intake/build_detail_inventory.py +349 -0
- package/assets/rebuild-object/forge/stage1_intake/camera_fitting_math.py +133 -0
- package/assets/rebuild-object/forge/stage1_intake/camera_fitting_solver.py +197 -0
- package/assets/rebuild-object/forge/stage1_intake/camera_fitting_types.py +291 -0
- package/assets/rebuild-object/forge/stage1_intake/camera_image_helpers.py +133 -0
- package/assets/rebuild-object/forge/stage1_intake/check_intake_correctness.py +116 -0
- package/assets/rebuild-object/forge/stage1_intake/check_reference_admission.py +203 -0
- package/assets/rebuild-object/forge/stage1_intake/cs2_foundation.py +139 -0
- package/assets/rebuild-object/forge/stage1_intake/cs2_manifest.py +230 -0
- package/assets/rebuild-object/forge/stage1_intake/cs2_review_contract.py +42 -0
- package/assets/rebuild-object/forge/stage1_intake/delight_albedo.py +352 -0
- package/assets/rebuild-object/forge/stage1_intake/detect_cs2.py +276 -0
- package/assets/rebuild-object/forge/stage1_intake/detect_reference_effects.py +275 -0
- package/assets/rebuild-object/forge/stage1_intake/extract_cs2_textures.py +126 -0
- package/assets/rebuild-object/forge/stage1_intake/extract_gradient_stops.py +149 -0
- package/assets/rebuild-object/forge/stage1_intake/extract_hair_evidence.py +385 -0
- package/assets/rebuild-object/forge/stage1_intake/extract_landmarks.py +456 -0
- package/assets/rebuild-object/forge/stage1_intake/extract_part_color_recipe.py +496 -0
- package/assets/rebuild-object/forge/stage1_intake/extract_pbr_evidence.py +843 -0
- package/assets/rebuild-object/forge/stage1_intake/fetch_cs2_metadata.py +147 -0
- package/assets/rebuild-object/forge/stage1_intake/label_glb_nodes.py +318 -0
- package/assets/rebuild-object/forge/stage1_intake/locate_cs2_vpk.py +73 -0
- package/assets/rebuild-object/forge/stage1_intake/material_region_analysis.py +227 -0
- package/assets/rebuild-object/forge/stage1_intake/probe_glb.py +357 -0
- package/assets/rebuild-object/forge/stage1_intake/probe_image.py +168 -0
- package/assets/rebuild-object/forge/stage1_intake/run_vision_adapter.py +45 -0
- package/assets/rebuild-object/forge/stage1_intake/search_specs.py +258 -0
- package/assets/rebuild-object/forge/stage1_intake/semantic_decomposition.py +119 -0
- package/assets/rebuild-object/forge/stage1_intake/solve_camera_pose.py +254 -0
- package/assets/rebuild-object/forge/stage2_spec/apply_material_analysis.py +192 -0
- package/assets/rebuild-object/forge/stage2_spec/cs2_adapters.py +62 -0
- package/assets/rebuild-object/forge/stage2_spec/derive_geometry.py +118 -0
- package/assets/rebuild-object/forge/stage2_spec/hair_profile.py +306 -0
- package/assets/rebuild-object/forge/stage2_spec/humanoid_proportions.py +214 -0
- package/assets/rebuild-object/forge/stage2_spec/new_pre_spec_assessment.py +343 -0
- package/assets/rebuild-object/forge/stage2_spec/new_sculpt_spec.py +2396 -0
- package/assets/rebuild-object/forge/stage2_spec/validate_sculpt_spec.py +2871 -0
- package/assets/rebuild-object/forge/stage3_build/bake_projected_texture.py +181 -0
- package/assets/rebuild-object/forge/stage3_build/decimate.py +272 -0
- package/assets/rebuild-object/forge/stage3_build/generate_threejs_factory.py +4099 -0
- package/assets/rebuild-object/forge/stage3_build/module_cache.py +155 -0
- package/assets/rebuild-object/forge/stage3_build/morph_targets.py +178 -0
- package/assets/rebuild-object/forge/stage3_build/orchestrate_passes.py +653 -0
- package/assets/rebuild-object/forge/stage3_build/uv_unwrap.py +622 -0
- package/assets/rebuild-object/forge/stage3_build/visual_hull.py +357 -0
- package/assets/rebuild-object/forge/stage4_review/_fit_divine_eye.py +64 -0
- package/assets/rebuild-object/forge/stage4_review/append_review.py +453 -0
- package/assets/rebuild-object/forge/stage4_review/attachment_anchor.py +349 -0
- package/assets/rebuild-object/forge/stage4_review/calibrate_eye.py +131 -0
- package/assets/rebuild-object/forge/stage4_review/check_part_coverage.py +298 -0
- package/assets/rebuild-object/forge/stage4_review/compare_region_passes.py +169 -0
- package/assets/rebuild-object/forge/stage4_review/correction_loop.py +258 -0
- package/assets/rebuild-object/forge/stage4_review/cs2_review.py +224 -0
- package/assets/rebuild-object/forge/stage4_review/diagnose_render.py +356 -0
- package/assets/rebuild-object/forge/stage4_review/diagnose_render_multi_angle.py +143 -0
- package/assets/rebuild-object/forge/stage4_review/divine_eye.py +461 -0
- package/assets/rebuild-object/forge/stage4_review/fit_params.py +381 -0
- package/assets/rebuild-object/forge/stage4_review/geometry_integrity.py +294 -0
- package/assets/rebuild-object/forge/stage4_review/hair_gate.py +216 -0
- package/assets/rebuild-object/forge/stage4_review/interior_difference.py +188 -0
- package/assets/rebuild-object/forge/stage4_review/joint_loops.py +209 -0
- package/assets/rebuild-object/forge/stage4_review/make_comparison_sheet.py +292 -0
- package/assets/rebuild-object/forge/stage4_review/material_comparator.py +181 -0
- package/assets/rebuild-object/forge/stage4_review/material_feedback.py +143 -0
- package/assets/rebuild-object/forge/stage4_review/material_gate.py +126 -0
- package/assets/rebuild-object/forge/stage4_review/material_views.py +184 -0
- package/assets/rebuild-object/forge/stage4_review/mesh_reference_compare.py +362 -0
- package/assets/rebuild-object/forge/stage4_review/multi_pass.py +102 -0
- package/assets/rebuild-object/forge/stage4_review/objectness.py +143 -0
- package/assets/rebuild-object/forge/stage4_review/pairwise_penetration.py +376 -0
- package/assets/rebuild-object/forge/stage4_review/per_feature.py +215 -0
- package/assets/rebuild-object/forge/stage4_review/render_bridge.py +556 -0
- package/assets/rebuild-object/forge/stage4_review/scalp_exposure.py +257 -0
- package/assets/rebuild-object/forge/stage4_review/self_intersection.py +592 -0
- package/assets/rebuild-object/forge/stage4_review/swept_arc_gate.py +336 -0
- package/assets/rebuild-object/forge/stage4_review/turntable_gate.py +415 -0
- package/assets/rebuild-object/forge/stage4_review/validate_render_profile.py +182 -0
- package/assets/rebuild-object/forge/stage4_review/vertex_region_gate.py +456 -0
- package/assets/rebuild-object/forge/stage4_review/vlm_gate.py +196 -0
- package/assets/rebuild-object/forge/stage5_rig/NOTES.md +149 -0
- package/assets/rebuild-object/forge/stage5_rig/__init__.py +6 -0
- package/assets/rebuild-object/forge/stage5_rig/emit_rig.py +420 -0
- package/assets/rebuild-object/forge/stage5_rig/geodesic_skinning.py +508 -0
- package/assets/rebuild-object/forge/stage5_rig/rig_spec.py +174 -0
- package/assets/rebuild-object/forge/stage5_rig/validate_rig_payload.py +195 -0
- package/assets/rebuild-object/forge/state.py +98 -0
- package/assets/rebuild-object/steps.json +381 -0
- package/dist/{chunk-FB3UDZAV.js → chunk-24TITAFS.js} +1 -1
- package/dist/{chunk-QNWCBPVO.js → chunk-2C5PG2QO.js} +1 -1
- package/dist/{chunk-4RYTTD4D.js → chunk-2DEVOKI7.js} +1 -1
- package/dist/{chunk-RRI23NK2.js → chunk-2GHPYT2P.js} +1 -1
- package/dist/{chunk-QEKVZ7BX.js → chunk-2HXGMXGC.js} +1 -1
- package/dist/{chunk-N2UHAQXC.js → chunk-36FORP7T.js} +0 -1
- package/dist/{chunk-DH6WPL3X.js → chunk-3IXRQTRF.js} +1 -1
- package/dist/{chunk-SXYQL4GK.js → chunk-4YHA32OE.js} +1 -1
- package/dist/{chunk-V5ADM3WC.js → chunk-4ZGQKPK5.js} +1 -1
- package/dist/{chunk-BJAN3RMY.js → chunk-6CLUPFQA.js} +1 -1
- package/dist/{chunk-52E6EKZV.js → chunk-7WTF2BA4.js} +1 -1
- package/dist/{chunk-P74GTK23.js → chunk-AAXZNK4Z.js} +1 -1
- package/dist/{chunk-F4J6XCHT.js → chunk-ALLBT4FB.js} +1 -1
- package/dist/{chunk-HRKVAXNN.js → chunk-BAZDPPIG.js} +5 -5
- package/dist/{chunk-RPJR3S5S.js → chunk-CYDENLZ4.js} +5 -8
- package/dist/{chunk-I5LELJSK.js → chunk-DKSUD44G.js} +1 -1
- package/dist/{chunk-43P4U7CB.js → chunk-DWWSJKTE.js} +1 -1
- package/dist/{chunk-6IUFHPMV.js → chunk-E72TFJZP.js} +1 -1
- package/dist/{chunk-E3FJUPLT.js → chunk-EUAAQMUA.js} +2 -0
- package/dist/{chunk-37LLKM73.js → chunk-F7LYJSZE.js} +1 -1
- package/dist/{chunk-MEAO33XW.js → chunk-FMON3C74.js} +8 -8
- package/dist/{chunk-YLUB6252.js → chunk-FPILHRLZ.js} +1 -1
- package/dist/{chunk-4UU622RK.js → chunk-GGO6ZYYI.js} +1 -3
- package/dist/{chunk-2ZKS7V72.js → chunk-GZCRYYS6.js} +5 -5
- package/dist/{chunk-E7NDOZ27.js → chunk-LE4GVTYI.js} +8 -8
- package/dist/{chunk-UTSSDFQL.js → chunk-NO6KPV64.js} +1 -1
- package/dist/{chunk-W2QPNAZ3.js → chunk-NXW3Z4Y4.js} +1 -1
- package/dist/{chunk-NG2X3SMF.js → chunk-OHOAZGO4.js} +1 -1
- package/dist/chunk-PYJNI5WD.js +83 -0
- package/dist/{chunk-VUV5U4J5.js → chunk-Q4XAGTFX.js} +1 -1
- package/dist/{chunk-3UGGMFJJ.js → chunk-QMZBSVKF.js} +1 -1
- package/dist/{chunk-ABTUEIRC.js → chunk-QO66UBOS.js} +2 -2
- package/dist/{chunk-LONQWRTR.js → chunk-S4KVGQQO.js} +8 -8
- package/dist/{chunk-FJXPMA63.js → chunk-T777EXAO.js} +1 -1
- package/dist/{chunk-YXOGRERG.js → chunk-TZZNRA3S.js} +1 -1
- package/dist/{chunk-CTY2WZQK.js → chunk-UC3QLWMQ.js} +1 -1
- package/dist/{chunk-MR5KIFI7.js → chunk-UDJH2RED.js} +3 -3
- package/dist/{chunk-FNJL6Z5C.js → chunk-UIKYK7KI.js} +1 -1
- package/dist/{chunk-PKM3JOKQ.js → chunk-UJRSQO2B.js} +1 -1
- package/dist/{chunk-ALPTHSUT.js → chunk-V7LEYVXB.js} +28 -24
- package/dist/{chunk-DPLFCKXP.js → chunk-WRMQEXUC.js} +1 -1
- package/dist/{chunk-HSMG6U7J.js → chunk-WXSBNC67.js} +3 -9
- package/dist/{chunk-HSCTPDEU.js → chunk-X4QIOXNQ.js} +1 -1
- package/dist/{chunk-72KHWZMN.js → chunk-Y6WHUK2O.js} +1 -1
- package/dist/{chunk-VZEJ2ZHE.js → chunk-Z3E7ORGQ.js} +5 -5
- package/dist/index.js +20 -20
- package/package.json +32 -22
- package/dist/{chunk-OFJIG4K3.js → chunk-4ENHS32B.js} +0 -0
- package/dist/{chunk-Q3XQPNF6.js → chunk-BN7TR6OR.js} +3 -3
- package/dist/{chunk-LORGE2NB.js → chunk-U2NCN5RO.js} +3 -3
- package/dist/{chunk-UPHB5HWO.js → chunk-VQTTSPA3.js} +3 -3
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Create a side-by-side visual acceptance sheet for AI vision review.
|
|
3
|
+
|
|
4
|
+
The sheet is only evidence packaging. It does not score the images. the agent or
|
|
5
|
+
another AI vision reviewer should inspect the generated sheet and write the
|
|
6
|
+
score back with stage4_review/append_review.py.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import argparse
|
|
12
|
+
import json
|
|
13
|
+
import shutil
|
|
14
|
+
import struct
|
|
15
|
+
import subprocess
|
|
16
|
+
import sys
|
|
17
|
+
import tempfile
|
|
18
|
+
import zlib
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
|
|
21
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "_shared"))
|
|
22
|
+
from jpeg import UnsupportedJpeg, decode_jpeg, is_jpeg # noqa: E402
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def paeth_predictor(a: int, b: int, c: int) -> int:
|
|
29
|
+
p = a + b - c
|
|
30
|
+
pa = abs(p - a)
|
|
31
|
+
pb = abs(p - b)
|
|
32
|
+
pc = abs(p - c)
|
|
33
|
+
if pa <= pb and pa <= pc:
|
|
34
|
+
return a
|
|
35
|
+
if pb <= pc:
|
|
36
|
+
return b
|
|
37
|
+
return c
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def read_png(path: Path) -> tuple[int, int, list[tuple[int, int, int, int]]]:
|
|
41
|
+
data = path.read_bytes()
|
|
42
|
+
if not data.startswith(PNG_SIGNATURE):
|
|
43
|
+
raise ValueError("not a PNG file")
|
|
44
|
+
cursor = len(PNG_SIGNATURE)
|
|
45
|
+
width = height = bit_depth = color_type = interlace = None
|
|
46
|
+
idat = bytearray()
|
|
47
|
+
while cursor + 8 <= len(data):
|
|
48
|
+
length = struct.unpack(">I", data[cursor : cursor + 4])[0]
|
|
49
|
+
chunk_type = data[cursor + 4 : cursor + 8]
|
|
50
|
+
chunk_data = data[cursor + 8 : cursor + 8 + length]
|
|
51
|
+
cursor += 12 + length
|
|
52
|
+
if chunk_type == b"IHDR":
|
|
53
|
+
width, height, bit_depth, color_type, _, _, interlace = struct.unpack(">IIBBBBB", chunk_data)
|
|
54
|
+
elif chunk_type == b"IDAT":
|
|
55
|
+
idat.extend(chunk_data)
|
|
56
|
+
elif chunk_type == b"IEND":
|
|
57
|
+
break
|
|
58
|
+
if width is None or height is None or bit_depth != 8 or interlace != 0:
|
|
59
|
+
raise ValueError("unsupported PNG; expected 8-bit non-interlaced image")
|
|
60
|
+
channels_by_type = {0: 1, 2: 3, 4: 2, 6: 4}
|
|
61
|
+
if color_type not in channels_by_type:
|
|
62
|
+
raise ValueError("unsupported PNG color type; convert to RGB/RGBA first")
|
|
63
|
+
channels = channels_by_type[color_type]
|
|
64
|
+
row_bytes = width * channels
|
|
65
|
+
raw = zlib.decompress(bytes(idat))
|
|
66
|
+
rows: list[bytearray] = []
|
|
67
|
+
offset = 0
|
|
68
|
+
previous = bytearray(row_bytes)
|
|
69
|
+
for _ in range(height):
|
|
70
|
+
filter_type = raw[offset]
|
|
71
|
+
offset += 1
|
|
72
|
+
row = bytearray(raw[offset : offset + row_bytes])
|
|
73
|
+
offset += row_bytes
|
|
74
|
+
for index in range(row_bytes):
|
|
75
|
+
left = row[index - channels] if index >= channels else 0
|
|
76
|
+
up = previous[index]
|
|
77
|
+
up_left = previous[index - channels] if index >= channels else 0
|
|
78
|
+
if filter_type == 1:
|
|
79
|
+
row[index] = (row[index] + left) & 0xFF
|
|
80
|
+
elif filter_type == 2:
|
|
81
|
+
row[index] = (row[index] + up) & 0xFF
|
|
82
|
+
elif filter_type == 3:
|
|
83
|
+
row[index] = (row[index] + ((left + up) // 2)) & 0xFF
|
|
84
|
+
elif filter_type == 4:
|
|
85
|
+
row[index] = (row[index] + paeth_predictor(left, up, up_left)) & 0xFF
|
|
86
|
+
elif filter_type != 0:
|
|
87
|
+
raise ValueError(f"unsupported PNG filter {filter_type}")
|
|
88
|
+
rows.append(row)
|
|
89
|
+
previous = row
|
|
90
|
+
pixels: list[tuple[int, int, int, int]] = []
|
|
91
|
+
for row in rows:
|
|
92
|
+
for x in range(width):
|
|
93
|
+
base = x * channels
|
|
94
|
+
if color_type == 0:
|
|
95
|
+
gray = row[base]
|
|
96
|
+
pixels.append((gray, gray, gray, 255))
|
|
97
|
+
elif color_type == 2:
|
|
98
|
+
pixels.append((row[base], row[base + 1], row[base + 2], 255))
|
|
99
|
+
elif color_type == 4:
|
|
100
|
+
gray = row[base]
|
|
101
|
+
pixels.append((gray, gray, gray, row[base + 1]))
|
|
102
|
+
elif color_type == 6:
|
|
103
|
+
pixels.append((row[base], row[base + 1], row[base + 2], row[base + 3]))
|
|
104
|
+
return width, height, pixels
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def write_png_rgb(path: Path, width: int, height: int, pixels: list[tuple[int, int, int]]) -> None:
|
|
108
|
+
if len(pixels) != width * height:
|
|
109
|
+
raise ValueError("pixel payload has the wrong size")
|
|
110
|
+
|
|
111
|
+
def chunk(kind: bytes, payload: bytes) -> bytes:
|
|
112
|
+
checksum = zlib.crc32(kind)
|
|
113
|
+
checksum = zlib.crc32(payload, checksum) & 0xFFFFFFFF
|
|
114
|
+
return struct.pack(">I", len(payload)) + kind + payload + struct.pack(">I", checksum)
|
|
115
|
+
|
|
116
|
+
scanlines = bytearray()
|
|
117
|
+
for y in range(height):
|
|
118
|
+
scanlines.append(0)
|
|
119
|
+
for red, green, blue in pixels[y * width : (y + 1) * width]:
|
|
120
|
+
scanlines.extend((red, green, blue))
|
|
121
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
122
|
+
path.write_bytes(
|
|
123
|
+
PNG_SIGNATURE
|
|
124
|
+
+ chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0))
|
|
125
|
+
+ chunk(b"IDAT", zlib.compress(bytes(scanlines), level=6))
|
|
126
|
+
+ chunk(b"IEND", b"")
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def load_image(path: Path) -> tuple[int, int, list[tuple[int, int, int, int]]]:
|
|
131
|
+
try:
|
|
132
|
+
return read_png(path)
|
|
133
|
+
except Exception as direct_error:
|
|
134
|
+
jpeg_bytes = path.read_bytes()
|
|
135
|
+
if is_jpeg(jpeg_bytes):
|
|
136
|
+
try:
|
|
137
|
+
return decode_jpeg(jpeg_bytes)[:3]
|
|
138
|
+
except UnsupportedJpeg:
|
|
139
|
+
pass
|
|
140
|
+
sips = shutil.which("sips")
|
|
141
|
+
if not sips:
|
|
142
|
+
raise ValueError(f"could not decode {path.name} as PNG and sips is unavailable: {direct_error}") from direct_error
|
|
143
|
+
with tempfile.TemporaryDirectory() as tmpdir:
|
|
144
|
+
converted = Path(tmpdir) / "converted.png"
|
|
145
|
+
result = subprocess.run(
|
|
146
|
+
[sips, "-s", "format", "png", str(path), "--out", str(converted)],
|
|
147
|
+
capture_output=True,
|
|
148
|
+
text=True,
|
|
149
|
+
check=False,
|
|
150
|
+
)
|
|
151
|
+
if result.returncode != 0:
|
|
152
|
+
raise ValueError(result.stderr.strip() or result.stdout.strip() or "sips conversion failed")
|
|
153
|
+
return read_png(converted)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def composite_over_checker(pixel: tuple[int, int, int, int], x: int, y: int) -> tuple[int, int, int]:
|
|
157
|
+
red, green, blue, alpha = pixel
|
|
158
|
+
background = 238 if ((x // 12 + y // 12) % 2 == 0) else 210
|
|
159
|
+
mix = alpha / 255.0
|
|
160
|
+
return (
|
|
161
|
+
round(red * mix + background * (1 - mix)),
|
|
162
|
+
round(green * mix + background * (1 - mix)),
|
|
163
|
+
round(blue * mix + background * (1 - mix)),
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def resize_cover(
|
|
168
|
+
width: int,
|
|
169
|
+
height: int,
|
|
170
|
+
pixels: list[tuple[int, int, int, int]],
|
|
171
|
+
target_w: int,
|
|
172
|
+
target_h: int,
|
|
173
|
+
) -> list[tuple[int, int, int]]:
|
|
174
|
+
scale = max(target_w / width, target_h / height)
|
|
175
|
+
scaled_w = max(1, round(width * scale))
|
|
176
|
+
scaled_h = max(1, round(height * scale))
|
|
177
|
+
offset_x = max(0, (scaled_w - target_w) // 2)
|
|
178
|
+
offset_y = max(0, (scaled_h - target_h) // 2)
|
|
179
|
+
output: list[tuple[int, int, int]] = []
|
|
180
|
+
for y in range(target_h):
|
|
181
|
+
source_y = min(height - 1, max(0, int((y + offset_y) / scale)))
|
|
182
|
+
for x in range(target_w):
|
|
183
|
+
source_x = min(width - 1, max(0, int((x + offset_x) / scale)))
|
|
184
|
+
output.append(composite_over_checker(pixels[source_y * width + source_x], x, y))
|
|
185
|
+
return output
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def fill_rect(
|
|
189
|
+
canvas: list[tuple[int, int, int]],
|
|
190
|
+
width: int,
|
|
191
|
+
x0: int,
|
|
192
|
+
y0: int,
|
|
193
|
+
rect_w: int,
|
|
194
|
+
rect_h: int,
|
|
195
|
+
color: tuple[int, int, int],
|
|
196
|
+
) -> None:
|
|
197
|
+
height = len(canvas) // width
|
|
198
|
+
for y in range(max(0, y0), min(height, y0 + rect_h)):
|
|
199
|
+
row = y * width
|
|
200
|
+
for x in range(max(0, x0), min(width, x0 + rect_w)):
|
|
201
|
+
canvas[row + x] = color
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def blit(
|
|
205
|
+
canvas: list[tuple[int, int, int]],
|
|
206
|
+
width: int,
|
|
207
|
+
image: list[tuple[int, int, int]],
|
|
208
|
+
image_w: int,
|
|
209
|
+
x0: int,
|
|
210
|
+
y0: int,
|
|
211
|
+
) -> None:
|
|
212
|
+
image_h = len(image) // image_w
|
|
213
|
+
height = len(canvas) // width
|
|
214
|
+
for y in range(image_h):
|
|
215
|
+
target_y = y0 + y
|
|
216
|
+
if target_y < 0 or target_y >= height:
|
|
217
|
+
continue
|
|
218
|
+
for x in range(image_w):
|
|
219
|
+
target_x = x0 + x
|
|
220
|
+
if 0 <= target_x < width:
|
|
221
|
+
canvas[target_y * width + target_x] = image[y * image_w + x]
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
# WHOLE-IMAGE ONLY. This composites the full reference beside the full render, at which scale a
|
|
225
|
+
# few-pixel tear is invisible to a human reviewer and to a VLM alike -- so a sheet that "looks right"
|
|
226
|
+
# is not evidence about small features. Feature crops belong here eventually; until then treat this
|
|
227
|
+
# as a macro-tier artifact. See grimoire/review/divine_eye_microscope.md.
|
|
228
|
+
def create_sheet(
|
|
229
|
+
reference: Path,
|
|
230
|
+
render: Path,
|
|
231
|
+
out: Path,
|
|
232
|
+
width: int,
|
|
233
|
+
height: int,
|
|
234
|
+
gutter: int,
|
|
235
|
+
) -> dict:
|
|
236
|
+
ref_w, ref_h, ref_pixels = load_image(reference)
|
|
237
|
+
ren_w, ren_h, ren_pixels = load_image(render)
|
|
238
|
+
panel_w = width
|
|
239
|
+
panel_h = height
|
|
240
|
+
canvas_w = panel_w * 2 + gutter * 3
|
|
241
|
+
header_h = 28
|
|
242
|
+
canvas_h = panel_h + gutter * 2 + header_h
|
|
243
|
+
canvas = [(246, 242, 236)] * (canvas_w * canvas_h)
|
|
244
|
+
fill_rect(canvas, canvas_w, gutter, gutter, panel_w, header_h, (40, 45, 48))
|
|
245
|
+
fill_rect(canvas, canvas_w, gutter * 2 + panel_w, gutter, panel_w, header_h, (40, 45, 48))
|
|
246
|
+
fill_rect(canvas, canvas_w, gutter, gutter + header_h, panel_w, panel_h, (230, 230, 230))
|
|
247
|
+
fill_rect(canvas, canvas_w, gutter * 2 + panel_w, gutter + header_h, panel_w, panel_h, (230, 230, 230))
|
|
248
|
+
ref_panel = resize_cover(ref_w, ref_h, ref_pixels, panel_w, panel_h)
|
|
249
|
+
ren_panel = resize_cover(ren_w, ren_h, ren_pixels, panel_w, panel_h)
|
|
250
|
+
blit(canvas, canvas_w, ref_panel, panel_w, gutter, gutter + header_h)
|
|
251
|
+
blit(canvas, canvas_w, ren_panel, panel_w, gutter * 2 + panel_w, gutter + header_h)
|
|
252
|
+
fill_rect(canvas, canvas_w, panel_w + gutter + gutter // 2, gutter, max(2, gutter // 5), canvas_h - gutter * 2, (170, 146, 92))
|
|
253
|
+
write_png_rgb(out, canvas_w, canvas_h, canvas)
|
|
254
|
+
return {
|
|
255
|
+
"comparisonImage": str(out.resolve()),
|
|
256
|
+
"referenceImage": str(reference.resolve()),
|
|
257
|
+
"renderScreenshot": str(render.resolve()),
|
|
258
|
+
"layout": "left=reference,right=render",
|
|
259
|
+
"panelWidth": panel_w,
|
|
260
|
+
"panelHeight": panel_h,
|
|
261
|
+
"note": "Send this image to AI vision for global, layer, and semantic feature scores; this script does not score.",
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def main(argv: list[str]) -> int:
|
|
266
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
267
|
+
parser.add_argument("--reference", type=Path, required=True)
|
|
268
|
+
parser.add_argument("--render", type=Path, required=True)
|
|
269
|
+
parser.add_argument("--out", type=Path, required=True)
|
|
270
|
+
parser.add_argument("--panel-width", type=int, default=720)
|
|
271
|
+
parser.add_argument("--panel-height", type=int, default=720)
|
|
272
|
+
parser.add_argument("--gutter", type=int, default=24)
|
|
273
|
+
parser.add_argument("--json", action="store_true")
|
|
274
|
+
args = parser.parse_args(argv)
|
|
275
|
+
try:
|
|
276
|
+
payload = create_sheet(
|
|
277
|
+
args.reference.expanduser().resolve(),
|
|
278
|
+
args.render.expanduser().resolve(),
|
|
279
|
+
args.out.expanduser().resolve(),
|
|
280
|
+
max(128, args.panel_width),
|
|
281
|
+
max(128, args.panel_height),
|
|
282
|
+
max(6, args.gutter),
|
|
283
|
+
)
|
|
284
|
+
except Exception as exc:
|
|
285
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
286
|
+
return 1
|
|
287
|
+
print(json.dumps(payload, indent=2, ensure_ascii=False) if args.json else payload["comparisonImage"])
|
|
288
|
+
return 0
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
if __name__ == "__main__":
|
|
292
|
+
raise SystemExit(main(sys.argv[1:]))
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Deterministic per-material crop comparison and mismatch classification."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import argparse
|
|
7
|
+
import json
|
|
8
|
+
import math
|
|
9
|
+
import sys
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
ROOT = Path(__file__).resolve().parents[2]
|
|
14
|
+
sys.path.insert(0, str(ROOT / "forge" / "stage1_intake"))
|
|
15
|
+
from extract_pbr_evidence import build_foreground_mask, load_image # noqa: E402
|
|
16
|
+
sys.path.insert(0, str(ROOT / "forge" / "_shared"))
|
|
17
|
+
from color_metrics import delta_e_rgb # noqa: E402
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
GRID = 48
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _grid(path: Path) -> tuple[list[tuple[int, int, int]], list[bool], dict[str, Any]]:
|
|
24
|
+
width, height, pixels, warnings = load_image(path)
|
|
25
|
+
mask, diagnostics, mask_warnings = build_foreground_mask(width, height, pixels)
|
|
26
|
+
values: list[tuple[int, int, int]] = []
|
|
27
|
+
selected: list[bool] = []
|
|
28
|
+
for y in range(GRID):
|
|
29
|
+
sy = min(height - 1, int((y + 0.5) * height / GRID))
|
|
30
|
+
for x in range(GRID):
|
|
31
|
+
sx = min(width - 1, int((x + 0.5) * width / GRID))
|
|
32
|
+
index = sy * width + sx
|
|
33
|
+
red, green, blue, _alpha = pixels[index]
|
|
34
|
+
values.append((red, green, blue))
|
|
35
|
+
selected.append(mask[index])
|
|
36
|
+
return values, selected, {
|
|
37
|
+
"width": width,
|
|
38
|
+
"height": height,
|
|
39
|
+
"foregroundCoverage": round(sum(selected) / max(1, len(selected)), 4),
|
|
40
|
+
"warnings": warnings + mask_warnings,
|
|
41
|
+
"readback": True,
|
|
42
|
+
"diagnostics": diagnostics,
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _mean(values: list[tuple[int, int, int]], selected: list[bool]) -> tuple[int, int, int]:
|
|
47
|
+
kept = [value for value, use in zip(values, selected) if use] or values
|
|
48
|
+
return tuple(round(sum(value[channel] for value in kept) / len(kept)) for channel in range(3)) # type: ignore[return-value]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _luma(rgb: tuple[int, int, int]) -> float:
|
|
52
|
+
return (rgb[0] * 0.2126 + rgb[1] * 0.7152 + rgb[2] * 0.0722) / 255.0
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _features(values: list[tuple[int, int, int]], selected: list[bool]) -> dict[str, float]:
|
|
56
|
+
luma = [_luma(value) for value in values]
|
|
57
|
+
kept = [value for value, use in zip(luma, selected) if use] or luma
|
|
58
|
+
average = sum(kept) / max(1, len(kept))
|
|
59
|
+
variance = sum((value - average) ** 2 for value in kept) / max(1, len(kept))
|
|
60
|
+
horizontal = 0.0
|
|
61
|
+
vertical = 0.0
|
|
62
|
+
count_h = count_v = 0
|
|
63
|
+
for y in range(GRID):
|
|
64
|
+
for x in range(GRID):
|
|
65
|
+
index = y * GRID + x
|
|
66
|
+
if x:
|
|
67
|
+
horizontal += abs(luma[index] - luma[index - 1])
|
|
68
|
+
count_h += 1
|
|
69
|
+
if y:
|
|
70
|
+
vertical += abs(luma[index] - luma[index - GRID])
|
|
71
|
+
count_v += 1
|
|
72
|
+
horizontal /= max(1, count_h)
|
|
73
|
+
vertical /= max(1, count_v)
|
|
74
|
+
anisotropy = max(horizontal, vertical) / max(1e-6, min(horizontal, vertical))
|
|
75
|
+
return {
|
|
76
|
+
"meanLuma": average,
|
|
77
|
+
"lumaVariance": variance,
|
|
78
|
+
"horizontalGradient": horizontal,
|
|
79
|
+
"verticalGradient": vertical,
|
|
80
|
+
"anisotropyProxy": min(4.0, anisotropy),
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _similarity(a: float, b: float, scale: float) -> float:
|
|
85
|
+
return max(0.0, min(1.0, 1.0 - abs(a - b) / max(1e-6, scale)))
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _expected_mismatch(expected: dict[str, Any] | None, features: dict[str, float]) -> list[str]:
|
|
89
|
+
if not expected:
|
|
90
|
+
return []
|
|
91
|
+
mismatches: list[str] = []
|
|
92
|
+
prior = expected.get("renderPrior", expected)
|
|
93
|
+
anisotropy_value = prior.get("anisotropy", 0.0) if isinstance(prior, dict) else 0.0
|
|
94
|
+
anisotropy = anisotropy_value.get("default", 0.0) if isinstance(anisotropy_value, dict) else anisotropy_value
|
|
95
|
+
if isinstance(anisotropy, (int, float)) and anisotropy > 0.5 and features["anisotropyProxy"] < 1.25:
|
|
96
|
+
mismatches.append("wrong-anisotropy")
|
|
97
|
+
roughness_value = prior.get("roughness", 0.5) if isinstance(prior, dict) else 0.5
|
|
98
|
+
roughness = roughness_value.get("default", 0.5) if isinstance(roughness_value, dict) else roughness_value
|
|
99
|
+
if isinstance(roughness, (int, float)):
|
|
100
|
+
# A roughness prior is only a cue here; image evidence cannot prove a scalar.
|
|
101
|
+
if roughness < 0.2 and features["lumaVariance"] < 0.003:
|
|
102
|
+
mismatches.append("highlight-response-too-flat")
|
|
103
|
+
if roughness > 0.8 and features["lumaVariance"] > 0.08:
|
|
104
|
+
mismatches.append("highlight-response-too-sharp")
|
|
105
|
+
return mismatches
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def compare_material_crops(
|
|
109
|
+
reference: Path,
|
|
110
|
+
render: Path,
|
|
111
|
+
*,
|
|
112
|
+
material_id: str | None = None,
|
|
113
|
+
expected: dict[str, Any] | None = None,
|
|
114
|
+
) -> dict[str, Any]:
|
|
115
|
+
reference_values, reference_mask, reference_meta = _grid(reference)
|
|
116
|
+
render_values, render_mask, render_meta = _grid(render)
|
|
117
|
+
reference_mean = _mean(reference_values, reference_mask)
|
|
118
|
+
render_mean = _mean(render_values, render_mask)
|
|
119
|
+
delta_e = delta_e_rgb(reference_mean, render_mean)
|
|
120
|
+
reference_features = _features(reference_values, reference_mask)
|
|
121
|
+
render_features = _features(render_values, render_mask)
|
|
122
|
+
scores = {
|
|
123
|
+
"baseColor": _similarity(delta_e, 0.0, 50.0),
|
|
124
|
+
"meanLuma": _similarity(reference_features["meanLuma"], render_features["meanLuma"], 0.45),
|
|
125
|
+
"microstructure": _similarity(reference_features["lumaVariance"], render_features["lumaVariance"], 0.12),
|
|
126
|
+
"directionalResponse": _similarity(reference_features["anisotropyProxy"], render_features["anisotropyProxy"], 2.0),
|
|
127
|
+
}
|
|
128
|
+
scores["overall"] = round(
|
|
129
|
+
scores["baseColor"] * 0.40
|
|
130
|
+
+ scores["meanLuma"] * 0.20
|
|
131
|
+
+ scores["microstructure"] * 0.25
|
|
132
|
+
+ scores["directionalResponse"] * 0.15,
|
|
133
|
+
4,
|
|
134
|
+
)
|
|
135
|
+
mismatches: list[str] = []
|
|
136
|
+
if delta_e > 20:
|
|
137
|
+
mismatches.append("wrong-base-color")
|
|
138
|
+
if scores["meanLuma"] < 0.72:
|
|
139
|
+
mismatches.append("wrong-exposure-or-value")
|
|
140
|
+
if scores["microstructure"] < 0.62:
|
|
141
|
+
mismatches.append("wrong-roughness-or-microstructure")
|
|
142
|
+
mismatches.extend(_expected_mismatch(expected, render_features))
|
|
143
|
+
if expected and expected.get("family") in {"metal", "glass", "gemstone"} and render_features["lumaVariance"] < 0.002:
|
|
144
|
+
mismatches.append("missing-environment-response")
|
|
145
|
+
unique_mismatches = list(dict.fromkeys(mismatches))
|
|
146
|
+
return {
|
|
147
|
+
"schemaVersion": 1,
|
|
148
|
+
"kind": "img2threejs.material-comparison",
|
|
149
|
+
"materialId": material_id,
|
|
150
|
+
"reference": {"path": str(reference.resolve()), "meanRgb": reference_mean, "features": reference_features, **reference_meta},
|
|
151
|
+
"render": {"path": str(render.resolve()), "meanRgb": render_mean, "features": render_features, **render_meta},
|
|
152
|
+
"metrics": {"deltaE00": round(delta_e, 3), "scores": scores},
|
|
153
|
+
"mismatches": unique_mismatches,
|
|
154
|
+
"passed": scores["overall"] >= 0.7 and not {"wrong-base-color", "missing-environment-response"} & set(unique_mismatches),
|
|
155
|
+
"nextAction": "continue" if scores["overall"] >= 0.7 and not unique_mismatches else "refine-code",
|
|
156
|
+
"limitation": "Deterministic crop metrics are evidence; material identity still requires vision review for ambiguous cases.",
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def main(argv: list[str]) -> int:
|
|
161
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
162
|
+
parser.add_argument("--reference", type=Path, required=True)
|
|
163
|
+
parser.add_argument("--render", type=Path, required=True)
|
|
164
|
+
parser.add_argument("--material-id")
|
|
165
|
+
parser.add_argument("--expected", type=Path)
|
|
166
|
+
parser.add_argument("--out", type=Path, required=True)
|
|
167
|
+
args = parser.parse_args(argv)
|
|
168
|
+
try:
|
|
169
|
+
expected = json.loads(args.expected.read_text(encoding="utf-8")) if args.expected else None
|
|
170
|
+
result = compare_material_crops(args.reference, args.render, material_id=args.material_id, expected=expected)
|
|
171
|
+
args.out.parent.mkdir(parents=True, exist_ok=True)
|
|
172
|
+
args.out.write_text(json.dumps(result, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
|
173
|
+
print(json.dumps({"passed": result["passed"], "overall": result["metrics"]["scores"]["overall"], "mismatches": result["mismatches"]}, indent=2))
|
|
174
|
+
return 0 if result["passed"] else 2
|
|
175
|
+
except Exception as exc:
|
|
176
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
177
|
+
return 1
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
if __name__ == "__main__":
|
|
181
|
+
raise SystemExit(main(sys.argv[1:]))
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Apply bounded, material-scoped feedback from crop comparison results."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import argparse
|
|
7
|
+
import copy
|
|
8
|
+
import json
|
|
9
|
+
import sys
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
ROOT = Path(__file__).resolve().parents[2]
|
|
14
|
+
sys.path.insert(0, str(ROOT / "forge" / "stage4_review"))
|
|
15
|
+
from correction_loop import decide # noqa: E402
|
|
16
|
+
sys.path.insert(0, str(ROOT / "forge"))
|
|
17
|
+
from materials.reference import load_reference # noqa: E402
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _prior_bounds(material: dict[str, Any], property_name: str, registry: dict[str, Any]) -> tuple[float, float]:
|
|
21
|
+
profile_id = material.get("referenceMaterialId")
|
|
22
|
+
profile = next((item for item in registry.get("materials", []) if item.get("id") == profile_id), None)
|
|
23
|
+
prior = profile.get("renderPrior", {}).get(property_name) if isinstance(profile, dict) else None
|
|
24
|
+
if isinstance(prior, dict) and isinstance(prior.get("range"), list):
|
|
25
|
+
return float(prior["range"][0]), float(prior["range"][1])
|
|
26
|
+
return (0.0, 1.0)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _base(value: Any, fallback: float = 0.0) -> float:
|
|
30
|
+
if isinstance(value, (int, float)) and not isinstance(value, bool):
|
|
31
|
+
return float(value)
|
|
32
|
+
if isinstance(value, dict) and isinstance(value.get("base"), (int, float)):
|
|
33
|
+
return float(value["base"])
|
|
34
|
+
return fallback
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def propose_patch(material: dict[str, Any], comparison: dict[str, Any], registry: dict[str, Any]) -> dict[str, Any]:
|
|
38
|
+
mismatches = set(comparison.get("mismatches", []))
|
|
39
|
+
changes: dict[str, Any] = {}
|
|
40
|
+
reasons: list[str] = []
|
|
41
|
+
if "wrong-roughness-or-microstructure" in mismatches or "highlight-response-too-flat" in mismatches:
|
|
42
|
+
low, high = _prior_bounds(material, "roughness", registry)
|
|
43
|
+
current = _base(material.get("roughness"), (low + high) / 2)
|
|
44
|
+
value = min(high, current + 0.08)
|
|
45
|
+
changes["roughness"] = {"base": round(value, 4), "variation": _base(material.get("roughness"), 0.0) * 0.0}
|
|
46
|
+
reasons.append("increase roughness within the profile prior")
|
|
47
|
+
if "highlight-response-too-sharp" in mismatches:
|
|
48
|
+
low, high = _prior_bounds(material, "roughness", registry)
|
|
49
|
+
current = _base(material.get("roughness"), (low + high) / 2)
|
|
50
|
+
changes["roughness"] = {"base": round(max(low, current - 0.08), 4), "variation": 0.0}
|
|
51
|
+
reasons.append("reduce roughness within the profile prior")
|
|
52
|
+
if "missing-environment-response" in mismatches:
|
|
53
|
+
changes["needsEnvironment"] = True
|
|
54
|
+
reasons.append("require a stable PMREM environment for conductor/transmissive response")
|
|
55
|
+
if "wrong-base-color" in mismatches:
|
|
56
|
+
target = comparison.get("render", {}).get("meanRgb")
|
|
57
|
+
reference = comparison.get("reference", {}).get("meanRgb")
|
|
58
|
+
if isinstance(reference, list) and len(reference) == 3:
|
|
59
|
+
changes["baseColor"] = "#%02X%02X%02X" % tuple(max(0, min(255, int(value))) for value in reference)
|
|
60
|
+
reasons.append("seed baseColor from the admitted reference crop; remove baked lighting in the next pass")
|
|
61
|
+
else:
|
|
62
|
+
reasons.append(f"base-color mismatch requires image evidence (render mean={target!r})")
|
|
63
|
+
if "wrong-anisotropy" in mismatches:
|
|
64
|
+
low, high = _prior_bounds(material, "anisotropy", registry)
|
|
65
|
+
current = _base(material.get("anisotropy"), (low + high) / 2)
|
|
66
|
+
changes["anisotropy"] = {"base": round(min(high, current + 0.1), 4), "variation": 0.0}
|
|
67
|
+
reasons.append("increase anisotropy and recapture a grazing view")
|
|
68
|
+
return {"changes": changes, "reasons": reasons, "requiresInput": not changes and bool(mismatches)}
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def apply_material_feedback(
|
|
72
|
+
spec: dict[str, Any],
|
|
73
|
+
material_id: str,
|
|
74
|
+
comparison: dict[str, Any],
|
|
75
|
+
*,
|
|
76
|
+
registry: dict[str, Any] | None = None,
|
|
77
|
+
history: list[dict[str, Any]] | None = None,
|
|
78
|
+
max_iter: int = 6,
|
|
79
|
+
) -> dict[str, Any]:
|
|
80
|
+
registry = registry or load_reference()
|
|
81
|
+
material = next((item for item in spec.get("materials", []) if isinstance(item, dict) and item.get("id") == material_id), None)
|
|
82
|
+
if material is None:
|
|
83
|
+
raise ValueError(f"material {material_id!r} not found in spec")
|
|
84
|
+
scores = comparison.get("metrics", {}).get("scores", {})
|
|
85
|
+
iteration_history = list(history or spec.get("materialFeedbackHistory", []))
|
|
86
|
+
entry = {
|
|
87
|
+
"fidelity": float(scores.get("overall", 0.0)),
|
|
88
|
+
"defectTags": list(comparison.get("mismatches", [])),
|
|
89
|
+
"reverted": False,
|
|
90
|
+
"materialId": material_id,
|
|
91
|
+
"comparisonArtifact": comparison.get("kind", "material-comparison"),
|
|
92
|
+
}
|
|
93
|
+
iteration_history.append(entry)
|
|
94
|
+
decision = decide(iteration_history, target_fidelity=0.85, max_iter=max_iter, min_delta=0.02)
|
|
95
|
+
patch = propose_patch(material, comparison, registry) if not decision["stop"] or decision["action"] == "refine-code" else {"changes": {}, "reasons": []}
|
|
96
|
+
before = {key: copy.deepcopy(material.get(key)) for key in patch["changes"]}
|
|
97
|
+
for key, value in patch["changes"].items():
|
|
98
|
+
material[key] = value
|
|
99
|
+
after = {key: copy.deepcopy(material.get(key)) for key in patch["changes"]}
|
|
100
|
+
spec.setdefault("materialFeedbackHistory", []).append({
|
|
101
|
+
"materialId": material_id,
|
|
102
|
+
"comparison": copy.deepcopy(comparison),
|
|
103
|
+
"decision": decision,
|
|
104
|
+
"patch": patch,
|
|
105
|
+
"before": before,
|
|
106
|
+
"after": after,
|
|
107
|
+
})
|
|
108
|
+
return {
|
|
109
|
+
"decision": decision,
|
|
110
|
+
"patch": patch,
|
|
111
|
+
"materialId": material_id,
|
|
112
|
+
"historyLength": len(iteration_history),
|
|
113
|
+
"spec": spec,
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def main(argv: list[str]) -> int:
|
|
118
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
119
|
+
parser.add_argument("--spec", type=Path, required=True)
|
|
120
|
+
parser.add_argument("--comparison", type=Path, required=True)
|
|
121
|
+
parser.add_argument("--material-id", required=True)
|
|
122
|
+
parser.add_argument("--out", type=Path)
|
|
123
|
+
parser.add_argument("--in-place", action="store_true")
|
|
124
|
+
parser.add_argument("--max-iter", type=int, default=6)
|
|
125
|
+
args = parser.parse_args(argv)
|
|
126
|
+
try:
|
|
127
|
+
spec = json.loads(args.spec.read_text(encoding="utf-8"))
|
|
128
|
+
comparison = json.loads(args.comparison.read_text(encoding="utf-8"))
|
|
129
|
+
result = apply_material_feedback(spec, args.material_id, comparison, max_iter=args.max_iter)
|
|
130
|
+
output = args.spec if args.in_place else args.out
|
|
131
|
+
if output is None:
|
|
132
|
+
raise ValueError("choose --in-place or --out")
|
|
133
|
+
output.parent.mkdir(parents=True, exist_ok=True)
|
|
134
|
+
output.write_text(json.dumps(result["spec"], indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
|
135
|
+
print(json.dumps({"decision": result["decision"], "patch": result["patch"], "out": str(output.resolve())}, indent=2))
|
|
136
|
+
return 0
|
|
137
|
+
except Exception as exc:
|
|
138
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
139
|
+
return 1
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
if __name__ == "__main__":
|
|
143
|
+
raise SystemExit(main(sys.argv[1:]))
|