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,254 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Estimate a starting referenceCamera block for a reference image.
|
|
3
|
+
|
|
4
|
+
This is not camera calibration and it does not solve for the true focal
|
|
5
|
+
length, sensor, or 6-DoF pose that produced the photo. A single 2D image
|
|
6
|
+
under-constrains that problem. Instead this script emits a reasonable
|
|
7
|
+
default guess (FOV) plus image-derived facts (aspect ratio) and explicit
|
|
8
|
+
agent-fill placeholders (orientation, position) that the agent is expected
|
|
9
|
+
to refine by rendering the fitted mesh from this camera and visually
|
|
10
|
+
overlaying it against the reference image until silhouettes line up. The
|
|
11
|
+
`agentFill` flag on each field marks what still needs that visual pass.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import argparse
|
|
17
|
+
import json
|
|
18
|
+
import math
|
|
19
|
+
import sys
|
|
20
|
+
from collections.abc import Sequence
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
|
|
23
|
+
if __package__:
|
|
24
|
+
from . import camera_fitting_math as _math
|
|
25
|
+
from . import camera_fitting_solver as _solver
|
|
26
|
+
from . import camera_fitting_types as _types
|
|
27
|
+
from . import camera_image_helpers as _images
|
|
28
|
+
else:
|
|
29
|
+
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
|
30
|
+
from forge.stage1_intake import camera_fitting_math as _math
|
|
31
|
+
from forge.stage1_intake import camera_fitting_solver as _solver
|
|
32
|
+
from forge.stage1_intake import camera_fitting_types as _types
|
|
33
|
+
from forge.stage1_intake import camera_image_helpers as _images
|
|
34
|
+
|
|
35
|
+
CONVERGED_RMS_PIXELS = _types.CONVERGED_RMS_PIXELS
|
|
36
|
+
DEFAULT_MAXIMUM_DAMPING_RETRIES = _types.DEFAULT_MAXIMUM_DAMPING_RETRIES
|
|
37
|
+
DEFAULT_MAXIMUM_ITERATIONS = _types.DEFAULT_MAXIMUM_ITERATIONS
|
|
38
|
+
FINITE_DIFFERENCE_STEPS = _types.FINITE_DIFFERENCE_STEPS
|
|
39
|
+
INITIAL_DAMPING = _types.INITIAL_DAMPING
|
|
40
|
+
MAXIMUM_DAMPING = _types.MAXIMUM_DAMPING
|
|
41
|
+
MAXIMUM_FOV_DEGREES = _types.MAXIMUM_FOV_DEGREES
|
|
42
|
+
MINIMUM_CAMERA_DEPTH = _types.MINIMUM_CAMERA_DEPTH
|
|
43
|
+
MINIMUM_CORRESPONDENCES = _types.MINIMUM_CORRESPONDENCES
|
|
44
|
+
MINIMUM_FOV_DEGREES = _types.MINIMUM_FOV_DEGREES
|
|
45
|
+
CameraFitDescriptor = _types.CameraFitDescriptor
|
|
46
|
+
CameraInitialization = _types.CameraInitialization
|
|
47
|
+
CameraParameters = _types.CameraParameters
|
|
48
|
+
DegenerateCorrespondencesError = _types.DegenerateCorrespondencesError
|
|
49
|
+
FitCameraParameters = _types.FitCameraParameters
|
|
50
|
+
InsufficientCorrespondencesError = _types.InsufficientCorrespondencesError
|
|
51
|
+
InvalidCameraDimensionsError = _types.InvalidCameraDimensionsError
|
|
52
|
+
InvalidInitialCameraError = _types.InvalidInitialCameraError
|
|
53
|
+
LandmarkCorrespondence = _types.LandmarkCorrespondence
|
|
54
|
+
NonFiniteCameraInputError = _types.NonFiniteCameraInputError
|
|
55
|
+
NormalizedCorrespondence = _types.NormalizedCorrespondence
|
|
56
|
+
ResidualDiagnostic = _types.ResidualDiagnostic
|
|
57
|
+
ScalarField = _types.ScalarField
|
|
58
|
+
SolverLimits = _types.SolverLimits
|
|
59
|
+
bmp_size = _images.bmp_size
|
|
60
|
+
build_camera = _images.build_camera
|
|
61
|
+
clamp = _images.clamp
|
|
62
|
+
detect_size = _images.detect_size
|
|
63
|
+
estimate_fov = _images.estimate_fov
|
|
64
|
+
gif_size = _images.gif_size
|
|
65
|
+
jpeg_size = _images.jpeg_size
|
|
66
|
+
png_size = _images.png_size
|
|
67
|
+
webp_size = _images.webp_size
|
|
68
|
+
|
|
69
|
+
# Mutable public seams retained for deterministic test callers.
|
|
70
|
+
MAXIMUM_ITERATIONS = DEFAULT_MAXIMUM_ITERATIONS
|
|
71
|
+
MAXIMUM_DAMPING_RETRIES = DEFAULT_MAXIMUM_DAMPING_RETRIES
|
|
72
|
+
|
|
73
|
+
__all__ = [
|
|
74
|
+
"CONVERGED_RMS_PIXELS",
|
|
75
|
+
"FINITE_DIFFERENCE_STEPS",
|
|
76
|
+
"INITIAL_DAMPING",
|
|
77
|
+
"MAXIMUM_DAMPING",
|
|
78
|
+
"MAXIMUM_DAMPING_RETRIES",
|
|
79
|
+
"MAXIMUM_FOV_DEGREES",
|
|
80
|
+
"MAXIMUM_ITERATIONS",
|
|
81
|
+
"MINIMUM_CAMERA_DEPTH",
|
|
82
|
+
"MINIMUM_CORRESPONDENCES",
|
|
83
|
+
"MINIMUM_FOV_DEGREES",
|
|
84
|
+
"CameraFitDescriptor",
|
|
85
|
+
"CameraInitialization",
|
|
86
|
+
"DegenerateCorrespondencesError",
|
|
87
|
+
"InsufficientCorrespondencesError",
|
|
88
|
+
"InvalidCameraDimensionsError",
|
|
89
|
+
"InvalidInitialCameraError",
|
|
90
|
+
"LandmarkCorrespondence",
|
|
91
|
+
"NonFiniteCameraInputError",
|
|
92
|
+
"bmp_size",
|
|
93
|
+
"build_camera",
|
|
94
|
+
"clamp",
|
|
95
|
+
"detect_size",
|
|
96
|
+
"estimate_fov",
|
|
97
|
+
"fit_camera_to_correspondences",
|
|
98
|
+
"gif_size",
|
|
99
|
+
"jpeg_size",
|
|
100
|
+
"main",
|
|
101
|
+
"png_size",
|
|
102
|
+
"webp_size",
|
|
103
|
+
]
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def fit_camera_to_correspondences(
|
|
107
|
+
correspondences: Sequence[LandmarkCorrespondence],
|
|
108
|
+
*,
|
|
109
|
+
initial_camera: CameraInitialization,
|
|
110
|
+
) -> CameraFitDescriptor:
|
|
111
|
+
"""Fit the seven-DOF camera model after parsing all public numerical input."""
|
|
112
|
+
normalized = _types.normalize_fit_input(correspondences, initial_camera)
|
|
113
|
+
if _math.has_degenerate_world_geometry(normalized.correspondences):
|
|
114
|
+
raise DegenerateCorrespondencesError(correspondence_count=len(normalized.correspondences))
|
|
115
|
+
initial_residuals = _math.residual_components(normalized.correspondences, normalized.initial_camera)
|
|
116
|
+
if initial_residuals is None:
|
|
117
|
+
raise _invalid_initial_camera_error(normalized.correspondences, normalized.initial_camera)
|
|
118
|
+
initial_error = _math.rms_reprojection_error(initial_residuals)
|
|
119
|
+
fit_state = _solver.fit_parameters(normalized.correspondences, normalized.initial_camera, _solver_limits())
|
|
120
|
+
fitted_camera = _camera_parameters_payload(fit_state.parameters)
|
|
121
|
+
residuals = _residual_diagnostics(normalized.correspondences, fit_state.parameters)
|
|
122
|
+
final_error = math.sqrt(sum(item["errorPixels"] * item["errorPixels"] for item in residuals) / len(residuals))
|
|
123
|
+
return {
|
|
124
|
+
"version": "1.0",
|
|
125
|
+
"sourceImage": "landmark-correspondences",
|
|
126
|
+
"solver": "stage1_intake/solve_camera_pose.py",
|
|
127
|
+
"method": "numerical-landmark-fit",
|
|
128
|
+
"imageWidth": fit_state.parameters.image_width,
|
|
129
|
+
"imageHeight": fit_state.parameters.image_height,
|
|
130
|
+
"fovDegrees": {
|
|
131
|
+
"value": fitted_camera["fovDegrees"],
|
|
132
|
+
"source": "numerical-landmark-fit",
|
|
133
|
+
"agentFill": False,
|
|
134
|
+
"rationale": "fitted from ordered 3D-to-2D landmark correspondences",
|
|
135
|
+
},
|
|
136
|
+
"aspect": {
|
|
137
|
+
"value": fit_state.parameters.image_width / fit_state.parameters.image_height,
|
|
138
|
+
"source": "initial-camera-image-dimensions",
|
|
139
|
+
"agentFill": False,
|
|
140
|
+
},
|
|
141
|
+
"orientation": {
|
|
142
|
+
"yawDegrees": _fitted_scalar(fitted_camera["yawDegrees"]),
|
|
143
|
+
"pitchDegrees": _fitted_scalar(fitted_camera["pitchDegrees"]),
|
|
144
|
+
"rollDegrees": _fitted_scalar(fitted_camera["rollDegrees"]),
|
|
145
|
+
"note": "Fitted using pitch, yaw, then roll rotations matching the stage-1 projection convention.",
|
|
146
|
+
},
|
|
147
|
+
"position": {
|
|
148
|
+
"hint": fitted_camera["position"],
|
|
149
|
+
"distance": _fitted_scalar(fitted_camera["position"][2]),
|
|
150
|
+
"note": "Fitted camera position in the existing scene-coordinate convention.",
|
|
151
|
+
},
|
|
152
|
+
"confidence": 0.95 if fit_state.status == "converged" else 0.5,
|
|
153
|
+
"limitations": [
|
|
154
|
+
"The fit holds image dimensions and principal point fixed from the initialization.",
|
|
155
|
+
"The fit does not estimate lens distortion, sensor size, or a multi-view reconstruction.",
|
|
156
|
+
],
|
|
157
|
+
"note": "Residuals are recomputed from the emitted cameraParameters descriptor in correspondence input order.",
|
|
158
|
+
"fit": {
|
|
159
|
+
"method": "central-difference-damped-least-squares",
|
|
160
|
+
"cameraParameters": fitted_camera,
|
|
161
|
+
"initialReprojectionError": initial_error,
|
|
162
|
+
"finalReprojectionError": final_error,
|
|
163
|
+
"residuals": residuals,
|
|
164
|
+
"convergence": {
|
|
165
|
+
"status": fit_state.status,
|
|
166
|
+
"iterations": fit_state.iterations,
|
|
167
|
+
"acceptedSteps": fit_state.accepted_steps,
|
|
168
|
+
"rejectedSteps": fit_state.rejected_steps,
|
|
169
|
+
"damping": fit_state.damping,
|
|
170
|
+
},
|
|
171
|
+
},
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _solver_limits() -> SolverLimits:
|
|
176
|
+
return SolverLimits(
|
|
177
|
+
maximum_iterations=MAXIMUM_ITERATIONS,
|
|
178
|
+
maximum_damping_retries=MAXIMUM_DAMPING_RETRIES,
|
|
179
|
+
initial_damping=INITIAL_DAMPING,
|
|
180
|
+
maximum_damping=MAXIMUM_DAMPING,
|
|
181
|
+
converged_rms_pixels=CONVERGED_RMS_PIXELS,
|
|
182
|
+
finite_difference_steps=FINITE_DIFFERENCE_STEPS,
|
|
183
|
+
)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _invalid_initial_camera_error(
|
|
187
|
+
correspondences: Sequence[NormalizedCorrespondence], camera: CameraParameters
|
|
188
|
+
) -> InvalidInitialCameraError:
|
|
189
|
+
for correspondence in correspondences:
|
|
190
|
+
if _math.project_landmark(correspondence.world, camera) is None:
|
|
191
|
+
return InvalidInitialCameraError(correspondence_name=correspondence.name)
|
|
192
|
+
return InvalidInitialCameraError(correspondence_name=correspondences[0].name)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _camera_parameters_payload(camera: CameraParameters) -> FitCameraParameters:
|
|
196
|
+
return {
|
|
197
|
+
"fovDegrees": camera.fov_degrees,
|
|
198
|
+
"yawDegrees": camera.yaw_degrees,
|
|
199
|
+
"pitchDegrees": camera.pitch_degrees,
|
|
200
|
+
"rollDegrees": camera.roll_degrees,
|
|
201
|
+
"position": [camera.position[0], camera.position[1], camera.position[2]],
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _fitted_scalar(value: float) -> ScalarField:
|
|
206
|
+
return {"value": value, "source": "numerical-landmark-fit", "agentFill": False}
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _residual_diagnostics(
|
|
210
|
+
correspondences: Sequence[NormalizedCorrespondence], camera: CameraParameters
|
|
211
|
+
) -> list[ResidualDiagnostic]:
|
|
212
|
+
diagnostics: list[ResidualDiagnostic] = []
|
|
213
|
+
for correspondence in correspondences:
|
|
214
|
+
projected = _math.project_landmark(correspondence.world, camera)
|
|
215
|
+
if projected is None:
|
|
216
|
+
raise _invalid_initial_camera_error(correspondences, camera)
|
|
217
|
+
diagnostics.append(
|
|
218
|
+
{
|
|
219
|
+
"name": correspondence.name,
|
|
220
|
+
"errorPixels": math.hypot(
|
|
221
|
+
projected[0] - correspondence.observed[0],
|
|
222
|
+
projected[1] - correspondence.observed[1],
|
|
223
|
+
),
|
|
224
|
+
}
|
|
225
|
+
)
|
|
226
|
+
return diagnostics
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def main(argv: list[str]) -> int:
|
|
230
|
+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
231
|
+
parser.add_argument("image", type=Path)
|
|
232
|
+
parser.add_argument("--fov-degrees", type=float, default=None, help="Override the default FOV guess")
|
|
233
|
+
parser.add_argument("--yaw", type=float, default=0.0, help="Orientation placeholder, degrees")
|
|
234
|
+
parser.add_argument("--pitch", type=float, default=0.0, help="Orientation placeholder, degrees")
|
|
235
|
+
parser.add_argument("--roll", type=float, default=0.0, help="Orientation placeholder, degrees")
|
|
236
|
+
parser.add_argument("--distance", type=float, default=None, help="Camera distance hint, scene units")
|
|
237
|
+
parser.add_argument("--height-offset", type=float, default=0.0, help="Camera Y offset hint, scene units")
|
|
238
|
+
parser.add_argument("--out", type=Path, help="Write the referenceCamera JSON block to this path")
|
|
239
|
+
args = parser.parse_args(argv)
|
|
240
|
+
image = args.image.expanduser().resolve()
|
|
241
|
+
if not image.exists():
|
|
242
|
+
parser.error(f"{image} does not exist")
|
|
243
|
+
camera = build_camera(image, args)
|
|
244
|
+
text = json.dumps({"referenceCamera": camera}, indent=2, ensure_ascii=False)
|
|
245
|
+
if args.out:
|
|
246
|
+
out_path = args.out.expanduser().resolve()
|
|
247
|
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
248
|
+
out_path.write_text(text + "\n", encoding="utf-8")
|
|
249
|
+
print(text)
|
|
250
|
+
return 0
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
if __name__ == "__main__":
|
|
254
|
+
raise SystemExit(main(sys.argv[1:]))
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Apply region-level material analysis to an ObjectSculptSpec.
|
|
3
|
+
|
|
4
|
+
This is the Phase 7 hand-off: analyzer output is copied with provenance into
|
|
5
|
+
the spec, profile priors become explicit candidate scalars, and components are
|
|
6
|
+
bound to the resolved material region. Existing specs remain valid when this
|
|
7
|
+
field is absent.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import argparse
|
|
13
|
+
import copy
|
|
14
|
+
import json
|
|
15
|
+
import sys
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
SCALAR_FIELDS = (
|
|
21
|
+
"metalness", "roughness", "clearcoat", "clearcoatRoughness", "ior",
|
|
22
|
+
"anisotropy", "sheen", "sheenRoughness", "transmission", "dispersion",
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _layer(existing: Any, value: Any) -> dict[str, Any]:
|
|
27
|
+
result = dict(existing) if isinstance(existing, dict) else {}
|
|
28
|
+
result["base"] = value
|
|
29
|
+
result.setdefault("variation", 0.0)
|
|
30
|
+
return result
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def apply_material_analysis(
|
|
34
|
+
spec: dict[str, Any],
|
|
35
|
+
analysis: dict[str, Any],
|
|
36
|
+
*,
|
|
37
|
+
allow_probe: bool = False,
|
|
38
|
+
) -> dict[str, Any]:
|
|
39
|
+
if not isinstance(spec, dict) or not isinstance(analysis, dict):
|
|
40
|
+
raise ValueError("spec and analysis must be JSON objects")
|
|
41
|
+
regions = analysis.get("regions")
|
|
42
|
+
if not isinstance(regions, list) or not regions:
|
|
43
|
+
raise ValueError("analysis.regions must be a non-empty array")
|
|
44
|
+
statuses = {str(item.get("assignment", {}).get("status")) for item in regions if isinstance(item, dict)}
|
|
45
|
+
analysis_status = str(analysis.get("status", "probe"))
|
|
46
|
+
unresolved_not_observed = analysis.get("unresolvedNotObservedMaterials", [])
|
|
47
|
+
if not isinstance(unresolved_not_observed, list):
|
|
48
|
+
raise ValueError("analysis.unresolvedNotObservedMaterials must be an array")
|
|
49
|
+
if analysis_status != "proceed" and not allow_probe:
|
|
50
|
+
raise ValueError("material analysis is not proceed; review unresolved material regions before wiring")
|
|
51
|
+
if not allow_probe and statuses - {"proceed"}:
|
|
52
|
+
raise ValueError("material analysis contains probe/unknown regions; pass --allow-probe after review")
|
|
53
|
+
materials = spec.setdefault("materials", [])
|
|
54
|
+
if not isinstance(materials, list):
|
|
55
|
+
raise ValueError("spec.materials must be an array")
|
|
56
|
+
components = spec.setdefault("componentTree", [])
|
|
57
|
+
if not isinstance(components, list):
|
|
58
|
+
raise ValueError("spec.componentTree must be an array")
|
|
59
|
+
by_material = {str(item.get("id")): item for item in materials if isinstance(item, dict) and item.get("id")}
|
|
60
|
+
by_component = {str(item.get("id")): item for item in components if isinstance(item, dict) and item.get("id")}
|
|
61
|
+
applied: list[dict[str, Any]] = []
|
|
62
|
+
for region in regions:
|
|
63
|
+
if not isinstance(region, dict):
|
|
64
|
+
raise ValueError("analysis region must be an object")
|
|
65
|
+
assignment = region.get("assignment")
|
|
66
|
+
if not isinstance(assignment, dict) or not assignment.get("profileId"):
|
|
67
|
+
raise ValueError(f"region {region.get('regionId')!r} has no resolved profile")
|
|
68
|
+
spec_material_id = str(region.get("materialSpecId") or region.get("regionId"))
|
|
69
|
+
material = by_material.get(spec_material_id)
|
|
70
|
+
if material is None:
|
|
71
|
+
material = {"id": spec_material_id, "baseColor": "#FFFFFF"}
|
|
72
|
+
materials.append(material)
|
|
73
|
+
by_material[spec_material_id] = material
|
|
74
|
+
profile_id = str(assignment["profileId"])
|
|
75
|
+
material["referenceMaterialId"] = profile_id
|
|
76
|
+
material["materialFamily"] = assignment.get("family")
|
|
77
|
+
material["materialSubtype"] = assignment.get("subtype")
|
|
78
|
+
material["materialFinish"] = assignment.get("finish")
|
|
79
|
+
material["materialReference"] = {
|
|
80
|
+
"registry": analysis.get("registry"),
|
|
81
|
+
"profileId": profile_id,
|
|
82
|
+
"method": assignment.get("method"),
|
|
83
|
+
"confidence": assignment.get("confidence"),
|
|
84
|
+
"sourceRefs": copy.deepcopy(assignment.get("sourceRefs", [])),
|
|
85
|
+
"requiredMaps": copy.deepcopy(assignment.get("requiredMaps", [])),
|
|
86
|
+
"optionalMaps": copy.deepcopy(assignment.get("optionalMaps", [])),
|
|
87
|
+
"validationViews": copy.deepcopy(assignment.get("validationViews", [])),
|
|
88
|
+
}
|
|
89
|
+
for field, value in assignment.get("renderPrior", {}).items():
|
|
90
|
+
if field in SCALAR_FIELDS and isinstance(value, (int, float)):
|
|
91
|
+
material[field] = _layer(material.get(field), value)
|
|
92
|
+
material.setdefault("textureResolution", 1024)
|
|
93
|
+
material.setdefault("textureProjection", {
|
|
94
|
+
"mode": "uv",
|
|
95
|
+
"repeat": [1, 1],
|
|
96
|
+
"anisotropy": 8,
|
|
97
|
+
"colorSpace": "SRGBColorSpace for albedo; NoColorSpace for scalar/normal maps",
|
|
98
|
+
"mapBindings": copy.deepcopy(assignment.get("requiredMaps", [])),
|
|
99
|
+
})
|
|
100
|
+
pbr = region.get("referencePbr")
|
|
101
|
+
if isinstance(pbr, dict):
|
|
102
|
+
material["referencePbr"] = copy.deepcopy(pbr)
|
|
103
|
+
texture_analysis = region.get("textureAnalysis")
|
|
104
|
+
if isinstance(texture_analysis, dict):
|
|
105
|
+
material["textureAnalysis"] = copy.deepcopy(texture_analysis)
|
|
106
|
+
material["materialEvidence"] = {
|
|
107
|
+
"componentId": region.get("componentId"),
|
|
108
|
+
"regionId": region.get("regionId"),
|
|
109
|
+
"crop": copy.deepcopy(region.get("crop")),
|
|
110
|
+
"observations": copy.deepcopy(region.get("observations", [])),
|
|
111
|
+
"hypothesis": copy.deepcopy(region.get("hypothesis", {})),
|
|
112
|
+
"alternatives": copy.deepcopy(assignment.get("alternatives", [])),
|
|
113
|
+
}
|
|
114
|
+
if assignment.get("family") in {"metal", "glass", "gemstone"}:
|
|
115
|
+
material["needsEnvironment"] = True
|
|
116
|
+
component = by_component.get(str(region.get("componentId")))
|
|
117
|
+
if component is not None:
|
|
118
|
+
component["material"] = spec_material_id
|
|
119
|
+
component.setdefault("uvContract", {
|
|
120
|
+
"status": "unwrapped",
|
|
121
|
+
"strategy": "generated procedural coordinates",
|
|
122
|
+
"materialId": spec_material_id,
|
|
123
|
+
})
|
|
124
|
+
component.setdefault("materialRegions", []).append({
|
|
125
|
+
"regionId": region.get("regionId"),
|
|
126
|
+
"materialId": spec_material_id,
|
|
127
|
+
"profileId": profile_id,
|
|
128
|
+
"crop": copy.deepcopy(region.get("crop")),
|
|
129
|
+
})
|
|
130
|
+
applied.append({
|
|
131
|
+
"componentId": region.get("componentId"),
|
|
132
|
+
"regionId": region.get("regionId"),
|
|
133
|
+
"specMaterialId": spec_material_id,
|
|
134
|
+
"profileId": profile_id,
|
|
135
|
+
"status": assignment.get("status"),
|
|
136
|
+
})
|
|
137
|
+
spec["materialPipeline"] = {
|
|
138
|
+
"schemaVersion": 1,
|
|
139
|
+
"status": (
|
|
140
|
+
"proceed"
|
|
141
|
+
if analysis_status == "proceed"
|
|
142
|
+
and not statuses - {"proceed"}
|
|
143
|
+
and not unresolved_not_observed
|
|
144
|
+
else "probe"
|
|
145
|
+
),
|
|
146
|
+
"registry": analysis.get("registry"),
|
|
147
|
+
"analysisArtifact": analysis.get("artifact", analysis.get("manifest")),
|
|
148
|
+
"targetThreshold": analysis.get("targetThreshold", 0.7),
|
|
149
|
+
"unresolvedNotObservedMaterials": copy.deepcopy(unresolved_not_observed),
|
|
150
|
+
"regions": applied,
|
|
151
|
+
"controlledViewsRequired": sorted({
|
|
152
|
+
view
|
|
153
|
+
for region in regions
|
|
154
|
+
if isinstance(region.get("assignment"), dict)
|
|
155
|
+
for view in region["assignment"].get("validationViews", [])
|
|
156
|
+
}),
|
|
157
|
+
}
|
|
158
|
+
spec.setdefault("materialAnalysisHistory", []).append({
|
|
159
|
+
"analysisArtifact": analysis.get("artifact", analysis.get("manifest")),
|
|
160
|
+
"status": spec["materialPipeline"]["status"],
|
|
161
|
+
"unresolvedNotObservedMaterials": copy.deepcopy(unresolved_not_observed),
|
|
162
|
+
"regions": len(applied),
|
|
163
|
+
})
|
|
164
|
+
return spec
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def main(argv: list[str]) -> int:
|
|
168
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
169
|
+
parser.add_argument("spec", type=Path)
|
|
170
|
+
parser.add_argument("analysis", type=Path)
|
|
171
|
+
parser.add_argument("--in-place", action="store_true")
|
|
172
|
+
parser.add_argument("--out", type=Path)
|
|
173
|
+
parser.add_argument("--allow-probe", action="store_true")
|
|
174
|
+
args = parser.parse_args(argv)
|
|
175
|
+
try:
|
|
176
|
+
spec = json.loads(args.spec.read_text(encoding="utf-8"))
|
|
177
|
+
analysis = json.loads(args.analysis.read_text(encoding="utf-8"))
|
|
178
|
+
result = apply_material_analysis(spec, analysis, allow_probe=args.allow_probe)
|
|
179
|
+
output = args.spec if args.in_place else args.out
|
|
180
|
+
if output is None:
|
|
181
|
+
raise ValueError("choose --in-place or --out")
|
|
182
|
+
output.parent.mkdir(parents=True, exist_ok=True)
|
|
183
|
+
output.write_text(json.dumps(result, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
|
184
|
+
print(json.dumps({"status": result["materialPipeline"]["status"], "out": str(output.resolve())}, indent=2))
|
|
185
|
+
return 0
|
|
186
|
+
except Exception as exc:
|
|
187
|
+
print(f"error: {exc}")
|
|
188
|
+
return 1
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
if __name__ == "__main__":
|
|
192
|
+
raise SystemExit(main(sys.argv[1:]))
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from dataclasses import dataclass, replace
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass(frozen=True, slots=True)
|
|
9
|
+
class FamilyAdapter:
|
|
10
|
+
family: str
|
|
11
|
+
subtype: str
|
|
12
|
+
topology: tuple[str, ...]
|
|
13
|
+
painted_regions: tuple[str, ...]
|
|
14
|
+
material_assignments: tuple[str, ...]
|
|
15
|
+
feature_targets: tuple[str, ...]
|
|
16
|
+
attachment_rules: tuple[str, ...]
|
|
17
|
+
review_viewpoints: tuple[str, ...]
|
|
18
|
+
|
|
19
|
+
def component_tree_contract(self) -> dict[str, Any]:
|
|
20
|
+
return {"family": self.family, "subtype": self.subtype, "topology": self.topology, "paintedRegions": self.painted_regions, "materialAssignments": self.material_assignments, "featureTargets": self.feature_targets, "attachmentRules": self.attachment_rules, "reviewViewpoints": self.review_viewpoints}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
_KNIFE = FamilyAdapter(
|
|
24
|
+
"knife", "generic-supported", ("ground-blade", "curve-sweep", "extrude", "assembled-solid"),
|
|
25
|
+
("blade-painted", "grip-painted", "guard-bare-metal", "pommel-bare-metal"),
|
|
26
|
+
("skin-finish", "substrate"),
|
|
27
|
+
("silhouette", "blade-edge-spine", "grip", "guard-quillon", "fastener", "pommel"),
|
|
28
|
+
("guard-to-blade", "grip-to-guard", "pommel-to-grip"),
|
|
29
|
+
("reference", "orbit-left", "orbit-right"),
|
|
30
|
+
)
|
|
31
|
+
SUPPORTED_KNIFE_SUBTYPES = frozenset({"karambit", "butterfly", "bayonet", "m9", "flip", "gut", "falchion", "bowie", "navaja", "talon", "classic"})
|
|
32
|
+
|
|
33
|
+
# A pistol is not a knife with different proportions: it is a two-body assembly (slide riding a
|
|
34
|
+
# frame) with a through-hole in the trigger guard, an internal mechanism the shell may reveal,
|
|
35
|
+
# and controls that stand proud of the broad faces. It gets its own tree rather than the knife
|
|
36
|
+
# tree with renamed parts.
|
|
37
|
+
_PISTOL = FamilyAdapter(
|
|
38
|
+
"pistol", "generic-supported",
|
|
39
|
+
("extrude-traced-outline", "outline-with-hole", "assembled-solid", "revolve"),
|
|
40
|
+
("slide-painted", "frame-painted", "magazine-painted", "grip-panel-painted",
|
|
41
|
+
"breech-bare-metal", "barrel-bare-metal", "controls-bare-polymer"),
|
|
42
|
+
("skin-finish", "substrate", "translucent-shell", "internal-mechanism"),
|
|
43
|
+
("silhouette", "slide-frame-parting-line", "ejection-port", "sights",
|
|
44
|
+
"trigger-and-safety-blade", "trigger-guard-loop", "grip-rake-and-panel",
|
|
45
|
+
"magazine-extension", "pin-and-control-placement", "muzzle-and-barrel"),
|
|
46
|
+
("slide-to-frame", "magazine-to-magwell", "trigger-to-pin",
|
|
47
|
+
"grip-panel-to-frame", "internals-inside-shell"),
|
|
48
|
+
("reference", "orbit-left", "orbit-right", "muzzle-on", "top-down"),
|
|
49
|
+
)
|
|
50
|
+
SUPPORTED_PISTOL_SUBTYPES = frozenset({"glock-18"})
|
|
51
|
+
|
|
52
|
+
_ADAPTERS = {"knife": (_KNIFE, SUPPORTED_KNIFE_SUBTYPES), "pistol": (_PISTOL, SUPPORTED_PISTOL_SUBTYPES)}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def get_family_adapter(family: str, subtype: str | None = None) -> FamilyAdapter:
|
|
56
|
+
entry = _ADAPTERS.get(family)
|
|
57
|
+
if entry is None:
|
|
58
|
+
raise ValueError(f"unsupported-family: {family}")
|
|
59
|
+
adapter, supported = entry
|
|
60
|
+
if subtype and subtype not in supported:
|
|
61
|
+
raise ValueError(f"unsupported-subtype: {subtype}")
|
|
62
|
+
return adapter if subtype is None else replace(adapter, subtype=subtype)
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Deterministic geometry derivation from a reference mask (Plan 1.3 §4, Phase 2).
|
|
3
|
+
|
|
4
|
+
Blum-Medial-Axis-style lathe-profile derivation: instead of hand-guessing a
|
|
5
|
+
LatheGeometry profile, COMPUTE it from the object's silhouette. For a roughly
|
|
6
|
+
axisymmetric subject (vase, bottle, handle, hilt), sweeping the local inscribed
|
|
7
|
+
half-width along the major axis yields a revolve profile that matches the
|
|
8
|
+
reference — stopping the "eyeballed profile" failure mode.
|
|
9
|
+
|
|
10
|
+
Pure Python stdlib (reuses extract_pbr_evidence's mask primitives). No PIL/numpy.
|
|
11
|
+
|
|
12
|
+
Output profile is a list of [radius, axisPos] pairs in object-relative units
|
|
13
|
+
(axisPos in [-0.5, 0.5], radius normalized by the object's long dimension),
|
|
14
|
+
directly consumable as LatheGeometry points (x = radius ≥ 0, revolved around Y).
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import argparse
|
|
20
|
+
import json
|
|
21
|
+
import sys
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import Any
|
|
24
|
+
|
|
25
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "stage1_intake"))
|
|
26
|
+
from extract_pbr_evidence import build_foreground_mask, load_image, mask_bbox # noqa: E402
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _row_span(mask: list[bool], width: int, y: int, x0: int, x1: int) -> tuple[int, int] | None:
|
|
30
|
+
left = right = None
|
|
31
|
+
for x in range(x0, x1 + 1):
|
|
32
|
+
if mask[y * width + x]:
|
|
33
|
+
if left is None:
|
|
34
|
+
left = x
|
|
35
|
+
right = x
|
|
36
|
+
if left is None:
|
|
37
|
+
return None
|
|
38
|
+
return (left, right)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _col_span(mask: list[bool], width: int, height: int, x: int, y0: int, y1: int) -> tuple[int, int] | None:
|
|
42
|
+
top = bottom = None
|
|
43
|
+
for y in range(y0, y1 + 1):
|
|
44
|
+
if mask[y * width + x]:
|
|
45
|
+
if top is None:
|
|
46
|
+
top = y
|
|
47
|
+
bottom = y
|
|
48
|
+
if top is None:
|
|
49
|
+
return None
|
|
50
|
+
return (top, bottom)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def derive_lathe_profile(
|
|
54
|
+
mask: list[bool],
|
|
55
|
+
width: int,
|
|
56
|
+
height: int,
|
|
57
|
+
samples: int = 24,
|
|
58
|
+
) -> dict[str, Any]:
|
|
59
|
+
"""Derive a revolve profile from the mask by sweeping inscribed half-width along
|
|
60
|
+
the object's major axis. Returns {axis, points:[[radius, axisPos],...], samples}."""
|
|
61
|
+
x0, y0, bw, bh = mask_bbox(width, height, mask)
|
|
62
|
+
x1, y1 = x0 + bw - 1, y0 + bh - 1
|
|
63
|
+
vertical = bh >= bw # revolve around the LONGER dimension's axis
|
|
64
|
+
long_len = bh if vertical else bw
|
|
65
|
+
if long_len <= 1:
|
|
66
|
+
return {"axis": "vertical" if vertical else "horizontal", "points": [], "samples": 0}
|
|
67
|
+
|
|
68
|
+
raw: list[tuple[float, float]] = [] # (axisPos_pixels_from_start, radius_pixels)
|
|
69
|
+
for i in range(samples):
|
|
70
|
+
t = i / (samples - 1)
|
|
71
|
+
if vertical:
|
|
72
|
+
y = int(round(y0 + t * (y1 - y0)))
|
|
73
|
+
span = _row_span(mask, width, y, x0, x1)
|
|
74
|
+
pos = y - y0
|
|
75
|
+
else:
|
|
76
|
+
x = int(round(x0 + t * (x1 - x0)))
|
|
77
|
+
span = _col_span(mask, width, height, x, y0, y1)
|
|
78
|
+
pos = x - x0
|
|
79
|
+
radius = 0.0 if span is None else (span[1] - span[0]) / 2.0
|
|
80
|
+
raw.append((float(pos), radius))
|
|
81
|
+
|
|
82
|
+
# Normalize: axisPos to [-0.5, 0.5] over the long dimension, radius by long dimension.
|
|
83
|
+
norm = float(long_len)
|
|
84
|
+
points = [[round(r / norm, 4), round(pos / norm - 0.5, 4)] for pos, r in raw]
|
|
85
|
+
return {
|
|
86
|
+
"axis": "vertical" if vertical else "horizontal",
|
|
87
|
+
"points": points,
|
|
88
|
+
"samples": samples,
|
|
89
|
+
"note": "Blum-medial-axis-derived revolve profile (radius along major axis); LatheGeometry-ready.",
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def derive_from_image(crop_path: Path, samples: int = 24) -> dict[str, Any]:
|
|
94
|
+
width, height, pixels, _warn = load_image(crop_path)
|
|
95
|
+
mask, _diag, _mw = build_foreground_mask(width, height, pixels)
|
|
96
|
+
result = derive_lathe_profile(mask, width, height, samples)
|
|
97
|
+
result["sourcePath"] = str(crop_path.resolve())
|
|
98
|
+
return result
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def main(argv: list[str]) -> int:
|
|
102
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
103
|
+
parser.add_argument("image", type=Path)
|
|
104
|
+
parser.add_argument("--samples", type=int, default=24)
|
|
105
|
+
parser.add_argument("--json", action="store_true")
|
|
106
|
+
args = parser.parse_args(argv)
|
|
107
|
+
try:
|
|
108
|
+
result = derive_from_image(args.image.expanduser().resolve(), args.samples)
|
|
109
|
+
except Exception as exc: # noqa: BLE001
|
|
110
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
111
|
+
return 1
|
|
112
|
+
print(json.dumps(result, indent=2, ensure_ascii=False) if args.json else
|
|
113
|
+
f"axis={result['axis']} points={len(result['points'])}")
|
|
114
|
+
return 0
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
if __name__ == "__main__":
|
|
118
|
+
raise SystemExit(main(sys.argv[1:]))
|