feat: Replace SDF kernel with OpenCASCADE, VTK with pygfx
Major architecture migration: - Remove SDF-based geometry kernel (sdf/) - Remove VTK renderer (drawing_modules/) - Remove old mesh modules (mesh_modules/) New components: - geometry/base.py: Abstract geometry kernel interface - geometry_occ/kernel.py: OpenCASCADE implementation via CadQuery/OCP - geometry_occ/sketch.py: 2D sketching with constraint solving - rendering/base.py: Abstract renderer interface - rendering/pygfx_renderer.py: WebGPU-based renderer - models/data_model.py: Project, Component, Sketch, Body classes - main.py: New Qt-based application Features: - STEP/IGES import/export - Exact BRep geometry (vs approximate SDF mesh) - Parametric sketching with constraints - Boolean operations (union, difference, intersection) - Fillet and chamfer operations - Modern pygfx renderer (~30MB vs VTK ~200MB) Dependencies: - cadquery >= 2.4 - ocp >= 7.9.3 - pygfx >= 0.7.0 - wgpu >= 0.19.0 - PySide6 >= 6.9.0
This commit is contained in:
@@ -0,0 +1,726 @@
|
||||
"""
|
||||
OpenCASCADE-based geometry kernel for Fluency CAD.
|
||||
|
||||
This module provides a concrete implementation of the geometry kernel
|
||||
using CadQuery and OCP (OpenCASCADE Python bindings).
|
||||
"""
|
||||
|
||||
from typing import List, Tuple, Optional, Any, Dict
|
||||
import numpy as np
|
||||
|
||||
from fluency.geometry.base import (
|
||||
GeometryKernel,
|
||||
GeometryObject,
|
||||
Point2D,
|
||||
Point3D,
|
||||
)
|
||||
|
||||
|
||||
class OCCGeometryObject(GeometryObject):
|
||||
"""Geometry object wrapper for OpenCASCADE shapes."""
|
||||
|
||||
def __init__(self, shape: Any = None, metadata: Optional[Dict] = None):
|
||||
super().__init__(shape, metadata)
|
||||
self._cadquery_obj: Any = None
|
||||
|
||||
@property
|
||||
def cq_obj(self) -> Any:
|
||||
"""Get the CadQuery object if available."""
|
||||
return self._cadquery_obj
|
||||
|
||||
@cq_obj.setter
|
||||
def cq_obj(self, value: Any) -> None:
|
||||
self._cadquery_obj = value
|
||||
|
||||
|
||||
class OCGeometryKernel(GeometryKernel):
|
||||
"""
|
||||
OpenCASCADE-based geometry kernel implementation.
|
||||
|
||||
This kernel uses CadQuery for high-level operations and
|
||||
OCP for direct OpenCASCADE access when needed.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._tolerance: float = 0.001
|
||||
self._mesh_tolerance: float = 0.1
|
||||
|
||||
def _get_shape(self, obj: GeometryObject) -> Any:
|
||||
"""Extract the underlying OCC shape from a GeometryObject."""
|
||||
if isinstance(obj, OCCGeometryObject):
|
||||
if obj._cadquery_obj is not None:
|
||||
shape = obj._cadquery_obj.val()
|
||||
if hasattr(shape, "wrapped"):
|
||||
return shape.wrapped
|
||||
return shape
|
||||
if obj.shape is not None:
|
||||
if hasattr(obj.shape, "wrapped"):
|
||||
return obj.shape.wrapped
|
||||
return obj.shape
|
||||
return obj.shape if obj.shape else obj
|
||||
|
||||
def _get_cq_obj(self, obj: GeometryObject) -> Any:
|
||||
"""Get CadQuery object from GeometryObject."""
|
||||
if isinstance(obj, OCCGeometryObject) and obj._cadquery_obj is not None:
|
||||
return obj._cadquery_obj
|
||||
return obj.shape
|
||||
|
||||
def create_point(self, x: float, y: float) -> GeometryObject:
|
||||
"""Create a 2D point."""
|
||||
import cadquery as cq
|
||||
|
||||
point = cq.Vector(x, y, 0)
|
||||
return OCCGeometryObject(point)
|
||||
|
||||
def create_line(self, start: Point2D, end: Point2D) -> GeometryObject:
|
||||
"""Create a 2D line segment."""
|
||||
import cadquery as cq
|
||||
|
||||
wire = cq.Workplane("XY").moveTo(start.x, start.y).lineTo(end.x, end.y)
|
||||
return OCCGeometryObject(wire.val(), {"type": "line"})
|
||||
|
||||
def create_circle(self, center: Point2D, radius: float) -> GeometryObject:
|
||||
"""Create a 2D circle."""
|
||||
import cadquery as cq
|
||||
|
||||
wire = cq.Workplane("XY").center(center.x, center.y).circle(radius)
|
||||
return OCCGeometryObject(wire.val(), {"type": "circle"})
|
||||
|
||||
def create_arc(
|
||||
self, center: Point2D, radius: float, start_angle: float, end_angle: float
|
||||
) -> GeometryObject:
|
||||
"""Create a 2D arc."""
|
||||
import cadquery as cq
|
||||
import math
|
||||
|
||||
start_rad = math.radians(start_angle)
|
||||
end_rad = math.radians(end_angle)
|
||||
|
||||
start_x = center.x + radius * math.cos(start_rad)
|
||||
start_y = center.y + radius * math.sin(start_rad)
|
||||
|
||||
wire = (
|
||||
cq.Workplane("XY")
|
||||
.moveTo(start_x, start_y)
|
||||
.radiusArc(
|
||||
(center.x + radius * math.cos(end_rad), center.y + radius * math.sin(end_rad)),
|
||||
radius,
|
||||
)
|
||||
)
|
||||
return OCCGeometryObject(wire.val(), {"type": "arc"})
|
||||
|
||||
def create_polygon(self, points: List[Point2D]) -> GeometryObject:
|
||||
"""Create a closed polygon from points."""
|
||||
import cadquery as cq
|
||||
|
||||
if len(points) < 3:
|
||||
raise ValueError("Polygon requires at least 3 points")
|
||||
|
||||
wp = cq.Workplane("XY").moveTo(points[0].x, points[0].y)
|
||||
for pt in points[1:]:
|
||||
wp = wp.lineTo(pt.x, pt.y)
|
||||
wp = wp.close()
|
||||
|
||||
return OCCGeometryObject(wp.val(), {"type": "polygon"})
|
||||
|
||||
def create_rectangle(
|
||||
self, width: float, height: float, center: Optional[Point2D] = None
|
||||
) -> GeometryObject:
|
||||
"""Create a rectangle."""
|
||||
import cadquery as cq
|
||||
|
||||
cx = center.x if center else 0
|
||||
cy = center.y if center else 0
|
||||
|
||||
wire = cq.Workplane("XY").center(cx, cy).rect(width, height)
|
||||
return OCCGeometryObject(wire.val(), {"type": "rectangle"})
|
||||
|
||||
def extrude(
|
||||
self,
|
||||
sketch: GeometryObject,
|
||||
height: float,
|
||||
direction: Tuple[float, float, float] = (0, 0, 1),
|
||||
symmetric: bool = False,
|
||||
) -> GeometryObject:
|
||||
"""Extrude a 2D sketch into a 3D solid."""
|
||||
import cadquery as cq
|
||||
|
||||
cq_obj = self._get_cq_obj(sketch)
|
||||
|
||||
if symmetric:
|
||||
half_height = height / 2
|
||||
if isinstance(cq_obj, cq.Workplane):
|
||||
solid = cq_obj.extrude(half_height, both=True)
|
||||
else:
|
||||
face = cq.Face.makeFromWires(cq_obj)
|
||||
solid = face.extrude(cq.Vector(0, 0, half_height) * 2)
|
||||
else:
|
||||
if isinstance(cq_obj, cq.Workplane):
|
||||
solid = cq_obj.extrude(height)
|
||||
else:
|
||||
face = cq.Face.makeFromWires(cq_obj)
|
||||
dir_vec = cq.Vector(*direction).normalized() * height
|
||||
solid = face.extrude(dir_vec)
|
||||
|
||||
return OCCGeometryObject(solid, {"type": "extrusion"})
|
||||
|
||||
def revolve(
|
||||
self,
|
||||
sketch: GeometryObject,
|
||||
angle: float = 360.0,
|
||||
axis: Tuple[float, float, float] = (0, 0, 1),
|
||||
origin: Tuple[float, float, float] = (0, 0, 0),
|
||||
) -> GeometryObject:
|
||||
"""Revolve a 2D sketch around an axis."""
|
||||
import cadquery as cq
|
||||
|
||||
cq_obj = self._get_cq_obj(sketch)
|
||||
|
||||
if isinstance(cq_obj, cq.Workplane):
|
||||
solid = cq_obj.revolve(angle)
|
||||
else:
|
||||
face = cq.Face.makeFromWires(cq_obj)
|
||||
axis_vec = cq.Vector(*axis)
|
||||
origin_vec = cq.Vector(*origin)
|
||||
solid = face.revolve(axis_vec, origin_vec, angle)
|
||||
|
||||
return OCCGeometryObject(solid, {"type": "revolution"})
|
||||
|
||||
def loft(self, profiles: List[GeometryObject], ruled: bool = False) -> GeometryObject:
|
||||
"""Create a loft between multiple profiles."""
|
||||
import cadquery as cq
|
||||
|
||||
if len(profiles) < 2:
|
||||
raise ValueError("Loft requires at least 2 profiles")
|
||||
|
||||
wires = []
|
||||
for profile in profiles:
|
||||
cq_obj = self._get_cq_obj(profile)
|
||||
if isinstance(cq_obj, cq.Workplane):
|
||||
wires.append(cq_obj.val())
|
||||
else:
|
||||
wires.append(cq_obj)
|
||||
|
||||
loft = cq.Solid.loft(wires, ruled)
|
||||
return OCCGeometryObject(loft, {"type": "loft"})
|
||||
|
||||
def sweep(
|
||||
self, profile: GeometryObject, path: GeometryObject, is_frenet: bool = False
|
||||
) -> GeometryObject:
|
||||
"""Sweep a profile along a path."""
|
||||
import cadquery as cq
|
||||
|
||||
profile_obj = self._get_cq_obj(profile)
|
||||
path_obj = self._get_cq_obj(path)
|
||||
|
||||
if isinstance(profile_obj, cq.Workplane):
|
||||
profile_wire = profile_obj.val()
|
||||
else:
|
||||
profile_wire = profile_obj
|
||||
|
||||
if isinstance(path_obj, cq.Workplane):
|
||||
path_wire = path_obj.val()
|
||||
else:
|
||||
path_wire = path_obj
|
||||
|
||||
solid = cq.Solid.sweep(profile_wire, path_wire, is_frenet)
|
||||
return OCCGeometryObject(solid, {"type": "sweep"})
|
||||
|
||||
def boolean_union(self, *bodies: GeometryObject) -> GeometryObject:
|
||||
"""Union multiple bodies."""
|
||||
import cadquery as cq
|
||||
|
||||
if len(bodies) < 2:
|
||||
return bodies[0] if bodies else OCCGeometryObject(None)
|
||||
|
||||
result = self._get_shape(bodies[0])
|
||||
for body in bodies[1:]:
|
||||
shape = self._get_shape(body)
|
||||
from OCP.BRepAlgoAPI import BRepAlgoAPI_Fuse
|
||||
|
||||
fuse = BRepAlgoAPI_Fuse(result, shape)
|
||||
fuse.Build()
|
||||
result = fuse.Shape()
|
||||
|
||||
return OCCGeometryObject(cq.Shape(result), {"type": "union"})
|
||||
|
||||
def boolean_difference(self, base: GeometryObject, tool: GeometryObject) -> GeometryObject:
|
||||
"""Subtract tool from base."""
|
||||
import cadquery as cq
|
||||
|
||||
base_shape = self._get_shape(base)
|
||||
tool_shape = self._get_shape(tool)
|
||||
|
||||
from OCP.BRepAlgoAPI import BRepAlgoAPI_Cut
|
||||
|
||||
cut = BRepAlgoAPI_Cut(base_shape, tool_shape)
|
||||
cut.Build()
|
||||
|
||||
return OCCGeometryObject(cq.Shape(cut.Shape()), {"type": "difference"})
|
||||
|
||||
def boolean_intersection(self, body1: GeometryObject, body2: GeometryObject) -> GeometryObject:
|
||||
"""Intersect two bodies."""
|
||||
import cadquery as cq
|
||||
|
||||
shape1 = self._get_shape(body1)
|
||||
shape2 = self._get_shape(body2)
|
||||
|
||||
from OCP.BRepAlgoAPI import BRepAlgoAPI_Common
|
||||
|
||||
common = BRepAlgoAPI_Common(shape1, shape2)
|
||||
common.Build()
|
||||
|
||||
return OCCGeometryObject(cq.Shape(common.Shape()), {"type": "intersection"})
|
||||
|
||||
def fillet(
|
||||
self, body: GeometryObject, radius: float, edges: Optional[List[Any]] = None
|
||||
) -> GeometryObject:
|
||||
"""Apply fillet to edges."""
|
||||
import cadquery as cq
|
||||
|
||||
cq_obj = self._get_cq_obj(body)
|
||||
|
||||
if isinstance(cq_obj, cq.Workplane):
|
||||
if edges:
|
||||
result = cq_obj.edges(edges).fillet(radius)
|
||||
else:
|
||||
result = cq_obj.edges().fillet(radius)
|
||||
else:
|
||||
shape = self._get_shape(body)
|
||||
from OCP.BRepFilletAPI import BRepFilletAPI_MakeFillet
|
||||
|
||||
fillet = BRepFilletAPI_MakeFillet(shape)
|
||||
|
||||
from OCP.TopExp import TopExp_Explorer
|
||||
from OCP.TopAbs import TopAbs_EDGE
|
||||
|
||||
explorer = TopExp_Explorer(shape, TopAbs_EDGE)
|
||||
while explorer.More():
|
||||
fillet.Add(radius, explorer.Current())
|
||||
explorer.Next()
|
||||
|
||||
result = cq.Shape(fillet.Shape())
|
||||
|
||||
return OCCGeometryObject(result, {"type": "fillet"})
|
||||
|
||||
def chamfer(
|
||||
self, body: GeometryObject, size: float, edges: Optional[List[Any]] = None
|
||||
) -> GeometryObject:
|
||||
"""Apply chamfer to edges."""
|
||||
import cadquery as cq
|
||||
|
||||
cq_obj = self._get_cq_obj(body)
|
||||
|
||||
if isinstance(cq_obj, cq.Workplane):
|
||||
if edges:
|
||||
result = cq_obj.edges(edges).chamfer(size)
|
||||
else:
|
||||
result = cq_obj.edges().chamfer(size)
|
||||
else:
|
||||
shape = self._get_shape(body)
|
||||
from OCP.BRepFilletAPI import BRepFilletAPI_MakeChamfer
|
||||
|
||||
chamfer = BRepFilletAPI_MakeChamfer(shape)
|
||||
|
||||
from OCP.TopExp import TopExp_Explorer
|
||||
from OCP.TopAbs import TopAbs_EDGE
|
||||
|
||||
explorer = TopExp_Explorer(shape, TopAbs_EDGE)
|
||||
while explorer.More():
|
||||
chamfer.Add(size, explorer.Current())
|
||||
explorer.Next()
|
||||
|
||||
result = cq.Shape(chamfer.Shape())
|
||||
|
||||
return OCCGeometryObject(result, {"type": "chamfer"})
|
||||
|
||||
def shell(
|
||||
self, body: GeometryObject, thickness: float, faces_to_remove: Optional[List[Any]] = None
|
||||
) -> GeometryObject:
|
||||
"""Create a shell (hollow body)."""
|
||||
import cadquery as cq
|
||||
|
||||
cq_obj = self._get_cq_obj(body)
|
||||
|
||||
if isinstance(cq_obj, cq.Workplane):
|
||||
if faces_to_remove:
|
||||
result = cq_obj.faces(faces_to_remove).shell(thickness)
|
||||
else:
|
||||
result = cq_obj.shell(thickness)
|
||||
else:
|
||||
shape = self._get_shape(body)
|
||||
from OCP.BRepOffsetAPI import BRepOffsetAPI_MakeThickSolid
|
||||
from OCP.TopTools import TopTools_ListOfShape
|
||||
|
||||
faces_list = TopTools_ListOfShape()
|
||||
if faces_to_remove:
|
||||
for face in faces_to_remove:
|
||||
faces_list.Append(face)
|
||||
|
||||
shell_maker = BRepOffsetAPI_MakeThickSolid()
|
||||
shell_maker.MakeThickSolidByJoin(shape, faces_list, thickness, 0.001)
|
||||
shell_maker.Build()
|
||||
result = cq.Shape(shell_maker.Shape())
|
||||
|
||||
return OCCGeometryObject(result, {"type": "shell"})
|
||||
|
||||
def offset(self, face: GeometryObject, distance: float) -> GeometryObject:
|
||||
"""Offset a face or surface."""
|
||||
import cadquery as cq
|
||||
|
||||
shape = self._get_shape(face)
|
||||
from OCP.BRepOffsetAPI import BRepOffsetAPI_MakeOffset
|
||||
|
||||
offset_maker = BRepOffsetAPI_MakeOffset(shape, False)
|
||||
offset_maker.Perform(distance)
|
||||
|
||||
return OCCGeometryObject(cq.Shape(offset_maker.Shape()), {"type": "offset"})
|
||||
|
||||
def translate(self, body: GeometryObject, vector: Tuple[float, float, float]) -> GeometryObject:
|
||||
"""Translate a body."""
|
||||
import cadquery as cq
|
||||
|
||||
cq_obj = self._get_cq_obj(body)
|
||||
|
||||
if isinstance(cq_obj, cq.Workplane):
|
||||
result = cq_obj.translate(vector)
|
||||
else:
|
||||
shape = self._get_shape(body)
|
||||
from OCP.BRepBuilderAPI import BRepBuilderAPI_Transform
|
||||
from OCP.gp import gp_Trsf, gp_Vec
|
||||
|
||||
transform = gp_Trsf()
|
||||
transform.SetTranslation(gp_Vec(*vector))
|
||||
transformer = BRepBuilderAPI_Transform(shape, transform)
|
||||
result = cq.Shape(transformer.Shape())
|
||||
|
||||
return OCCGeometryObject(result, {"type": "translated"})
|
||||
|
||||
def rotate(
|
||||
self,
|
||||
body: GeometryObject,
|
||||
axis: Tuple[float, float, float],
|
||||
angle: float,
|
||||
origin: Tuple[float, float, float] = (0, 0, 0),
|
||||
) -> GeometryObject:
|
||||
"""Rotate a body around an axis."""
|
||||
import cadquery as cq
|
||||
import math
|
||||
|
||||
cq_obj = self._get_cq_obj(body)
|
||||
|
||||
if isinstance(cq_obj, cq.Workplane):
|
||||
result = cq_obj.rotate(origin, axis, math.degrees(angle))
|
||||
else:
|
||||
shape = self._get_shape(body)
|
||||
from OCP.BRepBuilderAPI import BRepBuilderAPI_Transform
|
||||
from OCP.gp import gp_Trsf, gp_Ax1, gp_Pnt, gp_Dir, gp_Vec
|
||||
|
||||
ax1 = gp_Ax1(gp_Pnt(*origin), gp_Dir(*axis))
|
||||
transform = gp_Trsf()
|
||||
transform.SetRotation(ax1, angle)
|
||||
transformer = BRepBuilderAPI_Transform(shape, transform)
|
||||
result = cq.Shape(transformer.Shape())
|
||||
|
||||
return OCCGeometryObject(result, {"type": "rotated"})
|
||||
|
||||
def scale(self, body: GeometryObject, factor: float) -> GeometryObject:
|
||||
"""Scale a body uniformly."""
|
||||
import cadquery as cq
|
||||
|
||||
shape = self._get_shape(body)
|
||||
from OCP.BRepBuilderAPI import BRepBuilderAPI_Transform
|
||||
from OCP.gp import gp_Trsf
|
||||
|
||||
transform = gp_Trsf()
|
||||
transform.SetScale(factor)
|
||||
transformer = BRepBuilderAPI_Transform(shape, transform)
|
||||
|
||||
return OCCGeometryObject(cq.Shape(transformer.Shape()), {"type": "scaled"})
|
||||
|
||||
def mirror(
|
||||
self,
|
||||
body: GeometryObject,
|
||||
plane_normal: Tuple[float, float, float],
|
||||
plane_origin: Tuple[float, float, float] = (0, 0, 0),
|
||||
) -> GeometryObject:
|
||||
"""Mirror a body across a plane."""
|
||||
import cadquery as cq
|
||||
|
||||
shape = self._get_shape(body)
|
||||
from OCP.BRepBuilderAPI import BRepBuilderAPI_Transform
|
||||
from OCP.gp import gp_Trsf, gp_Ax2, gp_Pnt, gp_Dir
|
||||
|
||||
ax2 = gp_Ax2(gp_Pnt(*plane_origin), gp_Dir(*plane_normal))
|
||||
transform = gp_Trsf()
|
||||
transform.SetMirror(ax2)
|
||||
transformer = BRepBuilderAPI_Transform(shape, transform)
|
||||
|
||||
return OCCGeometryObject(cq.Shape(transformer.Shape()), {"type": "mirrored"})
|
||||
|
||||
def export_step(self, body: GeometryObject, filepath: str, schema: str = "AP214") -> bool:
|
||||
"""Export to STEP format."""
|
||||
try:
|
||||
import cadquery as cq
|
||||
|
||||
shape = self._get_shape(body)
|
||||
|
||||
if hasattr(shape, "exportStep"):
|
||||
shape.exportStep(filepath)
|
||||
return True
|
||||
|
||||
from OCP.STEPControl import STEPControl_Writer, STEPControl_AsIs
|
||||
from OCP.Interface import Interface_Static
|
||||
|
||||
writer = STEPControl_Writer()
|
||||
if schema == "AP214":
|
||||
Interface_Static.SetCVal_s("write.step.schema", "AP214")
|
||||
elif schema == "AP203":
|
||||
Interface_Static.SetCVal_s("write.step.schema", "AP203")
|
||||
|
||||
writer.Transfer(shape, STEPControl_AsIs)
|
||||
writer.Write(filepath)
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"STEP export error: {e}")
|
||||
return False
|
||||
|
||||
def export_iges(self, body: GeometryObject, filepath: str) -> bool:
|
||||
"""Export to IGES format."""
|
||||
try:
|
||||
import cadquery as cq
|
||||
|
||||
shape = self._get_shape(body)
|
||||
|
||||
from OCP.IGESControl import IGESControl_Writer
|
||||
from OCP.Interface import Interface_Static
|
||||
|
||||
Interface_Static.SetCVal_s("write.iges.schema", "5.3")
|
||||
writer = IGESControl_Writer()
|
||||
writer.AddShape(shape)
|
||||
writer.Write(filepath)
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"IGES export error: {e}")
|
||||
return False
|
||||
|
||||
def export_stl(
|
||||
self, body: GeometryObject, filepath: str, tolerance: float = 0.1, ascii_mode: bool = False
|
||||
) -> bool:
|
||||
"""Export to STL format."""
|
||||
try:
|
||||
import cadquery as cq
|
||||
|
||||
shape = self._get_shape(body)
|
||||
|
||||
if hasattr(shape, "exportStl"):
|
||||
shape.exportStl(filepath, tolerance)
|
||||
return True
|
||||
|
||||
from OCP.StlAPI import StlAPI_Writer
|
||||
from OCP.BRepMesh import BRepMesh_IncrementalMesh
|
||||
|
||||
mesh = BRepMesh_IncrementalMesh(shape, tolerance)
|
||||
mesh.Perform()
|
||||
|
||||
writer = StlAPI_Writer()
|
||||
writer.ASCIIMode = ascii_mode
|
||||
writer.Write(shape, filepath)
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"STL export error: {e}")
|
||||
return False
|
||||
|
||||
def import_step(self, filepath: str) -> GeometryObject:
|
||||
"""Import from STEP format."""
|
||||
import cadquery as cq
|
||||
|
||||
result = cq.importers.importStep(filepath)
|
||||
return OCCGeometryObject(result, {"type": "imported_step"})
|
||||
|
||||
def import_iges(self, filepath: str) -> GeometryObject:
|
||||
"""Import from IGES format."""
|
||||
import cadquery as cq
|
||||
|
||||
from OCP.IGESControl import IGESControl_Reader
|
||||
from OCP.IFSelect import IFSelect_RetDone
|
||||
|
||||
reader = IGESControl_Reader()
|
||||
status = reader.ReadFile(filepath)
|
||||
|
||||
if status != IFSelect_RetDone:
|
||||
raise ValueError(f"Failed to read IGES file: {filepath}")
|
||||
|
||||
reader.TransferRoots()
|
||||
shape = reader.OneShape()
|
||||
|
||||
return OCCGeometryObject(cq.Shape(shape), {"type": "imported_iges"})
|
||||
|
||||
def get_mesh(
|
||||
self, body: GeometryObject, tolerance: float = 0.1
|
||||
) -> Tuple[np.ndarray, np.ndarray]:
|
||||
"""Get triangulated mesh for rendering."""
|
||||
import cadquery as cq
|
||||
|
||||
shape = self._get_shape(body)
|
||||
|
||||
if hasattr(shape, "tessellate"):
|
||||
vertices, faces = shape.tessellate(tolerance)
|
||||
return np.array(vertices), np.array(faces)
|
||||
|
||||
from OCP.BRepMesh import BRepMesh_IncrementalMesh
|
||||
from OCP.TopExp import TopExp_Explorer
|
||||
from OCP.TopAbs import TopAbs_FACE
|
||||
from OCP.BRep import BRep_Tool
|
||||
from OCP.Poly import Poly_Triangulation
|
||||
from OCP.TopLoc import TopLoc_Location
|
||||
|
||||
mesh = BRepMesh_IncrementalMesh(shape, tolerance)
|
||||
mesh.Perform()
|
||||
|
||||
vertices_list: List[List[float]] = []
|
||||
faces_list: List[List[int]] = []
|
||||
vertex_offset = 0
|
||||
|
||||
explorer = TopExp_Explorer(shape, TopAbs_FACE)
|
||||
while explorer.More():
|
||||
face = explorer.Current()
|
||||
location = TopLoc_Location()
|
||||
triangulation = BRep_Tool.Triangulation_s(face, location)
|
||||
|
||||
if triangulation is not None:
|
||||
n_vertices = triangulation.NbNodes()
|
||||
for i in range(1, n_vertices + 1):
|
||||
p = triangulation.Node(i)
|
||||
vertices_list.append([p.X(), p.Y(), p.Z()])
|
||||
|
||||
n_triangles = triangulation.NbTriangles()
|
||||
for i in range(1, n_triangles + 1):
|
||||
tri = triangulation.Triangle(i)
|
||||
faces_list.append(
|
||||
[
|
||||
tri.Value(1) - 1 + vertex_offset,
|
||||
tri.Value(2) - 1 + vertex_offset,
|
||||
tri.Value(3) - 1 + vertex_offset,
|
||||
]
|
||||
)
|
||||
|
||||
vertex_offset += n_vertices
|
||||
|
||||
explorer.Next()
|
||||
|
||||
return np.array(vertices_list, dtype=np.float32), np.array(faces_list, dtype=np.int32)
|
||||
|
||||
def get_edges(self, body: GeometryObject) -> Tuple[np.ndarray, np.ndarray]:
|
||||
"""Get edge wireframe for rendering."""
|
||||
import cadquery as cq
|
||||
|
||||
shape = self._get_shape(body)
|
||||
|
||||
from OCP.TopExp import TopExp_Explorer
|
||||
from OCP.TopAbs import TopAbs_EDGE
|
||||
from OCP.BRep import BRep_Tool
|
||||
from OCP.TopLoc import TopLoc_Location
|
||||
from OCP.BRepAdaptor import BRepAdaptor_Curve
|
||||
from OCP.GeomAbs import GeomAbs_Line, GeomAbs_Circle, GeomAbs_Ellipse, GeomAbs_BSplineCurve
|
||||
|
||||
vertices_list: List[List[float]] = []
|
||||
edges_list: List[List[int]] = []
|
||||
vertex_offset = 0
|
||||
|
||||
def discretize_edge(edge: Any, num_points: int = 20) -> List[List[float]]:
|
||||
curve = BRepAdaptor_Curve(edge)
|
||||
curve_type = curve.GetType()
|
||||
|
||||
points = []
|
||||
|
||||
if curve_type == GeomAbs_Line:
|
||||
first = curve.FirstParameter()
|
||||
last = curve.LastParameter()
|
||||
p1 = curve.Value(first)
|
||||
p2 = curve.Value(last)
|
||||
points = [[p1.X(), p1.Y(), p1.Z()], [p2.X(), p2.Y(), p2.Z()]]
|
||||
else:
|
||||
first = curve.FirstParameter()
|
||||
last = curve.LastParameter()
|
||||
|
||||
for i in range(num_points + 1):
|
||||
t = first + (last - first) * i / num_points
|
||||
p = curve.Value(t)
|
||||
points.append([p.X(), p.Y(), p.Z()])
|
||||
|
||||
return points
|
||||
|
||||
explorer = TopExp_Explorer(shape, TopAbs_EDGE)
|
||||
while explorer.More():
|
||||
edge = explorer.Current()
|
||||
edge_points = discretize_edge(edge)
|
||||
|
||||
for i, pt in enumerate(edge_points):
|
||||
vertices_list.append(pt)
|
||||
if i < len(edge_points) - 1:
|
||||
edges_list.append([vertex_offset + i, vertex_offset + i + 1])
|
||||
|
||||
vertex_offset += len(edge_points)
|
||||
explorer.Next()
|
||||
|
||||
return np.array(vertices_list, dtype=np.float32), np.array(edges_list, dtype=np.int32)
|
||||
|
||||
def get_bounding_box(self, body: GeometryObject) -> Tuple[Point3D, Point3D]:
|
||||
"""Get the bounding box of a body."""
|
||||
import cadquery as cq
|
||||
|
||||
shape = self._get_shape(body)
|
||||
|
||||
from OCP.Bnd import Bnd_Box
|
||||
from OCP.BRepBndLib import BRepBndLib_AddClose
|
||||
|
||||
bbox = Bnd_Box()
|
||||
BRepBndLib_AddClose(shape, bbox)
|
||||
|
||||
xmin, ymin, zmin, xmax, ymax, zmax = bbox.Get()
|
||||
|
||||
return Point3D(xmin, ymin, zmin), Point3D(xmax, ymax, zmax)
|
||||
|
||||
def get_volume(self, body: GeometryObject) -> float:
|
||||
"""Calculate the volume of a solid body."""
|
||||
import cadquery as cq
|
||||
|
||||
shape = self._get_shape(body)
|
||||
|
||||
from OCP.GProp import GProp_GProps
|
||||
from OCP.BRepGProp import BRepGProp_VolumeProperties
|
||||
|
||||
props = GProp_GProps()
|
||||
BRepGProp_VolumeProperties(shape, props)
|
||||
|
||||
return props.Mass()
|
||||
|
||||
def get_surface_area(self, body: GeometryObject) -> float:
|
||||
"""Calculate the surface area of a body."""
|
||||
import cadquery as cq
|
||||
|
||||
shape = self._get_shape(body)
|
||||
|
||||
from OCP.GProp import GProp_GProps
|
||||
from OCP.BRepGProp import BRepGProp_SurfaceProperties
|
||||
|
||||
props = GProp_GProps()
|
||||
BRepGProp_SurfaceProperties(shape, props)
|
||||
|
||||
return props.Mass()
|
||||
|
||||
def get_center_of_mass(self, body: GeometryObject) -> Point3D:
|
||||
"""Calculate the center of mass of a solid body."""
|
||||
import cadquery as cq
|
||||
|
||||
shape = self._get_shape(body)
|
||||
|
||||
from OCP.GProp import GProp_GProps
|
||||
from OCP.BRepGProp import BRepGProp_VolumeProperties
|
||||
|
||||
props = GProp_GProps()
|
||||
BRepGProp_VolumeProperties(shape, props)
|
||||
|
||||
cg = props.CentreOfMass()
|
||||
return Point3D(cg.X(), cg.Y(), cg.Z())
|
||||
Reference in New Issue
Block a user