Silly98 commited on
Commit
1d21f4f
·
verified ·
1 Parent(s): d4cec1b

Create henry

Browse files
Files changed (1) hide show
  1. henry +291 -0
henry ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import os
3
+ import sys
4
+ import numpy as np
5
+ import torch
6
+ import open3d as o3d
7
+
8
+ from OCC.Core.STEPControl import STEPControl_Reader
9
+ from OCC.Core.IFSelect import IFSelect_RetDone
10
+ from OCC.Core.BRepMesh import BRepMesh_IncrementalMesh
11
+ from OCC.Core.TopExp import TopExp_Explorer
12
+ from OCC.Core.TopAbs import TopAbs_FACE
13
+ from OCC.Core.TopoDS import topods
14
+ from OCC.Core.BRep import BRep_Tool
15
+ from OCC.Core.TopLoc import TopLoc_Location
16
+ from OCC.Core.BRepTools import BRepTools
17
+
18
+ # --------------------------
19
+ # Device info (Torch optional)
20
+ # --------------------------
21
+ device = torch.device("cpu")
22
+ print(f"Using device: {device}")
23
+
24
+ # --------------------------
25
+ # Geometry helpers
26
+ # --------------------------
27
+ def triangle_area(v1, v2, v3):
28
+ """Area of triangle given 3 vertices (tuples/lists of xyz)."""
29
+ ax, ay, az = v2[0]-v1[0], v2[1]-v1[1], v2[2]-v1[2]
30
+ bx, by, bz = v3[0]-v1[0], v3[1]-v1[1], v3[2]-v1[2]
31
+ cross_x = ay*bz - az*by
32
+ cross_y = az*bx - ax*bz
33
+ cross_z = ax*by - ay*bx
34
+ cross_len = math.sqrt(cross_x**2 + cross_y**2 + cross_z**2)
35
+ return 0.5 * cross_len
36
+
37
+ def sample_triangle_points(args):
38
+ """
39
+ Uniformly sample points inside a single triangle using barycentric sampling.
40
+ Args: (v1, v2, v3, num_points_for_triangle)
41
+ Returns: list[[x, y, z], ...]
42
+ """
43
+ v1, v2, v3, num_points_for_triangle = args
44
+ if num_points_for_triangle <= 0:
45
+ return []
46
+
47
+ # Torch used for fast vectorized sampling on CPU
48
+ v1_t = torch.tensor(v1, dtype=torch.float)
49
+ v2_t = torch.tensor(v2, dtype=torch.float)
50
+ v3_t = torch.tensor(v3, dtype=torch.float)
51
+
52
+ rand_vals = torch.rand((num_points_for_triangle, 2))
53
+ u = rand_vals[:, 0]
54
+ w = rand_vals[:, 1]
55
+ # Reflect to keep samples inside the triangle
56
+ mask = (u + w) > 1.0
57
+ u[mask] = 1 - u[mask]
58
+ w[mask] = 1 - w[mask]
59
+
60
+ v2v1 = (v2_t - v1_t)
61
+ v3v1 = (v3_t - v1_t)
62
+ sampled_points = v1_t + u.unsqueeze(1) * v2v1 + w.unsqueeze(1) * v3v1
63
+ return sampled_points.numpy().tolist()
64
+
65
+ # --------------------------
66
+ # OCC meshing helpers
67
+ # --------------------------
68
+ def _clear_triangulation(shape):
69
+ """Remove any existing triangulations from a shape before remeshing."""
70
+ BRepTools.Clean(shape)
71
+
72
+ def _mesh_shape(shape, linear_deflection, angular_deflection=0.5, is_relative=True, is_in_parallel=True):
73
+ """
74
+ Run OCC incremental meshing on 'shape' with given params.
75
+ Returns True if meshing succeeds.
76
+ """
77
+ mesh = BRepMesh_IncrementalMesh(shape, linear_deflection, is_relative, angular_deflection, is_in_parallel)
78
+ mesh.Perform()
79
+ return mesh.IsDone()
80
+
81
+ def _count_triangles(shape):
82
+ """Return total triangle count in the current OCC triangulation."""
83
+ total = 0
84
+ face_exp = TopExp_Explorer(shape, TopAbs_FACE)
85
+ while face_exp.More():
86
+ face = topods.Face(face_exp.Current())
87
+ loc = TopLoc_Location()
88
+ triangulation = BRep_Tool.Triangulation(face, loc)
89
+ if triangulation is not None:
90
+ total += triangulation.NbTriangles()
91
+ face_exp.Next()
92
+ return total
93
+
94
+ def _shape_to_open3d_triangle_mesh(shape, round_digits=8):
95
+ """
96
+ Convert OCC triangulations of the entire shape into a single Open3D TriangleMesh.
97
+ Deduplicates vertices by rounding to 'round_digits' decimals.
98
+ """
99
+ vertex_map = {} # key: (x_r, y_r, z_r) -> new_idx
100
+ vertices = []
101
+ triangles = []
102
+
103
+ face_exp = TopExp_Explorer(shape, TopAbs_FACE)
104
+ while face_exp.More():
105
+ face = topods.Face(face_exp.Current())
106
+ loc = TopLoc_Location()
107
+ triangulation = BRep_Tool.Triangulation(face, loc)
108
+ if triangulation is not None:
109
+ trsf = loc.Transformation()
110
+ nb_tris = triangulation.NbTriangles()
111
+ for i in range(1, nb_tris + 1):
112
+ tri = triangulation.Triangle(i)
113
+ i1, i2, i3 = tri.Get()
114
+
115
+ p1 = triangulation.Node(i1)
116
+ p2 = triangulation.Node(i2)
117
+ p3 = triangulation.Node(i3)
118
+
119
+ # Apply location transform if needed
120
+ if not loc.IsIdentity():
121
+ p1 = p1.Transformed(trsf)
122
+ p2 = p2.Transformed(trsf)
123
+ p3 = p3.Transformed(trsf)
124
+
125
+ v1 = (p1.X(), p1.Y(), p1.Z())
126
+ v2 = (p2.X(), p2.Y(), p2.Z())
127
+ v3 = (p3.X(), p3.Y(), p3.Z())
128
+
129
+ def idx_for(v):
130
+ key = (round(v[0], round_digits), round(v[1], round_digits), round(v[2], round_digits))
131
+ if key in vertex_map:
132
+ return vertex_map[key]
133
+ idx = len(vertices)
134
+ vertices.append(v)
135
+ vertex_map[key] = idx
136
+ return idx
137
+
138
+ i_v1 = idx_for(v1)
139
+ i_v2 = idx_for(v2)
140
+ i_v3 = idx_for(v3)
141
+ triangles.append((i_v1, i_v2, i_v3))
142
+
143
+ face_exp.Next()
144
+
145
+ if not vertices or not triangles:
146
+ raise ValueError("No triangles found when converting shape to Open3D mesh.")
147
+
148
+ mesh = o3d.geometry.TriangleMesh()
149
+ mesh.vertices = o3d.utility.Vector3dVector(np.asarray(vertices, dtype=np.float64))
150
+ mesh.triangles = o3d.utility.Vector3iVector(np.asarray(triangles, dtype=np.int32))
151
+
152
+ # Clean-up to ensure decimation behaves well
153
+ mesh.remove_duplicated_vertices()
154
+ mesh.remove_degenerate_triangles()
155
+ mesh.remove_duplicated_triangles()
156
+ mesh.remove_non_manifold_edges()
157
+ mesh.compute_vertex_normals()
158
+ return mesh
159
+
160
+ def _search_deflection_for_target_triangles(shape,
161
+ target_total_triangles,
162
+ angular_deflection=0.5,
163
+ is_relative=True,
164
+ tol_ratio=0.05,
165
+ min_defl=1e-5,
166
+ max_defl=0.5,
167
+ max_iters=15):
168
+ """
169
+ Try to reach ~target_total_triangles by binary searching OCC's linear deflection.
170
+ Returns (best_deflection, achieved_triangle_count).
171
+ NOTE: This is approximate; for exact targets, decimate with Open3D.
172
+ """
173
+ def g(defl):
174
+ _clear_triangulation(shape)
175
+ ok = _mesh_shape(shape, defl, angular_deflection, is_relative=is_relative)
176
+ if not ok:
177
+ raise RuntimeError("Mesh generation failed during deflection search.")
178
+ return _count_triangles(shape)
179
+
180
+ # Evaluate at a fine deflection (many triangles)
181
+ d_lo = min_defl
182
+ n_lo = g(d_lo)
183
+
184
+ # If even at finest mesh we can't reach the target, give up (shape is too simple)
185
+ if n_lo < target_total_triangles:
186
+ print(f"[Deflection search] Max triangles at deflection={d_lo:g} is {n_lo} < target {target_total_triangles}.")
187
+ return d_lo, n_lo
188
+
189
+ # Evaluate at a coarse deflection (few triangles)
190
+ d_hi = max_defl
191
+ n_hi = g(d_hi)
192
+
193
+ # If still too many triangles at coarse deflection, expand up to deflection=1.0
194
+ while n_hi > target_total_triangles and d_hi < 1.0:
195
+ d_hi = min(1.0, d_hi * 2.0)
196
+ n_hi = g(d_hi)
197
+ if d_hi >= 1.0:
198
+ break
199
+
200
+ if n_hi > target_total_triangles:
201
+ # Can't go coarser; accept the coarsest result
202
+ print(f"[Deflection search] Coarsest triangles at deflection={d_hi:g} is {n_hi} > target {target_total_triangles}.")
203
+ return d_hi, n_hi
204
+
205
+ # Now we have n_lo >= target >= n_hi; do bisection
206
+ for _ in range(max_iters):
207
+ d_mid = 0.5 * (d_lo + d_hi)
208
+ n_mid = g(d_mid)
209
+
210
+ if n_mid >= target_total_triangles:
211
+ # Too many triangles -> increase deflection (move lo up)
212
+ d_lo, n_lo = d_mid, n_mid
213
+ else:
214
+ # Too few triangles -> decrease deflection (move hi down)
215
+ d_hi, n_hi = d_mid, n_mid
216
+
217
+ # Check tolerance
218
+ if abs(n_mid - target_total_triangles) <= tol_ratio * target_total_triangles:
219
+ return d_mid, n_mid
220
+
221
+ # Return the closer of (lo, hi)
222
+ if abs(n_lo - target_total_triangles) <= abs(n_hi - target_total_triangles):
223
+ return d_lo, n_lo
224
+ else:
225
+ return d_hi, n_hi
226
+
227
+ # --------------------------
228
+ # STEP -> Point cloud (with triangle budget option)
229
+ # --------------------------
230
+ def step_to_point_cloud(
231
+ step_file_path,
232
+ mesh_linear_deflection=0.05,
233
+ mesh_angular_deflection=0.5,
234
+ target_point_density=20,
235
+ max_total_points=5_000_000,
236
+ target_total_triangles=None, # << NEW: set to an int (e.g., 10000) to control mesh triangle count
237
+ triangles_mode="decimate", # "decimate" (exact-ish) or "deflection_search" (approximate)
238
+ save_decimated_mesh_path=None # if not None, save the decimated mesh here (PLY/OBJ/STL supported by Open3D)
239
+ ):
240
+ """
241
+ Convert STEP to point cloud by sampling triangles.
242
+ If 'target_total_triangles' is set:
243
+ - triangles_mode == "decimate": build a dense mesh, then decimate to exact target using Open3D.
244
+ - triangles_mode == "deflection_search": binary search OCC linear deflection to roughly reach the target.
245
+ Returns: open3d.geometry.PointCloud
246
+ """
247
+ print(f"Reading STEP file: {step_file_path}")
248
+ step_reader = STEPControl_Reader()
249
+ status = step_reader.ReadFile(step_file_path)
250
+ if status != IFSelect_RetDone:
251
+ raise ValueError(f"Cannot read STEP file: {step_file_path}")
252
+ print("STEP file read successfully.")
253
+
254
+ step_reader.TransferRoots()
255
+ shape = step_reader.OneShape()
256
+ if shape.IsNull():
257
+ raise ValueError("No shape found in STEP file.")
258
+ print("Shape transfer completed.")
259
+
260
+ # ---- Meshing strategy based on triangles control ----
261
+ if target_total_triangles is None:
262
+ # Original path: one-shot tessellation with given deflection
263
+ print("Starting tessellation (no triangle budget)...")
264
+ _clear_triangulation(shape)
265
+ ok = _mesh_shape(shape, mesh_linear_deflection, mesh_angular_deflection, is_relative=True, is_in_parallel=True)
266
+ if not ok:
267
+ raise RuntimeError("Mesh generation failed.")
268
+ print("Tessellation completed.")
269
+ # We'll use OCC triangulation directly for sampling
270
+ triangulation_source = "occ"
271
+ else:
272
+ if triangles_mode not in ("decimate", "deflection_search"):
273
+ raise ValueError("triangles_mode must be 'decimate' or 'deflection_search'.")
274
+
275
+ if triangles_mode == "deflection_search":
276
+ print(f"Starting tessellation (triangle budget via deflection search -> target={target_total_triangles})...")
277
+ best_defl, achieved = _search_deflection_for_target_triangles(
278
+ shape,
279
+ target_total_triangles=target_total_triangles,
280
+ angular_deflection=mesh_angular_deflection,
281
+ is_relative=True,
282
+ tol_ratio=0.05,
283
+ min_defl=1e-5,
284
+ max_defl=0.25,
285
+ max_iters=15
286
+ )
287
+ print(f"Deflection search result: deflection={best_defl:g}, triangles≈{achieved} (target={target_total_triangles})")
288
+ # Already meshed at best_defl inside search; use OCC triangulation directly
289
+ triangulation_source = "occ"
290
+
291
+