556 lines
22 KiB
Python
556 lines
22 KiB
Python
#!/usr/bin/env python3
|
|
"""Extract auditable STEP B-Rep topology and a display-only triangulation.
|
|
|
|
The JSON keeps exact OCCT Face/Wire/Edge identities and analytic curve parameters.
|
|
Triangle data and sampled edge points are emitted only for Three.js display/picking.
|
|
They are never used as the source of saved interface geometry.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import math
|
|
import sys
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
from OCP.Bnd import Bnd_Box
|
|
from OCP.BRep import BRep_Tool
|
|
from OCP.BRepAdaptor import BRepAdaptor_Curve, BRepAdaptor_Surface
|
|
from OCP.BRepBndLib import BRepBndLib
|
|
from OCP.BRepGProp import BRepGProp
|
|
from OCP.BRepMesh import BRepMesh_IncrementalMesh
|
|
from OCP.BRepTools import BRepTools, BRepTools_WireExplorer
|
|
from OCP.GProp import GProp_GProps
|
|
from OCP.GeomAbs import (
|
|
GeomAbs_BSplineCurve,
|
|
GeomAbs_BSplineSurface,
|
|
GeomAbs_BezierCurve,
|
|
GeomAbs_BezierSurface,
|
|
GeomAbs_Circle,
|
|
GeomAbs_Cone,
|
|
GeomAbs_Cylinder,
|
|
GeomAbs_Ellipse,
|
|
GeomAbs_Hyperbola,
|
|
GeomAbs_Line,
|
|
GeomAbs_OffsetCurve,
|
|
GeomAbs_OffsetSurface,
|
|
GeomAbs_OtherCurve,
|
|
GeomAbs_OtherSurface,
|
|
GeomAbs_Parabola,
|
|
GeomAbs_Plane,
|
|
GeomAbs_Sphere,
|
|
GeomAbs_SurfaceOfExtrusion,
|
|
GeomAbs_SurfaceOfRevolution,
|
|
GeomAbs_Torus,
|
|
)
|
|
from OCP.IFSelect import IFSelect_RetDone
|
|
from OCP.Interface import Interface_Static
|
|
from OCP.STEPControl import STEPControl_Reader
|
|
from OCP.TopAbs import TopAbs_EDGE, TopAbs_FACE, TopAbs_REVERSED
|
|
from OCP.TopExp import TopExp
|
|
from OCP.TopLoc import TopLoc_Location
|
|
from OCP.TopTools import TopTools_IndexedMapOfShape
|
|
from OCP.TopoDS import TopoDS
|
|
|
|
|
|
CURVE_TYPES = {
|
|
GeomAbs_Line: "line",
|
|
GeomAbs_Circle: "circle",
|
|
GeomAbs_Ellipse: "ellipse",
|
|
GeomAbs_Hyperbola: "hyperbola",
|
|
GeomAbs_Parabola: "parabola",
|
|
GeomAbs_BezierCurve: "bezier",
|
|
GeomAbs_BSplineCurve: "bspline",
|
|
GeomAbs_OffsetCurve: "offset",
|
|
GeomAbs_OtherCurve: "other",
|
|
}
|
|
|
|
SURFACE_TYPES = {
|
|
GeomAbs_Plane: "plane",
|
|
GeomAbs_Cylinder: "cylinder",
|
|
GeomAbs_Cone: "cone",
|
|
GeomAbs_Sphere: "sphere",
|
|
GeomAbs_Torus: "torus",
|
|
GeomAbs_BezierSurface: "bezier",
|
|
GeomAbs_BSplineSurface: "bspline",
|
|
GeomAbs_SurfaceOfRevolution: "revolution",
|
|
GeomAbs_SurfaceOfExtrusion: "extrusion",
|
|
GeomAbs_OffsetSurface: "offset",
|
|
GeomAbs_OtherSurface: "other",
|
|
}
|
|
|
|
|
|
def xyz(point: Any) -> list[float]:
|
|
return [float(point.X()), float(point.Y()), float(point.Z())]
|
|
|
|
|
|
def direction_xyz(direction: Any, reverse: bool = False) -> list[float]:
|
|
sign = -1.0 if reverse else 1.0
|
|
return [sign * float(direction.X()), sign * float(direction.Y()), sign * float(direction.Z())]
|
|
|
|
|
|
def distance(first: list[float], second: list[float]) -> float:
|
|
return math.sqrt(sum((a - b) ** 2 for a, b in zip(first, second)))
|
|
|
|
|
|
def dot(first: list[float], second: list[float]) -> float:
|
|
return sum(a * b for a, b in zip(first, second))
|
|
|
|
|
|
def normalized(vector: list[float]) -> list[float]:
|
|
length = math.sqrt(dot(vector, vector))
|
|
return [value / length for value in vector] if length > 1e-12 else [0.0, 0.0, 0.0]
|
|
|
|
|
|
def cross(first: list[float], second: list[float]) -> list[float]:
|
|
return [
|
|
first[1] * second[2] - first[2] * second[1],
|
|
first[2] * second[0] - first[0] * second[2],
|
|
first[0] * second[1] - first[1] * second[0],
|
|
]
|
|
|
|
|
|
def solve_three_by_three(matrix: list[list[float]], values: list[float]) -> list[float] | None:
|
|
augmented = [row[:] + [value] for row, value in zip(matrix, values)]
|
|
for column in range(3):
|
|
pivot = max(range(column, 3), key=lambda row: abs(augmented[row][column]))
|
|
if abs(augmented[pivot][column]) < 1e-12:
|
|
return None
|
|
augmented[column], augmented[pivot] = augmented[pivot], augmented[column]
|
|
divisor = augmented[column][column]
|
|
augmented[column] = [value / divisor for value in augmented[column]]
|
|
for row in range(3):
|
|
if row == column:
|
|
continue
|
|
factor = augmented[row][column]
|
|
augmented[row] = [
|
|
current - factor * pivot_value
|
|
for current, pivot_value in zip(augmented[row], augmented[column])
|
|
]
|
|
return [augmented[row][3] for row in range(3)]
|
|
|
|
|
|
def source_hash(path: Path) -> str:
|
|
digest = hashlib.sha256()
|
|
with path.open("rb") as stream:
|
|
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
|
digest.update(chunk)
|
|
return digest.hexdigest()
|
|
|
|
|
|
def shape_diagonal_mm(shape: Any) -> float:
|
|
box = Bnd_Box()
|
|
BRepBndLib.Add_s(shape, box, True)
|
|
if box.IsVoid():
|
|
return 100.0
|
|
xmin, ymin, zmin, xmax, ymax, zmax = box.Get()
|
|
return math.sqrt((xmax - xmin) ** 2 + (ymax - ymin) ** 2 + (zmax - zmin) ** 2)
|
|
|
|
|
|
def sample_curve(curve: BRepAdaptor_Curve, reversed_edge: bool) -> list[list[float]]:
|
|
first = float(curve.FirstParameter())
|
|
last = float(curve.LastParameter())
|
|
curve_type = curve.GetType()
|
|
if not math.isfinite(first) or not math.isfinite(last):
|
|
return []
|
|
if curve_type == GeomAbs_Line:
|
|
count = 2
|
|
elif curve_type in (GeomAbs_Circle, GeomAbs_Ellipse):
|
|
count = max(12, min(64, int(math.ceil(abs(last - first) / (math.pi / 24.0))) + 1))
|
|
else:
|
|
count = 32
|
|
points = [xyz(curve.Value(first + (last - first) * index / (count - 1))) for index in range(count)]
|
|
return list(reversed(points)) if reversed_edge else points
|
|
|
|
|
|
def edge_payload(edge: Any, edge_index: int, file_hash: str) -> dict[str, Any]:
|
|
curve = BRepAdaptor_Curve(edge)
|
|
curve_type = CURVE_TYPES.get(curve.GetType(), "other")
|
|
reversed_edge = edge.Orientation() == TopAbs_REVERSED
|
|
samples = sample_curve(curve, reversed_edge)
|
|
payload: dict[str, Any] = {
|
|
"id": f"brep:edge:{edge_index}",
|
|
"sourceRef": f"sha256:{file_hash}:edge:{edge_index}",
|
|
"curveType": curve_type,
|
|
"orientation": "reversed" if reversed_edge else "forward",
|
|
"firstParameter": float(curve.FirstParameter()),
|
|
"lastParameter": float(curve.LastParameter()),
|
|
"startMm": samples[0] if samples else None,
|
|
"endMm": samples[-1] if samples else None,
|
|
"samplesMm": samples,
|
|
"isExact": True,
|
|
# Any native STEP edge with a usable sampled trace can define the
|
|
# outer wire. Analytic line/circle parameters are preferred when
|
|
# available, while B-Spline/Bezier/ellipse edges retain their exact
|
|
# sourceRef plus display samples instead of being rejected by type.
|
|
"selectableAsBoundary": len(samples) >= 2,
|
|
}
|
|
if curve_type == "line":
|
|
line = curve.Line()
|
|
payload["direction"] = direction_xyz(line.Direction(), reversed_edge)
|
|
elif curve_type == "circle":
|
|
circle = curve.Circle()
|
|
payload.update({
|
|
"centerMm": xyz(circle.Location()),
|
|
"radiusMm": float(circle.Radius()),
|
|
"axis": direction_xyz(circle.Axis().Direction()),
|
|
"xDirection": direction_xyz(circle.Position().XDirection()),
|
|
"isFullCircle": abs(abs(float(curve.LastParameter()) - float(curve.FirstParameter())) - math.tau) <= 1e-6,
|
|
})
|
|
elif curve_type == "ellipse":
|
|
ellipse = curve.Ellipse()
|
|
payload.update({
|
|
"centerMm": xyz(ellipse.Location()),
|
|
"majorRadiusMm": float(ellipse.MajorRadius()),
|
|
"minorRadiusMm": float(ellipse.MinorRadius()),
|
|
"axis": direction_xyz(ellipse.Axis().Direction()),
|
|
})
|
|
return payload
|
|
|
|
|
|
def fitted_circular_wire_payload(
|
|
edges: list[dict[str, Any]],
|
|
face_normal: list[float] | None,
|
|
) -> dict[str, Any]:
|
|
if face_normal is None:
|
|
return {"isCircular": False}
|
|
points: list[list[float]] = []
|
|
for edge in edges:
|
|
for point in edge.get("samplesMm", []):
|
|
if not points or distance(points[-1], point) > 1e-8:
|
|
points.append(point)
|
|
if len(points) < 8:
|
|
return {"isCircular": False}
|
|
closure_tolerance_mm = 0.01
|
|
if distance(points[0], points[-1]) > closure_tolerance_mm:
|
|
return {"isCircular": False}
|
|
if distance(points[0], points[-1]) <= 1e-8:
|
|
points.pop()
|
|
|
|
normal = normalized(face_normal)
|
|
if dot(normal, normal) < 0.99:
|
|
return {"isCircular": False}
|
|
reference_axes = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
|
|
reference = min(reference_axes, key=lambda axis: abs(dot(axis, normal)))
|
|
x_axis = normalized(cross(normal, reference))
|
|
y_axis = normalized(cross(normal, x_axis))
|
|
origin = [sum(point[index] for point in points) / len(points) for index in range(3)]
|
|
projected = []
|
|
plane_residuals = []
|
|
for point in points:
|
|
offset = [point[index] - origin[index] for index in range(3)]
|
|
projected.append([dot(offset, x_axis), dot(offset, y_axis)])
|
|
plane_residuals.append(abs(dot(offset, normal)))
|
|
|
|
normal_matrix = [[0.0] * 3 for _ in range(3)]
|
|
normal_values = [0.0] * 3
|
|
for x_value, y_value in projected:
|
|
row = [2.0 * x_value, 2.0 * y_value, 1.0]
|
|
target = x_value * x_value + y_value * y_value
|
|
for row_index in range(3):
|
|
normal_values[row_index] += row[row_index] * target
|
|
for column_index in range(3):
|
|
normal_matrix[row_index][column_index] += row[row_index] * row[column_index]
|
|
solution = solve_three_by_three(normal_matrix, normal_values)
|
|
if solution is None:
|
|
return {"isCircular": False}
|
|
center_x, center_y, constant = solution
|
|
radius_squared = constant + center_x * center_x + center_y * center_y
|
|
if radius_squared <= 1e-12:
|
|
return {"isCircular": False}
|
|
radius = math.sqrt(radius_squared)
|
|
radial_residuals = [
|
|
abs(math.hypot(x_value - center_x, y_value - center_y) - radius)
|
|
for x_value, y_value in projected
|
|
]
|
|
max_residual = max(max(radial_residuals), max(plane_residuals))
|
|
circularity_tolerance_mm = max(0.005, radius * 0.0005)
|
|
if max_residual > circularity_tolerance_mm:
|
|
return {
|
|
"isCircular": False,
|
|
"fitResidualMm": max_residual,
|
|
}
|
|
|
|
radial_vectors = [(x_value - center_x, y_value - center_y) for x_value, y_value in projected]
|
|
sweep = 0.0
|
|
for index, current in enumerate(radial_vectors):
|
|
following = radial_vectors[(index + 1) % len(radial_vectors)]
|
|
cross_value = current[0] * following[1] - current[1] * following[0]
|
|
dot_value = current[0] * following[0] + current[1] * following[1]
|
|
sweep += abs(math.atan2(cross_value, dot_value))
|
|
if abs(sweep - math.tau) > 0.05:
|
|
return {"isCircular": False, "fitResidualMm": max_residual}
|
|
|
|
center = [
|
|
origin[index] + x_axis[index] * center_x + y_axis[index] * center_y
|
|
for index in range(3)
|
|
]
|
|
return {
|
|
"isCircular": True,
|
|
"centerMm": center,
|
|
"radiusMm": radius,
|
|
"axis": normal,
|
|
"fitResidualMm": max_residual,
|
|
"circularityMethod": "verified-fit",
|
|
}
|
|
|
|
|
|
def circular_wire_payload(
|
|
edges: list[dict[str, Any]],
|
|
face_normal: list[float] | None = None,
|
|
) -> dict[str, Any]:
|
|
if edges and all(edge["curveType"] == "circle" for edge in edges):
|
|
first = edges[0]
|
|
center = first.get("centerMm")
|
|
radius = first.get("radiusMm")
|
|
axis = normalized(first.get("axis", [0.0, 0.0, 0.0]))
|
|
if center is not None and radius is not None:
|
|
same_circle = all(
|
|
distance(center, edge.get("centerMm", [math.inf] * 3)) <= 1e-5
|
|
and abs(radius - float(edge.get("radiusMm", math.inf))) <= 1e-6
|
|
and abs(dot(axis, normalized(edge.get("axis", [0.0, 0.0, 0.0])))) >= 1.0 - 1e-8
|
|
for edge in edges[1:]
|
|
)
|
|
sweep = sum(abs(float(edge["lastParameter"]) - float(edge["firstParameter"])) for edge in edges)
|
|
if same_circle and abs(sweep - math.tau) <= 1e-5:
|
|
return {
|
|
"isCircular": True,
|
|
"centerMm": center,
|
|
"radiusMm": radius,
|
|
"axis": axis,
|
|
"fitResidualMm": 0.0,
|
|
"circularityMethod": "analytic",
|
|
}
|
|
return fitted_circular_wire_payload(edges, face_normal)
|
|
|
|
|
|
def face_triangulation(face: Any) -> dict[str, Any]:
|
|
location = TopLoc_Location()
|
|
triangulation = BRep_Tool.Triangulation_s(face, location)
|
|
if triangulation is None or triangulation.NbTriangles() <= 0:
|
|
return {"positionsMm": [], "indices": []}
|
|
transformation = location.Transformation()
|
|
used_nodes: dict[int, int] = {}
|
|
positions: list[float] = []
|
|
indices: list[int] = []
|
|
reversed_face = face.Orientation() == TopAbs_REVERSED
|
|
for triangle_index in range(1, triangulation.NbTriangles() + 1):
|
|
nodes = list(triangulation.Triangle(triangle_index).Get())
|
|
if reversed_face:
|
|
nodes[1], nodes[2] = nodes[2], nodes[1]
|
|
for node_index in nodes:
|
|
local_index = used_nodes.get(node_index)
|
|
if local_index is None:
|
|
point = triangulation.Node(node_index).Transformed(transformation)
|
|
local_index = len(positions) // 3
|
|
used_nodes[node_index] = local_index
|
|
positions.extend(xyz(point))
|
|
indices.append(local_index)
|
|
return {"positionsMm": positions, "indices": indices}
|
|
|
|
|
|
def surface_payload(face: Any) -> tuple[str, dict[str, Any]]:
|
|
adaptor = BRepAdaptor_Surface(face, True)
|
|
surface_type = SURFACE_TYPES.get(adaptor.GetType(), "other")
|
|
reversed_face = face.Orientation() == TopAbs_REVERSED
|
|
payload: dict[str, Any] = {"surfaceType": surface_type, "isPlanar": surface_type == "plane"}
|
|
if surface_type == "plane":
|
|
plane = adaptor.Plane()
|
|
payload.update({
|
|
"normal": direction_xyz(plane.Axis().Direction(), reversed_face),
|
|
"planeLocationMm": xyz(plane.Location()),
|
|
"xDirection": direction_xyz(plane.Position().XDirection()),
|
|
})
|
|
elif surface_type == "cylinder":
|
|
cylinder = adaptor.Cylinder()
|
|
payload.update({
|
|
"axis": direction_xyz(cylinder.Axis().Direction()),
|
|
"axisLocationMm": xyz(cylinder.Location()),
|
|
"radiusMm": float(cylinder.Radius()),
|
|
})
|
|
return surface_type, payload
|
|
|
|
|
|
def default_display_deflection_mm(diagonal_mm: float) -> float:
|
|
# Triangles are only used to render and pick the exact B-Rep faces. The
|
|
# previous 0.05-0.5 mm range produced browser payloads above 100 MB for
|
|
# otherwise valid components, without improving the saved interface data.
|
|
return max(0.2, min(2.0, diagonal_mm * 0.002))
|
|
|
|
|
|
def maximum_display_deflection_mm(initial_deflection_mm: float) -> float:
|
|
# Keep an adaptive escape hatch for highly detailed components. Exact
|
|
# Face/Wire/Edge data is unchanged; only the display mesh becomes coarser.
|
|
return max(2.0, min(10.0, initial_deflection_mm * 10.0))
|
|
|
|
|
|
def analyze(
|
|
input_path: Path,
|
|
linear_deflection_override_mm: float | None = None,
|
|
simplification_passes: int = 0,
|
|
) -> dict[str, Any]:
|
|
file_hash = source_hash(input_path)
|
|
Interface_Static.SetCVal_s("xstep.cascade.unit", "MM")
|
|
reader = STEPControl_Reader()
|
|
status = reader.ReadFile(str(input_path))
|
|
if status != IFSelect_RetDone:
|
|
raise RuntimeError(f"OCCT 无法读取 STEP 文件,状态:{status}")
|
|
transferred = reader.TransferRoots()
|
|
if transferred <= 0:
|
|
raise RuntimeError("STEP 文件没有可转换的根装配或实体。")
|
|
shape = reader.OneShape()
|
|
if shape.IsNull():
|
|
raise RuntimeError("STEP 文件转换后没有有效形状。")
|
|
|
|
diagonal_mm = shape_diagonal_mm(shape)
|
|
linear_deflection_mm = (
|
|
linear_deflection_override_mm
|
|
if linear_deflection_override_mm is not None
|
|
else default_display_deflection_mm(diagonal_mm)
|
|
)
|
|
BRepMesh_IncrementalMesh(shape, linear_deflection_mm, False, 0.5, True)
|
|
|
|
face_map = TopTools_IndexedMapOfShape()
|
|
edge_map = TopTools_IndexedMapOfShape()
|
|
TopExp.MapShapes_s(shape, TopAbs_FACE, face_map)
|
|
TopExp.MapShapes_s(shape, TopAbs_EDGE, edge_map)
|
|
|
|
edge_cache: dict[int, dict[str, Any]] = {}
|
|
edge_owners: dict[int, set[int]] = {}
|
|
faces: list[dict[str, Any]] = []
|
|
|
|
for face_index in range(1, face_map.Extent() + 1):
|
|
face = TopoDS.Face_s(face_map.FindKey(face_index))
|
|
properties = GProp_GProps()
|
|
BRepGProp.SurfaceProperties_s(face, properties)
|
|
center_of_mass = xyz(properties.CentreOfMass())
|
|
surface_type, surface = surface_payload(face)
|
|
outer_wire = BRepTools.OuterWire_s(face)
|
|
wires: list[dict[str, Any]] = []
|
|
wire_explorer = BRepTools_WireExplorer(outer_wire, face) if not outer_wire.IsNull() else None
|
|
|
|
# Enumerate outer wire first so its role is deterministic, then all inner wires.
|
|
ordered_wires: list[Any] = []
|
|
if wire_explorer is not None:
|
|
ordered_wires.append(outer_wire)
|
|
from OCP.TopExp import TopExp_Explorer
|
|
from OCP.TopAbs import TopAbs_WIRE
|
|
explorer = TopExp_Explorer(face, TopAbs_WIRE)
|
|
while explorer.More():
|
|
wire = TopoDS.Wire_s(explorer.Current())
|
|
if outer_wire.IsNull() or not wire.IsSame(outer_wire):
|
|
ordered_wires.append(wire)
|
|
explorer.Next()
|
|
|
|
for wire_index, wire in enumerate(ordered_wires, start=1):
|
|
is_outer = not outer_wire.IsNull() and wire.IsSame(outer_wire)
|
|
wire_edges: list[dict[str, Any]] = []
|
|
edge_explorer = BRepTools_WireExplorer(wire, face)
|
|
while edge_explorer.More():
|
|
edge = TopoDS.Edge_s(edge_explorer.Current())
|
|
edge_index = edge_map.FindIndex(edge)
|
|
if edge_index <= 0:
|
|
edge_index = edge_map.Add(edge)
|
|
if edge_index not in edge_cache:
|
|
edge_cache[edge_index] = edge_payload(edge, edge_index, file_hash)
|
|
wire_edges.append(dict(edge_cache[edge_index]))
|
|
edge_owners.setdefault(edge_index, set()).add(face_index)
|
|
edge_explorer.Next()
|
|
circular = circular_wire_payload(wire_edges, surface.get("normal"))
|
|
wires.append({
|
|
"id": f"brep:face:{face_index}:wire:{wire_index}",
|
|
"sourceRef": f"sha256:{file_hash}:face:{face_index}:wire:{wire_index}",
|
|
"isOuter": is_outer,
|
|
"isCircular": circular["isCircular"],
|
|
"centerMm": circular.get("centerMm"),
|
|
"radiusMm": circular.get("radiusMm"),
|
|
"axis": circular.get("axis"),
|
|
"fitResidualMm": circular.get("fitResidualMm"),
|
|
"circularityMethod": circular.get("circularityMethod"),
|
|
"edges": wire_edges,
|
|
})
|
|
|
|
faces.append({
|
|
"id": f"brep:face:{face_index}",
|
|
"sourceRef": f"sha256:{file_hash}:face:{face_index}",
|
|
**surface,
|
|
"pointMm": center_of_mass,
|
|
"areaMm2": float(properties.Mass()),
|
|
"orientation": "reversed" if face.Orientation() == TopAbs_REVERSED else "forward",
|
|
"adjacentFaceIds": [],
|
|
"triangles": face_triangulation(face),
|
|
"wires": wires,
|
|
})
|
|
|
|
adjacent: dict[int, set[int]] = {index: set() for index in range(1, len(faces) + 1)}
|
|
for owners in edge_owners.values():
|
|
for owner in owners:
|
|
adjacent[owner].update(other for other in owners if other != owner)
|
|
for face_index, face in enumerate(faces, start=1):
|
|
face["adjacentFaceIds"] = [f"brep:face:{index}" for index in sorted(adjacent[face_index])]
|
|
|
|
return {
|
|
"schemaVersion": "interface-step-brep/v1",
|
|
"sourceName": input_path.name,
|
|
"sourceSha256": file_hash,
|
|
"sourceUnits": "mm",
|
|
"scaleToMeters": 0.001,
|
|
"kernel": "OCCT 7.8",
|
|
"triangulationPurpose": "display-and-picking-only",
|
|
"linearDeflectionMm": linear_deflection_mm,
|
|
"displayMeshSimplificationPasses": simplification_passes,
|
|
"faceCount": len(faces),
|
|
"edgeCount": edge_map.Extent(),
|
|
"faces": faces,
|
|
}
|
|
|
|
|
|
def main() -> int:
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("input", type=Path)
|
|
parser.add_argument("--output", type=Path, required=True)
|
|
parser.add_argument("--max-output-bytes", type=int)
|
|
args = parser.parse_args()
|
|
if args.input.suffix.lower() not in (".step", ".stp"):
|
|
raise ValueError("只支持 .step 或 .stp 文件。")
|
|
input_path = args.input.resolve()
|
|
result = analyze(input_path)
|
|
serialized = json.dumps(result, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
|
|
|
# If a complex but valid component still exceeds the response budget,
|
|
# remesh only the display/picking triangles at a coarser tolerance. The
|
|
# authoritative analytic B-Rep metadata and source references stay intact.
|
|
simplification_passes = 0
|
|
max_deflection_mm = maximum_display_deflection_mm(result["linearDeflectionMm"])
|
|
while (
|
|
args.max_output_bytes is not None
|
|
and len(serialized) > args.max_output_bytes
|
|
and simplification_passes < 4
|
|
and result["linearDeflectionMm"] < max_deflection_mm
|
|
):
|
|
simplification_passes += 1
|
|
next_deflection_mm = min(max_deflection_mm, result["linearDeflectionMm"] * 2.0)
|
|
result = analyze(input_path, next_deflection_mm, simplification_passes)
|
|
serialized = json.dumps(result, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
|
|
|
args.output.parent.mkdir(parents=True, exist_ok=True)
|
|
args.output.write_bytes(serialized)
|
|
print(json.dumps({
|
|
"schemaVersion": result["schemaVersion"],
|
|
"faceCount": result["faceCount"],
|
|
"edgeCount": result["edgeCount"],
|
|
"output": str(args.output),
|
|
}, ensure_ascii=False))
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
raise SystemExit(main())
|
|
except Exception as error:
|
|
print(f"STEP_BREP_ERROR: {error}", file=sys.stderr)
|
|
raise SystemExit(2)
|