vibedgames 0.10.0 → 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-FXXVXDTW.js → chunk-24TITAFS.js} +1 -1
- package/dist/{chunk-OGX4DKIS.js → chunk-2C5PG2QO.js} +1 -1
- package/dist/{chunk-HYOXGNWS.js → chunk-2DEVOKI7.js} +1 -1
- package/dist/{chunk-RRI23NK2.js → chunk-2GHPYT2P.js} +1 -1
- package/dist/{chunk-S7HYWITX.js → chunk-2HXGMXGC.js} +1 -1
- package/dist/{chunk-N2UHAQXC.js → chunk-36FORP7T.js} +0 -1
- package/dist/{chunk-VB4WLJR2.js → chunk-3IXRQTRF.js} +1 -1
- package/dist/{chunk-2KVQJKIZ.js → chunk-4ENHS32B.js} +23 -36
- package/dist/{chunk-SXYQL4GK.js → chunk-4YHA32OE.js} +1 -1
- package/dist/{chunk-4FJXCS3K.js → chunk-4ZGQKPK5.js} +1 -1
- package/dist/{chunk-SBXCK2I2.js → chunk-6CLUPFQA.js} +2 -2
- package/dist/{chunk-TXOE5UY5.js → chunk-7WTF2BA4.js} +1 -1
- package/dist/{chunk-R2WVORGD.js → chunk-AAXZNK4Z.js} +1 -1
- package/dist/{chunk-DOOQUFPG.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-SUSX3QIA.js → chunk-E72TFJZP.js} +1 -1
- package/dist/{chunk-E3FJUPLT.js → chunk-EUAAQMUA.js} +2 -0
- package/dist/{chunk-U6DTE5IX.js → chunk-F7LYJSZE.js} +1 -1
- package/dist/{chunk-MEAO33XW.js → chunk-FMON3C74.js} +8 -8
- package/dist/{chunk-GLEW7VJQ.js → chunk-FPILHRLZ.js} +1 -1
- package/dist/{chunk-OPUCUUID.js → chunk-G63MXDX2.js} +4 -0
- 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-RKS7SI5L.js → chunk-NO6KPV64.js} +1 -1
- package/dist/{chunk-KJK5CB6E.js → chunk-NXW3Z4Y4.js} +1 -1
- package/dist/{chunk-7RPLQWR2.js → chunk-OHOAZGO4.js} +1 -1
- package/dist/chunk-PYJNI5WD.js +83 -0
- package/dist/{chunk-NCX6LYNJ.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-HX5Q63UA.js → chunk-T777EXAO.js} +1 -1
- package/dist/{chunk-UQ7VO6B3.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-ZHLPE6LI.js → chunk-UIKYK7KI.js} +1 -1
- package/dist/{chunk-KAGVI3CE.js → chunk-UJRSQO2B.js} +1 -1
- package/dist/{chunk-Q2QC6KAZ.js → chunk-V7LEYVXB.js} +29 -25
- package/dist/{chunk-DB7WVFS7.js → chunk-WRMQEXUC.js} +1 -1
- package/dist/{chunk-HSMG6U7J.js → chunk-WXSBNC67.js} +3 -9
- package/dist/{chunk-QLCVLCPM.js → chunk-X4QIOXNQ.js} +1 -1
- package/dist/{chunk-5YPLKGY3.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-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,592 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Detect a surface that has folded through its own volume, on a mesh whose topology is valid.
|
|
3
|
+
|
|
4
|
+
`geometry_integrity.mesh_edge_counts` counts `boundaryEdges` (an edge used by one triangle) and
|
|
5
|
+
`nonManifoldEdges` (an edge used by more than two). Those are the only geometry facts any gate in
|
|
6
|
+
this repository checks, and they are both topological. A real production defect walked straight
|
|
7
|
+
through them: a character's eye-socket recess was pushed deeper than the skull's local half-depth,
|
|
8
|
+
so the front surface passed THROUGH the back of the skull and emerged out the occiput. From behind
|
|
9
|
+
there was a clean hole through the head. The mesh was still perfectly closed -- boundaryEdges 0,
|
|
10
|
+
nonManifoldEdges 0 -- because pushing existing vertices around changes no connectivity at all. Every
|
|
11
|
+
existing gate passed it.
|
|
12
|
+
|
|
13
|
+
Self-intersection is a GEOMETRIC defect on a TOPOLOGICALLY VALID mesh. Edge counts cannot see it,
|
|
14
|
+
by construction. This module is the check that can.
|
|
15
|
+
|
|
16
|
+
Method: ray parity. Take a point on the surface, step a small epsilon along its outward direction,
|
|
17
|
+
and ask whether that point -- which by definition should be just OUTSIDE the object -- is in fact
|
|
18
|
+
inside the object's own volume. On a closed surface the answer is decided by counting how many of
|
|
19
|
+
the mesh's own triangles a ray from that point crosses: odd means inside. A point that is supposed
|
|
20
|
+
to be outside its own surface but measures inside can only mean the surface folded through itself
|
|
21
|
+
there.
|
|
22
|
+
|
|
23
|
+
Everything here is deterministic. No `random`, no sampling jitter, no wall-clock or hash-order
|
|
24
|
+
dependence: the same mesh yields the same verdict and the same reported positions every run, which
|
|
25
|
+
is what makes a gate's output reviewable.
|
|
26
|
+
|
|
27
|
+
Pure Python 3.10+ stdlib. No numpy, no pip installs.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
|
|
32
|
+
import argparse
|
|
33
|
+
import json
|
|
34
|
+
import sys
|
|
35
|
+
from math import sqrt
|
|
36
|
+
from pathlib import Path
|
|
37
|
+
from typing import Any
|
|
38
|
+
|
|
39
|
+
# A gate that quietly inspects a tenth of a mesh and then reports "clean" is worse than no gate, so
|
|
40
|
+
# this budget is a cap on WORK, never on what the result claims: every result carries
|
|
41
|
+
# sampledVertexCount / totalVertexCount / samplingStride so the coverage is on the face of it.
|
|
42
|
+
MAX_SAMPLED_VERTICES = 4000
|
|
43
|
+
|
|
44
|
+
# The offset distance is a fraction of the mesh's bounding-box diagonal rather than an absolute
|
|
45
|
+
# number, because an absolute epsilon is wrong at every scale but one: 0.001 units is a huge step
|
|
46
|
+
# across a 0.01-wide gem and invisible on a 1000-unit terrain. Tied to the diagonal it means the
|
|
47
|
+
# same thing on both. 1e-3 of the diagonal clears floating-point noise on the surface the point came
|
|
48
|
+
# from while staying far below any modelled feature.
|
|
49
|
+
EPSILON_BBOX_FRACTION = 1e-3
|
|
50
|
+
|
|
51
|
+
# Hits below this |dot(ray direction, face normal)| are edge-on: the intersection maths is dividing
|
|
52
|
+
# by a near-zero determinant and the answer is numerically meaningless. Such a sample is reported
|
|
53
|
+
# undecided rather than guessed at.
|
|
54
|
+
GRAZING_COS_THRESHOLD = 1e-4
|
|
55
|
+
|
|
56
|
+
# Same idea one step earlier: if the ray direction is this close to tangent to the surface AT the
|
|
57
|
+
# sample, the ray skims its own neighbourhood and the parity it returns is not trustworthy.
|
|
58
|
+
TANGENT_COS_THRESHOLD = 1e-3
|
|
59
|
+
|
|
60
|
+
# A hit this close to a triangle's edge is shared with the neighbouring triangle, so it is either
|
|
61
|
+
# double-counted or missed depending on rounding. Deliberately tight -- it should fire on genuine
|
|
62
|
+
# degeneracy, not on ordinary hits.
|
|
63
|
+
BARYCENTRIC_EDGE_TOLERANCE = 1e-9
|
|
64
|
+
|
|
65
|
+
# Fixed, mutually non-parallel, and deliberately not axis-aligned: axis-aligned rays lie exactly in
|
|
66
|
+
# the plane of the axis-aligned quads that box-derived geometry is full of, which is the single most
|
|
67
|
+
# common way a parity count goes wrong. Three directions give a majority; one bad ray cannot decide
|
|
68
|
+
# a sample on its own.
|
|
69
|
+
_RAW_RAY_DIRECTIONS: tuple[tuple[float, float, float], ...] = (
|
|
70
|
+
(1.0, 0.37, 0.19),
|
|
71
|
+
(0.23, 1.0, -0.41),
|
|
72
|
+
(-0.47, 0.29, 1.0),
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
WORST_REGION_LIMIT = 8
|
|
76
|
+
|
|
77
|
+
# Grid resolution per axis. Above this the bucket dictionary costs more to build than the triangle
|
|
78
|
+
# tests it saves.
|
|
79
|
+
GRID_MAX_RESOLUTION = 256
|
|
80
|
+
|
|
81
|
+
# A triangle whose footprint covers more cells than this is filed once in an "everywhere" list and
|
|
82
|
+
# tested against every sample, instead of being copied into thousands of buckets.
|
|
83
|
+
GRID_OVERSIZED_CELL_LIMIT = 1024
|
|
84
|
+
|
|
85
|
+
# Vertices are welded by rounded position at this precision, matching `geometry_integrity`'s own
|
|
86
|
+
# vertex identity, so that seam-duplicated vertices sharing a position are treated as one point.
|
|
87
|
+
WELD_PRECISION = 6
|
|
88
|
+
|
|
89
|
+
Vector3 = tuple[float, float, float]
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _normalize(vector: Vector3) -> Vector3 | None:
|
|
93
|
+
length = sqrt(vector[0] * vector[0] + vector[1] * vector[1] + vector[2] * vector[2])
|
|
94
|
+
if length <= 1e-15:
|
|
95
|
+
return None
|
|
96
|
+
return (vector[0] / length, vector[1] / length, vector[2] / length)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
RAY_DIRECTIONS: tuple[Vector3, ...] = tuple(
|
|
100
|
+
direction for direction in (_normalize(raw) for raw in _RAW_RAY_DIRECTIONS) if direction is not None
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _as_point(value: Any) -> Vector3:
|
|
105
|
+
if not isinstance(value, (list, tuple)) or len(value) < 3:
|
|
106
|
+
raise ValueError("vertices must contain 3D positions")
|
|
107
|
+
return (float(value[0]), float(value[1]), float(value[2]))
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _triangles(indices: Any) -> list[tuple[int, int, int]]:
|
|
111
|
+
"""Accept both index encodings `geometry_integrity` accepts: flat, or grouped in threes."""
|
|
112
|
+
if not isinstance(indices, list) or not indices:
|
|
113
|
+
raise ValueError("indices must be a non-empty array")
|
|
114
|
+
if isinstance(indices[0], (list, tuple)):
|
|
115
|
+
groups = indices
|
|
116
|
+
else:
|
|
117
|
+
if len(indices) % 3 != 0:
|
|
118
|
+
raise ValueError("flat triangle indices must be a multiple of three")
|
|
119
|
+
groups = [indices[i:i + 3] for i in range(0, len(indices), 3)]
|
|
120
|
+
triangles: list[tuple[int, int, int]] = []
|
|
121
|
+
for group in groups:
|
|
122
|
+
if not isinstance(group, (list, tuple)) or len(group) != 3:
|
|
123
|
+
raise ValueError("triangle indices must contain groups of three")
|
|
124
|
+
triangles.append((int(group[0]), int(group[1]), int(group[2])))
|
|
125
|
+
return triangles
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class _DirectionGrid:
|
|
129
|
+
"""Triangles bucketed by their footprint in the plane perpendicular to one ray direction.
|
|
130
|
+
|
|
131
|
+
Testing every sample against every triangle is ~1.5e9 operations on a 30k-vertex / 50k-triangle
|
|
132
|
+
mesh, which is not a check anyone will run. All rays of a given pass share one direction, so the
|
|
133
|
+
problem collapses to two dimensions: project every triangle onto the plane perpendicular to that
|
|
134
|
+
direction, bucket it by the cells its 2D bounding box covers, and a sample only ever tests the
|
|
135
|
+
triangles filed in its own cell. The grid is built once per direction and reused for every
|
|
136
|
+
sample, so the build cost is amortised across the whole mesh.
|
|
137
|
+
"""
|
|
138
|
+
|
|
139
|
+
def __init__(self, direction: Vector3, vertices: list[Vector3], triangles: list[tuple[int, int, int]]) -> None:
|
|
140
|
+
helper: Vector3 = (0.0, 0.0, 1.0) if abs(direction[2]) < 0.9 else (1.0, 0.0, 0.0)
|
|
141
|
+
axis_u = _normalize((
|
|
142
|
+
helper[1] * direction[2] - helper[2] * direction[1],
|
|
143
|
+
helper[2] * direction[0] - helper[0] * direction[2],
|
|
144
|
+
helper[0] * direction[1] - helper[1] * direction[0],
|
|
145
|
+
))
|
|
146
|
+
if axis_u is None: # unreachable for a unit direction, but a None basis would be silent nonsense
|
|
147
|
+
raise ValueError("cannot build a basis for the ray direction")
|
|
148
|
+
axis_v = (
|
|
149
|
+
direction[1] * axis_u[2] - direction[2] * axis_u[1],
|
|
150
|
+
direction[2] * axis_u[0] - direction[0] * axis_u[2],
|
|
151
|
+
direction[0] * axis_u[1] - direction[1] * axis_u[0],
|
|
152
|
+
)
|
|
153
|
+
self._u = axis_u
|
|
154
|
+
self._v = axis_v
|
|
155
|
+
self.oversized: list[int] = []
|
|
156
|
+
self._cells: dict[tuple[int, int], list[int]] = {}
|
|
157
|
+
|
|
158
|
+
ux, uy, uz = axis_u
|
|
159
|
+
vx, vy, vz = axis_v
|
|
160
|
+
boxes: list[tuple[float, float, float, float]] = []
|
|
161
|
+
min_u = min_v = float("inf")
|
|
162
|
+
max_u = max_v = float("-inf")
|
|
163
|
+
for a, b, c in triangles:
|
|
164
|
+
pa, pb, pc = vertices[a], vertices[b], vertices[c]
|
|
165
|
+
au = pa[0] * ux + pa[1] * uy + pa[2] * uz
|
|
166
|
+
bu = pb[0] * ux + pb[1] * uy + pb[2] * uz
|
|
167
|
+
cu = pc[0] * ux + pc[1] * uy + pc[2] * uz
|
|
168
|
+
av = pa[0] * vx + pa[1] * vy + pa[2] * vz
|
|
169
|
+
bv = pb[0] * vx + pb[1] * vy + pb[2] * vz
|
|
170
|
+
cv = pc[0] * vx + pc[1] * vy + pc[2] * vz
|
|
171
|
+
lo_u, hi_u = min(au, bu, cu), max(au, bu, cu)
|
|
172
|
+
lo_v, hi_v = min(av, bv, cv), max(av, bv, cv)
|
|
173
|
+
boxes.append((lo_u, lo_v, hi_u, hi_v))
|
|
174
|
+
min_u = lo_u if lo_u < min_u else min_u
|
|
175
|
+
max_u = hi_u if hi_u > max_u else max_u
|
|
176
|
+
min_v = lo_v if lo_v < min_v else min_v
|
|
177
|
+
max_v = hi_v if hi_v > max_v else max_v
|
|
178
|
+
|
|
179
|
+
resolution = max(1, min(GRID_MAX_RESOLUTION, int(sqrt(len(triangles))) or 1))
|
|
180
|
+
span_u = max_u - min_u
|
|
181
|
+
span_v = max_v - min_v
|
|
182
|
+
self._resolution = resolution
|
|
183
|
+
self._min_u = min_u
|
|
184
|
+
self._min_v = min_v
|
|
185
|
+
# A zero span means the whole mesh projects to a line or a point along that axis; one cell
|
|
186
|
+
# wide is then the correct answer rather than a division by zero.
|
|
187
|
+
self._cell_u = span_u / resolution if span_u > 0.0 else 1.0
|
|
188
|
+
self._cell_v = span_v / resolution if span_v > 0.0 else 1.0
|
|
189
|
+
|
|
190
|
+
cells = self._cells
|
|
191
|
+
for index, (lo_u, lo_v, hi_u, hi_v) in enumerate(boxes):
|
|
192
|
+
cu0 = self._cell_index(lo_u, self._min_u, self._cell_u)
|
|
193
|
+
cu1 = self._cell_index(hi_u, self._min_u, self._cell_u)
|
|
194
|
+
cv0 = self._cell_index(lo_v, self._min_v, self._cell_v)
|
|
195
|
+
cv1 = self._cell_index(hi_v, self._min_v, self._cell_v)
|
|
196
|
+
if (cu1 - cu0 + 1) * (cv1 - cv0 + 1) > GRID_OVERSIZED_CELL_LIMIT:
|
|
197
|
+
self.oversized.append(index)
|
|
198
|
+
continue
|
|
199
|
+
for cu in range(cu0, cu1 + 1):
|
|
200
|
+
for cv in range(cv0, cv1 + 1):
|
|
201
|
+
cells.setdefault((cu, cv), []).append(index)
|
|
202
|
+
|
|
203
|
+
def _cell_index(self, value: float, origin: float, size: float) -> int:
|
|
204
|
+
cell = int((value - origin) / size)
|
|
205
|
+
if cell < 0:
|
|
206
|
+
return 0
|
|
207
|
+
if cell >= self._resolution:
|
|
208
|
+
return self._resolution - 1
|
|
209
|
+
return cell
|
|
210
|
+
|
|
211
|
+
def candidates(self, point: Vector3) -> list[int]:
|
|
212
|
+
"""Triangles whose footprint covers this point's cell. Everything else cannot be hit."""
|
|
213
|
+
ux, uy, uz = self._u
|
|
214
|
+
vx, vy, vz = self._v
|
|
215
|
+
pu = point[0] * ux + point[1] * uy + point[2] * uz
|
|
216
|
+
pv = point[0] * vx + point[1] * vy + point[2] * vz
|
|
217
|
+
# Clamped exactly as insertion clamps, and for the same reason. A sample projecting onto the
|
|
218
|
+
# grid's outer edge -- the vertex that defines the maximum, plus its epsilon offset -- lands
|
|
219
|
+
# one cell past the end; treating that as "off the grid, nothing to test" silently drops
|
|
220
|
+
# every triangle in the boundary cell and returns a confident "outside". Clamping costs a
|
|
221
|
+
# few extra triangle tests for points that really are past the footprint, which is the right
|
|
222
|
+
# side to be wrong on.
|
|
223
|
+
cu = self._cell_index(pu, self._min_u, self._cell_u)
|
|
224
|
+
cv = self._cell_index(pv, self._min_v, self._cell_v)
|
|
225
|
+
cell = self._cells.get((cu, cv))
|
|
226
|
+
if cell is None:
|
|
227
|
+
return self.oversized
|
|
228
|
+
if not self.oversized:
|
|
229
|
+
return cell
|
|
230
|
+
return cell + self.oversized
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _count_crossings(
|
|
234
|
+
origin: Vector3,
|
|
235
|
+
direction: Vector3,
|
|
236
|
+
grid: _DirectionGrid,
|
|
237
|
+
prepared: list[tuple[float, ...]],
|
|
238
|
+
excluded: set[int],
|
|
239
|
+
t_min: float,
|
|
240
|
+
) -> tuple[int, bool]:
|
|
241
|
+
"""Möller-Trumbore parity count. Returns (crossings, reliable).
|
|
242
|
+
|
|
243
|
+
`reliable` goes false the moment a candidate triangle is near enough to edge-on that the
|
|
244
|
+
determinant cannot be trusted, or a hit lands on a triangle edge where it belongs equally to two
|
|
245
|
+
triangles. Those cases are handed back to the caller as undecided; they are never rounded into a
|
|
246
|
+
verdict.
|
|
247
|
+
"""
|
|
248
|
+
ox, oy, oz = origin
|
|
249
|
+
dx, dy, dz = direction
|
|
250
|
+
crossings = 0
|
|
251
|
+
for index in grid.candidates(origin):
|
|
252
|
+
if index in excluded:
|
|
253
|
+
continue
|
|
254
|
+
(ax, ay, az, e1x, e1y, e1z, e2x, e2y, e2z, normal_length) = prepared[index]
|
|
255
|
+
px = dy * e2z - dz * e2y
|
|
256
|
+
py = dz * e2x - dx * e2z
|
|
257
|
+
pz = dx * e2y - dy * e2x
|
|
258
|
+
det = e1x * px + e1y * py + e1z * pz
|
|
259
|
+
# det == dot(direction, e1 x e2), so |det| / |e1 x e2| is exactly the cosine between the ray
|
|
260
|
+
# and the face normal -- the edge-on test, for free, with no square root.
|
|
261
|
+
limit = GRAZING_COS_THRESHOLD * normal_length
|
|
262
|
+
if -limit < det < limit:
|
|
263
|
+
return 0, False
|
|
264
|
+
inv_det = 1.0 / det
|
|
265
|
+
tx = ox - ax
|
|
266
|
+
ty = oy - ay
|
|
267
|
+
tz = oz - az
|
|
268
|
+
u = (tx * px + ty * py + tz * pz) * inv_det
|
|
269
|
+
if u < -BARYCENTRIC_EDGE_TOLERANCE or u > 1.0 + BARYCENTRIC_EDGE_TOLERANCE:
|
|
270
|
+
continue
|
|
271
|
+
qx = ty * e1z - tz * e1y
|
|
272
|
+
qy = tz * e1x - tx * e1z
|
|
273
|
+
qz = tx * e1y - ty * e1x
|
|
274
|
+
v = (dx * qx + dy * qy + dz * qz) * inv_det
|
|
275
|
+
if v < -BARYCENTRIC_EDGE_TOLERANCE or u + v > 1.0 + BARYCENTRIC_EDGE_TOLERANCE:
|
|
276
|
+
continue
|
|
277
|
+
t = (e2x * qx + e2y * qy + e2z * qz) * inv_det
|
|
278
|
+
if t < t_min:
|
|
279
|
+
continue
|
|
280
|
+
if (
|
|
281
|
+
u < BARYCENTRIC_EDGE_TOLERANCE
|
|
282
|
+
or v < BARYCENTRIC_EDGE_TOLERANCE
|
|
283
|
+
or u + v > 1.0 - BARYCENTRIC_EDGE_TOLERANCE
|
|
284
|
+
):
|
|
285
|
+
return 0, False
|
|
286
|
+
crossings += 1
|
|
287
|
+
return crossings, True
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def _error_result(name: str, message: str, total_vertices: int = 0) -> dict[str, Any]:
|
|
291
|
+
"""Degenerate input is reported, not raised: one broken mesh must not abort a whole batch."""
|
|
292
|
+
return {
|
|
293
|
+
"name": name,
|
|
294
|
+
"analyzed": False,
|
|
295
|
+
"error": message,
|
|
296
|
+
"selfIntersecting": False,
|
|
297
|
+
"insideVertexCount": 0,
|
|
298
|
+
"undecidedVertexCount": 0,
|
|
299
|
+
"outsideVertexCount": 0,
|
|
300
|
+
"sampledVertexCount": 0,
|
|
301
|
+
"totalVertexCount": total_vertices,
|
|
302
|
+
"samplingStride": 0,
|
|
303
|
+
"triangleCount": 0,
|
|
304
|
+
"degenerateTriangleCount": 0,
|
|
305
|
+
"worstRegions": [],
|
|
306
|
+
"normalSource": None,
|
|
307
|
+
"normalFallbackCount": 0,
|
|
308
|
+
"epsilon": None,
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def analyze_mesh(
|
|
313
|
+
mesh: dict[str, Any],
|
|
314
|
+
*,
|
|
315
|
+
max_samples: int = MAX_SAMPLED_VERTICES,
|
|
316
|
+
epsilon: float | None = None,
|
|
317
|
+
) -> dict[str, Any]:
|
|
318
|
+
"""Report whether a mesh's surface passes through its own volume.
|
|
319
|
+
|
|
320
|
+
`mesh` takes the same shape `geometry_integrity` uses:
|
|
321
|
+
`{"vertices": [[x, y, z], ...], "indices": [...] or [[a, b, c], ...],
|
|
322
|
+
"normals": [[x, y, z], ...] (optional), "name": str (optional)}`.
|
|
323
|
+
|
|
324
|
+
`epsilon` is the distance the sample point is stepped along its outward direction. It defaults
|
|
325
|
+
to `EPSILON_BBOX_FRACTION` of the bounding-box diagonal so it scales with the model instead of
|
|
326
|
+
being an absolute number that is correct at exactly one scale.
|
|
327
|
+
"""
|
|
328
|
+
name = str(mesh.get("name") or mesh.get("id") or "mesh")
|
|
329
|
+
raw_vertices = mesh.get("vertices")
|
|
330
|
+
if not isinstance(raw_vertices, list) or not raw_vertices:
|
|
331
|
+
return _error_result(name, "mesh has no vertices")
|
|
332
|
+
try:
|
|
333
|
+
vertices = [_as_point(vertex) for vertex in raw_vertices]
|
|
334
|
+
except (TypeError, ValueError) as exc:
|
|
335
|
+
return _error_result(name, f"invalid vertex data: {exc}", len(raw_vertices))
|
|
336
|
+
try:
|
|
337
|
+
triangles = _triangles(mesh.get("indices"))
|
|
338
|
+
except (TypeError, ValueError) as exc:
|
|
339
|
+
return _error_result(name, str(exc), len(vertices))
|
|
340
|
+
vertex_count = len(vertices)
|
|
341
|
+
if any(index < 0 or index >= vertex_count for triangle in triangles for index in triangle):
|
|
342
|
+
return _error_result(name, "triangle index out of range", vertex_count)
|
|
343
|
+
|
|
344
|
+
lo = [min(vertex[axis] for vertex in vertices) for axis in range(3)]
|
|
345
|
+
hi = [max(vertex[axis] for vertex in vertices) for axis in range(3)]
|
|
346
|
+
diagonal = sqrt(sum((hi[axis] - lo[axis]) ** 2 for axis in range(3)))
|
|
347
|
+
if diagonal <= 0.0:
|
|
348
|
+
return _error_result(name, "mesh has zero extent", vertex_count)
|
|
349
|
+
offset = float(epsilon) if epsilon is not None else EPSILON_BBOX_FRACTION * diagonal
|
|
350
|
+
if offset <= 0.0:
|
|
351
|
+
return _error_result(name, "epsilon must be positive", vertex_count)
|
|
352
|
+
# Hits closer than this are the surface the sample point is standing on, reached through
|
|
353
|
+
# floating-point noise rather than through a real second surface.
|
|
354
|
+
t_min = offset * 1e-3
|
|
355
|
+
|
|
356
|
+
prepared: list[tuple[float, ...]] = []
|
|
357
|
+
live: list[tuple[int, int, int]] = []
|
|
358
|
+
degenerate = 0
|
|
359
|
+
for a, b, c in triangles:
|
|
360
|
+
pa, pb, pc = vertices[a], vertices[b], vertices[c]
|
|
361
|
+
e1 = (pb[0] - pa[0], pb[1] - pa[1], pb[2] - pa[2])
|
|
362
|
+
e2 = (pc[0] - pa[0], pc[1] - pa[1], pc[2] - pa[2])
|
|
363
|
+
cross = (
|
|
364
|
+
e1[1] * e2[2] - e1[2] * e2[1],
|
|
365
|
+
e1[2] * e2[0] - e1[0] * e2[2],
|
|
366
|
+
e1[0] * e2[1] - e1[1] * e2[0],
|
|
367
|
+
)
|
|
368
|
+
normal_length = sqrt(cross[0] * cross[0] + cross[1] * cross[1] + cross[2] * cross[2])
|
|
369
|
+
if normal_length <= 0.0:
|
|
370
|
+
# A zero-area triangle bounds no volume and its plane is undefined; counting it would
|
|
371
|
+
# only corrupt the parity.
|
|
372
|
+
degenerate += 1
|
|
373
|
+
continue
|
|
374
|
+
prepared.append((pa[0], pa[1], pa[2], *e1, *e2, normal_length))
|
|
375
|
+
live.append((a, b, c))
|
|
376
|
+
if not live:
|
|
377
|
+
return _error_result(name, "mesh has no non-degenerate triangles", vertex_count)
|
|
378
|
+
|
|
379
|
+
# Fixed stride, never random: the same mesh must produce the same sample set every run.
|
|
380
|
+
stride = max(1, -(-vertex_count // max(1, int(max_samples))))
|
|
381
|
+
sampled = list(range(0, vertex_count, stride))
|
|
382
|
+
|
|
383
|
+
normals = mesh.get("normals")
|
|
384
|
+
use_supplied_normals = isinstance(normals, list) and len(normals) == vertex_count
|
|
385
|
+
normal_source = "vertexNormals" if use_supplied_normals else "centroid"
|
|
386
|
+
centroid = (
|
|
387
|
+
sum(vertex[0] for vertex in vertices) / vertex_count,
|
|
388
|
+
sum(vertex[1] for vertex in vertices) / vertex_count,
|
|
389
|
+
sum(vertex[2] for vertex in vertices) / vertex_count,
|
|
390
|
+
)
|
|
391
|
+
|
|
392
|
+
# Weld by rounded position rather than by index so that a seam-duplicated vertex sharing a
|
|
393
|
+
# position still masks the triangles that meet there. Without this, the surface the sample sits
|
|
394
|
+
# on gets counted as a crossing and every seam vertex reads as a false positive.
|
|
395
|
+
keys = [tuple(round(value, WELD_PRECISION) for value in vertex) for vertex in vertices]
|
|
396
|
+
sampled_keys = {keys[index] for index in sampled}
|
|
397
|
+
incident: dict[tuple[float, ...], set[int]] = {key: set() for key in sampled_keys}
|
|
398
|
+
for triangle_index, triangle in enumerate(live):
|
|
399
|
+
for corner in triangle:
|
|
400
|
+
bucket = incident.get(keys[corner])
|
|
401
|
+
if bucket is not None:
|
|
402
|
+
bucket.add(triangle_index)
|
|
403
|
+
|
|
404
|
+
grids = [_DirectionGrid(direction, vertices, live) for direction in RAY_DIRECTIONS]
|
|
405
|
+
|
|
406
|
+
inside_indices: list[int] = []
|
|
407
|
+
undecided = 0
|
|
408
|
+
normal_fallbacks = 0
|
|
409
|
+
for vertex_index in sampled:
|
|
410
|
+
vertex = vertices[vertex_index]
|
|
411
|
+
outward: Vector3 | None = None
|
|
412
|
+
if use_supplied_normals:
|
|
413
|
+
try:
|
|
414
|
+
outward = _normalize(_as_point(normals[vertex_index]))
|
|
415
|
+
except (TypeError, ValueError):
|
|
416
|
+
outward = None
|
|
417
|
+
if outward is None:
|
|
418
|
+
if use_supplied_normals:
|
|
419
|
+
# A zero-length or malformed normal on one vertex is not a reason to abandon the
|
|
420
|
+
# good normals on every other vertex; fall back for this vertex and say how often.
|
|
421
|
+
normal_fallbacks += 1
|
|
422
|
+
outward = _normalize((
|
|
423
|
+
vertex[0] - centroid[0],
|
|
424
|
+
vertex[1] - centroid[1],
|
|
425
|
+
vertex[2] - centroid[2],
|
|
426
|
+
))
|
|
427
|
+
if outward is None:
|
|
428
|
+
# A vertex sitting exactly on the centroid has no outward direction to step along.
|
|
429
|
+
undecided += 1
|
|
430
|
+
continue
|
|
431
|
+
origin = (
|
|
432
|
+
vertex[0] + outward[0] * offset,
|
|
433
|
+
vertex[1] + outward[1] * offset,
|
|
434
|
+
vertex[2] + outward[2] * offset,
|
|
435
|
+
)
|
|
436
|
+
excluded = incident[keys[vertex_index]]
|
|
437
|
+
votes: list[bool] = []
|
|
438
|
+
reliable = True
|
|
439
|
+
for direction, grid in zip(RAY_DIRECTIONS, grids):
|
|
440
|
+
alignment = direction[0] * outward[0] + direction[1] * outward[1] + direction[2] * outward[2]
|
|
441
|
+
if -TANGENT_COS_THRESHOLD < alignment < TANGENT_COS_THRESHOLD:
|
|
442
|
+
reliable = False
|
|
443
|
+
break
|
|
444
|
+
# Cast into the outward hemisphere. An inward ray from a point that is legitimately
|
|
445
|
+
# just outside the surface re-crosses that same surface immediately, on triangles this
|
|
446
|
+
# pass has masked out, and the missing crossing flips the parity to a false positive.
|
|
447
|
+
ray = direction if alignment > 0.0 else (-direction[0], -direction[1], -direction[2])
|
|
448
|
+
crossings, ok = _count_crossings(origin, ray, grid, prepared, excluded, t_min)
|
|
449
|
+
if not ok:
|
|
450
|
+
reliable = False
|
|
451
|
+
break
|
|
452
|
+
votes.append(crossings % 2 == 1)
|
|
453
|
+
if not reliable:
|
|
454
|
+
undecided += 1
|
|
455
|
+
continue
|
|
456
|
+
inside_votes = sum(votes)
|
|
457
|
+
if inside_votes * 2 == len(votes):
|
|
458
|
+
# A tie has no majority, so there is no verdict to report.
|
|
459
|
+
undecided += 1
|
|
460
|
+
elif inside_votes * 2 > len(votes):
|
|
461
|
+
inside_indices.append(vertex_index)
|
|
462
|
+
|
|
463
|
+
# Spread the reported positions across the offending set instead of returning the first eight,
|
|
464
|
+
# which on a large defect would all come from one corner of one region. There is no severity
|
|
465
|
+
# ranking to apply to a boolean inside/outside verdict, so these are representative locations a
|
|
466
|
+
# human can navigate to, not a ranking.
|
|
467
|
+
region_stride = max(1, len(inside_indices) // WORST_REGION_LIMIT)
|
|
468
|
+
worst = [
|
|
469
|
+
{"vertexIndex": index, "position": list(vertices[index])}
|
|
470
|
+
for index in inside_indices[::region_stride][:WORST_REGION_LIMIT]
|
|
471
|
+
]
|
|
472
|
+
|
|
473
|
+
return {
|
|
474
|
+
"name": name,
|
|
475
|
+
"analyzed": True,
|
|
476
|
+
"error": None,
|
|
477
|
+
"selfIntersecting": bool(inside_indices),
|
|
478
|
+
"insideVertexCount": len(inside_indices),
|
|
479
|
+
"undecidedVertexCount": undecided,
|
|
480
|
+
"outsideVertexCount": len(sampled) - len(inside_indices) - undecided,
|
|
481
|
+
"sampledVertexCount": len(sampled),
|
|
482
|
+
"totalVertexCount": vertex_count,
|
|
483
|
+
"samplingStride": stride,
|
|
484
|
+
"triangleCount": len(live),
|
|
485
|
+
"degenerateTriangleCount": degenerate,
|
|
486
|
+
"worstRegions": worst,
|
|
487
|
+
"normalSource": normal_source,
|
|
488
|
+
"normalFallbackCount": normal_fallbacks,
|
|
489
|
+
"epsilon": offset,
|
|
490
|
+
"rayDirectionCount": len(RAY_DIRECTIONS),
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
def analyze_meshes(
|
|
495
|
+
meshes: list[dict[str, Any]],
|
|
496
|
+
*,
|
|
497
|
+
max_samples: int = MAX_SAMPLED_VERTICES,
|
|
498
|
+
epsilon: float | None = None,
|
|
499
|
+
) -> dict[str, Any]:
|
|
500
|
+
"""Run `analyze_mesh` over a list of meshes and aggregate the verdicts."""
|
|
501
|
+
reports: list[dict[str, Any]] = []
|
|
502
|
+
errors: list[str] = []
|
|
503
|
+
for index, mesh in enumerate(meshes):
|
|
504
|
+
if not isinstance(mesh, dict):
|
|
505
|
+
report = _error_result(f"mesh-{index}", "mesh entry is not an object")
|
|
506
|
+
else:
|
|
507
|
+
report = analyze_mesh(mesh, max_samples=max_samples, epsilon=epsilon)
|
|
508
|
+
if report["error"]:
|
|
509
|
+
errors.append(f"{report['name']}: {report['error']}")
|
|
510
|
+
reports.append(report)
|
|
511
|
+
return {
|
|
512
|
+
"selfIntersecting": any(report["selfIntersecting"] for report in reports),
|
|
513
|
+
"meshCount": len(reports),
|
|
514
|
+
"insideVertexCount": sum(report["insideVertexCount"] for report in reports),
|
|
515
|
+
"undecidedVertexCount": sum(report["undecidedVertexCount"] for report in reports),
|
|
516
|
+
"sampledVertexCount": sum(report["sampledVertexCount"] for report in reports),
|
|
517
|
+
"totalVertexCount": sum(report["totalVertexCount"] for report in reports),
|
|
518
|
+
"meshes": reports,
|
|
519
|
+
"errors": errors,
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
def _load_meshes(path: Path) -> list[dict[str, Any]]:
|
|
524
|
+
payload = json.loads(path.read_text())
|
|
525
|
+
if isinstance(payload, list):
|
|
526
|
+
return payload
|
|
527
|
+
if isinstance(payload, dict):
|
|
528
|
+
meshes = payload.get("meshes")
|
|
529
|
+
if meshes is None:
|
|
530
|
+
meshes = payload.get("components")
|
|
531
|
+
if isinstance(meshes, dict):
|
|
532
|
+
return [dict(value, id=key) if isinstance(value, dict) else {"id": key} for key, value in meshes.items()]
|
|
533
|
+
if isinstance(meshes, list):
|
|
534
|
+
return meshes
|
|
535
|
+
if isinstance(payload.get("vertices"), list):
|
|
536
|
+
return [payload]
|
|
537
|
+
raise ValueError("input must be a mesh, an array of meshes, or an object with meshes/components")
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
def _format_summary(result: dict[str, Any]) -> str:
|
|
541
|
+
lines: list[str] = []
|
|
542
|
+
for report in result["meshes"]:
|
|
543
|
+
if report["error"]:
|
|
544
|
+
lines.append(f" [ERROR] {report['name']}: {report['error']}")
|
|
545
|
+
continue
|
|
546
|
+
flag = "SELF-INTERSECTING" if report["selfIntersecting"] else "ok"
|
|
547
|
+
lines.append(
|
|
548
|
+
f" [{flag}] {report['name']} "
|
|
549
|
+
f"sampled={report['sampledVertexCount']}/{report['totalVertexCount']} "
|
|
550
|
+
f"(stride {report['samplingStride']}) "
|
|
551
|
+
f"inside={report['insideVertexCount']} undecided={report['undecidedVertexCount']} "
|
|
552
|
+
f"normals={report['normalSource']} epsilon={report['epsilon']:.6g}"
|
|
553
|
+
)
|
|
554
|
+
for region in report["worstRegions"]:
|
|
555
|
+
position = ", ".join(f"{value:.4f}" for value in region["position"])
|
|
556
|
+
lines.append(f" vertex {region['vertexIndex']} at ({position})")
|
|
557
|
+
if result["errors"]:
|
|
558
|
+
verdict = "ERROR"
|
|
559
|
+
elif result["selfIntersecting"]:
|
|
560
|
+
verdict = "SELF-INTERSECTION DETECTED"
|
|
561
|
+
else:
|
|
562
|
+
verdict = "no self-intersection"
|
|
563
|
+
lines.append(f"verdict: {verdict}")
|
|
564
|
+
return "\n".join(lines)
|
|
565
|
+
|
|
566
|
+
|
|
567
|
+
def main(argv: list[str]) -> int:
|
|
568
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
569
|
+
parser.add_argument("meshes", type=Path, help="JSON file: a mesh, an array of meshes, or {meshes: [...]}")
|
|
570
|
+
parser.add_argument("--max-samples", type=int, default=MAX_SAMPLED_VERTICES)
|
|
571
|
+
parser.add_argument("--epsilon", type=float, default=None)
|
|
572
|
+
parser.add_argument("--json", action="store_true", help="print JSON instead of a summary")
|
|
573
|
+
args = parser.parse_args(argv)
|
|
574
|
+
|
|
575
|
+
try:
|
|
576
|
+
meshes = _load_meshes(args.meshes)
|
|
577
|
+
result = analyze_meshes(meshes, max_samples=args.max_samples, epsilon=args.epsilon)
|
|
578
|
+
if args.json:
|
|
579
|
+
print(json.dumps(result, indent=2, ensure_ascii=False))
|
|
580
|
+
else:
|
|
581
|
+
print(_format_summary(result))
|
|
582
|
+
# An unreadable mesh is an error, not a clean bill of health, so it outranks the verdict.
|
|
583
|
+
if result["errors"]:
|
|
584
|
+
return 2
|
|
585
|
+
return 1 if result["selfIntersecting"] else 0
|
|
586
|
+
except Exception as exc:
|
|
587
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
588
|
+
return 2
|
|
589
|
+
|
|
590
|
+
|
|
591
|
+
if __name__ == "__main__":
|
|
592
|
+
raise SystemExit(main(sys.argv[1:]))
|