diff --git a/scripts/ragflow_sync.py b/scripts/ragflow_sync.py index 3331ab9a..303a4fbb 100755 --- a/scripts/ragflow_sync.py +++ b/scripts/ragflow_sync.py @@ -221,7 +221,6 @@ class SimpleCADAPIRAGFlowSync: # 创建分块标题和内容 chunk_title = f"{title}" if title else f"Section {i+1}" - full_content = f"# {chunk_title}\n\n{content}" # 提取重要关键词 keywords = self._extract_keywords(content, chunk_title, doc_name) @@ -230,6 +229,7 @@ class SimpleCADAPIRAGFlowSync: if keywords is None: keywords = [] keywords = [k for k in keywords if k is not None and k.strip()] + keywords_str = ', '.join(keywords) if keywords else '' try: # 简化内容格式,避免特殊字符问题 @@ -238,7 +238,7 @@ class SimpleCADAPIRAGFlowSync: clean_content = f"Empty content for section: {chunk_title}" # 创建简单的内容格式 - final_content = f"{chunk_title}\n\n{clean_content}" + final_content = f"# {chunk_title}\n\n{clean_content}\n\n# tags: {keywords_str}\n\n" # 确保关键词都是有效的字符串 clean_keywords = [] @@ -246,10 +246,6 @@ class SimpleCADAPIRAGFlowSync: if kw and isinstance(kw, str) and len(kw.strip()) > 0: clean_keywords.append(kw.strip()) - # 限制关键词数量和长度 - clean_keywords = clean_keywords[:5] # 只取前5个关键词 - clean_keywords = [kw[:50] for kw in clean_keywords] # 限制每个关键词长度 - print(f" 添加分块: {chunk_title}") print(f" 内容长度: {len(final_content)}, 关键词: {clean_keywords}") diff --git a/src/simplecadapi/operations.py b/src/simplecadapi/operations.py index fd337b04..db6fabf0 100644 --- a/src/simplecadapi/operations.py +++ b/src/simplecadapi/operations.py @@ -3,49 +3,57 @@ SimpleCAD API操作函数实现 基于README中的API设计,实现各种几何操作 """ -from typing import List, Tuple, Union, Optional, Any, Sequence +from typing import List, Tuple, Union, Optional, Sequence import numpy as np import math import cadquery as cq -from cadquery import Vector, Plane +from cadquery import Vector from .core import ( - Vertex, Edge, Wire, Face, Shell, Solid, Compound, - AnyShape, CoordinateSystem, SimpleWorkplane, get_current_cs + Vertex, + Edge, + Wire, + Face, + Shell, + Solid, + Compound, + AnyShape, + get_current_cs, ) -from cadquery.occ_impl.shapes import fuse, cut, intersect +from cadquery.occ_impl.shapes import fuse, cut, intersect, revolve # ============================================================================= # 基础图形创建函数 # ============================================================================= + def make_point_rvertex(x: float, y: float, z: float) -> Vertex: """创建三维空间中的点并返回顶点对象 - + Args: x (float): X坐标值,用于定义点在X轴方向的位置 y (float): Y坐标值,用于定义点在Y轴方向的位置 z (float): Z坐标值,用于定义点在Z轴方向的位置 - + Returns: Vertex: 创建的顶点对象,包含指定坐标的点 - + Raises: ValueError: 当坐标无效时抛出异常 - + Usage: 创建三维空间中的几何点,通常用作其他几何对象的构造参数,如作为线段的端点、 圆弧的控制点等。支持当前坐标系变换。 - + Example: # 创建原点 origin = make_point_rvertex(0, 0, 0) - + # 创建指定坐标的点 point = make_point_rvertex(1.5, 2.0, 3.0) - + # 在工作平面中创建点 with SimpleWorkplane((1, 1, 1)): ... local_point = make_point_rvertex(0, 0, 0) # 实际位置为(1, 1, 1) @@ -59,31 +67,32 @@ def make_point_rvertex(x: float, y: float, z: float) -> Vertex: raise ValueError(f"创建点失败: {e}. 请检查坐标值是否有效。") -def make_line_redge(start: Tuple[float, float, float], - end: Tuple[float, float, float]) -> Edge: +def make_line_redge( + start: Tuple[float, float, float], end: Tuple[float, float, float] +) -> Edge: """创建两点之间的直线段并返回边对象 - + Args: start (Tuple[float, float, float]): 起始点坐标 (x, y, z),定义线段的起点 end (Tuple[float, float, float]): 结束点坐标 (x, y, z),定义线段的终点 - + Returns: Edge: 创建的边对象,表示连接两点的直线段 - + Raises: ValueError: 当坐标无效或起始点与结束点重合时抛出异常 - + Usage: 创建两点之间的直线段,是构建复杂几何形状的基础元素。可用于构造线框、 创建草图轮廓、定义路径等。支持当前坐标系变换。 - + Example: # 创建水平线段 line = make_line_redge((0, 0, 0), (5, 0, 0)) - + # 创建三维空间中的线段 line_3d = make_line_redge((1, 1, 1), (3, 2, 4)) - + # 在工作平面中创建线段 with SimpleWorkplane((0, 0, 1)): ... elevated_line = make_line_redge((0, 0, 0), (2, 2, 0)) @@ -92,63 +101,65 @@ def make_line_redge(start: Tuple[float, float, float], cs = get_current_cs() start_global = cs.transform_point(np.array(start)) end_global = cs.transform_point(np.array(end)) - + start_vec = Vector(*start_global) end_vec = Vector(*end_global) - + cq_edge = cq.Edge.makeLine(start_vec, end_vec) return Edge(cq_edge) except Exception as e: raise ValueError(f"创建线段失败: {e}. 请检查起始点和结束点坐标是否有效。") -def make_segment_redge(start: Tuple[float, float, float], - end: Tuple[float, float, float]) -> Edge: +def make_segment_redge( + start: Tuple[float, float, float], end: Tuple[float, float, float] +) -> Edge: """创建线段并返回边对象(make_line_redge的别名函数) - + Args: start (Tuple[float, float, float]): 起始点坐标 (x, y, z),定义线段的起点 end (Tuple[float, float, float]): 结束点坐标 (x, y, z),定义线段的终点 - + Returns: Edge: 创建的边对象,表示连接两点的直线段 - + Usage: 与make_line_redge功能完全相同,提供更直观的函数名称。用于创建两点之间的 直线段,是构建复杂几何形状的基础元素。 - + Example: # 创建垂直线段 vertical_line = make_segment_redge((0, 0, 0), (0, 0, 5)) - + # 创建对角线段 diagonal = make_segment_redge((0, 0, 0), (1, 1, 1)) """ return make_line_redge(start, end) -def make_segment_rwire(start: Tuple[float, float, float], - end: Tuple[float, float, float]) -> Wire: +def make_segment_rwire( + start: Tuple[float, float, float], end: Tuple[float, float, float] +) -> Wire: """创建线段并返回线对象 - + Args: start (Tuple[float, float, float]): 起始点坐标 (x, y, z),定义线段的起点 end (Tuple[float, float, float]): 结束点坐标 (x, y, z),定义线段的终点 - + Returns: Wire: 创建的线对象,包含一个连接两点的直线段 - + Raises: ValueError: 当坐标无效或创建线对象失败时抛出异常 - + Usage: 创建包含单个线段的线对象,用于构建更复杂的线框结构。与make_segment_redge 不同,此函数返回的是线对象,可以与其他线对象连接形成复杂路径。 - + Example: # 创建基本线段线 wire = make_segment_rwire((0, 0, 0), (3, 0, 0)) - + # 创建斜线段 diagonal_wire = make_segment_rwire((0, 0, 0), (2, 2, 0)) """ @@ -160,79 +171,83 @@ def make_segment_rwire(start: Tuple[float, float, float], raise ValueError(f"创建线段线失败: {e}") -def make_circle_redge(center: Tuple[float, float, float], - radius: float, - normal: Tuple[float, float, float] = (0, 0, 1)) -> Edge: +def make_circle_redge( + center: Tuple[float, float, float], + radius: float, + normal: Tuple[float, float, float] = (0, 0, 1), +) -> Edge: """创建圆形并返回边对象 - + Args: center (Tuple[float, float, float]): 圆心坐标 (x, y, z),定义圆的中心位置 radius (float): 圆的半径,必须为正数 normal (Tuple[float, float, float], optional): 圆所在平面的法向量 (x, y, z), 默认为 (0, 0, 1) 表示XY平面 - + Returns: Edge: 创建的边对象,表示一个完整的圆形 - + Raises: ValueError: 当半径小于等于0或其他参数无效时抛出异常 - + Usage: 创建圆形边对象,用于构建圆形轮廓、圆弧路径等。圆的方向由法向量确定, 支持在任意平面内创建圆形。支持当前坐标系变换。 - + Example: # 创建XY平面上的圆 circle = make_circle_redge((0, 0, 0), 2.0) - + # 创建垂直平面上的圆 vertical_circle = make_circle_redge((0, 0, 0), 1.5, (1, 0, 0)) - + # 创建指定位置的圆 offset_circle = make_circle_redge((2, 3, 1), 1.0, (0, 0, 1)) """ try: if radius <= 0: raise ValueError("半径必须大于0") - + cs = get_current_cs() center_global = cs.transform_point(np.array(center)) normal_global = cs.transform_point(np.array(normal)) - cs.origin - + center_vec = Vector(*center_global) normal_vec = Vector(*normal_global) - + cq_edge = cq.Edge.makeCircle(radius, center_vec, normal_vec) return Edge(cq_edge) except Exception as e: raise ValueError(f"创建圆失败: {e}. 请检查圆心坐标、半径和法向量是否有效。") -def make_circle_rwire(center: Tuple[float, float, float], - radius: float, - normal: Tuple[float, float, float] = (0, 0, 1)) -> Wire: +def make_circle_rwire( + center: Tuple[float, float, float], + radius: float, + normal: Tuple[float, float, float] = (0, 0, 1), +) -> Wire: """创建圆形并返回线对象 - + Args: center (Tuple[float, float, float]): 圆心坐标 (x, y, z),定义圆的中心位置 radius (float): 圆的半径,必须为正数 normal (Tuple[float, float, float], optional): 圆所在平面的法向量 (x, y, z), 默认为 (0, 0, 1) 表示XY平面 - + Returns: Wire: 创建的线对象,表示一个完整的圆形轮廓 - + Raises: ValueError: 当半径小于等于0或其他参数无效时抛出异常 - + Usage: 创建圆形线对象,用于构建封闭的圆形轮廓。与make_circle_redge不同, 此函数返回的是线对象,可以直接用于创建面或进行其他线操作。 - + Example: # 创建标准圆形轮廓 circle_wire = make_circle_rwire((0, 0, 0), 3.0) - + # 创建小圆轮廓 small_circle = make_circle_rwire((1, 1, 0), 0.5) """ @@ -244,32 +259,34 @@ def make_circle_rwire(center: Tuple[float, float, float], raise ValueError(f"创建圆线失败: {e}") -def make_circle_rface(center: Tuple[float, float, float], - radius: float, - normal: Tuple[float, float, float] = (0, 0, 1)) -> Face: +def make_circle_rface( + center: Tuple[float, float, float], + radius: float, + normal: Tuple[float, float, float] = (0, 0, 1), +) -> Face: """创建圆形并返回面对象 - + Args: center (Tuple[float, float, float]): 圆心坐标 (x, y, z),定义圆的中心位置 radius (float): 圆的半径,必须为正数 normal (Tuple[float, float, float], optional): 圆所在平面的法向量 (x, y, z), 默认为 (0, 0, 1) 表示XY平面 - + Returns: Face: 创建的面对象,表示一个实心的圆形面 - + Raises: ValueError: 当半径小于等于0或其他参数无效时抛出异常 - + Usage: 创建圆形面对象,用于构建实心圆形截面。可以用于拉伸、旋转等操作来创建 圆柱体、圆锥体等三维几何体。面积等于πr²。 - + Example: # 创建标准圆形面 circle_face = make_circle_rface((0, 0, 0), 2.0) area = circle_face.get_area() # 面积为π×2²≈12.57 - + # 创建用于拉伸的圆形截面 profile = make_circle_rface((0, 0, 0), 1.0) cylinder = extrude_rsolid(profile, (0, 0, 1), 5.0) @@ -282,11 +299,14 @@ def make_circle_rface(center: Tuple[float, float, float], raise ValueError(f"创建圆面失败: {e}") -def make_rectangle_rwire(width: float, height: float, - center: Tuple[float, float, float] = (0, 0, 0), - normal: Tuple[float, float, float] = (0, 0, 1)) -> Wire: +def make_rectangle_rwire( + width: float, + height: float, + center: Tuple[float, float, float] = (0, 0, 0), + normal: Tuple[float, float, float] = (0, 0, 1), +) -> Wire: """创建矩形并返回线对象 - + Args: width (float): 矩形的宽度,必须为正数 height (float): 矩形的高度,必须为正数 @@ -294,85 +314,90 @@ def make_rectangle_rwire(width: float, height: float, 默认为 (0, 0, 0) normal (Tuple[float, float, float], optional): 矩形所在平面的法向量 (x, y, z), 默认为 (0, 0, 1) 表示XY平面 - + Returns: Wire: 创建的线对象,表示一个封闭的矩形轮廓 - + Raises: ValueError: 当宽度或高度小于等于0或其他参数无效时抛出异常 - + Usage: 创建矩形线对象,用于构建矩形轮廓。矩形以指定中心点为中心,在指定平面内 创建。可以用于构建复杂的多边形轮廓或作为拉伸的基础轮廓。 - + Example: # 创建标准矩形轮廓 rect = make_rectangle_rwire(4.0, 3.0) - + # 创建偏移的矩形 offset_rect = make_rectangle_rwire(2.0, 2.0, (1, 1, 0)) - + # 创建垂直平面上的矩形 vertical_rect = make_rectangle_rwire(3.0, 2.0, (0, 0, 0), (1, 0, 0)) """ try: if width <= 0 or height <= 0: raise ValueError("宽度和高度必须大于0") - + cs = get_current_cs() center_global = cs.transform_point(np.array(center)) normal_global = cs.transform_point(np.array(normal)) - cs.origin - + # 标准化法向量 normal_vec = normal_global / np.linalg.norm(normal_global) - + # 创建本地坐标系 # 如果法向量接近Z轴,使用X轴作为参考 if abs(normal_vec[2]) > 0.9: ref_vec = np.array([1.0, 0.0, 0.0]) else: ref_vec = np.array([0.0, 0.0, 1.0]) - + # 计算本地坐标系的X和Y轴 local_x = np.cross(normal_vec, ref_vec) local_x = local_x / np.linalg.norm(local_x) local_y = np.cross(normal_vec, local_x) local_y = local_y / np.linalg.norm(local_y) - + # 创建矩形的四个顶点(在本地坐标系中) half_w, half_h = width / 2, height / 2 local_points = [ (-half_w, -half_h), (half_w, -half_h), (half_w, half_h), - (-half_w, half_h) + (-half_w, half_h), ] - + # 转换到全局坐标系 global_points = [] for local_point in local_points: # 在本地坐标系中的点 - point_3d = center_global + local_point[0] * local_x + local_point[1] * local_y + point_3d = ( + center_global + local_point[0] * local_x + local_point[1] * local_y + ) global_points.append(Vector(*point_3d)) - + # 创建边 edges = [] for i in range(len(global_points)): start = global_points[i] end = global_points[(i + 1) % len(global_points)] edges.append(cq.Edge.makeLine(start, end)) - + cq_wire = cq.Wire.assembleEdges(edges) return Wire(cq_wire) except Exception as e: raise ValueError(f"创建矩形失败: {e}. 请检查宽度、高度和中心点坐标是否有效。") -def make_rectangle_rface(width: float, height: float, - center: Tuple[float, float, float] = (0, 0, 0), - normal: Tuple[float, float, float] = (0, 0, 1)) -> Face: +def make_rectangle_rface( + width: float, + height: float, + center: Tuple[float, float, float] = (0, 0, 0), + normal: Tuple[float, float, float] = (0, 0, 1), +) -> Face: """创建矩形并返回面对象 - + Args: width (float): 矩形的宽度,必须为正数 height (float): 矩形的高度,必须为正数 @@ -380,22 +405,22 @@ def make_rectangle_rface(width: float, height: float, 默认为 (0, 0, 0) normal (Tuple[float, float, float], optional): 矩形所在平面的法向量 (x, y, z), 默认为 (0, 0, 1) 表示XY平面 - + Returns: Face: 创建的面对象,表示一个实心的矩形面 - + Raises: ValueError: 当宽度或高度小于等于0或其他参数无效时抛出异常 - + Usage: 创建矩形面对象,用于构建实心矩形截面。可以用于拉伸、旋转等操作来创建 立方体、棱柱等三维几何体。面积等于width×height。 - + Example: # 创建标准矩形面 rect_face = make_rectangle_rface(5.0, 3.0) area = rect_face.get_area() # 面积为5×3=15 - + # 创建用于拉伸的矩形截面 profile = make_rectangle_rface(2.0, 2.0) box = extrude_rsolid(profile, (0, 0, 1), 3.0) @@ -408,33 +433,35 @@ def make_rectangle_rface(width: float, height: float, raise ValueError(f"创建矩形面失败: {e}") -def make_face_from_wire_rface(wire: Wire, normal: Tuple[float, float, float] = (0, 0, 1)) -> Face: +def make_face_from_wire_rface( + wire: Wire, normal: Tuple[float, float, float] = (0, 0, 1) +) -> Face: """从封闭的线对象创建面对象 - + Args: wire (Wire): 输入的线对象,必须是封闭的线轮廓 normal (Tuple[float, float, float], optional): 期望的面法向量 (x, y, z), 用于确定面的方向,默认为 (0, 0, 1) - + Returns: Face: 创建的面对象,由输入的线轮廓围成的面 - + Raises: ValueError: 当输入的线对象无效、不封闭或创建面失败时抛出异常 - + Usage: 将封闭的线轮廓转换为面对象,用于从复杂的线框轮廓创建面。输入的线必须 是封闭的,函数会检查面的法向量方向,如果与期望方向相反会发出警告。 - + Example: # 从矩形线创建面 rect_wire = make_rectangle_rwire(3.0, 2.0) rect_face = make_face_from_wire_rface(rect_wire) - + # 从圆形线创建面 circle_wire = make_circle_rwire((0, 0, 0), 1.5) circle_face = make_face_from_wire_rface(circle_wire) - + # 从多边形线创建面 points = [(0, 0, 0), (2, 0, 0), (2, 2, 0), (0, 2, 0)] poly_wire = make_polyline_rwire(points, closed=True) @@ -451,61 +478,62 @@ def make_face_from_wire_rface(wire: Wire, normal: Tuple[float, float, float] = ( # 获取当前坐标系并转换法向量 cs = get_current_cs() global_normal = cs.transform_point(np.array(normal)) - cs.origin - + # 标准化法向量 normal_vec = global_normal / np.linalg.norm(global_normal) - + # 创建面 cq_face = cq.Face.makeFromWires(wire.cq_wire) - + # 检查面的法向量是否与期望方向一致 # normalAt方法返回tuple (normal_vector, u_vector) face_normal_tuple = cq_face.normalAt(0.5, 0.5) face_normal = face_normal_tuple[0] # 取第一个元素作为法向量 face_normal_vec = np.array([face_normal.x, face_normal.y, face_normal.z]) - + # 计算法向量的点积,如果小于0则需要反向 dot_product = np.dot(normal_vec, face_normal_vec) - + if dot_product < 0: # 反向面(通过反向Wire的方向) # CADQuery的Wire没有直接的reverse方法,我们需要重新构建 # 简单的方法是使用makeFromWires的orientation参数 # 或者我们接受当前面的方向,添加一个警告 print(f"警告: 创建的面的法向量与期望方向相反 (点积: {dot_product:.3f})") - + face = Face(cq_face) - + # 复制标签和元数据 face._tags = wire._tags.copy() face._metadata = wire._metadata.copy() - + return face except Exception as e: raise ValueError(f"创建面失败: {e}. 请检查输入的线是否有效且封闭。") - + + def make_wire_from_edges_rwire(edges: List[Edge]) -> Wire: """从边对象列表创建线对象 - + Args: edges (List[Edge]): 输入的边对象列表,边应该能够连接成连续的线 - + Returns: Wire: 创建的线对象,由输入的边组成的连续线 - + Raises: ValueError: 当边列表为空或边无法连接时抛出异常 - + Usage: 将多个边对象连接成一个连续的线对象。边的顺序很重要,相邻的边应该 能够连接在一起。用于构建复杂的线框结构。 - + Example: # 创建L形线 edge1 = make_line_redge((0, 0, 0), (2, 0, 0)) # 水平线 edge2 = make_line_redge((2, 0, 0), (2, 2, 0)) # 垂直线 l_wire = make_wire_from_edges_rwire([edge1, edge2]) - + # 创建包含直线和圆弧的复杂线 line = make_line_redge((0, 0, 0), (2, 0, 0)) arc = make_three_point_arc_redge((2, 0, 0), (3, 1, 0), (2, 2, 0)) @@ -521,39 +549,43 @@ def make_wire_from_edges_rwire(edges: List[Edge]) -> Wire: raise ValueError(f"创建线失败: {e}. 请检查输入的边是否有效。") -def make_box_rsolid(width: float, height: float, depth: float, - center: Tuple[float, float, float] = (0, 0, 0)) -> Solid: +def make_box_rsolid( + width: float, + height: float, + depth: float, + center: Tuple[float, float, float] = (0, 0, 0), +) -> Solid: """创建立方体并返回实体对象 - + Args: width (float): 立方体的宽度(X方向尺寸),必须为正数 height (float): 立方体的高度(Y方向尺寸),必须为正数 depth (float): 立方体的深度(Z方向尺寸),必须为正数 center (Tuple[float, float, float], optional): 立方体的中心坐标 (x, y, z), 默认为 (0, 0, 0) - + Returns: Solid: 创建的实体对象,表示一个立方体 - + Raises: ValueError: 当宽度、高度或深度小于等于0时抛出异常 - + Usage: 创建矩形立方体实体,是最基础的三维几何体之一。自动为立方体的面添加 标签(top、bottom、front、back、left、right),便于后续的面选择操作。 体积等于width×height×depth。 - + Example: # 创建标准单位立方体 unit_cube = make_box_rsolid(1.0, 1.0, 1.0) volume = unit_cube.get_volume() # 体积为1 - + # 创建矩形立方体 rect_box = make_box_rsolid(4.0, 2.0, 3.0) - + # 创建偏移的立方体 offset_box = make_box_rsolid(2.0, 2.0, 2.0, (1, 1, 1)) - + # 获取立方体的面进行后续操作 faces = unit_cube.get_faces() top_faces = [f for f in faces if f.has_tag("top")] @@ -561,27 +593,30 @@ def make_box_rsolid(width: float, height: float, depth: float, try: if width <= 0 or height <= 0 or depth <= 0: raise ValueError("宽度、高度和深度必须大于0") - + cs = get_current_cs() center_global = cs.transform_point(np.array(center)) - + # 创建立方体 cq_solid = cq.Solid.makeBox(width, height, depth, Vector(*center_global)) solid = Solid(cq_solid) - + # 自动标记面 solid.auto_tag_faces("box") - + return solid except Exception as e: raise ValueError(f"创建立方体失败: {e}. 请检查尺寸和中心点坐标是否有效。") -def make_cylinder_rsolid(radius: float, height: float, - center: Tuple[float, float, float] = (0, 0, 0), - axis: Tuple[float, float, float] = (0, 0, 1)) -> Solid: +def make_cylinder_rsolid( + radius: float, + height: float, + center: Tuple[float, float, float] = (0, 0, 0), + axis: Tuple[float, float, float] = (0, 0, 1), +) -> Solid: """创建圆柱体并返回实体对象 - + Args: radius (float): 圆柱体的半径,必须为正数 height (float): 圆柱体的高度,必须为正数 @@ -589,28 +624,28 @@ def make_cylinder_rsolid(radius: float, height: float, 默认为 (0, 0, 0) axis (Tuple[float, float, float], optional): 圆柱体的轴向向量 (x, y, z), 定义圆柱体的方向,默认为 (0, 0, 1) 表示沿Z轴方向 - + Returns: Solid: 创建的实体对象,表示一个圆柱体 - + Raises: ValueError: 当半径或高度小于等于0时抛出异常 - + Usage: 创建圆柱体实体,是基础的三维几何体之一。自动为圆柱体的面添加标签 (top、bottom、cylindrical),便于后续的面选择操作。体积等于πr²h。 - + Example: # 创建标准圆柱体 cylinder = make_cylinder_rsolid(2.0, 5.0) volume = cylinder.get_volume() # 体积为π×2²×5≈62.83 - + # 创建水平圆柱体 horizontal_cyl = make_cylinder_rsolid(1.0, 4.0, (0, 0, 0), (1, 0, 0)) - + # 创建偏移的圆柱体 offset_cyl = make_cylinder_rsolid(1.5, 3.0, (2, 2, 0)) - + # 获取圆柱体的面进行后续操作 faces = cylinder.get_faces() top_faces = [f for f in faces if f.has_tag("top")] @@ -618,55 +653,58 @@ def make_cylinder_rsolid(radius: float, height: float, try: if radius <= 0 or height <= 0: raise ValueError("半径和高度必须大于0") - + cs = get_current_cs() center_global = cs.transform_point(np.array(center)) axis_global = cs.transform_vector(np.array(axis)) - + center_vec = Vector(*center_global) axis_vec = Vector(*axis_global) - + cq_solid = cq.Solid.makeCylinder(radius, height, center_vec, axis_vec) solid = Solid(cq_solid) - + # 自动标记面 solid.auto_tag_faces("cylinder") - + return solid except Exception as e: - raise ValueError(f"创建圆柱体失败: {e}. 请检查半径、高度、中心点和轴向是否有效。") + raise ValueError( + f"创建圆柱体失败: {e}. 请检查半径、高度、中心点和轴向是否有效。" + ) -def make_sphere_rsolid(radius: float, - center: Tuple[float, float, float] = (0, 0, 0)) -> Solid: +def make_sphere_rsolid( + radius: float, center: Tuple[float, float, float] = (0, 0, 0) +) -> Solid: """创建球体并返回实体对象 - + Args: radius (float): 球体的半径,必须为正数 center (Tuple[float, float, float], optional): 球体的中心坐标 (x, y, z), 默认为 (0, 0, 0) - + Returns: Solid: 创建的实体对象,表示一个球体 - + Raises: ValueError: 当半径小于等于0时抛出异常 - + Usage: 创建球体实体,是基础的三维几何体之一。自动为球体的面添加标签(surface), 便于后续的面选择操作。体积等于(4/3)πr³。 - + Example: # 创建标准单位球体 unit_sphere = make_sphere_rsolid(1.0) volume = unit_sphere.get_volume() # 体积为(4/3)π≈4.19 - + # 创建大球体 large_sphere = make_sphere_rsolid(3.0) - + # 创建偏移的球体 offset_sphere = make_sphere_rsolid(2.0, (1, 1, 1)) - + # 获取球体的面进行后续操作 faces = unit_sphere.get_faces() surface_faces = [f for f in faces if f.has_tag("surface")] @@ -674,54 +712,62 @@ def make_sphere_rsolid(radius: float, try: if radius <= 0: raise ValueError("半径必须大于0") - + cs = get_current_cs() center_global = cs.transform_point(np.array(center)) - + # 使用Workplane.sphere方法创建球体,然后移动到正确位置 if center_global[0] != 0 or center_global[1] != 0 or center_global[2] != 0: - cq_solid = cq.Workplane("XY").center(center_global[0], center_global[1]).workplane(offset=center_global[2]).sphere(radius).val() + cq_solid = ( + cq.Workplane("XY") + .center(center_global[0], center_global[1]) + .workplane(offset=center_global[2]) + .sphere(radius) + .val() + ) else: cq_solid = cq.Workplane("XY").sphere(radius).val() - + solid = Solid(cq_solid) - + # 自动标记面 solid.auto_tag_faces("sphere") - + return solid except Exception as e: raise ValueError(f"创建球体失败: {e}. 请检查半径和中心点坐标是否有效。") -def make_three_point_arc_redge(start: Tuple[float, float, float], - middle: Tuple[float, float, float], - end: Tuple[float, float, float]) -> Edge: +def make_three_point_arc_redge( + start: Tuple[float, float, float], + middle: Tuple[float, float, float], + end: Tuple[float, float, float], +) -> Edge: """通过三点创建圆弧并返回边对象 - + Args: start (Tuple[float, float, float]): 圆弧的起始点坐标 (x, y, z) middle (Tuple[float, float, float]): 圆弧上的中间点坐标 (x, y, z), 用于确定圆弧的曲率和方向 end (Tuple[float, float, float]): 圆弧的结束点坐标 (x, y, z) - + Returns: Edge: 创建的边对象,表示通过三点的圆弧 - + Raises: ValueError: 当三个点共线或坐标无效时抛出异常 - + Usage: 通过三个点创建圆弧边,三个点不能共线。圆弧从起始点经过中间点到结束点。 中间点的位置决定了圆弧的弯曲程度和方向。 - + Example: # 创建90度圆弧 arc = make_three_point_arc_redge((0, 0, 0), (1, 1, 0), (2, 0, 0)) - + # 创建大圆弧 large_arc = make_three_point_arc_redge((0, 0, 0), (0, 3, 0), (0, 6, 0)) - + # 创建3D圆弧 arc_3d = make_three_point_arc_redge((0, 0, 0), (1, 1, 1), (2, 0, 2)) """ @@ -730,42 +776,44 @@ def make_three_point_arc_redge(start: Tuple[float, float, float], start_global = cs.transform_point(np.array(start)) middle_global = cs.transform_point(np.array(middle)) end_global = cs.transform_point(np.array(end)) - + start_vec = Vector(*start_global) middle_vec = Vector(*middle_global) end_vec = Vector(*end_global) - + cq_edge = cq.Edge.makeThreePointArc(start_vec, middle_vec, end_vec) return Edge(cq_edge) except Exception as e: raise ValueError(f"创建三点圆弧失败: {e}. 请检查三个点的坐标是否有效且不共线。") -def make_three_point_arc_rwire(start: Tuple[float, float, float], - middle: Tuple[float, float, float], - end: Tuple[float, float, float]) -> Wire: +def make_three_point_arc_rwire( + start: Tuple[float, float, float], + middle: Tuple[float, float, float], + end: Tuple[float, float, float], +) -> Wire: """通过三点创建圆弧并返回线对象 - + Args: start (Tuple[float, float, float]): 圆弧的起始点坐标 (x, y, z) middle (Tuple[float, float, float]): 圆弧上的中间点坐标 (x, y, z), 用于确定圆弧的曲率和方向 end (Tuple[float, float, float]): 圆弧的结束点坐标 (x, y, z) - + Returns: Wire: 创建的线对象,包含一个通过三点的圆弧 - + Raises: ValueError: 当三个点共线或坐标无效时抛出异常 - + Usage: 通过三个点创建圆弧线对象,与make_three_point_arc_redge功能相同, 但返回的是线对象,可以与其他线对象连接或用于构建复杂轮廓。 - + Example: # 创建圆弧线 arc_wire = make_three_point_arc_rwire((0, 0, 0), (1, 1, 0), (0, 2, 0)) - + # 与直线连接创建复杂轮廓 line = make_segment_rwire((0, 2, 0), (3, 2, 0)) # 然后可以连接arc_wire和line @@ -778,13 +826,15 @@ def make_three_point_arc_rwire(start: Tuple[float, float, float], raise ValueError(f"创建三点圆弧线失败: {e}") -def make_angle_arc_redge(center: Tuple[float, float, float], - radius: float, - start_angle: float, - end_angle: float, - normal: Tuple[float, float, float] = (0, 0, 1)) -> Edge: +def make_angle_arc_redge( + center: Tuple[float, float, float], + radius: float, + start_angle: float, + end_angle: float, + normal: Tuple[float, float, float] = (0, 0, 1), +) -> Edge: """通过角度创建圆弧并返回边对象 - + Args: center (Tuple[float, float, float]): 圆弧的中心点坐标 (x, y, z) radius (float): 圆弧的半径,必须为正数 @@ -792,27 +842,27 @@ def make_angle_arc_redge(center: Tuple[float, float, float], end_angle (float): 结束角度,单位为度数(0-360) normal (Tuple[float, float, float], optional): 圆弧所在平面的法向量 (x, y, z), 默认为 (0, 0, 1) 表示XY平面 - + Returns: Edge: 创建的边对象,表示指定角度范围的圆弧 - + Raises: ValueError: 当半径小于等于0或其他参数无效时抛出异常 - + Usage: 通过指定中心点、半径和角度范围创建圆弧边。角度采用度数制, 0度对应X轴正方向,逆时针为正角度。可以创建任意角度范围的圆弧。 - + Example: # 创建90度圆弧(从0度到90度) arc_90 = make_angle_arc_redge((0, 0, 0), 2.0, 0, 90) - + # 创建180度半圆弧 semicircle = make_angle_arc_redge((0, 0, 0), 1.5, 0, 180) - + # 创建270度圆弧 arc_270 = make_angle_arc_redge((0, 0, 0), 1.0, 45, 315) - + # 创建垂直平面上的圆弧 vertical_arc = make_angle_arc_redge((0, 0, 0), 1.0, 0, 90, (1, 0, 0)) """ @@ -821,42 +871,50 @@ def make_angle_arc_redge(center: Tuple[float, float, float], raise ValueError("半径必须大于0") if start_angle == end_angle: raise ValueError("起始角度和结束角度不能相同") - + cs = get_current_cs() center_global = cs.transform_point(np.array(center)) normal_global = cs.transform_point(np.array(normal)) - cs.origin - + # 标准化法向量 normal_vec = normal_global / np.linalg.norm(normal_global) - + # 创建本地坐标系 # 如果法向量接近Z轴,使用X轴作为参考 if abs(normal_vec[2]) > 0.9: ref_vec = np.array([1.0, 0.0, 0.0]) else: ref_vec = np.array([0.0, 0.0, 1.0]) - + # 计算本地坐标系的X和Y轴 local_x = np.cross(normal_vec, ref_vec) local_x = local_x / np.linalg.norm(local_x) local_y = np.cross(normal_vec, local_x) local_y = local_y / np.linalg.norm(local_y) - + # 在本地坐标系中计算起始、结束和中间点 - start_local = np.array([radius * np.cos(start_angle), radius * np.sin(start_angle), 0]) - end_local = np.array([radius * np.cos(end_angle), radius * np.sin(end_angle), 0]) + start_local = np.array( + [radius * np.cos(start_angle), radius * np.sin(start_angle), 0] + ) + end_local = np.array( + [radius * np.cos(end_angle), radius * np.sin(end_angle), 0] + ) mid_angle = (start_angle + end_angle) / 2 - mid_local = np.array([radius * np.cos(mid_angle), radius * np.sin(mid_angle), 0]) - + mid_local = np.array( + [radius * np.cos(mid_angle), radius * np.sin(mid_angle), 0] + ) + # 转换到全局坐标系 - start_global = center_global + start_local[0] * local_x + start_local[1] * local_y + start_global = ( + center_global + start_local[0] * local_x + start_local[1] * local_y + ) end_global = center_global + end_local[0] * local_x + end_local[1] * local_y mid_global = center_global + mid_local[0] * local_x + mid_local[1] * local_y - + start_vec = Vector(*start_global) end_vec = Vector(*end_global) mid_vec = Vector(*mid_global) - + # 使用三点圆弧方法 cq_edge = cq.Edge.makeThreePointArc(start_vec, mid_vec, end_vec) return Edge(cq_edge) @@ -864,13 +922,14 @@ def make_angle_arc_redge(center: Tuple[float, float, float], raise ValueError(f"创建角度圆弧失败: {e}. 请检查参数是否有效。") -def make_angle_arc_rwire(center: Tuple[float, float, float], - radius: float, - start_angle: float, - end_angle: float, - normal: Tuple[float, float, float] = (0, 0, 1)) -> Wire: - - """ 通过角度创建圆弧并返回线对象 +def make_angle_arc_rwire( + center: Tuple[float, float, float], + radius: float, + start_angle: float, + end_angle: float, + normal: Tuple[float, float, float] = (0, 0, 1), +) -> Wire: + """通过角度创建圆弧并返回线对象 Args: center: 圆心坐标 @@ -881,29 +940,28 @@ def make_angle_arc_rwire(center: Tuple[float, float, float], Returns: Wire: 线对象,表示通过角度创建的圆弧线 - + Raises: ValueError: 当半径小于等于0或其他参数无效时 - + Usage: 通过指定中心点、半径和角度范围创建圆弧线。 角度采用度数制,0度对应X轴正方向,逆时针为正角度。 可以创建任意角度范围的圆弧线。 - + Example: # 创建90度圆弧线(从0度到90度) arc_90_wire = make_angle_arc_rwire((0, 0, 0), 2.0, 0, 90) - + # 创建180度半圆弧线 semicircle_wire = make_angle_arc_rwire((0, 0, 0), 1.5, 0, 180) # 创建270度圆弧线 arc_270_wire = make_angle_arc_rwire((0, 0, 0), 1.0, 45, 315) - + # 创建垂直平面(YZ,法相指向X轴正方向)上的圆弧线 vertical_arc_wire = make_angle_arc_rwire((0, 0, 0), 1.0, 0, 90, (1, 0, 0)) """ - - + try: edge = make_angle_arc_redge(center, radius, start_angle, end_angle, normal) cq_wire = cq.Wire.assembleEdges([edge.cq_edge]) @@ -912,36 +970,38 @@ def make_angle_arc_rwire(center: Tuple[float, float, float], raise ValueError(f"创建角度圆弧线失败: {e}") -def make_spline_redge(points: List[Tuple[float, float, float]], - tangents: Optional[List[Tuple[float, float, float]]] = None) -> Edge: +def make_spline_redge( + points: List[Tuple[float, float, float]], + tangents: Optional[List[Tuple[float, float, float]]] = None, +) -> Edge: """创建样条曲线并返回边对象 - + Args: points (List[Tuple[float, float, float]]): 控制点坐标列表 [(x, y, z), ...], 至少需要2个点,点的顺序决定样条曲线的走向 - tangents (Optional[List[Tuple[float, float, float]]], optional): + tangents (Optional[List[Tuple[float, float, float]]], optional): 可选的切线向量列表 [(x, y, z), ...],如果提供则数量必须与控制点一致 - + Returns: Edge: 创建的边对象,表示通过控制点的平滑样条曲线 - + Raises: ValueError: 当控制点少于2个或切线向量数量不匹配时抛出异常 - + Usage: 创建平滑的样条曲线边,用于构建复杂的曲线路径。样条曲线会平滑地通过 所有控制点,可选择性地指定每个点的切线方向来控制曲线的形状。 - + Example: # 创建简单的样条曲线 points = [(0, 0, 0), (1, 2, 0), (3, 1, 0), (4, 3, 0)] spline = make_spline_redge(points) - + # 创建带切线控制的样条曲线 points = [(0, 0, 0), (2, 0, 0), (4, 0, 0)] tangents = [(1, 0, 0), (0, 1, 0), (1, 0, 0)] controlled_spline = make_spline_redge(points, tangents) - + # 创建3D样条曲线 points_3d = [(0, 0, 0), (1, 1, 1), (2, 0, 2), (3, 1, 1)] spline_3d = make_spline_redge(points_3d) @@ -949,15 +1009,15 @@ def make_spline_redge(points: List[Tuple[float, float, float]], try: if len(points) < 2: raise ValueError("至少需要2个控制点") - + cs = get_current_cs() - + # 转换控制点到全局坐标系 global_points = [] for point in points: global_point = cs.transform_point(np.array(point)) global_points.append(Vector(*global_point)) - + # 转换切线向量(如果提供) global_tangents = None if tangents: @@ -967,45 +1027,47 @@ def make_spline_redge(points: List[Tuple[float, float, float]], for tangent in tangents: global_tangent = cs.transform_point(np.array(tangent)) - cs.origin global_tangents.append(Vector(*global_tangent)) - + if global_tangents: # CADQuery的makeSpline不支持tangents参数,使用makeSplineApprox cq_edge = cq.Edge.makeSplineApprox(global_points) else: cq_edge = cq.Edge.makeSpline(global_points) - + return Edge(cq_edge) except Exception as e: raise ValueError(f"创建样条曲线失败: {e}. 请检查控制点和切线向量是否有效。") -def make_spline_rwire(points: List[Tuple[float, float, float]], - tangents: Optional[List[Tuple[float, float, float]]] = None, - closed: bool = False) -> Wire: +def make_spline_rwire( + points: List[Tuple[float, float, float]], + tangents: Optional[List[Tuple[float, float, float]]] = None, + closed: bool = False, +) -> Wire: """创建样条曲线并返回线对象 - + Args: points (List[Tuple[float, float, float]]): 控制点坐标列表 [(x, y, z), ...], 至少需要2个点,点的顺序决定样条曲线的走向 - tangents (Optional[List[Tuple[float, float, float]]], optional): + tangents (Optional[List[Tuple[float, float, float]]], optional): 可选的切线向量列表 [(x, y, z), ...],如果提供则数量必须与控制点一致 closed (bool, optional): 是否创建闭合的样条曲线,默认为False - + Returns: Wire: 创建的线对象,包含一个样条曲线 - + Raises: ValueError: 当控制点少于2个或切线向量数量不匹配时抛出异常 - + Usage: 创建样条曲线线对象,与make_spline_redge功能相同但返回线对象。 可以设置为闭合样条曲线,适用于构建复杂的封闭轮廓。 - + Example: # 创建开放样条曲线线 points = [(0, 0, 0), (2, 3, 0), (4, 1, 0), (6, 2, 0)] spline_wire = make_spline_rwire(points) - + # 创建闭合样条曲线 points = [(0, 0, 0), (2, 2, 0), (4, 0, 0), (2, -2, 0)] closed_spline = make_spline_rwire(points, closed=True) @@ -1021,35 +1083,36 @@ def make_spline_rwire(points: List[Tuple[float, float, float]], raise ValueError(f"创建样条曲线线失败: {e}") -def make_polyline_rwire(points: List[Tuple[float, float, float]], - closed: bool = False) -> Wire: +def make_polyline_rwire( + points: List[Tuple[float, float, float]], closed: bool = False +) -> Wire: """创建多段线并返回线对象 - + Args: points (List[Tuple[float, float, float]]): 顶点坐标列表 [(x, y, z), ...], 至少需要2个点,相邻点之间用直线连接 closed (bool, optional): 是否创建闭合的多段线,默认为False。 如果为True,会自动连接最后一个点和第一个点 - + Returns: Wire: 创建的线对象,由多个直线段组成的多段线 - + Raises: ValueError: 当顶点少于2个时抛出异常 - + Usage: 创建由多个直线段连接的多段线,用于构建折线、多边形轮廓等。 相邻点之间用直线连接,可以创建开放或闭合的多段线。 - + Example: # 创建L形多段线 points = [(0, 0, 0), (3, 0, 0), (3, 2, 0)] l_shape = make_polyline_rwire(points) - + # 创建三角形轮廓 triangle_points = [(0, 0, 0), (2, 0, 0), (1, 2, 0)] triangle = make_polyline_rwire(triangle_points, closed=True) - + # 创建复杂的多边形 polygon_points = [(0, 0, 0), (2, 0, 0), (3, 1, 0), (2, 2, 0), (0, 2, 0)] polygon = make_polyline_rwire(polygon_points, closed=True) @@ -1057,46 +1120,48 @@ def make_polyline_rwire(points: List[Tuple[float, float, float]], try: if len(points) < 2: raise ValueError("至少需要2个点") - + cs = get_current_cs() - + # 转换所有点到全局坐标系 global_points = [] for point in points: global_point = cs.transform_point(np.array(point)) global_points.append(Vector(*global_point)) - + # 创建边列表 edges = [] num_points = len(global_points) - + # 创建连接相邻点的边 for i in range(num_points - 1): start_vec = global_points[i] end_vec = global_points[i + 1] edge = cq.Edge.makeLine(start_vec, end_vec) edges.append(edge) - + # 如果闭合,添加最后一条边 if closed and num_points > 2: start_vec = global_points[-1] end_vec = global_points[0] edge = cq.Edge.makeLine(start_vec, end_vec) edges.append(edge) - + cq_wire = cq.Wire.assembleEdges(edges) return Wire(cq_wire.close() if closed else cq_wire) except Exception as e: raise ValueError(f"创建多段线失败: {e}. 请检查点坐标是否有效。") -def make_helix_redge(pitch: float, - height: float, - radius: float, - center: Tuple[float, float, float] = (0, 0, 0), - dir: Tuple[float, float, float] = (0, 0, 1)) -> Edge: +def make_helix_redge( + pitch: float, + height: float, + radius: float, + center: Tuple[float, float, float] = (0, 0, 0), + dir: Tuple[float, float, float] = (0, 0, 1), +) -> Edge: """创建螺旋线并返回边对象 - + Args: pitch (float): 螺距,每转一圈在轴向上的距离,必须为正数 height (float): 螺旋线的总高度,必须为正数 @@ -1105,24 +1170,24 @@ def make_helix_redge(pitch: float, 默认为 (0, 0, 0) dir (Tuple[float, float, float], optional): 螺旋轴的方向向量 (x, y, z), 默认为 (0, 0, 1) 表示沿Z轴方向 - + Returns: Edge: 创建的边对象,表示一个螺旋线 - + Raises: ValueError: 当螺距、高度或半径小于等于0时抛出异常 - + Usage: 创建螺旋线边对象,用于构建螺旋形状的路径或进行螺旋扫掠。 螺旋线绕指定轴旋转,同时沿轴向移动,形成螺旋形状。 - + Example: # 创建标准螺旋线 helix = make_helix_redge(2.0, 10.0, 1.0) # 螺距2,高度10,半径1 - + # 创建紧密螺旋线 tight_helix = make_helix_redge(0.5, 5.0, 0.5) - + # 创建水平螺旋线 horizontal_helix = make_helix_redge(1.0, 8.0, 2.0, (0, 0, 0), (1, 0, 0)) """ @@ -1133,14 +1198,14 @@ def make_helix_redge(pitch: float, raise ValueError("高度必须大于0") if radius <= 0: raise ValueError("半径必须大于0") - + cs = get_current_cs() global_center = cs.transform_point(np.array(center)) global_dir = cs.transform_point(np.array(dir)) - cs.origin - + center_vec = Vector(*global_center) dir_vec = Vector(*global_dir) - + # 使用CADQuery的Wire.makeHelix方法创建螺旋线,然后提取边 cq_wire = cq.Wire.makeHelix(pitch, height, radius, center_vec, dir_vec) # 螺旋线通常是连续的,所以我们取第一个边 @@ -1153,13 +1218,15 @@ def make_helix_redge(pitch: float, raise ValueError(f"创建螺旋线边失败: {e}. 请检查参数是否有效。") -def make_helix_rwire(pitch: float, - height: float, - radius: float, - center: Tuple[float, float, float] = (0, 0, 0), - dir: Tuple[float, float, float] = (0, 0, 1)) -> Wire: +def make_helix_rwire( + pitch: float, + height: float, + radius: float, + center: Tuple[float, float, float] = (0, 0, 0), + dir: Tuple[float, float, float] = (0, 0, 1), +) -> Wire: """创建螺旋线并返回线对象 - + Args: pitch (float): 螺距,每转一圈在轴向上的距离,必须为正数 height (float): 螺旋线的总高度,必须为正数 @@ -1168,21 +1235,21 @@ def make_helix_rwire(pitch: float, 默认为 (0, 0, 0) dir (Tuple[float, float, float], optional): 螺旋轴的方向向量 (x, y, z), 默认为 (0, 0, 1) 表示沿Z轴方向 - + Returns: Wire: 创建的线对象,包含一个螺旋线 - + Raises: ValueError: 当螺距、高度或半径小于等于0时抛出异常 - + Usage: 创建螺旋线线对象,与make_helix_redge功能相同但返回线对象。 可以用于后续的扫掠操作或作为复杂路径的一部分。 - + Example: # 创建螺旋线线对象 helix_wire = make_helix_rwire(1.5, 6.0, 1.0) - + # 用于扫掠操作的螺旋路径 profile = make_circle_rface((0, 0, 0), 0.1) helix_path = make_helix_rwire(2.0, 10.0, 2.0) @@ -1192,10 +1259,10 @@ def make_helix_rwire(pitch: float, cs = get_current_cs() global_center = cs.transform_point(np.array(center)) global_dir = cs.transform_point(np.array(dir)) - cs.origin - + center_vec = Vector(*global_center) dir_vec = Vector(*global_dir) - + # 使用CADQuery的Wire.makeHelix方法 cq_wire = cq.Wire.makeHelix(pitch, height, radius, center_vec, dir_vec) return Wire(cq_wire) @@ -1207,33 +1274,34 @@ def make_helix_rwire(pitch: float, # 变换操作函数 # ============================================================================= + def translate_shape(shape: AnyShape, vector: Tuple[float, float, float]) -> AnyShape: """平移几何体到新位置 - + Args: shape (AnyShape): 要平移的几何体,可以是点、边、线、面、实体等任意几何对象 vector (Tuple[float, float, float]): 平移向量 (dx, dy, dz), 定义在X、Y、Z方向上的平移距离 - + Returns: AnyShape: 平移后的几何体,类型与输入相同 - + Raises: ValueError: 当几何体或平移向量无效时抛出异常 - + Usage: 将几何体从当前位置平移到新位置,不改变几何体的形状和大小。 平移操作支持当前坐标系变换,适用于所有类型的几何对象。 - + Example: # 平移立方体 box = make_box_rsolid(2, 2, 2) moved_box = translate_shape(box, (5, 0, 0)) # 沿X轴移动5个单位 - + # 平移圆形面 circle = make_circle_rface((0, 0, 0), 1.0) moved_circle = translate_shape(circle, (1, 1, 2)) - + # 平移线段 line = make_line_redge((0, 0, 0), (1, 0, 0)) moved_line = translate_shape(line, (0, 3, 0)) @@ -1241,9 +1309,9 @@ def translate_shape(shape: AnyShape, vector: Tuple[float, float, float]) -> AnyS try: cs = get_current_cs() global_vector = cs.transform_point(np.array(vector)) - cs.origin - + translation_vec = Vector(*global_vector) - + if isinstance(shape, Vertex): new_cq_shape = shape.cq_vertex.translate(translation_vec) new_shape = Vertex(new_cq_shape) @@ -1265,24 +1333,24 @@ def translate_shape(shape: AnyShape, vector: Tuple[float, float, float]) -> AnyS elif isinstance(shape, Compound): new_cq_shape = shape.cq_compound.translate(translation_vec) new_shape = Compound(new_cq_shape) - else: - raise ValueError(f"不支持的几何体类型: {type(shape)}") - + # 复制标签和元数据 new_shape._tags = shape._tags.copy() new_shape._metadata = shape._metadata.copy() - + return new_shape except Exception as e: raise ValueError(f"平移几何体失败: {e}. 请检查几何体和平移向量是否有效。") -def rotate_shape(shape: AnyShape, - angle: float, - axis: Tuple[float, float, float] = (0, 0, 1), - origin: Tuple[float, float, float] = (0, 0, 0)) -> AnyShape: +def rotate_shape( + shape: AnyShape, + angle: float, + axis: Tuple[float, float, float] = (0, 0, 1), + origin: Tuple[float, float, float] = (0, 0, 0), +) -> AnyShape: """旋转几何体到新方向 - + Args: shape (AnyShape): 要旋转的几何体,可以是点、边、线、面、实体等任意几何对象 angle (float): 旋转角度,单位为度数(0-360),正值表示逆时针旋转 @@ -1290,27 +1358,27 @@ def rotate_shape(shape: AnyShape, 默认为 (0, 0, 1) 表示绕Z轴旋转 origin (Tuple[float, float, float], optional): 旋转中心点坐标 (x, y, z), 默认为 (0, 0, 0) - + Returns: AnyShape: 旋转后的几何体,类型与输入相同 - + Raises: ValueError: 当几何体或旋转参数无效时抛出异常 - + Usage: 围绕指定轴和中心点旋转几何体,不改变几何体的形状和大小。 旋转操作支持当前坐标系变换,适用于所有类型的几何对象。 角度使用度数制,正值表示右手定则的逆时针旋转。 - + Example: # 绕Z轴旋转立方体45度 box = make_box_rsolid(2, 2, 2) rotated_box = rotate_shape(box, 45) - + # 绕X轴旋转圆形面90度 circle = make_circle_rface((0, 0, 0), 1.0) rotated_circle = rotate_shape(circle, 90, (1, 0, 0)) - + # 围绕指定点旋转 line = make_line_redge((0, 0, 0), (2, 0, 0)) rotated_line = rotate_shape(line, 90, (0, 0, 1), (1, 0, 0)) @@ -1321,10 +1389,10 @@ def rotate_shape(shape: AnyShape, cs = get_current_cs() global_axis = cs.transform_point(np.array(axis)) - cs.origin global_origin = cs.transform_point(np.array(origin)) - + axis_vec = Vector(*global_axis) origin_vec = Vector(*global_origin) - + if isinstance(shape, Vertex): new_cq_shape = shape.cq_vertex.rotate(origin_vec, axis_vec, angle) new_shape = Vertex(new_cq_shape) @@ -1347,51 +1415,54 @@ def rotate_shape(shape: AnyShape, new_cq_shape = shape.cq_compound.rotate(origin_vec, axis_vec, angle) new_shape = Compound(new_cq_shape) else: - raise ValueError(f"不支持的几何体类型: {type(shape)}") - + raise ValueError(f"不支持的几何体类型: {type(shape)}") # type: ignore[unreachable] + # 复制标签和元数据 new_shape._tags = shape._tags.copy() new_shape._metadata = shape._metadata.copy() - + return new_shape except Exception as e: - raise ValueError(f"旋转几何体失败: {e}. 请检查几何体、角度、轴向和中心点是否有效。") + raise ValueError( + f"旋转几何体失败: {e}. 请检查几何体、角度、轴向和中心点是否有效。" + ) # ============================================================================= # 3D操作函数 # ============================================================================= -def extrude_rsolid(profile: Union[Wire, Face], - direction: Tuple[float, float, float], - distance: float) -> Solid: + +def extrude_rsolid( + profile: Union[Wire, Face], direction: Tuple[float, float, float], distance: float +) -> Solid: """拉伸轮廓创建实体 - + Args: profile (Union[Wire, Face]): 要拉伸的轮廓,可以是封闭的线或面 direction (Tuple[float, float, float]): 拉伸方向向量 (x, y, z), 定义拉伸的方向,会被标准化处理 distance (float): 拉伸距离,必须为正数 - + Returns: Solid: 拉伸后的实体对象 - + Raises: ValueError: 当轮廓不是封闭的线、距离小于等于0或其他参数无效时抛出异常 - + Usage: 沿指定方向拉伸二维轮廓创建三维实体。如果输入是线,必须是封闭的线; 如果输入是面,直接进行拉伸。这是创建柱状、管状等规则几何体的基础操作。 - + Example: # 拉伸圆形面创建圆柱体 circle = make_circle_rface((0, 0, 0), 1.0) cylinder = extrude_rsolid(circle, (0, 0, 1), 5.0) - + # 拉伸矩形面创建立方体 rect = make_rectangle_rface(2.0, 2.0) box = extrude_rsolid(rect, (0, 0, 1), 3.0) - + # 拉伸复杂轮廓 points = [(0, 0, 0), (2, 0, 0), (2, 1, 0), (0, 1, 0)] profile_wire = make_polyline_rwire(points, closed=True) @@ -1400,12 +1471,12 @@ def extrude_rsolid(profile: Union[Wire, Face], try: if distance <= 0: raise ValueError("拉伸距离必须大于0") - + cs = get_current_cs() global_direction = cs.transform_point(np.array(direction)) - cs.origin - + direction_vec = Vector(*global_direction).normalized() * distance - + if isinstance(profile, Wire): # 如果是线,先转换为面 if profile.is_closed(): @@ -1415,27 +1486,29 @@ def extrude_rsolid(profile: Union[Wire, Face], elif isinstance(profile, Face): face = profile else: - raise ValueError("只能拉伸线或面") - + raise ValueError("只能拉伸线或面") # type: ignore[unreachable] + # 使用CADQuery的Solid.extrudeLinear方法 cq_solid = cq.Solid.extrudeLinear(face.cq_face, direction_vec) solid = Solid(cq_solid) - + # 复制标签和元数据 solid._tags = profile._tags.copy() solid._metadata = profile._metadata.copy() - + return solid except Exception as e: raise ValueError(f"拉伸失败: {e}. 请检查轮廓、方向和距离是否有效。") -def revolve_rsolid(profile: Union[Wire, Face], - axis: Tuple[float, float, float] = (0, 0, 1), - angle: float = 2 * np.pi, - origin: Tuple[float, float, float] = (0, 0, 0)) -> Solid: +def revolve_rsolid( + profile: Union[Wire, Face], + axis: Tuple[float, float, float] = (0, 0, 1), + angle: float = 360, + origin: Tuple[float, float, float] = (0, 0, 0), +) -> Solid: """围绕轴旋转轮廓创建实体 - + Args: profile (Union[Wire, Face]): 要旋转的轮廓,可以是封闭的线或面 axis (Tuple[float, float, float], optional): 旋转轴向量 (x, y, z), @@ -1443,28 +1516,28 @@ def revolve_rsolid(profile: Union[Wire, Face], angle (float, optional): 旋转角度,单位为度数(0-360), 默认为360度(完整旋转),正值表示逆时针旋转 origin (Tuple[float, float, float], optional): 旋转轴通过的点坐标 (x, y, z), - 默认为 (0, 0, 0) - + 默认为 (0, 0, 0), 由此我们知道,origin和axis可以求出转轴两点,一点是origin本身,另一点是origin+axis向量的终点 + Returns: Solid: 旋转后的实体对象 - + Raises: ValueError: 当轮廓不是封闭的线、角度小于等于0或其他参数无效时抛出异常 - + Usage: 围绕指定轴旋转二维轮廓创建三维实体。常用于创建轴对称的几何体, 如圆柱体、圆锥体、球体等。如果输入是线,必须是封闭的线。 - + Example: # 旋转矩形创建圆柱体 rect = make_rectangle_rface(1.0, 3.0, (2, 0, 0)) # 远离旋转轴 cylinder = revolve_rsolid(rect, (0, 0, 1), 360) - + # 创建圆锥体 triangle_points = [(1, 0, 0), (2, 0, 0), (1.5, 2, 0)] triangle = make_polyline_rwire(triangle_points, closed=True) cone = revolve_rsolid(triangle, (0, 0, 1), 360) - + # 创建部分旋转体(90度扇形) rect = make_rectangle_rface(0.5, 2.0, (1.5, 0, 0)) partial_solid = revolve_rsolid(rect, (0, 0, 1), 90) @@ -1472,11 +1545,11 @@ def revolve_rsolid(profile: Union[Wire, Face], try: if angle <= 0: raise ValueError("旋转角度必须大于0") - + cs = get_current_cs() global_axis = cs.transform_point(np.array(axis)) - cs.origin global_origin = cs.transform_point(np.array(origin)) - + # 获取轮廓对应的面 if isinstance(profile, Wire): # 如果是线,先转换为面 @@ -1488,25 +1561,38 @@ def revolve_rsolid(profile: Union[Wire, Face], face = profile else: raise ValueError("只能旋转线或面") - - # 使用CADQuery的Workplane方法进行旋转 - # 将角度转换为度数 - angle_degrees = angle * 180 / np.pi - - # 创建一个临时的Workplane,添加面,然后旋转 - wp = cq.Workplane("XY") - wp.objects = [face.cq_face] - - # 执行旋转 - revolved_wp = wp.revolve(angleDegrees=angle_degrees) - cq_solid = revolved_wp.val() - + + print(f"revolve_rsolid: profile type: {type(profile)}, face type: {type(face)}") + print( + f"with parameters: axis={global_axis}, angle={angle}, origin={global_origin}" + ) + + rv = revolve( + face.cq_face, + p=Vector((global_origin[0], global_origin[1], global_origin[2])), + d=Vector( + ( + global_axis[0], + global_axis[1], + global_axis[2], + ) + ).normalized(), + a=angle, + ) + + print(f"Revolve result type: {type(rv)}") + + if hasattr(rv, "Solids") and rv.Solids(): + cq_solid = rv.Solids()[0] + else: + cq_solid = rv + solid = Solid(cq_solid) - + # 复制标签和元数据 solid._tags = profile._tags.copy() solid._metadata = profile._metadata.copy() - + return solid except Exception as e: raise ValueError(f"旋转失败: {e}. 请检查轮廓、轴向、角度和中心点是否有效。") @@ -1516,13 +1602,14 @@ def revolve_rsolid(profile: Union[Wire, Face], # 标签和选择函数 # ============================================================================= + def set_tag(shape: AnyShape, tag: str) -> AnyShape: """为几何体设置标签 - + Args: shape: 几何体 tag: 标签名称 - + Returns: 设置标签后的几何体 """ @@ -1535,11 +1622,11 @@ def set_tag(shape: AnyShape, tag: str) -> AnyShape: def select_faces_by_tag(solid: Solid, tag: str) -> List[Face]: """根据标签选择面 - + Args: solid: 实体 tag: 标签名称 - + Returns: 匹配标签的面列表 """ @@ -1552,11 +1639,11 @@ def select_faces_by_tag(solid: Solid, tag: str) -> List[Face]: def select_edges_by_tag(shape: Union[Face, Solid], tag: str) -> List[Edge]: """根据标签选择边 - + Args: shape: 面或实体 tag: 标签名称 - + Returns: 匹配标签的边列表 """ @@ -1567,7 +1654,7 @@ def select_edges_by_tag(shape: Union[Face, Solid], tag: str) -> List[Edge]: edges = shape.get_edges() else: raise ValueError("只能从面或实体中选择边") - + return [edge for edge in edges if edge.has_tag(tag)] except Exception as e: raise ValueError(f"选择边失败: {e}. 请检查几何体和标签名称是否有效。") @@ -1577,32 +1664,33 @@ def select_edges_by_tag(shape: Union[Face, Solid], tag: str) -> List[Edge]: # 布尔运算函数 # ============================================================================= + def union_rsolid(solid1: Solid, solid2: Solid) -> Solid: """实体并集运算 - + Args: solid1 (Solid): 第一个参与运算的实体对象 solid2 (Solid): 第二个参与运算的实体对象 - + Returns: Solid: 两个实体的并集结果,包含两个实体的所有体积 - + Raises: ValueError: 当输入实体无效或运算失败时抛出异常 - + Usage: 计算两个实体的并集,返回包含两个实体所有体积的新实体。 并集运算会合并两个实体的重叠部分,结果体积大于等于任一输入实体。 - + Example: # 创建两个重叠的立方体 box1 = make_box_rsolid(2, 2, 2, (0, 0, 0)) box2 = make_box_rsolid(2, 2, 2, (1, 0, 0)) - + # 计算并集 union_result = union_rsolid(box1, box2) # 结果是一个组合的形状,体积小于两个立方体体积之和 - + # 圆柱和立方体的并集 cylinder = make_cylinder_rsolid(1.0, 3.0) box = make_box_rsolid(1, 1, 1, (0, 0, 1)) @@ -1615,20 +1703,20 @@ def union_rsolid(solid1: Solid, solid2: Solid) -> Solid: # 如果intersection是0,会给出一个error if s1.isNull() or s2.isNull(): raise ValueError("输入实体无效,无法进行并集运算。") - + rv = fuse(s1, s2) # 确保结果是Solid类型 - if hasattr(rv, 'Solids') and rv.Solids(): + if hasattr(rv, "Solids") and rv.Solids(): cq_result = rv.Solids()[0] - else: - cq_result = rv - + else: + cq_result = rv + result = Solid(cq_result) - + # 合并标签和元数据 result._tags = solid1._tags.union(solid2._tags) result._metadata = {**solid1._metadata, **solid2._metadata} - + return result except Exception as e: raise ValueError(f"并集运算失败: {e}. 请检查两个实体是否有效。") @@ -1636,48 +1724,57 @@ def union_rsolid(solid1: Solid, solid2: Solid) -> Solid: def cut_rsolid(solid1: Solid, solid2: Solid) -> Solid: """实体差集运算(布尔减法) - + Args: solid1 (Solid): 被减实体,作为基础实体 solid2 (Solid): 减去的实体,将从基础实体中移除 - + Returns: Solid: 差集结果实体,从solid1中减去solid2的重叠部分 - + Raises: ValueError: 当输入实体无效或运算失败时抛出异常 - + Usage: 从第一个实体中减去第二个实体的重叠部分,常用于创建孔洞、凹槽等。 结果实体的体积等于solid1减去两个实体重叠部分的体积。 - + Example: # 在立方体中创建圆形孔 box = make_box_rsolid(4, 4, 4) hole = make_cylinder_rsolid(1.0, 4.0) box_with_hole = cut_rsolid(box, hole) - + # 创建槽形结构 base = make_box_rsolid(6, 3, 2) slot = make_box_rsolid(4, 1, 2, (0, 0, 1)) slotted_base = cut_rsolid(base, slot) - + # 从球体中减去立方体 sphere = make_sphere_rsolid(2.0) cube = make_box_rsolid(2, 2, 2) carved_sphere = cut_rsolid(sphere, cube) """ try: - cq_result = solid1.cq_solid.cut(solid2.cq_solid) - # 确保结果是Solid类型 - if hasattr(cq_result, 'Solids') and cq_result.Solids(): - cq_result = cq_result.Solids()[0] + s1 = solid1.cq_solid + s2 = solid2.cq_solid + + if s1.isNull() or s2.isNull(): + raise ValueError("输入实体无效,无法进行差集运算。") + + rv = cut(s1, s2) + + if hasattr(rv, "Solids") and rv.Solids(): + cq_result = rv.Solids()[0] + else: + cq_result = rv + result = Solid(cq_result) - + # 保留第一个实体的标签和元数据 result._tags = solid1._tags.copy() result._metadata = solid1._metadata.copy() - + return result except Exception as e: raise ValueError(f"差集运算失败: {e}. 请检查两个实体是否有效。") @@ -1685,49 +1782,59 @@ def cut_rsolid(solid1: Solid, solid2: Solid) -> Solid: def intersect_rsolid(solid1: Solid, solid2: Solid) -> Solid: """实体交集运算(布尔交集) - + Args: solid1 (Solid): 第一个参与运算的实体对象 solid2 (Solid): 第二个参与运算的实体对象 - + Returns: Solid: 两个实体的交集结果,只包含两个实体的重叠部分 - + Raises: ValueError: 当输入实体无效或运算失败时抛出异常 - + Usage: 计算两个实体的交集,返回只包含两个实体重叠部分的新实体。 如果两个实体不相交,可能返回空实体。交集体积小于等于任一输入实体。 - + Example: # 计算两个重叠立方体的交集 box1 = make_box_rsolid(3, 3, 3, (0, 0, 0)) box2 = make_box_rsolid(3, 3, 3, (1, 1, 0)) intersection = intersect_rsolid(box1, box2) # 结果是一个2×2×3的立方体 - + # 球体和立方体的交集 sphere = make_sphere_rsolid(2.0) cube = make_box_rsolid(3, 3, 3) rounded_cube = intersect_rsolid(sphere, cube) - + # 圆柱体和平面的交集 cylinder = make_cylinder_rsolid(1.5, 4.0) slab = make_box_rsolid(4, 4, 2, (0, 0, 1)) partial_cylinder = intersect_rsolid(cylinder, slab) """ try: - cq_result = solid1.cq_solid.intersect(solid2.cq_solid) - # 确保结果是Solid类型 - if hasattr(cq_result, 'Solids') and cq_result.Solids(): - cq_result = cq_result.Solids()[0] + + s1 = solid1.cq_solid + s2 = solid2.cq_solid + + if s1.isNull() or s2.isNull(): + raise ValueError("输入实体无效,无法进行交集运算。") + + rv = intersect(s1, s2) + + if hasattr(rv, "Solids") and rv.Solids(): + cq_result = rv.Solids()[0] + else: + cq_result = rv + result = Solid(cq_result) - + # 合并标签和元数据 result._tags = solid1._tags.intersection(solid2._tags) result._metadata = {**solid1._metadata, **solid2._metadata} - + return result except Exception as e: raise ValueError(f"交集运算失败: {e}. 请检查两个实体是否有效。") @@ -1737,13 +1844,14 @@ def intersect_rsolid(solid1: Solid, solid2: Solid) -> Solid: # 导出函数 # ============================================================================= + def export_step(shapes: Union[AnyShape, Sequence[AnyShape]], filename: str) -> None: """导出为STEP格式 - + Args: shapes: 要导出的几何体或几何体列表 filename: 输出文件名 - + Raises: ValueError: 当导出失败时 """ @@ -1753,7 +1861,7 @@ def export_step(shapes: Union[AnyShape, Sequence[AnyShape]], filename: str) -> N shape_list = list(shapes) else: shape_list = [shapes] - + # 创建CADQuery的Workplane并添加所有几何体 wp = cq.Workplane() for shape in shape_list: @@ -1775,7 +1883,7 @@ def export_step(shapes: Union[AnyShape, Sequence[AnyShape]], filename: str) -> N for solid in solids: wp = wp.add(solid.cq_solid) # 注意:复合体可能还包含其他类型的几何体,但这里先只处理实体 - + # 导出到STEP文件 cq.exporters.export(wp, filename) except Exception as e: @@ -1784,11 +1892,11 @@ def export_step(shapes: Union[AnyShape, Sequence[AnyShape]], filename: str) -> N def export_stl(shapes: Union[AnyShape, Sequence[AnyShape]], filename: str) -> None: """导出为STL格式 - + Args: shapes: 要导出的几何体或几何体列表 filename: 输出文件名 - + Raises: ValueError: 当导出失败时 """ @@ -1798,7 +1906,7 @@ def export_stl(shapes: Union[AnyShape, Sequence[AnyShape]], filename: str) -> No shape_list = list(shapes) else: shape_list = [shapes] - + # 创建CADQuery的Workplane并添加所有几何体 wp = cq.Workplane() for shape in shape_list: @@ -1814,7 +1922,7 @@ def export_stl(shapes: Union[AnyShape, Sequence[AnyShape]], filename: str) -> No for solid in solids: wp = wp.add(solid.cq_solid) # STL只支持实体和面 - + # 导出到STL文件 cq.exporters.export(wp, filename) except Exception as e: @@ -1825,37 +1933,38 @@ def export_stl(shapes: Union[AnyShape, Sequence[AnyShape]], filename: str) -> No # 高级特征操作函数 # ============================================================================= + def fillet_rsolid(solid: Solid, edges: List[Edge], radius: float) -> Solid: """对实体的边进行圆角操作 - + Args: solid (Solid): 要进行圆角操作的实体对象 edges (List[Edge]): 要进行圆角的边列表,通常从实体获取 radius (float): 圆角半径,必须为正数,不能大于相邻面的最小尺寸 - + Returns: Solid: 圆角后的实体对象 - + Raises: ValueError: 当圆角半径小于等于0或圆角操作失败时抛出异常 - + Usage: 对实体的指定边进行圆角处理,创建平滑的过渡面。常用于消除尖锐边缘, 改善外观和减少应力集中。圆角半径不能太大,否则可能导致几何冲突。 - + Example: # 对立方体的所有边进行圆角 box = make_box_rsolid(4, 4, 4) all_edges = box.get_edges() rounded_box = fillet_rsolid(box, all_edges[:4], 0.5) # 只对前4条边圆角 - + # 对圆柱体的边进行圆角 cylinder = make_cylinder_rsolid(2.0, 5.0) edges = cylinder.get_edges() # 选择顶部和底部的圆边 circular_edges = [e for e in edges if e.has_tag("circular")] rounded_cylinder = fillet_rsolid(cylinder, circular_edges, 0.3) - + # 对复杂几何体的特定边圆角 complex_solid = union_rsolid(box, cylinder) selected_edges = complex_solid.get_edges()[:6] @@ -1864,18 +1973,18 @@ def fillet_rsolid(solid: Solid, edges: List[Edge], radius: float) -> Solid: try: if radius <= 0: raise ValueError("圆角半径必须大于0") - + # 转换为CADQuery边对象 cq_edges = [edge.cq_edge for edge in edges] - + # 执行圆角操作 cq_result = solid.cq_solid.fillet(radius, cq_edges) result = Solid(cq_result) - + # 复制标签和元数据 result._tags = solid._tags.copy() result._metadata = solid._metadata.copy() - + return result except Exception as e: raise ValueError(f"圆角操作失败: {e}. 请检查实体、边和半径是否有效。") @@ -1883,33 +1992,33 @@ def fillet_rsolid(solid: Solid, edges: List[Edge], radius: float) -> Solid: def chamfer_rsolid(solid: Solid, edges: List[Edge], distance: float) -> Solid: """对实体的边进行倒角操作 - + Args: solid (Solid): 要进行倒角操作的实体对象 edges (List[Edge]): 要进行倒角的边列表,通常从实体获取 distance (float): 倒角距离,必须为正数,定义从边缘向内的倒角深度 - + Returns: Solid: 倒角后的实体对象 - + Raises: ValueError: 当倒角距离小于等于0或倒角操作失败时抛出异常 - + Usage: 对实体的指定边进行倒角处理,创建斜面过渡。与圆角不同,倒角创建的是 平面过渡而不是圆弧过渡。常用于机械零件的边缘处理,便于装配和安全。 - + Example: # 对立方体的边进行倒角 box = make_box_rsolid(4, 4, 4) edges = box.get_edges() chamfered_box = chamfer_rsolid(box, edges[:4], 0.3) - + # 对圆柱体的边倒角 cylinder = make_cylinder_rsolid(2.0, 5.0) cylinder_edges = cylinder.get_edges() chamfered_cylinder = chamfer_rsolid(cylinder, cylinder_edges[:2], 0.2) - + # 选择性倒角 complex_solid = make_box_rsolid(6, 3, 2) top_edges = [e for e in complex_solid.get_edges() if e.has_tag("top")] @@ -1918,18 +2027,18 @@ def chamfer_rsolid(solid: Solid, edges: List[Edge], distance: float) -> Solid: try: if distance <= 0: raise ValueError("倒角距离必须大于0") - + # 转换为CADQuery边对象 cq_edges = [edge.cq_edge for edge in edges] - + # 执行倒角操作 cq_result = solid.cq_solid.chamfer(distance, None, cq_edges) result = Solid(cq_result) - + # 复制标签和元数据 result._tags = solid._tags.copy() result._metadata = solid._metadata.copy() - + return result except Exception as e: raise ValueError(f"倒角操作失败: {e}. 请检查实体、边和距离是否有效。") @@ -1937,34 +2046,34 @@ def chamfer_rsolid(solid: Solid, edges: List[Edge], distance: float) -> Solid: def shell_rsolid(solid: Solid, faces_to_remove: List[Face], thickness: float) -> Solid: """对实体进行抽壳操作,创建空心结构 - + Args: solid (Solid): 要抽壳的实体对象 faces_to_remove (List[Face]): 要移除的面列表,这些面将被开口, 如果为空列表则不移除任何面(闭合抽壳) thickness (float): 壁厚,必须为正数,定义抽壳后的壁厚度 - + Returns: Solid: 抽壳后的实体对象,内部为空心结构 - + Raises: ValueError: 当壁厚小于等于0或抽壳操作失败时抛出异常 - + Usage: 将实体转换为空心结构,常用于创建容器、外壳等。通过移除指定面 创建开口,壁厚决定了外壳的厚度。如果不移除任何面则创建闭合空心体。 - + Example: # 创建空心立方体容器 box = make_box_rsolid(4, 4, 4) top_faces = [f for f in box.get_faces() if f.has_tag("top")] container = shell_rsolid(box, top_faces, 0.2) - + # 创建空心球体 sphere = make_sphere_rsolid(3.0) # 不移除任何面,创建闭合空心球 hollow_sphere = shell_rsolid(sphere, [], 0.3) - + # 创建有开口的圆柱体容器 cylinder = make_cylinder_rsolid(2.0, 5.0) top_faces = [f for f in cylinder.get_faces() if f.has_tag("top")] @@ -1973,18 +2082,20 @@ def shell_rsolid(solid: Solid, faces_to_remove: List[Face], thickness: float) -> try: if thickness <= 0: raise ValueError("壁厚必须大于0") - + # 转换为CADQuery面对象 - cq_faces = [face.cq_face for face in faces_to_remove] if faces_to_remove else None - + cq_faces = ( + [face.cq_face for face in faces_to_remove] if faces_to_remove else None + ) + # 执行抽壳操作 cq_result = solid.cq_solid.shell(cq_faces, thickness) result = Solid(cq_result) - + # 复制标签和元数据 result._tags = solid._tags.copy() result._metadata = solid._metadata.copy() - + return result except Exception as e: raise ValueError(f"抽壳操作失败: {e}. 请检查实体、面和壁厚是否有效。") @@ -1992,35 +2103,35 @@ def shell_rsolid(solid: Solid, faces_to_remove: List[Face], thickness: float) -> def loft_rsolid(profiles: List[Wire], ruled: bool = False) -> Solid: """通过多个轮廓放样创建实体 - + Args: profiles (List[Wire]): 轮廓线列表,至少需要2个轮廓, 轮廓按顺序连接,第一个为起始轮廓,最后一个为结束轮廓 ruled (bool, optional): 是否为直纹面,默认为False。 True表示轮廓间用直线连接,False表示用平滑曲面连接 - + Returns: Solid: 放样后的实体对象 - + Raises: ValueError: 当轮廓少于2个或放样操作失败时抛出异常 - + Usage: 通过多个二维轮廓创建三维实体,轮廓间通过放样面连接。 常用于创建复杂的过渡形状,如飞机机翼、船体等变截面结构。 - + Example: # 创建方形到圆形的过渡体 square = make_rectangle_rwire(2, 2, (0, 0, 0)) circle = make_circle_rwire((0, 0, 3), 1.0) transition = loft_rsolid([square, circle]) - + # 创建多层过渡的复杂形状 bottom = make_rectangle_rwire(4, 4, (0, 0, 0)) middle = make_circle_rwire((0, 0, 2), 2.0) top = make_rectangle_rwire(1, 1, (0, 0, 4)) complex_shape = loft_rsolid([bottom, middle, top]) - + # 创建直纹面放样 profile1 = make_circle_rwire((0, 0, 0), 2.0) profile2 = make_circle_rwire((0, 0, 5), 1.0) @@ -2029,34 +2140,34 @@ def loft_rsolid(profiles: List[Wire], ruled: bool = False) -> Solid: try: if len(profiles) < 2: raise ValueError("放样至少需要2个轮廓") - + # 转换为CADQuery线对象 cq_wires = [profile.cq_wire for profile in profiles] - + # 执行放样操作 cq_result = cq.Solid.makeLoft(cq_wires, ruled) result = Solid(cq_result) - + # 合并所有轮廓的标签和元数据 all_tags = set() all_metadata = {} for profile in profiles: all_tags.update(profile._tags) all_metadata.update(profile._metadata) - + result._tags = all_tags result._metadata = all_metadata - + return result except Exception as e: raise ValueError(f"放样操作失败: {e}. 请检查轮廓是否有效。") -def sweep_rsolid(profile: Face, path: Wire, - make_solid: bool = True, - is_frenet: bool = False) -> Union[Solid, Shell]: +def sweep_rsolid( + profile: Face, path: Wire, make_solid: bool = True, is_frenet: bool = False +) -> Union[Solid, Shell]: """沿路径扫掠轮廓创建实体 - + Args: profile (Face): 要扫掠的轮廓面,定义扫掠的横截面形状 path (Wire): 扫掠路径线,定义轮廓沿其移动的路径 @@ -2064,28 +2175,28 @@ def sweep_rsolid(profile: Face, path: Wire, False时创建壳体 is_frenet (bool, optional): 是否使用Frenet框架,默认为False。 True时轮廓沿路径的法向量旋转,False时保持轮廓方向 - + Returns: Union[Solid, Shell]: 扫掠后的实体或壳体,取决于make_solid参数 - + Raises: ValueError: 当轮廓、路径无效或扫掠操作失败时抛出异常 - + Usage: 沿指定路径扫掠二维轮廓创建三维实体或壳体。常用于创建管道、导线、 复杂曲面等。Frenet框架控制轮廓在路径上的旋转行为。 - + Example: # 沿直线扫掠圆形创建圆管 circle = make_circle_rface((0, 0, 0), 0.5) line_path = make_segment_rwire((0, 0, 0), (10, 0, 0)) tube = sweep_rsolid(circle, line_path) - + # 沿螺旋路径扫掠创建螺旋管 square = make_rectangle_rface(0.2, 0.2) helix_path = make_helix_rwire(1.0, 5.0, 2.0) spiral_tube = sweep_rsolid(square, helix_path, is_frenet=True) - + # 沿曲线扫掠创建复杂形状 profile = make_rectangle_rface(1.0, 0.5) curve_points = [(0, 0, 0), (2, 2, 1), (4, 0, 2), (6, -1, 3)] @@ -2094,57 +2205,57 @@ def sweep_rsolid(profile: Face, path: Wire, """ try: # 执行扫掠操作 - cq_result = cq.Solid.sweep(profile.cq_face, path.cq_wire, - makeSolid=make_solid, isFrenet=is_frenet) - + cq_result = cq.Solid.sweep( + profile.cq_face, path.cq_wire, makeSolid=make_solid, isFrenet=is_frenet + ) + if make_solid: result = Solid(cq_result) else: # 如果不是实体,则创建Shell result = Shell(cq_result) - + # 合并轮廓和路径的标签和元数据 result._tags = profile._tags.union(path._tags) result._metadata = {**profile._metadata, **path._metadata} - + return result except Exception as e: raise ValueError(f"扫掠操作失败: {e}. 请检查轮廓和路径是否有效。") -def linear_pattern_rsolidlist(shape: AnyShape, - direction: Tuple[float, float, float], - count: int, - spacing: float) -> List[Solid]: +def linear_pattern_rsolidlist( + shape: AnyShape, direction: Tuple[float, float, float], count: int, spacing: float +) -> List[Solid]: """创建线性阵列 - + Args: shape (AnyShape): 要阵列的几何体,可以是任意类型的几何对象 direction (Tuple[float, float, float]): 阵列方向向量 (x, y, z), 定义阵列的方向,会被标准化处理 count (int): 阵列数量,必须为正整数,包括原始对象 spacing (float): 阵列间距,必须为正数,定义相邻对象间的距离 - + Returns: List[Solid]: 阵列后的几何体列表,包含原始对象和所有复制的对象 - + Raises: ValueError: 当阵列数量小于等于0或间距小于等于0时抛出异常 - + Usage: 沿指定方向创建几何体的线性阵列,生成指定数量的等间距排列对象。 常用于创建重复结构,如齿轮齿、栅栏、螺栓阵列等。 - + Example: # 创建立方体的线性阵列 box = make_box_rsolid(1, 1, 1) boxes = linear_pattern_rsolidlist(box, (2, 0, 0), 5, 2.0) # 创建5个立方体,沿X轴方向间距2.0 - + # 创建圆柱体的对角线阵列 cylinder = make_cylinder_rsolid(0.5, 2.0) cylinders = linear_pattern_rsolidlist(cylinder, (1, 1, 0), 4, 1.5) - + # 创建复杂几何体的阵列 complex_shape = union_rsolid(box, cylinder) array = linear_pattern_rsolidlist(complex_shape, (0, 3, 0), 3, 3.0) @@ -2154,17 +2265,17 @@ def linear_pattern_rsolidlist(shape: AnyShape, raise ValueError("阵列数量必须大于0") if spacing <= 0: raise ValueError("阵列间距必须大于0") - + cs = get_current_cs() global_direction = cs.transform_point(np.array(direction)) - cs.origin direction_vec = Vector(*global_direction).normalized() - + shapes = [] for i in range(count): offset = direction_vec * (spacing * i) translated_shape = translate_shape(shape, (offset.x, offset.y, offset.z)) shapes.append(translated_shape) - + # 创建复合体 if isinstance(shape, Vertex): cq_shapes = [s.cq_vertex for s in shapes] @@ -2180,10 +2291,10 @@ def linear_pattern_rsolidlist(shape: AnyShape, cq_shapes = [s.cq_solid for s in shapes] else: raise ValueError(f"不支持的几何体类型: {type(shape)}") - + cq_compound = cq.Compound.makeCompound(cq_shapes) result = Compound(cq_compound) - + # 复制原始形状的标签和元数据 result._tags = shape._tags.copy() result._metadata = shape._metadata.copy() @@ -2192,20 +2303,22 @@ def linear_pattern_rsolidlist(shape: AnyShape, for i, s in enumerate(result.get_solids()): s.add_tag(f"linear_pattern_{i+1}") rv.append(s) - - return rv - + + return rv + except Exception as e: raise ValueError(f"线性阵列失败: {e}. 请检查参数是否有效。") -def radial_pattern_rsolidlist(shape: AnyShape, - center: Tuple[float, float, float], - axis: Tuple[float, float, float], - count: int, - total_rotation_angle: float) -> List[Solid]: +def radial_pattern_rsolidlist( + shape: AnyShape, + center: Tuple[float, float, float], + axis: Tuple[float, float, float], + count: int, + total_rotation_angle: float, +) -> List[Solid]: """创建径向阵列(圆形阵列) - + Args: shape (AnyShape): 要阵列的几何体,可以是任意类型的几何对象 center (Tuple[float, float, float]): 旋转中心点坐标 (x, y, z) @@ -2213,26 +2326,26 @@ def radial_pattern_rsolidlist(shape: AnyShape, count (int): 阵列数量,必须为正整数,包括原始对象 total_rotation_angle (float): 总旋转角度,单位为度数(0-360), 定义整个阵列的角度范围 - + Returns: List[Solid]: 径向阵列后的几何体列表,包含原始对象和所有旋转的对象 - + Raises: ValueError: 当阵列数量小于等于0或角度无效时抛出异常 - + Usage: 围绕指定轴创建几何体的径向阵列,生成等角度间隔的旋转排列。 常用于创建齿轮、花瓣、螺栓圆形分布等对称结构。 - + Example: # 创建立方体的径向阵列(6个,360度) box = make_box_rsolid(1, 0.5, 0.5, (2, 0, 0)) # 距离中心2单位 radial_boxes = radial_pattern_rsolidlist(box, (0, 0, 0), (0, 0, 1), 6, 360) - + # 创建半圆阵列 cylinder = make_cylinder_rsolid(0.3, 1.0, (1.5, 0, 0)) half_circle = radial_pattern_rsolidlist(cylinder, (0, 0, 0), (0, 0, 1), 4, 180) - + # 围绕Y轴的径向阵列 element = make_sphere_rsolid(0.5, (3, 0, 0)) vertical_array = radial_pattern_rsolidlist(element, (0, 0, 0), (0, 1, 0), 8, 360) @@ -2242,15 +2355,15 @@ def radial_pattern_rsolidlist(shape: AnyShape, raise ValueError("阵列数量必须大于0") if total_rotation_angle <= 0: raise ValueError("角度必须大于0") - + shapes = [] angle_step = total_rotation_angle / count # 修正角度计算,均匀分布 - + for i in range(count): rotation_angle = angle_step * i rotated_shape = rotate_shape(shape, rotation_angle, axis, center) shapes.append(rotated_shape) - + # 创建复合体 if isinstance(shape, Vertex): cq_shapes = [s.cq_vertex for s in shapes] @@ -2266,14 +2379,14 @@ def radial_pattern_rsolidlist(shape: AnyShape, cq_shapes = [s.cq_solid for s in shapes] else: raise ValueError(f"不支持的几何体类型: {type(shape)}") - + cq_compound = cq.Compound.makeCompound(cq_shapes) result = Compound(cq_compound) - + # 复制原始形状的标签和元数据 result._tags = shape._tags.copy() result._metadata = shape._metadata.copy() - + rv = [] for i, s in enumerate(shapes): s.add_tag(f"radial_pattern_{i+1}") @@ -2284,37 +2397,39 @@ def radial_pattern_rsolidlist(shape: AnyShape, raise ValueError(f"径向阵列失败: {e}. 请检查参数是否有效。") -def mirror_shape(shape: AnyShape, - plane_origin: Tuple[float, float, float], - plane_normal: Tuple[float, float, float]) -> AnyShape: +def mirror_shape( + shape: AnyShape, + plane_origin: Tuple[float, float, float], + plane_normal: Tuple[float, float, float], +) -> AnyShape: """镜像几何体 - + Args: shape (AnyShape): 要镜像的几何体,可以是任意类型的几何对象 plane_origin (Tuple[float, float, float]): 镜像平面上的一个点坐标 (x, y, z), 定义镜像平面的位置 plane_normal (Tuple[float, float, float]): 镜像平面的法向量 (x, y, z), 定义镜像平面的方向,会被标准化处理 - + Returns: AnyShape: 镜像后的几何体,类型与输入相同 - + Raises: ValueError: 当几何体或镜像平面参数无效时抛出异常 - + Usage: 将几何体沿指定平面进行镜像复制,创建对称的几何结构。 镜像平面由一个点和法向量定义,几何体在平面另一侧生成对称副本。 - + Example: # 沿YZ平面镜像立方体 box = make_box_rsolid(2, 2, 2, (1, 0, 0)) mirrored_box = mirror_shape(box, (0, 0, 0), (1, 0, 0)) - + # 沿XY平面镜像圆柱体 cylinder = make_cylinder_rsolid(1.0, 3.0, (0, 0, 1)) mirrored_cyl = mirror_shape(cylinder, (0, 0, 0), (0, 0, 1)) - + # 沿任意平面镜像 sphere = make_sphere_rsolid(1.5, (2, 2, 0)) mirrored_sphere = mirror_shape(sphere, (1, 1, 0), (1, 1, 0)) @@ -2323,63 +2438,49 @@ def mirror_shape(shape: AnyShape, cs = get_current_cs() global_origin = cs.transform_point(np.array(plane_origin)) global_normal = cs.transform_vector(np.array(plane_normal)) - + # 确保法向量不是零向量 if np.linalg.norm(global_normal) < 1e-10: raise ValueError("镜像平面法向量不能是零向量") - - # 坐标系转换:SimpleCAD (X前,Y右,Z上) -> CadQuery (X右,Y上,Z前) - cq_origin = Vector(global_origin[1], global_origin[2], global_origin[0]) - cq_normal = Vector(global_normal[1], global_normal[2], global_normal[0]) - - # 创建镜像平面 - mirror_plane = Plane(origin=cq_origin, normal=cq_normal) - - # 使用Workplane进行镜像操作 + + cq_origin = Vector(global_origin[0], global_origin[1], global_origin[2]) + cq_normal = Vector(global_normal[0], global_normal[1], global_normal[2]) + if isinstance(shape, Solid): # 对于Solid,创建一个包含该Solid的Workplane wp = cq.Workplane().add(shape.cq_solid) - - # 根据法向量确定镜像平面 - abs_normal = np.abs(cq_normal.toTuple()) - max_idx = np.argmax(abs_normal) - - if max_idx == 0: # X方向 - mirror_plane_str = "YZ" - elif max_idx == 1: # Y方向 - mirror_plane_str = "XZ" - else: # Z方向 - mirror_plane_str = "XY" - + # 执行镜像 - mirrored_wp = wp.mirror(mirror_plane_str, basePointVector=cq_origin.toTuple()) - + mirrored_wp = wp.mirror(cq_normal, basePointVector=cq_origin.toTuple()) + # 获取镜像后的Solid mirrored_solid = mirrored_wp.val() new_shape = Solid(mirrored_solid) - + else: # 对于其他类型的几何体,暂时不支持 raise ValueError(f"暂不支持镜像 {type(shape).__name__} 类型的几何体") - + # 复制标签和元数据 new_shape._tags = shape._tags.copy() new_shape._metadata = shape._metadata.copy() new_shape.add_tag("mirrored") - + return new_shape except Exception as e: raise ValueError(f"镜像操作失败: {e}. 请检查几何体和镜像平面是否有效。") -def helical_sweep_rsolid(profile: Wire, - pitch: float, - height: float, - radius: float, - center: Tuple[float, float, float] = (0, 0, 0), - dir: Tuple[float, float, float] = (0, 0, 1)) -> Solid: +def helical_sweep_rsolid( + profile: Wire, + pitch: float, + height: float, + radius: float, + center: Tuple[float, float, float] = (0, 0, 0), + dir: Tuple[float, float, float] = (0, 0, 1), +) -> Solid: """沿螺旋路径扫掠轮廓创建实体 - + Args: profile (Wire): 要扫掠的轮廓线,必须是封闭的线轮廓 pitch (float): 螺距,每转一圈在轴向上的距离,必须为正数 @@ -2389,30 +2490,30 @@ def helical_sweep_rsolid(profile: Wire, 默认为 (0, 0, 0) dir (Tuple[float, float, float], optional): 螺旋轴方向向量 (x, y, z), 默认为 (0, 0, 1) 表示沿Z轴方向 - + Returns: Solid: 螺旋扫掠后的实体对象 - + Raises: ValueError: 当轮廓不封闭、螺距/高度/半径无效或扫掠失败时抛出异常 - + Usage: 沿螺旋路径扫掠二维轮廓创建三维实体,常用于创建螺纹、弹簧、 螺旋管道等具有螺旋特征的几何体。轮廓必须是封闭的。 - + 函数会自动矫正profile的朝向和位置: - 确保profile的法向量朝向X轴正方向或负方向 - 将profile移动到距离旋转中心指定半径的位置 - + Example: # 创建螺旋弹簧 circle_profile = make_circle_rwire((0, 0, 0), 0.2) spring = helical_sweep_rsolid(circle_profile, 1.0, 10.0, 2.0) - + # 创建方形截面的螺旋管 square_profile = make_rectangle_rwire(0.5, 0.5) square_helix = helical_sweep_rsolid(square_profile, 2.0, 8.0, 1.5) - + # 创建紧密螺旋结构 small_circle = make_circle_rwire((0, 0, 0), 0.1) tight_helix = helical_sweep_rsolid(small_circle, 0.5, 5.0, 1.0) @@ -2424,46 +2525,46 @@ def helical_sweep_rsolid(profile: Wire, raise ValueError("高度必须大于0") if radius <= 0: raise ValueError("半径必须大于0") - + cs = get_current_cs() global_center = cs.transform_point(np.array(center)) global_dir = cs.transform_point(np.array(dir)) - cs.origin - + center_vec = Vector(*global_center) dir_vec = Vector(*global_dir).normalized() - + # 复制profile以避免修改原始轮廓 corrected_profile = Wire(profile.cq_wire.copy()) - + # 将Wire转换为Face用于扫掠 try: profile_face = cq.Face.makeFromWires(corrected_profile.cq_wire) - except: + except Exception as _: raise ValueError("螺旋扫掠轮廓必须是闭合的") - + # 1. 矫正profile的法向量:确保法向量朝向X轴正方向 # 获取profile的法向量(在面的中心点) try: # 获取face的法向量,normalAt返回(Vector, Vector),取第一个 profile_normal = profile_face.normalAt(0.5, 0.5)[0] - except: + except Exception as _: try: profile_normal = profile_face.normalAt(0, 0)[0] - except: + except Exception as _: # 最后的fallback,假设法向量为Z轴方向 profile_normal = Vector(0, 0, 1) - + # 定义目标法向量:Y轴正方向 target_normal = Vector(0, 1, 0) - + # 检查当前法向量与目标法向量的夹角 dot_product = profile_normal.dot(target_normal) - + # 如果法向量不朝向X轴正方向,需要旋转 if abs(dot_product) < 0.99: # 容差,允许约8度的偏差 # 计算旋转轴(叉积) rotation_axis = profile_normal.cross(target_normal) - + # 如果法向量与X轴相反(dot_product < 0),需要180度旋转 if dot_product < -0.99: # 使用Y轴或Z轴作为旋转轴 @@ -2477,55 +2578,59 @@ def helical_sweep_rsolid(profile: Wire, # 如果叉积为零向量,说明已经平行,不需要旋转 rotation_angle = 0 rotation_axis = Vector(0, 0, 1) - + # 如果需要旋转 if rotation_angle > 1e-6: # 获取profile的中心点作为旋转中心 profile_center = profile_face.Center() - rotation_center = Vector(profile_center.x, profile_center.y, profile_center.z) - + rotation_center = Vector( + profile_center.x, profile_center.y, profile_center.z + ) + # 应用旋转 - profile_face = profile_face.rotate(rotation_center, rotation_axis, math.degrees(rotation_angle)) - + profile_face = profile_face.rotate( + rotation_center, rotation_axis, math.degrees(rotation_angle) + ) + # 2. 矫正profile的位置:将profile移动到指定半径的位置 # 获取旋转后的profile中心点 profile_center = profile_face.Center() - + # 计算当前profile中心到旋转中心的距离 current_center = Vector(profile_center.x, profile_center.y, profile_center.z) spiral_center = center_vec - + # 计算在垂直于旋转轴的平面上的投影 to_profile = current_center - spiral_center projection_on_axis = to_profile.dot(dir_vec) * dir_vec radial_vector = to_profile - projection_on_axis - + # 如果radial_vector太小,默认使用X轴方向 if radial_vector.Length < 1e-6: radial_vector = Vector(1, 0, 0) - + # 归一化径向向量并缩放到目标半径 radial_direction = radial_vector.normalized() target_position = spiral_center + radial_direction * radius + projection_on_axis - + # 计算平移向量 translation = target_position - current_center - + # 应用平移 profile_face = profile_face.translate(translation) - + # 创建螺旋路径 helix = cq.Wire.makeHelix(pitch, height, radius, center_vec, dir_vec) - + # 沿螺旋路径扫掠 cq_result = cq.Solid.sweep(profile_face, helix, makeSolid=True, isFrenet=True) result = Solid(cq_result) - + # 复制轮廓的标签和元数据 result._tags = profile._tags.copy() result._metadata = profile._metadata.copy() result.add_tag("helical_sweep") - + return result except Exception as e: raise ValueError(f"螺旋扫掠失败: {e}. 请检查参数是否有效。") diff --git a/test/test_all_features.py b/test/test_all_features.py index 1b71c1b1..614c9ca7 100644 --- a/test/test_all_features.py +++ b/test/test_all_features.py @@ -11,186 +11,190 @@ import tempfile import shutil # 添加项目路径到Python路径 -sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src')) +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src")) import simplecadapi as scad class TestBasicShapes(unittest.TestCase): """测试基础几何体创建""" - + def test_create_point(self): """测试点创建""" point = scad.make_point_rvertex(1, 2, 3) # 暂时跳过坐标检查,因为点类型可能不同 self.assertIsInstance(point, scad.Vertex) - + def test_create_line(self): """测试线段创建""" line = scad.make_line_redge((0, 0, 0), (1, 0, 0)) self.assertIsInstance(line, scad.Edge) - + def test_create_circle_edge(self): """测试圆边创建""" circle_edge = scad.make_circle_redge((0, 0, 0), 1.0) self.assertIsInstance(circle_edge, scad.Edge) - + def test_create_circle_wire(self): """测试圆线创建""" circle_wire = scad.make_circle_rwire((0, 0, 0), 1.0) self.assertIsInstance(circle_wire, scad.Wire) - + def test_create_circle_face(self): """测试圆面创建""" circle_face = scad.make_circle_rface((0, 0, 0), 1.0) area = circle_face.get_area() self.assertAlmostEqual(area, np.pi, places=6) - + def test_create_rectangle_wire(self): """测试矩形线创建""" rect_wire = scad.make_rectangle_rwire(2.0, 1.0) self.assertIsInstance(rect_wire, scad.Wire) - + def test_create_rectangle_face(self): """测试矩形面创建""" rect_face = scad.make_rectangle_rface(2.0, 1.0) area = rect_face.get_area() self.assertAlmostEqual(area, 2.0, places=6) - + def test_create_box(self): """测试立方体创建""" box = scad.make_box_rsolid(1.0, 1.0, 1.0) volume = box.get_volume() self.assertAlmostEqual(volume, 1.0, places=6) - + def test_create_cylinder(self): """测试圆柱体创建""" cylinder = scad.make_cylinder_rsolid(1.0, 2.0) volume = cylinder.get_volume() expected_volume = np.pi * 1.0**2 * 2.0 self.assertAlmostEqual(volume, expected_volume, places=6) - + def test_create_sphere(self): """测试球体创建""" sphere = scad.make_sphere_rsolid(1.0) volume = sphere.get_volume() - expected_volume = (4/3) * np.pi * 1.0**3 + expected_volume = (4 / 3) * np.pi * 1.0**3 self.assertAlmostEqual(volume, expected_volume, places=5) - + def test_create_arc(self): """测试三点圆弧创建""" arc = scad.make_three_point_arc_redge((0, 0, 0), (1, 1, 0), (2, 0, 0)) self.assertIsInstance(arc, scad.Edge) - + def test_create_spline(self): """测试样条曲线创建""" points = [(0.0, 0.0, 0.0), (1.0, 1.0, 0.0), (2.0, 0.0, 0.0)] spline = scad.make_spline_redge(points) self.assertIsInstance(spline, scad.Edge) - + def test_create_segment_edge(self): """测试线段边创建""" segment = scad.make_segment_redge((0, 0, 0), (1, 0, 0)) self.assertIsInstance(segment, scad.Edge) - + def test_create_segment_wire(self): """测试线段线创建""" segment_wire = scad.make_segment_rwire((0, 0, 0), (1, 0, 0)) self.assertIsInstance(segment_wire, scad.Wire) - + def test_create_angle_arc_edge(self): """测试角度圆弧边创建""" - arc = scad.make_angle_arc_redge((0, 0, 0), 1.0, 0, np.pi/2) + arc = scad.make_angle_arc_redge((0, 0, 0), 1.0, 0, np.pi / 2) self.assertIsInstance(arc, scad.Edge) - + def test_create_angle_arc_wire(self): """测试角度圆弧线创建""" - arc_wire = scad.make_angle_arc_rwire((0, 0, 0), 1.0, 0, np.pi/2) + arc_wire = scad.make_angle_arc_rwire((0, 0, 0), 1.0, 0, np.pi / 2) self.assertIsInstance(arc_wire, scad.Wire) - + def test_create_three_point_arc_wire(self): """测试三点圆弧线创建""" arc_wire = scad.make_three_point_arc_rwire((0, 0, 0), (1, 1, 0), (2, 0, 0)) self.assertIsInstance(arc_wire, scad.Wire) - + def test_create_spline_wire(self): """测试样条曲线线创建""" points = [(0.0, 0.0, 0.0), (1.0, 1.0, 0.0), (2.0, 0.0, 0.0)] spline_wire = scad.make_spline_rwire(points) self.assertIsInstance(spline_wire, scad.Wire) - + def test_create_polyline_wire(self): """测试多段线线创建""" points = [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 1.0, 0.0), (0.0, 1.0, 0.0)] polyline_wire = scad.make_polyline_rwire(points) self.assertIsInstance(polyline_wire, scad.Wire) - + # 测试闭合多段线 closed_polyline = scad.make_polyline_rwire(points, closed=True) self.assertIsInstance(closed_polyline, scad.Wire) self.assertTrue(closed_polyline.is_closed()) - + def test_create_helix_edge(self): """测试螺旋线边创建""" helix = scad.make_helix_redge(pitch=1.0, height=3.0, radius=0.5) self.assertIsInstance(helix, scad.Edge) - + def test_create_helix_wire(self): """测试螺旋线线创建""" helix_wire = scad.make_helix_rwire(pitch=1.0, height=3.0, radius=0.5) self.assertIsInstance(helix_wire, scad.Wire) - + def test_new_function_error_handling(self): """测试新函数的错误处理""" # 测试无效参数 with self.assertRaises(ValueError): - scad.make_angle_arc_redge((0, 0, 0), -1.0, 0, np.pi/2) # 负半径 - + scad.make_angle_arc_redge((0, 0, 0), -1.0, 0, np.pi / 2) # 负半径 + with self.assertRaises(ValueError): scad.make_angle_arc_redge((0, 0, 0), 1.0, 0, 0) # 相同角度 - + with self.assertRaises(ValueError): scad.make_helix_redge(-1.0, 3.0, 0.5) # 负螺距 - + with self.assertRaises(ValueError): scad.make_helix_redge(1.0, -3.0, 0.5) # 负高度 - + with self.assertRaises(ValueError): scad.make_helix_redge(1.0, 3.0, -0.5) # 负半径 - + with self.assertRaises(ValueError): scad.make_spline_redge([(0, 0, 0)]) # 点数不足 - + with self.assertRaises(ValueError): scad.make_polyline_rwire([(0, 0, 0)]) # 点数不足 class TestTransformations(unittest.TestCase): """测试变换操作""" - + def setUp(self): self.box = scad.make_box_rsolid(1.0, 1.0, 1.0) - + def test_translate(self): """测试平移操作""" translated = scad.translate_shape(self.box, (1, 0, 0)) self.assertIsInstance(translated, scad.Solid) # 体积应保持不变 if isinstance(translated, scad.Solid): - self.assertAlmostEqual(translated.get_volume(), self.box.get_volume(), places=6) - + self.assertAlmostEqual( + translated.get_volume(), self.box.get_volume(), places=6 + ) + def test_rotate(self): """测试旋转操作""" - rotated = scad.rotate_shape(self.box, np.pi/4, (0, 0, 1)) + rotated = scad.rotate_shape(self.box, np.pi / 4, (0, 0, 1)) self.assertIsInstance(rotated, scad.Solid) # 体积应保持不变 if isinstance(rotated, scad.Solid): - self.assertAlmostEqual(rotated.get_volume(), self.box.get_volume(), places=6) + self.assertAlmostEqual( + rotated.get_volume(), self.box.get_volume(), places=6 + ) class Test3DOperations(unittest.TestCase): """测试3D操作""" - + def test_extrude(self): """测试拉伸操作""" rect = scad.make_rectangle_rface(2.0, 1.0) @@ -199,22 +203,22 @@ class Test3DOperations(unittest.TestCase): # 体积应该是面积乘以高度 expected_volume = rect.get_area() * 2.0 self.assertAlmostEqual(extruded.get_volume(), expected_volume, places=6) - + def test_revolve(self): """测试旋转成型操作""" rect = scad.make_rectangle_rface(1.0, 2.0, center=(2, 0, 0)) - revolved = scad.revolve_rsolid(rect, (0, 0, 1), np.pi, (0, 0, 0)) + revolved = scad.revolve_rsolid(rect, (0, 1, 0), 180, (0, 0, 0)) self.assertIsInstance(revolved, scad.Solid) self.assertGreater(revolved.get_volume(), 0) class TestBooleanOperations(unittest.TestCase): """测试布尔运算""" - + def setUp(self): self.box1 = scad.make_box_rsolid(2.0, 2.0, 2.0) self.box2 = scad.make_box_rsolid(1.0, 1.0, 3.0, center=(0.5, 0.5, 0)) - + def test_union(self): """测试并集运算""" result = scad.union_rsolid(self.box1, self.box2) @@ -222,14 +226,14 @@ class TestBooleanOperations(unittest.TestCase): # 并集体积应该大于任一单独体积 self.assertGreater(result.get_volume(), self.box1.get_volume()) self.assertGreater(result.get_volume(), self.box2.get_volume()) - + def test_cut(self): """测试差集运算""" result = scad.cut_rsolid(self.box1, self.box2) self.assertIsInstance(result, scad.Solid) # 差集体积应该小于原体积 self.assertLess(result.get_volume(), self.box1.get_volume()) - + def test_intersect(self): """测试交集运算""" result = scad.intersect_rsolid(self.box1, self.box2) @@ -241,18 +245,18 @@ class TestBooleanOperations(unittest.TestCase): class TestAdvancedFeatures(unittest.TestCase): """测试高级特征操作""" - + def setUp(self): self.box = scad.make_box_rsolid(2.0, 2.0, 2.0) self.box.auto_tag_faces("box") - + def test_fillet(self): """测试圆角操作""" # 获取所有边 edges = self.box.get_edges() # 选择前4条边进行圆角 selected_edges = edges[:4] - + try: filleted = scad.fillet_rsolid(self.box, selected_edges, 0.2) self.assertIsInstance(filleted, scad.Solid) @@ -260,14 +264,14 @@ class TestAdvancedFeatures(unittest.TestCase): self.assertLess(filleted.get_volume(), self.box.get_volume()) except Exception as e: self.skipTest(f"Fillet operation not fully implemented: {e}") - + def test_chamfer(self): """测试倒角操作""" # 获取所有边 edges = self.box.get_edges() # 选择前4条边进行倒角 selected_edges = edges[:4] - + try: chamfered = scad.chamfer_rsolid(self.box, selected_edges, 0.2) self.assertIsInstance(chamfered, scad.Solid) @@ -275,13 +279,13 @@ class TestAdvancedFeatures(unittest.TestCase): self.assertLess(chamfered.get_volume(), self.box.get_volume()) except Exception as e: self.skipTest(f"Chamfer operation not fully implemented: {e}") - + def test_shell(self): """测试抽壳操作""" # 获取顶面 faces = self.box.get_faces() top_faces = [face for face in faces if face.has_tag("top")] - + try: shelled = scad.shell_rsolid(self.box, top_faces, 0.2) self.assertIsInstance(shelled, scad.Solid) @@ -289,69 +293,68 @@ class TestAdvancedFeatures(unittest.TestCase): self.assertLess(shelled.get_volume(), self.box.get_volume()) except Exception as e: self.skipTest(f"Shell operation not fully implemented: {e}") - + def test_loft(self): """测试放样操作""" # 创建两个不同大小的矩形轮廓 rect1 = scad.create_rectangle_wire(2.0, 2.0, center=(0, 0, 0)) rect2 = scad.create_rectangle_wire(1.0, 1.0, center=(0, 0, 2)) - + try: lofted = scad.loft_rsolid([rect1, rect2]) self.assertIsInstance(lofted, scad.Solid) self.assertGreater(lofted.get_volume(), 0) except Exception as e: self.skipTest(f"Loft operation not fully implemented: {e}") - + def test_linear_pattern(self): """测试线性阵列""" small_box = scad.create_box(0.5, 0.5, 0.5) - - try: - pattern = scad.linear_pattern_rsolidlist(small_box, (1, 0, 0), 5, 1.0) - self.assertIsInstance(pattern, scad.Compound) - # 检查复合体包含5个实体 - solids = pattern - self.assertEqual(len(solids), 5) - except Exception as e: - self.skipTest(f"Linear pattern operation not fully implemented: {e}") - + + pattern = scad.linear_pattern_rsolidlist(small_box, (1, 0, 0), 5, 1.0) + self.assertIsInstance(pattern, list) + # 检查复合体包含5个实体 + solids = pattern + self.assertEqual(len(solids), 5) + + self.assertIsInstance(solids[0], scad.Solid) + def test_radial_pattern(self): """测试径向阵列""" small_box = scad.create_box(0.2, 0.2, 1.0, center=(2, 0, 0)) - - try: - pattern = scad.radial_pattern_rsolidlist(small_box, (0, 0, 0), (0, 0, 1), 6, 2*np.pi) - self.assertIsInstance(pattern, scad.Compound) - # 检查复合体包含6个实体 - solids = pattern - self.assertEqual(len(solids), 6) - except Exception as e: - self.skipTest(f"Radial pattern operation not fully implemented: {e}") - + + pattern = scad.radial_pattern_rsolidlist( + small_box, (0, 0, 0), (0, 0, 1), 6, 2 * np.pi + ) + self.assertIsInstance(pattern, list) + # 检查复合体包含6个实体 + solids = pattern + self.assertEqual(len(solids), 6) + + self.assertIsInstance(solids[0], scad.Solid) + def test_mirror(self): """测试镜像操作""" - try: - mirrored = scad.mirror_shape(self.box, (0, 0, 0), (1, 0, 0)) - self.assertIsInstance(mirrored, scad.Solid) - # 镜像后体积应该保持不变 - if isinstance(mirrored, scad.Solid): - self.assertAlmostEqual(mirrored.get_volume(), self.box.get_volume(), places=6) - except Exception as e: - self.skipTest(f"Mirror operation not fully implemented: {e}") + mirrored = scad.mirror_shape(self.box, (0, 0, 0), (1, 0, 0)) + self.assertIsInstance(mirrored, scad.Solid) + # 镜像后体积应该保持不变 + if isinstance(mirrored, scad.Solid): + self.assertAlmostEqual( + mirrored.get_volume(), self.box.get_volume(), places=6 + ) class TestTagging(unittest.TestCase): """测试标签系统""" - + def setUp(self): self.box = scad.create_box(1.0, 1.0, 1.0) - + def test_set_tag(self): """测试设置标签""" scad.set_tag(self.box, "test_box") self.assertTrue(self.box.has_tag("test_box")) - + def test_multiple_tags(self): """测试多个标签""" scad.set_tag(self.box, "tag1") @@ -359,32 +362,32 @@ class TestTagging(unittest.TestCase): tags = self.box.get_tags() self.assertIn("tag1", tags) self.assertIn("tag2", tags) - + def test_auto_tag_faces_box(self): """测试立方体自动标记面""" self.box.auto_tag_faces("box") faces = self.box.get_faces() - + # 检查是否有标记的面 tagged_faces = [face for face in faces if len(face.get_tags()) > 0] self.assertGreater(len(tagged_faces), 0) - + def test_auto_tag_faces_cylinder(self): """测试圆柱体自动标记面""" cylinder = scad.create_cylinder(1.0, 2.0) cylinder.auto_tag_faces("cylinder") faces = cylinder.get_faces() - + # 检查是否有标记的面 tagged_faces = [face for face in faces if len(face.get_tags()) > 0] self.assertGreater(len(tagged_faces), 0) - + def test_auto_tag_faces_sphere(self): """测试球体自动标记面""" sphere = scad.create_sphere(1.0) sphere.auto_tag_faces("sphere") faces = sphere.get_faces() - + # 球体应该只有一个面,且被标记为surface self.assertEqual(len(faces), 1) self.assertTrue(faces[0].has_tag("surface")) @@ -392,20 +395,20 @@ class TestTagging(unittest.TestCase): class TestCoordinateSystem(unittest.TestCase): """测试坐标系功能""" - + def test_world_coordinate_system(self): """测试世界坐标系""" point = scad.make_point_rvertex(1, 0, 0) # 暂时跳过坐标检查 self.assertIsInstance(point, scad.Vertex) - + def test_workplane_translation(self): """测试工作平面平移""" with scad.SimpleWorkplane(origin=(1, 1, 1)): point = scad.make_point_rvertex(1, 0, 0) # 暂时跳过坐标检查 self.assertIsInstance(point, scad.Vertex) - + def test_nested_workplane(self): """测试嵌套工作平面""" with scad.SimpleWorkplane(origin=(1, 0, 0)): @@ -417,14 +420,14 @@ class TestCoordinateSystem(unittest.TestCase): class TestExport(unittest.TestCase): """测试导出功能""" - + def setUp(self): self.temp_dir = tempfile.mkdtemp() self.box = scad.make_box_rsolid(1.0, 1.0, 1.0) - + def tearDown(self): shutil.rmtree(self.temp_dir) - + def test_export_stl(self): """测试STL导出""" stl_path = os.path.join(self.temp_dir, "test.stl") @@ -436,7 +439,7 @@ class TestExport(unittest.TestCase): self.assertGreater(os.path.getsize(stl_path), 0) except Exception as e: self.skipTest(f"STL export not fully implemented: {e}") - + def test_export_step(self): """测试STEP导出""" step_path = os.path.join(self.temp_dir, "test.step") @@ -448,13 +451,13 @@ class TestExport(unittest.TestCase): self.assertGreater(os.path.getsize(step_path), 0) except Exception as e: self.skipTest(f"STEP export not fully implemented: {e}") - + def test_export_multiple_shapes(self): """测试导出多个几何体""" box1 = scad.make_box_rsolid(1.0, 1.0, 1.0) box2 = scad.make_box_rsolid(0.5, 0.5, 0.5, center=(2, 0, 0)) stl_path = os.path.join(self.temp_dir, "multiple.stl") - + try: scad.export_stl([box1, box2], stl_path) # 检查文件是否创建 @@ -467,60 +470,60 @@ class TestExport(unittest.TestCase): class TestComplexExamples(unittest.TestCase): """测试复杂示例""" - + def test_create_bracket(self): """测试创建支架示例""" # 创建主体 base = scad.make_box_rsolid(10, 5, 2) - + # 创建孔 hole1 = scad.make_cylinder_rsolid(1, 3, center=(2, 0, 0)) hole2 = scad.make_cylinder_rsolid(1, 3, center=(8, 0, 0)) - + # 组合 bracket = scad.cut_rsolid(base, hole1) bracket = scad.cut_rsolid(bracket, hole2) - + # 添加标签 scad.set_tag(bracket, "bracket") - + # 验证 self.assertIsInstance(bracket, scad.Solid) self.assertTrue(bracket.has_tag("bracket")) self.assertLess(bracket.get_volume(), base.get_volume()) - + def test_create_gear_like_shape(self): """测试创建类似齿轮的形状""" # 创建基础圆盘 base_circle = scad.make_circle_rface((0, 0, 0), 5) gear_base = scad.extrude_rsolid(base_circle, (0, 0, 1), 1) - + # 创建中心孔 center_hole = scad.make_cylinder_rsolid(1, 1.5, center=(0, 0, 0.5)) gear_base = scad.cut_rsolid(gear_base, center_hole) - + # 创建齿(简化版本) tooth_profile = scad.make_rectangle_rface(0.5, 0.3, center=(4.5, 0, 0)) tooth = scad.extrude_rsolid(tooth_profile, (0, 0, 1), 1.2) - + # 合并一个齿到基础上 gear = scad.union_rsolid(gear_base, tooth) - + # 验证 self.assertIsInstance(gear, scad.Solid) self.assertGreater(gear.get_volume(), gear_base.get_volume()) - + def test_complex_boolean_operations(self): """测试复杂布尔运算""" # 创建三个重叠的立方体 box1 = scad.make_box_rsolid(2, 2, 2, center=(0, 0, 0)) box2 = scad.make_box_rsolid(2, 2, 2, center=(1, 0, 0)) box3 = scad.make_box_rsolid(2, 2, 2, center=(0, 1, 0)) - + # 复合布尔运算:(box1 ∪ box2) ∩ box3 union_result = scad.union_rsolid(box1, box2) final_result = scad.intersect_rsolid(union_result, box3) - + # 验证 self.assertIsInstance(final_result, scad.Solid) self.assertGreater(final_result.get_volume(), 0) @@ -529,27 +532,27 @@ class TestComplexExamples(unittest.TestCase): class TestErrorHandling(unittest.TestCase): """测试错误处理""" - + def test_invalid_dimensions(self): """测试无效尺寸""" with self.assertRaises(ValueError): scad.make_box_rsolid(-1, 1, 1) - + with self.assertRaises(ValueError): scad.make_cylinder_rsolid(-1, 1) - + with self.assertRaises(ValueError): scad.make_sphere_rsolid(-1) - + def test_invalid_coordinates(self): """测试无效坐标""" # 这些不应该抛出异常,但结果应该是有效的 try: - point = scad.make_point_rvertex(float('inf'), 0, 0) + _ = scad.make_point_rvertex(float("inf"), 0, 0) # 只要不抛出异常就算通过 - except: + except Exception as _: pass - + def test_empty_profile_loft(self): """测试空轮廓放样""" try: @@ -561,20 +564,21 @@ class TestErrorHandling(unittest.TestCase): class TestNewFunctionIntegration(unittest.TestCase): """测试新函数的集成应用""" - + def test_spline_with_tangents(self): """测试带切线的样条曲线""" points = [(0.0, 0.0, 0.0), (1.0, 1.0, 0.0), (2.0, 0.0, 0.0)] tangents = [(1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (1.0, 0.0, 0.0)] - + # 注意:目前CADQuery的makeSpline不支持tangents,但函数应该能处理 spline = scad.make_spline_redge(points, tangents) self.assertIsInstance(spline, scad.Edge) - + def test_complex_polyline_shapes(self): """测试复杂多段线形状""" # 创建一个复杂的星形多段线 import math + star_points = [] for i in range(10): angle = i * 2 * math.pi / 10 @@ -585,64 +589,65 @@ class TestNewFunctionIntegration(unittest.TestCase): x = radius * math.cos(angle) y = radius * math.sin(angle) star_points.append((x, y, 0.0)) - + star_wire = scad.make_polyline_rwire(star_points, closed=True) self.assertIsInstance(star_wire, scad.Wire) self.assertTrue(star_wire.is_closed()) - + def test_helix_with_different_parameters(self): """测试不同参数的螺旋线""" # 测试不同的螺旋参数 helix1 = scad.make_helix_rwire(0.5, 2.0, 0.3) # 密螺旋 helix2 = scad.make_helix_rwire(2.0, 4.0, 1.0) # 疏螺旋 helix3 = scad.make_helix_rwire(1.0, 3.0, 0.5, center=(1, 1, 0)) # 偏心螺旋 - + self.assertIsInstance(helix1, scad.Wire) self.assertIsInstance(helix2, scad.Wire) self.assertIsInstance(helix3, scad.Wire) - + def test_angle_arc_various_angles(self): """测试不同角度的圆弧""" # 90度圆弧 - arc90 = scad.make_angle_arc_rwire((0, 0, 0), 1.0, 0, np.pi/2) + arc90 = scad.make_angle_arc_rwire((0, 0, 0), 1.0, 0, np.pi / 2) self.assertIsInstance(arc90, scad.Wire) - + # 180度圆弧 arc180 = scad.make_angle_arc_rwire((0, 0, 0), 1.0, 0, np.pi) self.assertIsInstance(arc180, scad.Wire) - + # 270度圆弧 - arc270 = scad.make_angle_arc_rwire((0, 0, 0), 1.0, 0, 3*np.pi/2) + arc270 = scad.make_angle_arc_rwire((0, 0, 0), 1.0, 0, 3 * np.pi / 2) self.assertIsInstance(arc270, scad.Wire) - + def test_new_functions_with_extrusion(self): """测试新函数与拉伸的结合""" # 创建一个复杂轮廓并拉伸 points = [(0.0, 0.0, 0.0), (2.0, 0.0, 0.0), (2.0, 1.0, 0.0), (0.0, 1.0, 0.0)] rect_wire = scad.make_polyline_rwire(points, closed=True) - + try: # 将Wire转换为Face并拉伸 import cadquery as cq + rect_face = scad.Face(cq.Face.makeFromWires(rect_wire.cq_wire)) extruded = scad.extrude_rsolid(rect_face, (0, 0, 1), 1.0) self.assertIsInstance(extruded, scad.Solid) self.assertAlmostEqual(extruded.get_volume(), 2.0, places=6) except Exception as e: self.skipTest(f"Extrusion integration not fully working: {e}") - + def test_alias_functions(self): """测试别名函数""" # 测试一些主要的别名函数 segment = scad.create_segment((0, 0, 0), (1, 0, 0)) self.assertIsInstance(segment, scad.Edge) - + arc = scad.create_arc((0, 0, 0), (1, 1, 0), (2, 0, 0)) self.assertIsInstance(arc, scad.Edge) - + spline = scad.create_spline([(0, 0, 0), (1, 1, 0), (2, 0, 0)]) self.assertIsInstance(spline, scad.Edge) - + try: helix = scad.create_helix(1.0, 3.0, 0.5) self.assertIsInstance(helix, scad.Edge) @@ -655,10 +660,10 @@ def run_comprehensive_tests(): """运行全面测试""" print("SimpleCAD API 全面单元测试") print("=" * 60) - + # 创建测试套件 test_suite = unittest.TestSuite() - + # 添加所有测试类 test_classes = [ TestBasicShapes, @@ -671,42 +676,44 @@ def run_comprehensive_tests(): TestCoordinateSystem, TestExport, TestComplexExamples, - TestErrorHandling + TestErrorHandling, ] - + for test_class in test_classes: tests = unittest.TestLoader().loadTestsFromTestCase(test_class) test_suite.addTests(tests) - + # 运行测试 runner = unittest.TextTestRunner(verbosity=2) result = runner.run(test_suite) - + # 测试结果统计 print("\n" + "=" * 60) print(f"测试总数: {result.testsRun}") - print(f"成功: {result.testsRun - len(result.failures) - len(result.errors) - len(result.skipped)}") + print( + f"成功: {result.testsRun - len(result.failures) - len(result.errors) - len(result.skipped)}" + ) print(f"失败: {len(result.failures)}") print(f"错误: {len(result.errors)}") print(f"跳过: {len(result.skipped)}") - + if result.failures: print("\n失败的测试:") for test, traceback in result.failures: print(f"- {test}: {traceback.split('AssertionError:')[-1].strip()}") - + if result.errors: print("\n错误的测试:") for test, traceback in result.errors: print(f"- {test}: {traceback.split('Exception:')[-1].strip()}") - + if result.skipped: print("\n跳过的测试:") for test, reason in result.skipped: print(f"- {test}: {reason}") - + print("\n" + "=" * 60) - + # 返回是否所有测试都通过 return len(result.failures) == 0 and len(result.errors) == 0 @@ -714,13 +721,13 @@ def run_comprehensive_tests(): if __name__ == "__main__": # 确保输出目录存在 os.makedirs("output", exist_ok=True) - + # 运行测试 success = run_comprehensive_tests() - + if success: print("所有测试通过!SimpleCAD API 功能正常。") else: print("部分测试失败。请检查上述错误信息。") - + sys.exit(0 if success else 1)