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.
Files changed (174) hide show
  1. package/assets/rebuild-object/.cache/spec-search/core_3d.json +1 -0
  2. package/assets/rebuild-object/.cache/spec-search/cs2.json +1 -0
  3. package/assets/rebuild-object/LICENSE +201 -0
  4. package/assets/rebuild-object/NOTICE +7 -0
  5. package/assets/rebuild-object/docs/materials/material-reference.json +2324 -0
  6. package/assets/rebuild-object/docs/specs/render-profile.v2.example.json +63 -0
  7. package/assets/rebuild-object/docs/specs/render-profile.v2.schema.json +56 -0
  8. package/assets/rebuild-object/docs/specs/vocabulary/README.md +86 -0
  9. package/assets/rebuild-object/docs/specs/vocabulary/core_3d.jsonl +12 -0
  10. package/assets/rebuild-object/docs/specs/vocabulary/core_3d_reconstruction.jsonl +37 -0
  11. package/assets/rebuild-object/docs/specs/vocabulary/cs2.jsonl +8 -0
  12. package/assets/rebuild-object/docs/specs/vocabulary/cs2_reconstruction.jsonl +62 -0
  13. package/assets/rebuild-object/forge/_shared/artifact_cache.py +54 -0
  14. package/assets/rebuild-object/forge/_shared/chirality.py +272 -0
  15. package/assets/rebuild-object/forge/_shared/color_metrics.py +107 -0
  16. package/assets/rebuild-object/forge/_shared/feature_acceptance_policy.py +113 -0
  17. package/assets/rebuild-object/forge/_shared/image_hash.py +113 -0
  18. package/assets/rebuild-object/forge/_shared/jpeg.py +448 -0
  19. package/assets/rebuild-object/forge/_shared/material_physics.py +253 -0
  20. package/assets/rebuild-object/forge/_shared/pipeline_routing.py +177 -0
  21. package/assets/rebuild-object/forge/_shared/scalp_field.py +302 -0
  22. package/assets/rebuild-object/forge/_shared/sdf_primitives.py +172 -0
  23. package/assets/rebuild-object/forge/_shared/spec_search.py +1792 -0
  24. package/assets/rebuild-object/forge/_shared/spec_search_profiles.json +58 -0
  25. package/assets/rebuild-object/forge/_shared/status_banner.py +35 -0
  26. package/assets/rebuild-object/forge/_shared/subdivision.py +232 -0
  27. package/assets/rebuild-object/forge/_shared/vertex_paint.py +236 -0
  28. package/assets/rebuild-object/forge/_shared/workflow_state.py +406 -0
  29. package/assets/rebuild-object/forge/materials/__init__.py +17 -0
  30. package/assets/rebuild-object/forge/materials/compatibility.py +106 -0
  31. package/assets/rebuild-object/forge/materials/reference.py +240 -0
  32. package/assets/rebuild-object/forge/next.py +116 -0
  33. package/assets/rebuild-object/forge/report.py +38 -0
  34. package/assets/rebuild-object/forge/requirements.txt +6 -0
  35. package/assets/rebuild-object/forge/stage1_intake/analyze_texture.py +255 -0
  36. package/assets/rebuild-object/forge/stage1_intake/bind_detail_properties.py +99 -0
  37. package/assets/rebuild-object/forge/stage1_intake/build_detail_inventory.py +349 -0
  38. package/assets/rebuild-object/forge/stage1_intake/camera_fitting_math.py +133 -0
  39. package/assets/rebuild-object/forge/stage1_intake/camera_fitting_solver.py +197 -0
  40. package/assets/rebuild-object/forge/stage1_intake/camera_fitting_types.py +291 -0
  41. package/assets/rebuild-object/forge/stage1_intake/camera_image_helpers.py +133 -0
  42. package/assets/rebuild-object/forge/stage1_intake/check_intake_correctness.py +116 -0
  43. package/assets/rebuild-object/forge/stage1_intake/check_reference_admission.py +203 -0
  44. package/assets/rebuild-object/forge/stage1_intake/cs2_foundation.py +139 -0
  45. package/assets/rebuild-object/forge/stage1_intake/cs2_manifest.py +230 -0
  46. package/assets/rebuild-object/forge/stage1_intake/cs2_review_contract.py +42 -0
  47. package/assets/rebuild-object/forge/stage1_intake/delight_albedo.py +352 -0
  48. package/assets/rebuild-object/forge/stage1_intake/detect_cs2.py +276 -0
  49. package/assets/rebuild-object/forge/stage1_intake/detect_reference_effects.py +275 -0
  50. package/assets/rebuild-object/forge/stage1_intake/extract_cs2_textures.py +126 -0
  51. package/assets/rebuild-object/forge/stage1_intake/extract_gradient_stops.py +149 -0
  52. package/assets/rebuild-object/forge/stage1_intake/extract_hair_evidence.py +385 -0
  53. package/assets/rebuild-object/forge/stage1_intake/extract_landmarks.py +456 -0
  54. package/assets/rebuild-object/forge/stage1_intake/extract_part_color_recipe.py +496 -0
  55. package/assets/rebuild-object/forge/stage1_intake/extract_pbr_evidence.py +843 -0
  56. package/assets/rebuild-object/forge/stage1_intake/fetch_cs2_metadata.py +147 -0
  57. package/assets/rebuild-object/forge/stage1_intake/label_glb_nodes.py +318 -0
  58. package/assets/rebuild-object/forge/stage1_intake/locate_cs2_vpk.py +73 -0
  59. package/assets/rebuild-object/forge/stage1_intake/material_region_analysis.py +227 -0
  60. package/assets/rebuild-object/forge/stage1_intake/probe_glb.py +357 -0
  61. package/assets/rebuild-object/forge/stage1_intake/probe_image.py +168 -0
  62. package/assets/rebuild-object/forge/stage1_intake/run_vision_adapter.py +45 -0
  63. package/assets/rebuild-object/forge/stage1_intake/search_specs.py +258 -0
  64. package/assets/rebuild-object/forge/stage1_intake/semantic_decomposition.py +119 -0
  65. package/assets/rebuild-object/forge/stage1_intake/solve_camera_pose.py +254 -0
  66. package/assets/rebuild-object/forge/stage2_spec/apply_material_analysis.py +192 -0
  67. package/assets/rebuild-object/forge/stage2_spec/cs2_adapters.py +62 -0
  68. package/assets/rebuild-object/forge/stage2_spec/derive_geometry.py +118 -0
  69. package/assets/rebuild-object/forge/stage2_spec/hair_profile.py +306 -0
  70. package/assets/rebuild-object/forge/stage2_spec/humanoid_proportions.py +214 -0
  71. package/assets/rebuild-object/forge/stage2_spec/new_pre_spec_assessment.py +343 -0
  72. package/assets/rebuild-object/forge/stage2_spec/new_sculpt_spec.py +2396 -0
  73. package/assets/rebuild-object/forge/stage2_spec/validate_sculpt_spec.py +2871 -0
  74. package/assets/rebuild-object/forge/stage3_build/bake_projected_texture.py +181 -0
  75. package/assets/rebuild-object/forge/stage3_build/decimate.py +272 -0
  76. package/assets/rebuild-object/forge/stage3_build/generate_threejs_factory.py +4099 -0
  77. package/assets/rebuild-object/forge/stage3_build/module_cache.py +155 -0
  78. package/assets/rebuild-object/forge/stage3_build/morph_targets.py +178 -0
  79. package/assets/rebuild-object/forge/stage3_build/orchestrate_passes.py +653 -0
  80. package/assets/rebuild-object/forge/stage3_build/uv_unwrap.py +622 -0
  81. package/assets/rebuild-object/forge/stage3_build/visual_hull.py +357 -0
  82. package/assets/rebuild-object/forge/stage4_review/_fit_divine_eye.py +64 -0
  83. package/assets/rebuild-object/forge/stage4_review/append_review.py +453 -0
  84. package/assets/rebuild-object/forge/stage4_review/attachment_anchor.py +349 -0
  85. package/assets/rebuild-object/forge/stage4_review/calibrate_eye.py +131 -0
  86. package/assets/rebuild-object/forge/stage4_review/check_part_coverage.py +298 -0
  87. package/assets/rebuild-object/forge/stage4_review/compare_region_passes.py +169 -0
  88. package/assets/rebuild-object/forge/stage4_review/correction_loop.py +258 -0
  89. package/assets/rebuild-object/forge/stage4_review/cs2_review.py +224 -0
  90. package/assets/rebuild-object/forge/stage4_review/diagnose_render.py +356 -0
  91. package/assets/rebuild-object/forge/stage4_review/diagnose_render_multi_angle.py +143 -0
  92. package/assets/rebuild-object/forge/stage4_review/divine_eye.py +461 -0
  93. package/assets/rebuild-object/forge/stage4_review/fit_params.py +381 -0
  94. package/assets/rebuild-object/forge/stage4_review/geometry_integrity.py +294 -0
  95. package/assets/rebuild-object/forge/stage4_review/hair_gate.py +216 -0
  96. package/assets/rebuild-object/forge/stage4_review/interior_difference.py +188 -0
  97. package/assets/rebuild-object/forge/stage4_review/joint_loops.py +209 -0
  98. package/assets/rebuild-object/forge/stage4_review/make_comparison_sheet.py +292 -0
  99. package/assets/rebuild-object/forge/stage4_review/material_comparator.py +181 -0
  100. package/assets/rebuild-object/forge/stage4_review/material_feedback.py +143 -0
  101. package/assets/rebuild-object/forge/stage4_review/material_gate.py +126 -0
  102. package/assets/rebuild-object/forge/stage4_review/material_views.py +184 -0
  103. package/assets/rebuild-object/forge/stage4_review/mesh_reference_compare.py +362 -0
  104. package/assets/rebuild-object/forge/stage4_review/multi_pass.py +102 -0
  105. package/assets/rebuild-object/forge/stage4_review/objectness.py +143 -0
  106. package/assets/rebuild-object/forge/stage4_review/pairwise_penetration.py +376 -0
  107. package/assets/rebuild-object/forge/stage4_review/per_feature.py +215 -0
  108. package/assets/rebuild-object/forge/stage4_review/render_bridge.py +556 -0
  109. package/assets/rebuild-object/forge/stage4_review/scalp_exposure.py +257 -0
  110. package/assets/rebuild-object/forge/stage4_review/self_intersection.py +592 -0
  111. package/assets/rebuild-object/forge/stage4_review/swept_arc_gate.py +336 -0
  112. package/assets/rebuild-object/forge/stage4_review/turntable_gate.py +415 -0
  113. package/assets/rebuild-object/forge/stage4_review/validate_render_profile.py +182 -0
  114. package/assets/rebuild-object/forge/stage4_review/vertex_region_gate.py +456 -0
  115. package/assets/rebuild-object/forge/stage4_review/vlm_gate.py +196 -0
  116. package/assets/rebuild-object/forge/stage5_rig/NOTES.md +149 -0
  117. package/assets/rebuild-object/forge/stage5_rig/__init__.py +6 -0
  118. package/assets/rebuild-object/forge/stage5_rig/emit_rig.py +420 -0
  119. package/assets/rebuild-object/forge/stage5_rig/geodesic_skinning.py +508 -0
  120. package/assets/rebuild-object/forge/stage5_rig/rig_spec.py +174 -0
  121. package/assets/rebuild-object/forge/stage5_rig/validate_rig_payload.py +195 -0
  122. package/assets/rebuild-object/forge/state.py +98 -0
  123. package/assets/rebuild-object/steps.json +381 -0
  124. package/dist/{chunk-FB3UDZAV.js → chunk-24TITAFS.js} +1 -1
  125. package/dist/{chunk-QNWCBPVO.js → chunk-2C5PG2QO.js} +1 -1
  126. package/dist/{chunk-4RYTTD4D.js → chunk-2DEVOKI7.js} +1 -1
  127. package/dist/{chunk-RRI23NK2.js → chunk-2GHPYT2P.js} +1 -1
  128. package/dist/{chunk-QEKVZ7BX.js → chunk-2HXGMXGC.js} +1 -1
  129. package/dist/{chunk-N2UHAQXC.js → chunk-36FORP7T.js} +0 -1
  130. package/dist/{chunk-DH6WPL3X.js → chunk-3IXRQTRF.js} +1 -1
  131. package/dist/{chunk-SXYQL4GK.js → chunk-4YHA32OE.js} +1 -1
  132. package/dist/{chunk-V5ADM3WC.js → chunk-4ZGQKPK5.js} +1 -1
  133. package/dist/{chunk-BJAN3RMY.js → chunk-6CLUPFQA.js} +1 -1
  134. package/dist/{chunk-52E6EKZV.js → chunk-7WTF2BA4.js} +1 -1
  135. package/dist/{chunk-P74GTK23.js → chunk-AAXZNK4Z.js} +1 -1
  136. package/dist/{chunk-F4J6XCHT.js → chunk-ALLBT4FB.js} +1 -1
  137. package/dist/{chunk-HRKVAXNN.js → chunk-BAZDPPIG.js} +5 -5
  138. package/dist/{chunk-RPJR3S5S.js → chunk-CYDENLZ4.js} +5 -8
  139. package/dist/{chunk-I5LELJSK.js → chunk-DKSUD44G.js} +1 -1
  140. package/dist/{chunk-43P4U7CB.js → chunk-DWWSJKTE.js} +1 -1
  141. package/dist/{chunk-6IUFHPMV.js → chunk-E72TFJZP.js} +1 -1
  142. package/dist/{chunk-E3FJUPLT.js → chunk-EUAAQMUA.js} +2 -0
  143. package/dist/{chunk-37LLKM73.js → chunk-F7LYJSZE.js} +1 -1
  144. package/dist/{chunk-MEAO33XW.js → chunk-FMON3C74.js} +8 -8
  145. package/dist/{chunk-YLUB6252.js → chunk-FPILHRLZ.js} +1 -1
  146. package/dist/{chunk-4UU622RK.js → chunk-GGO6ZYYI.js} +1 -3
  147. package/dist/{chunk-2ZKS7V72.js → chunk-GZCRYYS6.js} +5 -5
  148. package/dist/{chunk-E7NDOZ27.js → chunk-LE4GVTYI.js} +8 -8
  149. package/dist/{chunk-UTSSDFQL.js → chunk-NO6KPV64.js} +1 -1
  150. package/dist/{chunk-W2QPNAZ3.js → chunk-NXW3Z4Y4.js} +1 -1
  151. package/dist/{chunk-NG2X3SMF.js → chunk-OHOAZGO4.js} +1 -1
  152. package/dist/chunk-PYJNI5WD.js +83 -0
  153. package/dist/{chunk-VUV5U4J5.js → chunk-Q4XAGTFX.js} +1 -1
  154. package/dist/{chunk-3UGGMFJJ.js → chunk-QMZBSVKF.js} +1 -1
  155. package/dist/{chunk-ABTUEIRC.js → chunk-QO66UBOS.js} +2 -2
  156. package/dist/{chunk-LONQWRTR.js → chunk-S4KVGQQO.js} +8 -8
  157. package/dist/{chunk-FJXPMA63.js → chunk-T777EXAO.js} +1 -1
  158. package/dist/{chunk-YXOGRERG.js → chunk-TZZNRA3S.js} +1 -1
  159. package/dist/{chunk-CTY2WZQK.js → chunk-UC3QLWMQ.js} +1 -1
  160. package/dist/{chunk-MR5KIFI7.js → chunk-UDJH2RED.js} +3 -3
  161. package/dist/{chunk-FNJL6Z5C.js → chunk-UIKYK7KI.js} +1 -1
  162. package/dist/{chunk-PKM3JOKQ.js → chunk-UJRSQO2B.js} +1 -1
  163. package/dist/{chunk-ALPTHSUT.js → chunk-V7LEYVXB.js} +28 -24
  164. package/dist/{chunk-DPLFCKXP.js → chunk-WRMQEXUC.js} +1 -1
  165. package/dist/{chunk-HSMG6U7J.js → chunk-WXSBNC67.js} +3 -9
  166. package/dist/{chunk-HSCTPDEU.js → chunk-X4QIOXNQ.js} +1 -1
  167. package/dist/{chunk-72KHWZMN.js → chunk-Y6WHUK2O.js} +1 -1
  168. package/dist/{chunk-VZEJ2ZHE.js → chunk-Z3E7ORGQ.js} +5 -5
  169. package/dist/index.js +20 -20
  170. package/package.json +32 -22
  171. package/dist/{chunk-OFJIG4K3.js → chunk-4ENHS32B.js} +0 -0
  172. package/dist/{chunk-Q3XQPNF6.js → chunk-BN7TR6OR.js} +3 -3
  173. package/dist/{chunk-LORGE2NB.js → chunk-U2NCN5RO.js} +3 -3
  174. package/dist/{chunk-UPHB5HWO.js → chunk-VQTTSPA3.js} +3 -3
