Create henry
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291import mathimport osimport sysimport numpy as npimport torchimport open3d as o3d from OCC.Core.STEPControl import STEPControl_Readerfrom OCC.Core.IFSelect import IFSelect_RetDonefrom OCC.Core.BRepMesh import BRepMesh_IncrementalMeshfrom OCC.Core.TopExp import TopExp_Explorerfrom OCC.Core.TopAbs import TopAbs_FACEfrom OCC.Core.TopoDS import topodsfrom OCC.Core.BRep import BRep_Toolfrom OCC.Core.TopLoc import TopLoc_Locationfrom OCC.Core.BRepTools import BRepTools # --------------------------# Device info (Torch optional)# --------------------------device = torch.device("cpu")print(f"Using device: {device}") # --------------------------# Geometry helpers# --------------------------def triangle_area(v1, v2, v3): """Area of triangle given 3 vertices (tuples/lists of xyz).""" ax, ay, az = v2[0]-v1[0], v2[1]-v1[1], v2[2]-v1[2] bx, by, bz = v3[0]-v1[0], v3[1]-v1[1], v3[2]-v1[2] cross_x = ay*bz - az*by cross_y = az*bx - ax*bz cross_z = ax*by - ay*bx cross_len = math.sqrt(cross_x**2 + cross_y**2 + cross_z**2) return 0.5 * cross_len def sample_triangle_points(args): """ Uniformly sample points inside a single triangle using barycentric sampling. Args: (v1, v2, v3, num_points_for_triangle) Returns: list[[x, y, z], ...] """ v1, v2, v3, num_points_for_triangle = args if num_points_for_triangle <= 0: return [] # Torch used for fast vectorized sampling on CPU v1_t = torch.tensor(v1, dtype=torch.float) v2_t = torch.tensor(v2, dtype=torch.float) v3_t = torch.tensor(v3, dtype=torch.float) rand_vals = torch.rand((num_points_for_triangle, 2)) u = rand_vals[:, 0] w = rand_vals[:, 1] # Reflect to keep samples inside the triangle mask = (u + w) > 1.0 u[mask] = 1 - u[mask] w[mask] = 1 - w[mask] v2v1 = (v2_t - v1_t) v3v1 = (v3_t - v1_t) sampled_points = v1_t + u.unsqueeze(1) * v2v1 + w.unsqueeze(1) * v3v1 return sampled_points.numpy().tolist() # --------------------------# OCC meshing helpers# --------------------------def _clear_triangulation(shape): """Remove any existing triangulations from a shape before remeshing.""" BRepTools.Clean(shape) def _mesh_shape(shape, linear_deflection, angular_deflection=0.5, is_relative=True, is_in_parallel=True): """ Run OCC incremental meshing on 'shape' with given params. Returns True if meshing succeeds. """ mesh = BRepMesh_IncrementalMesh(shape, linear_deflection, is_relative, angular_deflection, is_in_parallel) mesh.Perform() return mesh.IsDone() def _count_triangles(shape): """Return total triangle count in the current OCC triangulation.""" total = 0 face_exp = TopExp_Explorer(shape, TopAbs_FACE) while face_exp.More(): face = topods.Face(face_exp.Current()) loc = TopLoc_Location() triangulation = BRep_Tool.Triangulation(face, loc) if triangulation is not None: total += triangulation.NbTriangles() face_exp.Next() return total def _shape_to_open3d_triangle_mesh(shape, round_digits=8): """ Convert OCC triangulations of the entire shape into a single Open3D TriangleMesh. Deduplicates vertices by rounding to 'round_digits' decimals. """ vertex_map = {} # key: (x_r, y_r, z_r) -> new_idx vertices = [] triangles = [] face_exp = TopExp_Explorer(shape, TopAbs_FACE) while face_exp.More(): face = topods.Face(face_exp.Current()) loc = TopLoc_Location() triangulation = BRep_Tool.Triangulation(face, loc) if triangulation is not None: trsf = loc.Transformation() nb_tris = triangulation.NbTriangles() for i in range(1, nb_tris + 1): tri = triangulation.Triangle(i) i1, i2, i3 = tri.Get() p1 = triangulation.Node(i1) p2 = triangulation.Node(i2) p3 = triangulation.Node(i3) # Apply location transform if needed if not loc.IsIdentity(): p1 = p1.Transformed(trsf) p2 = p2.Transformed(trsf) p3 = p3.Transformed(trsf) v1 = (p1.X(), p1.Y(), p1.Z()) v2 = (p2.X(), p2.Y(), p2.Z()) v3 = (p3.X(), p3.Y(), p3.Z()) def idx_for(v): key = (round(v[0], round_digits), round(v[1], round_digits), round(v[2], round_digits)) if key in vertex_map: return vertex_map[key] idx = len(vertices) vertices.append(v) vertex_map[key] = idx return idx i_v1 = idx_for(v1) i_v2 = idx_for(v2) i_v3 = idx_for(v3) triangles.append((i_v1, i_v2, i_v3)) face_exp.Next() if not vertices or not triangles: raise ValueError("No triangles found when converting shape to Open3D mesh.") mesh = o3d.geometry.TriangleMesh() mesh.vertices = o3d.utility.Vector3dVector(np.asarray(vertices, dtype=np.float64)) mesh.triangles = o3d.utility.Vector3iVector(np.asarray(triangles, dtype=np.int32)) # Clean-up to ensure decimation behaves well mesh.remove_duplicated_vertices() mesh.remove_degenerate_triangles() mesh.remove_duplicated_triangles() mesh.remove_non_manifold_edges() mesh.compute_vertex_normals() return mesh def _search_deflection_for_target_triangles(shape, target_total_triangles, angular_deflection=0.5, is_relative=True, tol_ratio=0.05, min_defl=1e-5, max_defl=0.5, max_iters=15): """ Try to reach ~target_total_triangles by binary searching OCC's linear deflection. Returns (best_deflection, achieved_triangle_count). NOTE: This is approximate; for exact targets, decimate with Open3D. """ def g(defl): _clear_triangulation(shape) ok = _mesh_shape(shape, defl, angular_deflection, is_relative=is_relative) if not ok: raise RuntimeError("Mesh generation failed during deflection search.") return _count_triangles(shape) # Evaluate at a fine deflection (many triangles) d_lo = min_defl n_lo = g(d_lo) # If even at finest mesh we can't reach the target, give up (shape is too simple) if n_lo < target_total_triangles: print(f"[Deflection search] Max triangles at deflection={d_lo:g} is {n_lo} < target {target_total_triangles}.") return d_lo, n_lo # Evaluate at a coarse deflection (few triangles) d_hi = max_defl n_hi = g(d_hi) # If still too many triangles at coarse deflection, expand up to deflection=1.0 while n_hi > target_total_triangles and d_hi < 1.0: d_hi = min(1.0, d_hi * 2.0) n_hi = g(d_hi) if d_hi >= 1.0: break if n_hi > target_total_triangles: # Can't go coarser; accept the coarsest result print(f"[Deflection search] Coarsest triangles at deflection={d_hi:g} is {n_hi} > target {target_total_triangles}.") return d_hi, n_hi # Now we have n_lo >= target >= n_hi; do bisection for _ in range(max_iters): d_mid = 0.5 * (d_lo + d_hi) n_mid = g(d_mid) if n_mid >= target_total_triangles: # Too many triangles -> increase deflection (move lo up) d_lo, n_lo = d_mid, n_mid else: # Too few triangles -> decrease deflection (move hi down) d_hi, n_hi = d_mid, n_mid # Check tolerance if abs(n_mid - target_total_triangles) <= tol_ratio * target_total_triangles: return d_mid, n_mid # Return the closer of (lo, hi) if abs(n_lo - target_total_triangles) <= abs(n_hi - target_total_triangles): return d_lo, n_lo else: return d_hi, n_hi # --------------------------# STEP -> Point cloud (with triangle budget option)# --------------------------def step_to_point_cloud( step_file_path, mesh_linear_deflection=0.05, mesh_angular_deflection=0.5, target_point_density=20, max_total_points=5_000_000, target_total_triangles=None, # << NEW: set to an int (e.g., 10000) to control mesh triangle count triangles_mode="decimate", # "decimate" (exact-ish) or "deflection_search" (approximate) save_decimated_mesh_path=None # if not None, save the decimated mesh here (PLY/OBJ/STL supported by Open3D)): """ Convert STEP to point cloud by sampling triangles. If 'target_total_triangles' is set: - triangles_mode == "decimate": build a dense mesh, then decimate to exact target using Open3D. - triangles_mode == "deflection_search": binary search OCC linear deflection to roughly reach the target. Returns: open3d.geometry.PointCloud """ print(f"Reading STEP file: {step_file_path}") step_reader = STEPControl_Reader() status = step_reader.ReadFile(step_file_path) if status != IFSelect_RetDone: raise ValueError(f"Cannot read STEP file: {step_file_path}") print("STEP file read successfully.") step_reader.TransferRoots() shape = step_reader.OneShape() if shape.IsNull(): raise ValueError("No shape found in STEP file.") print("Shape transfer completed.") # ---- Meshing strategy based on triangles control ---- if target_total_triangles is None: # Original path: one-shot tessellation with given deflection print("Starting tessellation (no triangle budget)...") _clear_triangulation(shape) ok = _mesh_shape(shape, mesh_linear_deflection, mesh_angular_deflection, is_relative=True, is_in_parallel=True) if not ok: raise RuntimeError("Mesh generation failed.") print("Tessellation completed.") # We'll use OCC triangulation directly for sampling triangulation_source = "occ" else: if triangles_mode not in ("decimate", "deflection_search"): raise ValueError("triangles_mode must be 'decimate' or 'deflection_search'.") if triangles_mode == "deflection_search": print(f"Starting tessellation (triangle budget via deflection search -> target={target_total_triangles})...") best_defl, achieved = _search_deflection_for_target_triangles( shape, target_total_triangles=target_total_triangles, angular_deflection=mesh_angular_deflection, is_relative=True, tol_ratio=0.05, min_defl=1e-5, max_defl=0.25, max_iters=15 ) print(f"Deflection search result: deflection={best_defl:g}, triangles≈{achieved} (target={target_total_triangles})") # Already meshed at best_defl inside search; use OCC triangulation directly triangulation_source = "occ" henryAdded+291