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,181 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Emit a projection/UV-bake descriptor for photo-projected texturing.
|
|
3
|
+
|
|
4
|
+
This script does not perform GPU projective texturing and it does not
|
|
5
|
+
rasterize or bake any pixels. Actual camera-space projection of the
|
|
6
|
+
(ideally de-lit) reference image onto the fitted mesh, and the bake of that
|
|
7
|
+
projection into the mesh's UV space, is a Three.js runtime operation (a
|
|
8
|
+
projective ShaderMaterial, e.g. the `three-projected-material` technique).
|
|
9
|
+
What this script produces is the plan: a validated, versioned descriptor
|
|
10
|
+
that records which camera, which source image(s), which mesh, and which
|
|
11
|
+
projection settings the Three.js generator/agent should use to actually run
|
|
12
|
+
that bake, plus the back/side inference strategy for regions the camera
|
|
13
|
+
never saw.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import argparse
|
|
19
|
+
import json
|
|
20
|
+
import sys
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
VALID_PROJECTION_MODES = ("perspective-camera-projection", "orthographic-front-projection", "triplanar-fallback")
|
|
26
|
+
VALID_UNSEEN_STRATEGIES = ("mirror-symmetry", "palette-continue", "request-additional-view", "leave-unprojected")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def clamp01(value: float) -> float:
|
|
30
|
+
return max(0.0, min(1.0, value))
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def load_camera(camera_arg: str | None) -> tuple[dict[str, Any] | None, list[str]]:
|
|
34
|
+
warnings: list[str] = []
|
|
35
|
+
if not camera_arg:
|
|
36
|
+
warnings.append("no --camera reference supplied; projection will use an identity/front camera assumption")
|
|
37
|
+
return None, warnings
|
|
38
|
+
path = Path(camera_arg).expanduser()
|
|
39
|
+
if not path.exists():
|
|
40
|
+
warnings.append(f"--camera path {camera_arg!r} does not exist; recording it as an opaque reference id instead")
|
|
41
|
+
return {"reference": camera_arg}, warnings
|
|
42
|
+
try:
|
|
43
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
44
|
+
except Exception as exc:
|
|
45
|
+
warnings.append(f"could not parse --camera JSON at {path}: {exc}; recording it as an opaque reference id")
|
|
46
|
+
return {"reference": camera_arg}, warnings
|
|
47
|
+
camera = data.get("referenceCamera", data) if isinstance(data, dict) else None
|
|
48
|
+
if not isinstance(camera, dict):
|
|
49
|
+
warnings.append(f"--camera JSON at {path} did not contain a referenceCamera object")
|
|
50
|
+
return {"reference": camera_arg}, warnings
|
|
51
|
+
return camera, warnings
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def build_descriptor(args: argparse.Namespace) -> dict[str, Any]:
|
|
55
|
+
intake = None
|
|
56
|
+
if getattr(args, "manifest", None):
|
|
57
|
+
manifest_path = Path(args.manifest).expanduser()
|
|
58
|
+
intake_value = json.loads(manifest_path.read_text(encoding="utf-8"))
|
|
59
|
+
if not isinstance(intake_value, dict):
|
|
60
|
+
raise ValueError("CS2 intake manifest must be a JSON object")
|
|
61
|
+
intake = intake_value
|
|
62
|
+
if not args.reference_image:
|
|
63
|
+
views = intake.get("sourceViews", [])
|
|
64
|
+
if isinstance(views, list) and views and isinstance(views[0], dict):
|
|
65
|
+
source_path = views[0].get("path")
|
|
66
|
+
if isinstance(source_path, str):
|
|
67
|
+
args.reference_image = source_path
|
|
68
|
+
if intake.get("state") != "proceed":
|
|
69
|
+
return {"projectedTextureBake": {"version": "1.0", "status": "request-input", "reason": f"intake state is {intake.get('state', 'unknown')}"}}
|
|
70
|
+
if not args.reference_image:
|
|
71
|
+
raise ValueError("--reference-image or --manifest with a source view is required")
|
|
72
|
+
camera, camera_warnings = load_camera(args.camera)
|
|
73
|
+
warnings = list(camera_warnings)
|
|
74
|
+
|
|
75
|
+
source_images: dict[str, str] = {"reference": str(Path(args.reference_image).expanduser())}
|
|
76
|
+
if args.delit_image:
|
|
77
|
+
source_images["delit"] = str(Path(args.delit_image).expanduser())
|
|
78
|
+
else:
|
|
79
|
+
warnings.append(
|
|
80
|
+
"no --delit-image supplied; projecting the raw reference will bake its lighting into the mesh "
|
|
81
|
+
"unless the runtime applies its own de-lighting pass first"
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
unseen_strategy = args.unseen_strategy
|
|
85
|
+
unseen_confidence = {
|
|
86
|
+
"mirror-symmetry": 0.45,
|
|
87
|
+
"palette-continue": 0.3,
|
|
88
|
+
"request-additional-view": 0.0,
|
|
89
|
+
"leave-unprojected": 0.0,
|
|
90
|
+
}[unseen_strategy]
|
|
91
|
+
|
|
92
|
+
bake_steps = [
|
|
93
|
+
"load the fitted mesh identified by targetMeshId and its UV layout",
|
|
94
|
+
"load sourceImages.delit if present, otherwise sourceImages.reference, as the projection source texture",
|
|
95
|
+
"construct a projection camera in the Three.js scene from the camera block (fovDegrees, aspect, orientation, position)",
|
|
96
|
+
f"apply {args.projection_mode} to project the source texture onto mesh surfaces facing the projection camera within tolerance",
|
|
97
|
+
f"for surfaces outside the camera's view frustum or facing away, apply the '{unseen_strategy}' strategy",
|
|
98
|
+
f"rasterize the resulting camera-space projection into a {args.texture_size}x{args.texture_size} UV-space texture",
|
|
99
|
+
"flag any UV texels that received no projected sample (fully unseen regions) in the bake output metadata",
|
|
100
|
+
"hand the baked texture back to the material pipeline as the projected albedo input",
|
|
101
|
+
]
|
|
102
|
+
|
|
103
|
+
return {
|
|
104
|
+
"projectedTextureBake": {
|
|
105
|
+
"version": "1.0",
|
|
106
|
+
"generator": "stage3_build/bake_projected_texture.py",
|
|
107
|
+
"status": "descriptor-only; no pixels are baked or rasterized by this script",
|
|
108
|
+
"targetMeshId": args.mesh_id,
|
|
109
|
+
"projectionMode": args.projection_mode,
|
|
110
|
+
"textureSize": args.texture_size,
|
|
111
|
+
"camera": camera,
|
|
112
|
+
"sourceImages": source_images,
|
|
113
|
+
"unseenRegionStrategy": {
|
|
114
|
+
"mode": unseen_strategy,
|
|
115
|
+
"confidence": unseen_confidence,
|
|
116
|
+
"note": "Regions the reference camera never saw (back, occluded folds, underside) are inferred, not observed.",
|
|
117
|
+
},
|
|
118
|
+
"runtimeApproach": (
|
|
119
|
+
"actual projective texturing and UV bake happen in the Three.js runtime via a projective "
|
|
120
|
+
"ShaderMaterial (the three-projected-material approach) or an equivalent camera-space "
|
|
121
|
+
"projection shader; this descriptor only records the plan for that step"
|
|
122
|
+
),
|
|
123
|
+
"bakeSteps": bake_steps,
|
|
124
|
+
"limitations": [
|
|
125
|
+
"this script performs no image sampling, projection math, or UV rasterization",
|
|
126
|
+
"camera accuracy is inherited from whatever produced the camera block; an unrefined camera will misalign the projection",
|
|
127
|
+
"unseen-region inference is a heuristic guess, not observed geometry or texture",
|
|
128
|
+
"the resulting bake still needs a rendered overlay review against the reference image before being trusted",
|
|
129
|
+
]
|
|
130
|
+
+ warnings,
|
|
131
|
+
"note": (
|
|
132
|
+
"Feed this descriptor to the Three.js generator/agent to run the actual projection and bake, "
|
|
133
|
+
"then re-render and visually compare the baked mesh against the reference image before "
|
|
134
|
+
"accepting the result as final."
|
|
135
|
+
),
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def main(argv: list[str]) -> int:
|
|
141
|
+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
142
|
+
parser.add_argument("--reference-image", help="Path to the original reference photo")
|
|
143
|
+
parser.add_argument("--manifest", type=Path, help="Validated cs2-intake.json with source view and camera evidence")
|
|
144
|
+
parser.add_argument("--delit-image", help="Path to a de-lit albedo produced by stage1_intake/delight_albedo.py, if available")
|
|
145
|
+
parser.add_argument("--camera", help="Path to a referenceCamera JSON produced by stage1_intake/solve_camera_pose.py")
|
|
146
|
+
parser.add_argument("--mesh-id", required=True, help="Identifier of the target mesh/node to project onto")
|
|
147
|
+
parser.add_argument(
|
|
148
|
+
"--projection-mode",
|
|
149
|
+
choices=VALID_PROJECTION_MODES,
|
|
150
|
+
default="perspective-camera-projection",
|
|
151
|
+
help="Projection technique the Three.js runtime should use (default perspective-camera-projection)",
|
|
152
|
+
)
|
|
153
|
+
parser.add_argument("--texture-size", type=int, default=1024, help="Target baked texture resolution (square)")
|
|
154
|
+
parser.add_argument(
|
|
155
|
+
"--unseen-strategy",
|
|
156
|
+
choices=VALID_UNSEEN_STRATEGIES,
|
|
157
|
+
default="mirror-symmetry",
|
|
158
|
+
help="How to handle mesh regions outside the reference camera's view (default mirror-symmetry)",
|
|
159
|
+
)
|
|
160
|
+
parser.add_argument("--out", type=Path, help="Write the descriptor JSON to this path")
|
|
161
|
+
args = parser.parse_args(argv)
|
|
162
|
+
|
|
163
|
+
if args.texture_size <= 0:
|
|
164
|
+
parser.error("--texture-size must be positive")
|
|
165
|
+
|
|
166
|
+
try:
|
|
167
|
+
descriptor = build_descriptor(args)
|
|
168
|
+
text = json.dumps(descriptor, indent=2, ensure_ascii=False)
|
|
169
|
+
if args.out:
|
|
170
|
+
out_path = args.out.expanduser().resolve()
|
|
171
|
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
172
|
+
out_path.write_text(text + "\n", encoding="utf-8")
|
|
173
|
+
print(text)
|
|
174
|
+
return 0
|
|
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,272 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Mesh decimation by quadric error metric, so an lodPlan can be produced rather than only declared.
|
|
3
|
+
|
|
4
|
+
`lodPlan` is validated in three places in this repository and generated in none. A validated
|
|
5
|
+
declaration is a promise about tiers that nothing ever built; `measure_geometry_integrity` reports
|
|
6
|
+
`lodPlanValid` and the tiers behind it do not exist.
|
|
7
|
+
|
|
8
|
+
Quadric error metrics (Garland & Heckbert 1997): every vertex accumulates the squared-distance-to-plane
|
|
9
|
+
form of the faces around it, as a symmetric 4x4. Collapsing an edge costs the quadric sum evaluated at
|
|
10
|
+
the merged position, so the cheapest collapse is the one that moves the surface least. Collapses are
|
|
11
|
+
taken in cost order, and each one refreshes the costs of the edges it touched.
|
|
12
|
+
|
|
13
|
+
Two collapses are refused outright, because both produce a mesh that still passes a triangle count but
|
|
14
|
+
is no longer a surface:
|
|
15
|
+
|
|
16
|
+
* a collapse that would FLIP a face -- the neighbouring normal reversing means the surface folded
|
|
17
|
+
through itself, exactly the defect `self_intersection.py` exists to catch, and creating it here
|
|
18
|
+
while reporting a successful decimation would be the pipeline sabotaging its own gate;
|
|
19
|
+
* a collapse on a BOUNDARY edge -- an open border erodes inward and the silhouette visibly retreats,
|
|
20
|
+
which is the classic "the LOD is smaller than the original" artefact.
|
|
21
|
+
|
|
22
|
+
Pure Python 3.10+ stdlib. No pip installs, no numpy.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import argparse
|
|
28
|
+
import heapq
|
|
29
|
+
import json
|
|
30
|
+
import math
|
|
31
|
+
import sys
|
|
32
|
+
from pathlib import Path
|
|
33
|
+
from typing import Any
|
|
34
|
+
|
|
35
|
+
DEFAULT_TARGET_RATIO = 0.5
|
|
36
|
+
MIN_TRIANGLES = 4
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _triangles(indices: Any) -> list[tuple[int, int, int]]:
|
|
40
|
+
if indices and isinstance(indices[0], (list, tuple)):
|
|
41
|
+
return [(int(t[0]), int(t[1]), int(t[2])) for t in indices]
|
|
42
|
+
return [
|
|
43
|
+
(int(indices[i]), int(indices[i + 1]), int(indices[i + 2]))
|
|
44
|
+
for i in range(0, len(indices) - 2, 3)
|
|
45
|
+
]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _plane(p0, p1, p2) -> tuple[float, float, float, float] | None:
|
|
49
|
+
e1 = [p1[i] - p0[i] for i in range(3)]
|
|
50
|
+
e2 = [p2[i] - p0[i] for i in range(3)]
|
|
51
|
+
n = [
|
|
52
|
+
e1[1] * e2[2] - e1[2] * e2[1],
|
|
53
|
+
e1[2] * e2[0] - e1[0] * e2[2],
|
|
54
|
+
e1[0] * e2[1] - e1[1] * e2[0],
|
|
55
|
+
]
|
|
56
|
+
length = math.sqrt(sum(component * component for component in n))
|
|
57
|
+
if length <= 1e-12:
|
|
58
|
+
return None
|
|
59
|
+
n = [component / length for component in n]
|
|
60
|
+
return n[0], n[1], n[2], -(n[0] * p0[0] + n[1] * p0[1] + n[2] * p0[2])
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _quadric(plane: tuple[float, float, float, float]) -> list[float]:
|
|
64
|
+
a, b, c, d = plane
|
|
65
|
+
# Upper triangle of the symmetric 4x4, in row-major order.
|
|
66
|
+
return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d]
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _add(q1: list[float], q2: list[float]) -> list[float]:
|
|
70
|
+
return [x + y for x, y in zip(q1, q2)]
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _error(q: list[float], v: list[float]) -> float:
|
|
74
|
+
x, y, z = v
|
|
75
|
+
return (
|
|
76
|
+
q[0] * x * x + 2 * q[1] * x * y + 2 * q[2] * x * z + 2 * q[3] * x
|
|
77
|
+
+ q[4] * y * y + 2 * q[5] * y * z + 2 * q[6] * y
|
|
78
|
+
+ q[7] * z * z + 2 * q[8] * z
|
|
79
|
+
+ q[9]
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def decimate(
|
|
84
|
+
mesh: dict[str, Any],
|
|
85
|
+
target_ratio: float = DEFAULT_TARGET_RATIO,
|
|
86
|
+
) -> dict[str, Any]:
|
|
87
|
+
vertices = [list(v) for v in mesh["vertices"]]
|
|
88
|
+
faces = _triangles(mesh["indices"])
|
|
89
|
+
if not faces:
|
|
90
|
+
raise ValueError("mesh has no triangles")
|
|
91
|
+
if not 0.0 < target_ratio <= 1.0:
|
|
92
|
+
raise ValueError("target_ratio must be in (0, 1]")
|
|
93
|
+
|
|
94
|
+
original_count = len(faces)
|
|
95
|
+
target_count = max(MIN_TRIANGLES, int(original_count * target_ratio))
|
|
96
|
+
|
|
97
|
+
alive = [True] * len(faces)
|
|
98
|
+
vertex_faces: list[set[int]] = [set() for _ in vertices]
|
|
99
|
+
for index, face in enumerate(faces):
|
|
100
|
+
for vertex in face:
|
|
101
|
+
vertex_faces[vertex].add(index)
|
|
102
|
+
|
|
103
|
+
quadrics = [[0.0] * 10 for _ in vertices]
|
|
104
|
+
for index, face in enumerate(faces):
|
|
105
|
+
plane = _plane(*(vertices[i] for i in face))
|
|
106
|
+
if plane is None:
|
|
107
|
+
alive[index] = False
|
|
108
|
+
continue
|
|
109
|
+
q = _quadric(plane)
|
|
110
|
+
for vertex in face:
|
|
111
|
+
quadrics[vertex] = _add(quadrics[vertex], q)
|
|
112
|
+
|
|
113
|
+
edge_faces: dict[tuple[int, int], int] = {}
|
|
114
|
+
for index, face in enumerate(faces):
|
|
115
|
+
a, b, c = face
|
|
116
|
+
for u, v in ((a, b), (b, c), (c, a)):
|
|
117
|
+
key = (u, v) if u < v else (v, u)
|
|
118
|
+
edge_faces[key] = edge_faces.get(key, 0) + 1
|
|
119
|
+
boundary = {edge for edge, count in edge_faces.items() if count == 1}
|
|
120
|
+
|
|
121
|
+
def cost(u: int, v: int) -> tuple[float, list[float]]:
|
|
122
|
+
# Midpoint rather than the quadric-optimal position: solving the 3x3 needs an inverse that is
|
|
123
|
+
# singular on flat regions, and the midpoint keeps the collapse on the original surface, which
|
|
124
|
+
# matters more here than the last few percent of accuracy.
|
|
125
|
+
merged = [(vertices[u][i] + vertices[v][i]) / 2 for i in range(3)]
|
|
126
|
+
return _error(_add(quadrics[u], quadrics[v]), merged), merged
|
|
127
|
+
|
|
128
|
+
heap: list[tuple[float, int, int]] = []
|
|
129
|
+
for (u, v) in edge_faces:
|
|
130
|
+
if (u, v) in boundary:
|
|
131
|
+
continue
|
|
132
|
+
heapq.heappush(heap, (cost(u, v)[0], u, v))
|
|
133
|
+
|
|
134
|
+
removed = 0
|
|
135
|
+
refused_flip = 0
|
|
136
|
+
refused_boundary = len(boundary)
|
|
137
|
+
live_faces = sum(1 for flag in alive if flag)
|
|
138
|
+
|
|
139
|
+
while heap and live_faces > target_count:
|
|
140
|
+
_, u, v = heapq.heappop(heap)
|
|
141
|
+
if not vertex_faces[u] or not vertex_faces[v]:
|
|
142
|
+
continue
|
|
143
|
+
if u == v:
|
|
144
|
+
continue
|
|
145
|
+
shared = vertex_faces[u] & vertex_faces[v]
|
|
146
|
+
if not any(alive[index] for index in shared):
|
|
147
|
+
continue
|
|
148
|
+
_, merged = cost(u, v)
|
|
149
|
+
|
|
150
|
+
# Would any surviving face flip? Compare each affected face's normal before and after.
|
|
151
|
+
flips = False
|
|
152
|
+
for index in (vertex_faces[u] | vertex_faces[v]) - shared:
|
|
153
|
+
if not alive[index]:
|
|
154
|
+
continue
|
|
155
|
+
face = faces[index]
|
|
156
|
+
before = _plane(*(vertices[i] for i in face))
|
|
157
|
+
after_points = [merged if i in (u, v) else vertices[i] for i in face]
|
|
158
|
+
after = _plane(*after_points)
|
|
159
|
+
if before is None or after is None:
|
|
160
|
+
flips = True
|
|
161
|
+
break
|
|
162
|
+
if before[0] * after[0] + before[1] * after[1] + before[2] * after[2] < 0.0:
|
|
163
|
+
flips = True
|
|
164
|
+
break
|
|
165
|
+
if flips:
|
|
166
|
+
refused_flip += 1
|
|
167
|
+
continue
|
|
168
|
+
|
|
169
|
+
vertices[u] = merged
|
|
170
|
+
quadrics[u] = _add(quadrics[u], quadrics[v])
|
|
171
|
+
for index in shared:
|
|
172
|
+
if alive[index]:
|
|
173
|
+
alive[index] = False
|
|
174
|
+
live_faces -= 1
|
|
175
|
+
removed += 1
|
|
176
|
+
for index in list(vertex_faces[v]):
|
|
177
|
+
if not alive[index]:
|
|
178
|
+
continue
|
|
179
|
+
faces[index] = tuple(u if i == v else i for i in faces[index]) # type: ignore[assignment]
|
|
180
|
+
vertex_faces[u].add(index)
|
|
181
|
+
vertex_faces[v] = set()
|
|
182
|
+
|
|
183
|
+
for index in list(vertex_faces[u]):
|
|
184
|
+
if not alive[index]:
|
|
185
|
+
continue
|
|
186
|
+
for w in faces[index]:
|
|
187
|
+
if w != u:
|
|
188
|
+
heapq.heappush(heap, (cost(u, w)[0], u, w))
|
|
189
|
+
|
|
190
|
+
kept = [faces[index] for index in range(len(faces)) if alive[index]]
|
|
191
|
+
used = sorted({vertex for face in kept for vertex in face})
|
|
192
|
+
remap = {old: new for new, old in enumerate(used)}
|
|
193
|
+
out_vertices = [vertices[old] for old in used]
|
|
194
|
+
out_indices: list[int] = []
|
|
195
|
+
for face in kept:
|
|
196
|
+
out_indices.extend(remap[vertex] for vertex in face)
|
|
197
|
+
|
|
198
|
+
return {
|
|
199
|
+
"vertices": out_vertices,
|
|
200
|
+
"indices": out_indices,
|
|
201
|
+
"originalTriangleCount": original_count,
|
|
202
|
+
"triangleCount": len(kept),
|
|
203
|
+
"targetTriangleCount": target_count,
|
|
204
|
+
"achievedRatio": round(len(kept) / original_count, 6),
|
|
205
|
+
"collapsesRefusedForFlip": refused_flip,
|
|
206
|
+
"boundaryEdgesProtected": refused_boundary,
|
|
207
|
+
# Reported because a decimation that stops short is not a failure but IS something the caller
|
|
208
|
+
# must know: on a mesh whose collapses would all flip a face, the honest outcome is fewer
|
|
209
|
+
# triangles removed, not a folded mesh that hits the number.
|
|
210
|
+
"reachedTarget": len(kept) <= target_count,
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def build_lod_plan(
|
|
215
|
+
mesh: dict[str, Any],
|
|
216
|
+
ratios: list[float],
|
|
217
|
+
distances: list[float],
|
|
218
|
+
) -> dict[str, Any]:
|
|
219
|
+
"""Generate the tiers `lodPlan` has only ever declared.
|
|
220
|
+
|
|
221
|
+
Tiers must have strictly increasing distance and strictly decreasing triangle count -- that is what
|
|
222
|
+
`_has_reduced_lod_tiers` in geometry_integrity.py already enforces, so a plan generated here has to
|
|
223
|
+
satisfy the validator that until now had nothing real to validate.
|
|
224
|
+
"""
|
|
225
|
+
if len(ratios) != len(distances):
|
|
226
|
+
raise ValueError("ratios and distances must be the same length")
|
|
227
|
+
tiers = []
|
|
228
|
+
meshes = []
|
|
229
|
+
for ratio, distance in sorted(zip(ratios, distances), key=lambda pair: pair[1]):
|
|
230
|
+
result = decimate(mesh, ratio)
|
|
231
|
+
tiers.append({"distance": distance, "triangleCount": result["triangleCount"]})
|
|
232
|
+
meshes.append(result)
|
|
233
|
+
for earlier, later in zip(tiers, tiers[1:]):
|
|
234
|
+
if later["triangleCount"] >= earlier["triangleCount"]:
|
|
235
|
+
raise ValueError(
|
|
236
|
+
f"tier at distance {later['distance']} has {later['triangleCount']} triangles, not "
|
|
237
|
+
f"fewer than {earlier['triangleCount']} at {earlier['distance']}; the requested "
|
|
238
|
+
"ratios do not produce a monotonic plan"
|
|
239
|
+
)
|
|
240
|
+
return {"lodPlan": tiers, "meshes": meshes}
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def main(argv: list[str]) -> int:
|
|
244
|
+
parser = argparse.ArgumentParser(description="Decimate a mesh by quadric error metric.")
|
|
245
|
+
parser.add_argument("mesh", type=Path)
|
|
246
|
+
parser.add_argument("--ratio", type=float, default=DEFAULT_TARGET_RATIO)
|
|
247
|
+
parser.add_argument("--out", type=Path)
|
|
248
|
+
parser.add_argument("--json", action="store_true")
|
|
249
|
+
args = parser.parse_args(argv)
|
|
250
|
+
try:
|
|
251
|
+
mesh = json.loads(args.mesh.read_text())
|
|
252
|
+
if isinstance(mesh, dict) and isinstance(mesh.get("meshes"), list) and mesh["meshes"]:
|
|
253
|
+
mesh = mesh["meshes"][0]
|
|
254
|
+
result = decimate(mesh, args.ratio)
|
|
255
|
+
except Exception as exc:
|
|
256
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
257
|
+
return 2
|
|
258
|
+
if args.out:
|
|
259
|
+
args.out.write_text(json.dumps(result))
|
|
260
|
+
if args.json:
|
|
261
|
+
print(json.dumps(result, indent=2))
|
|
262
|
+
else:
|
|
263
|
+
print(
|
|
264
|
+
f"{result['originalTriangleCount']} -> {result['triangleCount']} triangles "
|
|
265
|
+
f"(ratio {result['achievedRatio']}), {result['collapsesRefusedForFlip']} collapses "
|
|
266
|
+
f"refused to avoid folding the surface"
|
|
267
|
+
)
|
|
268
|
+
return 0
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
if __name__ == "__main__":
|
|
272
|
+
raise SystemExit(main(sys.argv[1:]))
|