@@ -0,0 +1,456 @@
1
+ #!/usr/bin/env python3
2
+ """Gate colour-region boundaries on executed geometry, before any browser render.
3
+
4
+ WHAT THIS IS FOR. When a subject's identity is carried by flat colour regions with hard boundaries
5
+ -- a tuxedo cat's blaze, bib and socks; a livery stripe; a painted marking -- the position of those
6
+ boundaries is an identity feature, and identity features are gated, not eyeballed. Neither existing
7
+ instrument can do it:
8
+
9
+ - `divine_eye.py` scores a 64x64 luma grid over the whole frame. A bib boundary a few pixels out
10
+ moves a handful of cells and is lost in the global score.
11
+ - `interior_difference.py` measures inside the silhouette, but against a rendered image, so it
12
+ cannot run until a browser has produced pixels -- and by then the spec is already built.
13
+
14
+ This gate runs on exported geometry: world positions plus the vertex colours the model will
15
+ actually be shaded with. It projects those vertices to a review azimuth, computes each colour
16
+ region's 2D bounding box normalised to the model's own projected bounding box, and compares that
17
+ against the box measured on the reference at the same azimuth. Same units on both sides, and no
18
+ renderer involved.
19
+
20
+ WHAT IT DOES NOT SEE, stated because a clean verdict here is not a clean model:
21
+
22
+ - It measures a bounding box, not a shape. A region of the right extent and the wrong outline
23
+ passes. Shape is the visual review's job.
24
+ - It classifies a vertex by matching its colour to the declared palette. Vertices inside a soft
25
+ boundary fringe match nothing and are reported as `unclassifiedFraction` rather than being
26
+ silently assigned. Read that number before believing the verdict.
27
+ - Vertex density is not uniform over a mesh, so `areaFraction` here is a vertex-count fraction and
28
+ is a weaker signal than the box. It is reported, never gated on.
29
+ - A region hidden behind another surface at this azimuth is still measured: these are vertices, not
30
+ pixels, and there is no occlusion test.
31
+
32
+ Exit codes: 0 clean, 1 gate failure, 2 error.
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import argparse
38
+ import json
39
+ import math
40
+ import sys
41
+ from pathlib import Path
42
+ from typing import Any
43
+
44
+ DEFAULT_COLOR_TOLERANCE = 0.06
45
+
46
+
47
+ def _load_json(path: Path, label: str) -> Any:
48
+ try:
49
+ return json.loads(path.read_text(encoding="utf-8"))
50
+ except (OSError, json.JSONDecodeError) as error:
51
+ raise SystemExit(f"{label} error: {error}")
52
+
53
+
54
+ def _hex_to_rgb(value: str) -> tuple[float, float, float]:
55
+ number = int(value.lstrip("#"), 16)
56
+ return (((number >> 16) & 255) / 255.0, ((number >> 8) & 255) / 255.0, (number & 255) / 255.0)
57
+
58
+
59
+ def collect_vertices(geometry: Any) -> list[dict[str, Any]]:
60
+ """Flatten an exported geometry payload into per-mesh position/colour arrays.
61
+
62
+ Accepts the shape `runtime/scripts/export_mesh_geometry.mjs` emits (a list of meshes, each with
63
+ a flat `positions` array) extended with a matching flat `colors` array.
64
+ """
65
+ meshes = geometry.get("meshes") if isinstance(geometry, dict) else geometry
66
+ if not isinstance(meshes, list):
67
+ raise SystemExit("geometry error: expected a list of meshes or {\"meshes\": [...]}")
68
+ out = []
69
+ for index, mesh in enumerate(meshes):
70
+ if not isinstance(mesh, dict):
71
+ continue
72
+ positions = mesh.get("positions") or mesh.get("worldPositions")
73
+ colors = mesh.get("colors")
74
+ if not isinstance(positions, list) or not positions:
75
+ continue
76
+ if len(positions) % 3:
77
+ raise SystemExit(f"geometry error: mesh {index} positions length is not a multiple of 3")
78
+ if colors is not None:
79
+ if not isinstance(colors, list) or len(colors) != len(positions):
80
+ raise SystemExit(
81
+ f"geometry error: mesh {index} colors must be the same length as positions"
82
+ )
83
+ out.append(
84
+ {
85
+ "id": mesh.get("id") or mesh.get("name") or f"mesh-{index}",
86
+ "positions": positions,
87
+ "colors": colors,
88
+ }
89
+ )
90
+ if not out:
91
+ raise SystemExit("geometry error: no mesh carried positions")
92
+ return out
93
+
94
+
95
+ def project(positions: list[float], azimuth_degrees: float) -> list[tuple[float, float]]:
96
+ """Rotate about world Y by -azimuth, then drop Z. Azimuth 0 looks along -Z at the model's front."""
97
+ angle = math.radians(-azimuth_degrees)
98
+ cos_a, sin_a = math.cos(angle), math.sin(angle)
99
+ points = []
100
+ for index in range(0, len(positions), 3):
101
+ x, y, z = positions[index], positions[index + 1], positions[index + 2]
102
+ points.append((x * cos_a + z * sin_a, y))
103
+ return points
104
+
105
+
106
+ def classify(color: tuple[float, float, float], palette: dict[str, tuple[float, float, float]],
107
+ tolerance: float) -> str | None:
108
+ best_id = None
109
+ best_distance = tolerance
110
+ for region_id, target in palette.items():
111
+ distance = math.sqrt(
112
+ (color[0] - target[0]) ** 2 + (color[1] - target[1]) ** 2 + (color[2] - target[2]) ** 2
113
+ )
114
+ if distance <= best_distance:
115
+ best_distance = distance
116
+ best_id = region_id
117
+ return best_id
118
+
119
+
120
+ def measure(
121
+ meshes: list[dict[str, Any]],
122
+ palette: dict[str, tuple[float, float, float]],
123
+ azimuth: float,
124
+ tolerance: float,
125
+ scope: set[str] | None = None,
126
+ ) -> dict[str, Any]:
127
+ """Measure colour regions at one azimuth.
128
+
129
+ `scope` restricts which MESHES contribute region buckets, while the model's projected bounding
130
+ box is always computed from every mesh. Both halves of that matter: a subject can carry the
131
+ same colour in several unrelated places — a tuxedo cat's white is its bib, its four socks and
132
+ its muzzle at once — so colour alone cannot separate them, and the part they sit on can. And
133
+ normalising to the whole model keeps a scoped measurement in the same coordinates as the
134
+ reference box it is compared against, instead of in the scoped part's own frame.
135
+ """
136
+ all_points: list[tuple[float, float]] = []
137
+ labelled: list[tuple[str | None, tuple[float, float]]] = []
138
+ for mesh in meshes:
139
+ points = project(mesh["positions"], azimuth)
140
+ all_points.extend(points)
141
+ if scope is not None and mesh["id"] not in scope and mesh.get("name") not in scope:
142
+ continue
143
+ colors = mesh["colors"]
144
+ for index, point in enumerate(points):
145
+ if colors is None:
146
+ labelled.append((None, point))
147
+ continue
148
+ color = (colors[index * 3], colors[index * 3 + 1], colors[index * 3 + 2])
149
+ labelled.append((classify(color, palette, tolerance), point))
150
+ if not labelled:
151
+ raise SystemExit(
152
+ "geometry error: the requested mesh scope selected no vertices; check the mesh ids"
153
+ )
154
+
155
+ xs = [p[0] for p in all_points]
156
+ ys = [p[1] for p in all_points]
157
+ span_x = max(xs) - min(xs)
158
+ span_y = max(ys) - min(ys)
159
+ if span_x <= 0 or span_y <= 0:
160
+ raise SystemExit("geometry error: projected model has zero extent at this azimuth")
161
+ origin = (min(xs), min(ys))
162
+
163
+ buckets: dict[str, list[tuple[float, float]]] = {}
164
+ unclassified = 0
165
+ for label, point in labelled:
166
+ if label is None:
167
+ unclassified += 1
168
+ continue
169
+ buckets.setdefault(label, []).append(point)
170
+
171
+ regions = {}
172
+ for region_id, points in buckets.items():
173
+ blobs = projected_blobs(points, origin, span_x, span_y)
174
+ rxs = [(p[0] - origin[0]) / span_x for p in points]
175
+ # Image space runs downward while world Y runs up, so the reference's y0 is the model's
176
+ # TOP. Flipping here keeps both sides of every comparison in reference coordinates.
177
+ rys = [1.0 - (p[1] - origin[1]) / span_y for p in points]
178
+ regions[region_id] = {
179
+ "x0": round(min(rxs), 4),
180
+ "x1": round(max(rxs), 4),
181
+ "y0": round(min(rys), 4),
182
+ "y1": round(max(rys), 4),
183
+ "vertexCount": len(points),
184
+ "areaFraction": round(len(points) / len(labelled), 5),
185
+ "blobs": [
186
+ {
187
+ "vertexCount": len(members),
188
+ "centroidX": round(
189
+ sum((points[i][0] - origin[0]) / span_x for i in members) / len(members), 4
190
+ ),
191
+ "centroidY": round(
192
+ sum(1.0 - (points[i][1] - origin[1]) / span_y for i in members)
193
+ / len(members), 4
194
+ ),
195
+ "x0": round(min((points[i][0] - origin[0]) / span_x for i in members), 4),
196
+ "x1": round(max((points[i][0] - origin[0]) / span_x for i in members), 4),
197
+ "y0": round(min(1.0 - (points[i][1] - origin[1]) / span_y for i in members), 4),
198
+ "y1": round(max(1.0 - (points[i][1] - origin[1]) / span_y for i in members), 4),
199
+ }
200
+ for members in blobs
201
+ ],
202
+ }
203
+ return {
204
+ "azimuth": azimuth,
205
+ "projectedExtent": {"width": span_x, "height": span_y},
206
+ "sampledVertexCount": len(labelled),
207
+ "unclassifiedFraction": round(unclassified / len(labelled), 5) if labelled else 1.0,
208
+ "regions": regions,
209
+ }
210
+
211
+
212
+ # The clustering grid is derived from the point count, not fixed.
213
+ #
214
+ # A fixed fine grid does not cluster: neighbouring vertices land in non-adjacent cells and every
215
+ # vertex becomes its own blob — a 288-point fixture split into 24. A fixed coarse grid merges
216
+ # regions that are genuinely apart. Sizing it as sqrt(count)/2 keeps roughly a handful of vertices
217
+ # per occupied cell at any mesh density, which is what connectivity needs.
218
+ MIN_BLOB_GRID = 6
219
+ MAX_BLOB_GRID = 96
220
+
221
+
222
+ def projected_blobs(points: list[tuple[float, float]], origin, span_x, span_y):
223
+ """Split a region's projected points into connected blobs, largest first.
224
+
225
+ WHY. The reference side of every comparison is a connected blob found in the image; once the
226
+ model's parts are FUSED into one mesh, colour alone cannot tell the model's equivalent blobs
227
+ apart. A tuxedo cat's white is its bib, its four socks and its muzzle at once, all one colour
228
+ on one mesh, so the measured "sock" box ran from the muzzle to the ground and the comparison
229
+ was meaningless. Clustering the projection puts both sides on the same instrument.
230
+
231
+ The grid is coarse on purpose: it is a connectivity test, not a shape measurement, and the box
232
+ is still computed from the real point coordinates rather than from grid cells.
233
+ """
234
+ if not points:
235
+ return []
236
+ grid = max(MIN_BLOB_GRID, min(MAX_BLOB_GRID, int(len(points) ** 0.5 / 2)))
237
+ cells: dict[tuple[int, int], list[int]] = {}
238
+ for index, (x, y) in enumerate(points):
239
+ column = min(grid - 1, max(0, int((x - origin[0]) / span_x * grid)))
240
+ row = min(grid - 1, max(0, int((y - origin[1]) / span_y * grid)))
241
+ cells.setdefault((column, row), []).append(index)
242
+
243
+ seen: set[tuple[int, int]] = set()
244
+ blobs = []
245
+ for start in cells:
246
+ if start in seen:
247
+ continue
248
+ stack = [start]
249
+ seen.add(start)
250
+ members: list[int] = []
251
+ while stack:
252
+ cell = stack.pop()
253
+ members.extend(cells[cell])
254
+ for step in ((1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1)):
255
+ neighbour = (cell[0] + step[0], cell[1] + step[1])
256
+ if neighbour in cells and neighbour not in seen:
257
+ seen.add(neighbour)
258
+ stack.append(neighbour)
259
+ blobs.append(members)
260
+ blobs.sort(key=len, reverse=True)
261
+ return blobs
262
+
263
+
264
+ def union_box(regions: dict[str, Any], ids: list[str]) -> dict[str, float] | None:
265
+ present = [regions[region_id] for region_id in ids if region_id in regions]
266
+ if not present:
267
+ return None
268
+ return {
269
+ "x0": min(box["x0"] for box in present),
270
+ "x1": max(box["x1"] for box in present),
271
+ "y0": min(box["y0"] for box in present),
272
+ "y1": max(box["y1"] for box in present),
273
+ }
274
+
275
+
276
+ def evaluate(measured: dict[str, Any], expectations: list[dict[str, Any]]) -> dict[str, Any]:
277
+ """Evaluate expectations against a per-expectation measurement.
278
+
279
+ `measured` may be a single measurement (every expectation reads the same regions) or a mapping
280
+ of expectation id to measurement, which is what a scoped run produces.
281
+ """
282
+ results = []
283
+ failures = 0
284
+ for expectation in expectations:
285
+ ids = expectation.get("regions") or [expectation["id"]]
286
+ tolerance = float(expectation.get("tolerance", 0.04))
287
+ expected = expectation["expected"]
288
+ source = measured.get("byExpectation", {}).get(expectation["id"], measured)
289
+ wanted = expectation.get("blobs")
290
+ spatial = expectation.get("blobFilter")
291
+ if spatial is not None:
292
+ # Selection by a DECLARED spatial fact, not by area rank.
293
+ #
294
+ # Rank is not stable between the two sides: on the reference the bib is the largest
295
+ # white blob, but once the model's legs and paws are fused the four socks merge into
296
+ # one band that is larger still, so rank 0 means the bib on one side and the socks on
297
+ # the other. Measured: every sock comparison was off by -0.45 in y0 and every bib
298
+ # comparison by +0.56 or more, all in the same direction — the signature of a swapped
299
+ # correspondence rather than a misplaced boundary.
300
+ #
301
+ # "the socks are the white below the belly line" is a fact about the subject, stated
302
+ # once, and it is independent of the box being tested — so using it to pick the blob
303
+ # does not make the comparison circular.
304
+ kept = []
305
+ for region_id in ids:
306
+ for blob in source["regions"].get(region_id, {}).get("blobs", []):
307
+ low = spatial.get("centroidYMin", 0.0)
308
+ high = spatial.get("centroidYMax", 1.0)
309
+ if low <= blob["centroidY"] <= high:
310
+ kept.append(blob)
311
+ if not kept:
312
+ results.append({
313
+ "id": expectation["id"], "status": "missing",
314
+ "detail": f"no blob of {ids} has its centroid in {spatial}",
315
+ "availableCentroids": [
316
+ blob["centroidY"]
317
+ for region_id in ids
318
+ for blob in source["regions"].get(region_id, {}).get("blobs", [])
319
+ ],
320
+ })
321
+ failures += 1
322
+ continue
323
+ actual = {
324
+ "x0": min(box["x0"] for box in kept), "x1": max(box["x1"] for box in kept),
325
+ "y0": min(box["y0"] for box in kept), "y1": max(box["y1"] for box in kept),
326
+ }
327
+ elif wanted is None:
328
+ actual = union_box(source["regions"], ids)
329
+ else:
330
+ # Blob selection mirrors how the reference blob was isolated: by connectivity, then by
331
+ # size rank. Naming a blob that does not exist is a failure, not a silent fallback to
332
+ # the whole region.
333
+ boxes = []
334
+ missing = []
335
+ for region_id in ids:
336
+ blobs = source["regions"].get(region_id, {}).get("blobs", [])
337
+ for rank in wanted:
338
+ if rank < len(blobs):
339
+ boxes.append(blobs[rank])
340
+ else:
341
+ missing.append(f"{region_id}[{rank}]")
342
+ if missing or not boxes:
343
+ results.append({
344
+ "id": expectation["id"], "status": "missing",
345
+ "detail": f"requested blobs not present: {missing or ids}",
346
+ "availableBlobCounts": {
347
+ region_id: len(source["regions"].get(region_id, {}).get("blobs", []))
348
+ for region_id in ids
349
+ },
350
+ })
351
+ failures += 1
352
+ continue
353
+ actual = {
354
+ "x0": min(box["x0"] for box in boxes), "x1": max(box["x1"] for box in boxes),
355
+ "y0": min(box["y0"] for box in boxes), "y1": max(box["y1"] for box in boxes),
356
+ }
357
+ if actual is None:
358
+ results.append(
359
+ {
360
+ "id": expectation["id"],
361
+ "status": "missing",
362
+ "detail": f"no vertex carried any of the colours for {ids}",
363
+ }
364
+ )
365
+ failures += 1
366
+ continue
367
+ deltas = {edge: round(actual[edge] - expected[edge], 4) for edge in ("x0", "x1", "y0", "y1")}
368
+ worst = max(abs(value) for value in deltas.values())
369
+ status = "pass" if worst <= tolerance else "fail"
370
+ if status == "fail":
371
+ failures += 1
372
+ results.append(
373
+ {
374
+ "id": expectation["id"],
375
+ "status": status,
376
+ "regions": ids,
377
+ "expected": expected,
378
+ "actual": {edge: round(actual[edge], 4) for edge in ("x0", "x1", "y0", "y1")},
379
+ "deltas": deltas,
380
+ "worstDelta": round(worst, 4),
381
+ "tolerance": tolerance,
382
+ }
383
+ )
384
+ return {"failures": failures, "results": results}
385
+
386
+
387
+ def main(argv: list[str]) -> int:
388
+ parser = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0])
389
+ parser.add_argument("--geometry", type=Path, required=True, help="exported mesh geometry JSON")
390
+ parser.add_argument("--palette", type=Path, required=True,
391
+ help="{regionId: '#rrggbb'} for every region to measure")
392
+ parser.add_argument("--expect", type=Path,
393
+ help="expectation list; without it the gate only reports measurements")
394
+ parser.add_argument("--azimuth", type=float, default=0.0,
395
+ help="review azimuth in degrees; 0 looks at the model's front")
396
+ parser.add_argument("--color-tolerance", type=float, default=DEFAULT_COLOR_TOLERANCE)
397
+ parser.add_argument("--max-unclassified", type=float, default=0.25,
398
+ help="fail if more than this fraction of vertices match no palette colour")
399
+ parser.add_argument("--out", type=Path)
400
+ parser.add_argument("--json", action="store_true")
401
+ args = parser.parse_args(argv)
402
+
403
+ geometry = _load_json(args.geometry, "geometry")
404
+ palette_raw = _load_json(args.palette, "palette")
405
+ if not isinstance(palette_raw, dict) or not palette_raw:
406
+ raise SystemExit("palette error: expected a non-empty {regionId: '#rrggbb'} object")
407
+ palette = {key: _hex_to_rgb(value) for key, value in palette_raw.items()}
408
+
409
+ meshes = collect_vertices(geometry)
410
+ measured = measure(meshes, palette, args.azimuth, args.color_tolerance)
411
+
412
+ report: dict[str, Any] = {"measured": measured, "palette": palette_raw}
413
+ exit_code = 0
414
+ if measured["unclassifiedFraction"] > args.max_unclassified:
415
+ report["unclassifiedVerdict"] = (
416
+ f"{measured['unclassifiedFraction']:.3f} of vertices matched no palette colour, above "
417
+ f"the {args.max_unclassified} limit — the measurement below covers less of the model "
418
+ "than it appears to"
419
+ )
420
+ exit_code = 1
421
+
422
+ if args.expect is not None:
423
+ expectations = _load_json(args.expect, "expectations")
424
+ if not isinstance(expectations, list):
425
+ raise SystemExit("expectations error: expected a list")
426
+ # An expectation may name the meshes it applies to. Each such expectation gets its own
427
+ # scoped measurement, so a white bib is never accidentally satisfied by a white sock.
428
+ by_expectation: dict[str, Any] = {}
429
+ for expectation in expectations:
430
+ scope = expectation.get("meshes")
431
+ if isinstance(scope, list) and scope:
432
+ by_expectation[expectation["id"]] = measure(
433
+ meshes, palette, args.azimuth, args.color_tolerance, scope=set(scope)
434
+ )
435
+ measured["byExpectation"] = by_expectation
436
+ evaluation = evaluate(measured, expectations)
437
+ report["evaluation"] = evaluation
438
+ if evaluation["failures"]:
439
+ exit_code = 1
440
+
441
+ report["exitCode"] = exit_code
442
+ if args.out:
443
+ args.out.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
444
+ if args.json or not args.out:
445
+ print(json.dumps(report, indent=2))
446
+ return exit_code
447
+
448
+
449
+ if __name__ == "__main__":
450
+ try:
451
+ raise SystemExit(main(sys.argv[1:]))
452
+ except SystemExit as exit_error:
453
+ if isinstance(exit_error.code, str):
454
+ print(exit_error.code, file=sys.stderr)
455
+ raise SystemExit(2)
456
+ raise
@@ -0,0 +1,196 @@
1
+ #!/usr/bin/env python3
2
+ """VLM gating layer (Plan 1.3 §3.4) — the model as gated, calibrated, cross-checked lubricant.
3
+
4
+ The VLM is the ONLY place a model opinion enters the Divine Eye, and it is deliberately
5
+ subordinate to the deterministic ensemble (divine_eye.py). This module encodes the RULES
6
+ around the model so a wrong/overconfident model verdict cannot mislead the generator:
7
+
8
+ 1. The VLM NEVER runs on a render that failed a deterministic HARD gate. A geometrically
9
+ broken render is rejected by math; asking the model about it only invites a confident-
10
+ but-wrong "looks fine". (Reliability property, not a token optimization.)
11
+ 2. Multi-sample self-consistency voting: sample the VLM N times, aggregate (median), and
12
+ treat high spread across samples as an uncertainty signal → probe, never a coin-flip.
13
+ 3. Post-hoc score calibration: raw VLM scores are remapped through a monotonic calibration
14
+ fitted on the §5 corpus (true temperature scaling is impossible without logits). Default
15
+ is identity until calibration data exists.
16
+ 4. Evidence cross-check: the VLM's claimed object class is checked against the deterministic
17
+ geometric descriptor; a contradiction flags the verdict uncertain (the model's semantics
18
+ must not override measured geometry).
19
+ 5. Hard vs soft: the VLM can NEVER grant past a hard geometric failure (it doesn't even run
20
+ then), but it CAN rescue a SOFT near-threshold reject when its criteria + evidence agree.
21
+
22
+ The actual VLM call is INJECTED as `vlm_sampler` (a callable), so this whole layer is
23
+ deterministic + testable with a stub — no real model, no token, in tests. Pure stdlib.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import argparse
29
+ import json
30
+ import sys
31
+ from pathlib import Path
32
+ from typing import Any, Callable
33
+
34
+ CRITERIA = ("objectness", "semantic", "structural", "specular")
35
+ DEFAULT_CRITERIA_MIN = 0.80
36
+ VARIANCE_SPREAD_MAX = 0.20 # spread across samples above this ⇒ uncertain → probe
37
+
38
+
39
+ def _median(xs: list[float]) -> float:
40
+ if not xs:
41
+ return 0.0
42
+ s = sorted(xs)
43
+ m = len(s) // 2
44
+ return s[m] if len(s) % 2 else 0.5 * (s[m - 1] + s[m])
45
+
46
+
47
+ def aggregate_samples(samples: list[dict]) -> dict[str, Any]:
48
+ """Median per criterion + the worst (max) per-criterion spread across samples."""
49
+ agg: dict[str, float] = {}
50
+ max_spread = 0.0
51
+ for crit in CRITERIA:
52
+ vals = [float(s.get(crit, 0.0)) for s in samples]
53
+ agg[crit] = _median(vals)
54
+ if vals:
55
+ max_spread = max(max_spread, max(vals) - min(vals))
56
+ # majority claimed class (ties → first seen)
57
+ classes = [s.get("claimedClass") for s in samples if s.get("claimedClass")]
58
+ claimed = None
59
+ if classes:
60
+ counts: dict[str, int] = {}
61
+ for c in classes:
62
+ counts[c] = counts.get(c, 0) + 1
63
+ claimed = max(counts, key=lambda k: counts[k])
64
+ return {"criteria": agg, "maxSpread": max_spread, "claimedClass": claimed}
65
+
66
+
67
+ def calibrate(score: float, calibration: list[list[float]] | None = None) -> float:
68
+ """Monotonic piecewise-linear remap fitted on the §5 corpus. `calibration` is a sorted
69
+ list of [raw, calibrated] control points. Default (None) is identity."""
70
+ if not calibration:
71
+ return score
72
+ pts = sorted(calibration, key=lambda p: p[0])
73
+ if score <= pts[0][0]:
74
+ return pts[0][1]
75
+ if score >= pts[-1][0]:
76
+ return pts[-1][1]
77
+ for i in range(1, len(pts)):
78
+ x0, y0 = pts[i - 1]
79
+ x1, y1 = pts[i]
80
+ if x0 <= score <= x1:
81
+ t = 0.0 if x1 == x0 else (score - x0) / (x1 - x0)
82
+ return y0 + t * (y1 - y0)
83
+ return score
84
+
85
+
86
+ def evidence_consistent(vlm_class: str | None, geometry_class: str | None) -> bool:
87
+ """True if the VLM's claimed class does not contradict the deterministic geometry
88
+ descriptor. Unknown geometry (None) cannot contradict → consistent."""
89
+ if not vlm_class or not geometry_class:
90
+ return True
91
+ return vlm_class.strip().lower() == geometry_class.strip().lower()
92
+
93
+
94
+ def gate(
95
+ eye_result: dict[str, Any],
96
+ vlm_sampler: Callable[[int], dict] | None,
97
+ n_samples: int = 3,
98
+ criteria_min: float = DEFAULT_CRITERIA_MIN,
99
+ calibration: list[list[float]] | None = None,
100
+ geometry_class: str | None = None,
101
+ ) -> dict[str, Any]:
102
+ """Decide the final verdict given the deterministic Eye result + an (injected) VLM sampler."""
103
+ hard_failures = eye_result.get("hardGateFailures") or []
104
+ if hard_failures:
105
+ # RULE 1: never consult the VLM on a hard-gate failure.
106
+ return {
107
+ "verdict": "reject",
108
+ "action": "refine-code",
109
+ "ranVlm": False,
110
+ "reason": f"deterministic hard gate failed ({'; '.join(hard_failures)}); VLM not consulted",
111
+ }
112
+
113
+ if vlm_sampler is None:
114
+ # No VLM available: fall back to the deterministic verdict unchanged.
115
+ return {
116
+ "verdict": eye_result.get("verdict", "reject"),
117
+ "action": eye_result.get("action", "refine-code"),
118
+ "ranVlm": False,
119
+ "reason": "no VLM sampler provided; deterministic verdict stands",
120
+ }
121
+
122
+ samples = [vlm_sampler(i) for i in range(max(1, n_samples))]
123
+ agg = aggregate_samples(samples)
124
+ calibrated = {c: calibrate(agg["criteria"].get(c, 0.0), calibration) for c in CRITERIA}
125
+
126
+ # RULE 2: high spread across samples ⇒ uncertain → probe.
127
+ if agg["maxSpread"] > VARIANCE_SPREAD_MAX:
128
+ return {
129
+ "verdict": "uncertain", "action": "probe", "ranVlm": True,
130
+ "criteria": calibrated, "maxSpread": agg["maxSpread"],
131
+ "reason": f"VLM sample spread {agg['maxSpread']:.2f} > {VARIANCE_SPREAD_MAX} (unstable opinion)",
132
+ }
133
+ # RULE 4: evidence cross-check against geometry.
134
+ if not evidence_consistent(agg.get("claimedClass"), geometry_class):
135
+ return {
136
+ "verdict": "uncertain", "action": "probe", "ranVlm": True,
137
+ "criteria": calibrated, "claimedClass": agg.get("claimedClass"),
138
+ "reason": f"VLM claimed {agg.get('claimedClass')!r} contradicts geometry {geometry_class!r}",
139
+ }
140
+
141
+ below = {c: v for c, v in calibrated.items() if v < criteria_min}
142
+ if not below:
143
+ # All criteria satisfied. Confirm a pass, or RESCUE a soft near-threshold reject.
144
+ eye_verdict = eye_result.get("verdict")
145
+ rescued = eye_verdict in ("low-confidence", "reject") # soft (no hard failure — checked above)
146
+ return {
147
+ "verdict": "pass", "action": "continue", "ranVlm": True,
148
+ "criteria": calibrated,
149
+ "reason": ("VLM criteria all ≥ min; soft-reject rescued (deterministic hard gates already passed)"
150
+ if rescued else "VLM criteria all ≥ min; pass confirmed"),
151
+ }
152
+
153
+ # RULE 5: a criterion is below min → withhold. Route by which criterion.
154
+ conceptual = any(c in below for c in ("objectness", "semantic"))
155
+ return {
156
+ "verdict": "withhold",
157
+ "action": "refine-spec" if conceptual else "refine-code",
158
+ "ranVlm": True,
159
+ "criteria": calibrated,
160
+ "below": below,
161
+ "reason": ("VLM objectness/semantic below min (conceptual — spec wrong)"
162
+ if conceptual else "VLM structural/specular below min (execution — code wrong)"),
163
+ }
164
+
165
+
166
+ def main(argv: list[str]) -> int:
167
+ parser = argparse.ArgumentParser(description=__doc__)
168
+ parser.add_argument("--eye", required=True, type=Path, help="divine_eye result JSON")
169
+ parser.add_argument("--samples", type=Path, help="JSON list of VLM sample dicts (offline/testing)")
170
+ parser.add_argument("--geometry-class", default=None)
171
+ parser.add_argument("--criteria-min", type=float, default=DEFAULT_CRITERIA_MIN)
172
+ parser.add_argument("--json", action="store_true")
173
+ args = parser.parse_args(argv)
174
+ try:
175
+ eye = json.loads(args.eye.read_text(encoding="utf-8"))
176
+ sampler = None
177
+ preloaded = None
178
+ if args.samples:
179
+ preloaded = json.loads(args.samples.read_text(encoding="utf-8"))
180
+ if not isinstance(preloaded, list) or not preloaded:
181
+ raise ValueError("--samples must contain a non-empty JSON list")
182
+ if not all(isinstance(sample, dict) for sample in preloaded):
183
+ raise ValueError("--samples entries must be JSON objects")
184
+ sampler = lambda i: preloaded[i % len(preloaded)] # noqa: E731
185
+ result = gate(eye, sampler, n_samples=len(preloaded) if preloaded else 3,
186
+ criteria_min=args.criteria_min, geometry_class=args.geometry_class)
187
+ except Exception as exc: # noqa: BLE001
188
+ print(f"error: {exc}", file=sys.stderr)
189
+ return 2
190
+ print(json.dumps(result, indent=2, ensure_ascii=False) if args.json
191
+ else f"{result['verdict'].upper()} → {result['action']} (ranVlm={result['ranVlm']})")
192
+ return 0 if result["verdict"] == "pass" else 1
193
+
194
+
195
+ if __name__ == "__main__":
196
+ raise SystemExit(main(sys.argv[1:]))