实现声明式装配约束并精简 sandbox 示例
This commit is contained in:
+17
-1
@@ -1,6 +1,6 @@
|
||||
# SimpleCAD API 文档索引
|
||||
|
||||
本文档包含了 SimpleCAD API (来自 `operations.py` 和 `evolve.py`) 的所有函数说明。
|
||||
本文档包含了 SimpleCAD API (来自 `operations.py`、`evolve.py`、`constraints.py`) 的所有函数说明。
|
||||
|
||||
## 基础图形创建
|
||||
|
||||
@@ -72,6 +72,22 @@
|
||||
- [make_naca_propeller_blade_rsolid](make_naca_propeller_blade_rsolid.md) *(来自 evolve.py)*
|
||||
- [make_threaded_rod_rsolid](make_threaded_rod_rsolid.md) *(来自 evolve.py)*
|
||||
|
||||
## 声明式装配约束
|
||||
|
||||
- [add_part_rassembly](add_part_rassembly.md) *(来自 constraints.py)*
|
||||
- [clear_constraints_rassembly](clear_constraints_rassembly.md) *(来自 constraints.py)*
|
||||
- [clone_assembly_rassembly](clone_assembly_rassembly.md) *(来自 constraints.py)*
|
||||
- [constrain_coincident_rassembly](constrain_coincident_rassembly.md) *(来自 constraints.py)*
|
||||
- [constrain_concentric_rassembly](constrain_concentric_rassembly.md) *(来自 constraints.py)*
|
||||
- [constrain_distance_rassembly](constrain_distance_rassembly.md) *(来自 constraints.py)*
|
||||
- [constrain_offset_rassembly](constrain_offset_rassembly.md) *(来自 constraints.py)*
|
||||
- [make_assembly_rassembly](make_assembly_rassembly.md) *(来自 constraints.py)*
|
||||
- [rotate_part_rassembly](rotate_part_rassembly.md) *(来自 constraints.py)*
|
||||
- [solve_assembly_rresult](solve_assembly_rresult.md) *(来自 constraints.py)*
|
||||
- [stack](stack.md) *(来自 constraints.py)*
|
||||
- [stack_rassembly](stack_rassembly.md) *(来自 constraints.py)*
|
||||
- [translate_part_rassembly](translate_part_rassembly.md) *(来自 constraints.py)*
|
||||
|
||||
## 其他
|
||||
|
||||
- [linear_pattern_rsolidlist](linear_pattern_rsolidlist.md) *(来自 operations.py)*
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
# add_part_rassembly
|
||||
|
||||
## API定义
|
||||
|
||||
```python
|
||||
def add_part_rassembly(assembly: Assembly, name: str, solid: Solid, parent: Optional[Union[str, PartHandle]] = None, local_transform: Optional[Union[np.ndarray, Sequence[Sequence[float]]]] = None) -> Assembly
|
||||
```
|
||||
|
||||
*来源文件: constraints.py*
|
||||
|
||||
## API作用
|
||||
|
||||
Type-2映射:在装配空间中新增零件并返回新装配对象。
|
||||
@@ -0,0 +1,13 @@
|
||||
# clear_constraints_rassembly
|
||||
|
||||
## API定义
|
||||
|
||||
```python
|
||||
def clear_constraints_rassembly(assembly: Assembly) -> Assembly
|
||||
```
|
||||
|
||||
*来源文件: constraints.py*
|
||||
|
||||
## API作用
|
||||
|
||||
Type-2映射:清空约束并返回新装配对象。
|
||||
@@ -0,0 +1,13 @@
|
||||
# clone_assembly_rassembly
|
||||
|
||||
## API定义
|
||||
|
||||
```python
|
||||
def clone_assembly_rassembly(assembly: Assembly) -> Assembly
|
||||
```
|
||||
|
||||
*来源文件: constraints.py*
|
||||
|
||||
## API作用
|
||||
|
||||
Type-2映射:装配对象到装配对象(克隆)。
|
||||
@@ -0,0 +1,13 @@
|
||||
# constrain_coincident_rassembly
|
||||
|
||||
## API定义
|
||||
|
||||
```python
|
||||
def constrain_coincident_rassembly(assembly: Assembly, reference: PointAnchor, moving: PointAnchor) -> Assembly
|
||||
```
|
||||
|
||||
*来源文件: constraints.py*
|
||||
|
||||
## API作用
|
||||
|
||||
Type-2映射:添加点重合约束并返回新装配对象。
|
||||
@@ -0,0 +1,13 @@
|
||||
# constrain_concentric_rassembly
|
||||
|
||||
## API定义
|
||||
|
||||
```python
|
||||
def constrain_concentric_rassembly(assembly: Assembly, reference: AxisAnchor, moving: AxisAnchor, same_direction: bool = False) -> Assembly
|
||||
```
|
||||
|
||||
*来源文件: constraints.py*
|
||||
|
||||
## API作用
|
||||
|
||||
Type-2映射:添加同轴约束并返回新装配对象。
|
||||
@@ -0,0 +1,13 @@
|
||||
# constrain_distance_rassembly
|
||||
|
||||
## API定义
|
||||
|
||||
```python
|
||||
def constrain_distance_rassembly(assembly: Assembly, reference: PointAnchor, moving: PointAnchor, distance: float, fallback_axis: AxisLike = 'x') -> Assembly
|
||||
```
|
||||
|
||||
*来源文件: constraints.py*
|
||||
|
||||
## API作用
|
||||
|
||||
Type-2映射:添加点距约束并返回新装配对象。
|
||||
@@ -0,0 +1,13 @@
|
||||
# constrain_offset_rassembly
|
||||
|
||||
## API定义
|
||||
|
||||
```python
|
||||
def constrain_offset_rassembly(assembly: Assembly, reference: PointAnchor, moving: PointAnchor, distance: float, axis: AxisLike = 'z') -> Assembly
|
||||
```
|
||||
|
||||
*来源文件: constraints.py*
|
||||
|
||||
## API作用
|
||||
|
||||
Type-2映射:添加轴向偏移约束并返回新装配对象。
|
||||
@@ -0,0 +1,13 @@
|
||||
# make_assembly_rassembly
|
||||
|
||||
## API定义
|
||||
|
||||
```python
|
||||
def make_assembly_rassembly(parts: Sequence[Tuple[str, Solid]], name: str = 'assembly', parents: Optional[Dict[str, str]] = None, local_transforms: Optional[Dict[str, Union[np.ndarray, Sequence[Sequence[float]]]]] = None) -> Assembly
|
||||
```
|
||||
|
||||
*来源文件: constraints.py*
|
||||
|
||||
## API作用
|
||||
|
||||
Type-1映射:从参数描述提升到装配对象。
|
||||
@@ -0,0 +1,13 @@
|
||||
# rotate_part_rassembly
|
||||
|
||||
## API定义
|
||||
|
||||
```python
|
||||
def rotate_part_rassembly(assembly: Assembly, part: Union[str, PartHandle], angle_deg: float, axis: AxisLike = 'z', origin: Vec3Like = (0.0, 0.0, 0.0), frame: Literal['world', 'local'] = 'world') -> Assembly
|
||||
```
|
||||
|
||||
*来源文件: constraints.py*
|
||||
|
||||
## API作用
|
||||
|
||||
Type-2映射:旋转零件并返回新装配对象。
|
||||
@@ -0,0 +1,13 @@
|
||||
# solve_assembly_rresult
|
||||
|
||||
## API定义
|
||||
|
||||
```python
|
||||
def solve_assembly_rresult(assembly: Assembly, max_iterations: int = 30, tolerance: float = 1e-06) -> AssemblyResult
|
||||
```
|
||||
|
||||
*来源文件: constraints.py*
|
||||
|
||||
## API作用
|
||||
|
||||
Type-2映射:从装配对象映射到求解结果,不修改原对象。
|
||||
@@ -0,0 +1,27 @@
|
||||
# stack
|
||||
|
||||
## API定义
|
||||
|
||||
```python
|
||||
def stack(assembly: Assembly, parts: Sequence[Union[str, PartHandle]], axis: str = 'z', gap: float = 0.0, align: Literal['center', 'start', 'end'] = 'center', justify: Literal['start', 'center', 'end', 'space-between'] = 'start', bounds: Optional[Tuple[PointAnchor, PointAnchor]] = None) -> Assembly
|
||||
```
|
||||
|
||||
*来源文件: constraints.py*
|
||||
|
||||
## API作用
|
||||
|
||||
沿指定轴将多个零件做声明式堆叠。
|
||||
|
||||
语义:
|
||||
- 顺序堆叠:第i个零件贴在第i-1个零件之后,并留出 gap
|
||||
- 横向对齐:在其余两个轴上按 align 对齐
|
||||
- 主轴分布:通过 justify 控制整体在边界中的分布方式
|
||||
|
||||
BBox-first 说明:
|
||||
- 本函数使用轴对齐包围盒(AABB)锚点(如 `bbox.top` / `bbox.bottom`)
|
||||
来近似 Flexbox 的盒模型语义。
|
||||
- 对发生大角度旋转的零件,AABB 会随姿态变化,布局结果也会随之变化。
|
||||
这是当前 MVP 阶段的预期行为。
|
||||
|
||||
注意:
|
||||
- 这是容器语法糖,内部会编译成若干 `offset(...)` 约束。
|
||||
@@ -0,0 +1,13 @@
|
||||
# stack_rassembly
|
||||
|
||||
## API定义
|
||||
|
||||
```python
|
||||
def stack_rassembly(assembly: Assembly, parts: Sequence[Union[str, PartHandle]], axis: str = 'z', gap: float = 0.0, align: Literal['center', 'start', 'end'] = 'center', justify: Literal['start', 'center', 'end', 'space-between'] = 'start', bounds: Optional[Tuple[PointAnchor, PointAnchor]] = None) -> Assembly
|
||||
```
|
||||
|
||||
*来源文件: constraints.py*
|
||||
|
||||
## API作用
|
||||
|
||||
Type-2映射:应用 stack 布局并返回新装配对象。
|
||||
@@ -0,0 +1,13 @@
|
||||
# translate_part_rassembly
|
||||
|
||||
## API定义
|
||||
|
||||
```python
|
||||
def translate_part_rassembly(assembly: Assembly, part: Union[str, PartHandle], vector: Vec3Like, frame: Literal['world', 'local'] = 'world') -> Assembly
|
||||
```
|
||||
|
||||
*来源文件: constraints.py*
|
||||
|
||||
## API作用
|
||||
|
||||
Type-2映射:平移零件并返回新装配对象。
|
||||
@@ -19,6 +19,94 @@ Web 布局(如 HTML/CSS 的 Flexbox)证明了一个有效方向:
|
||||
- 增加一个可选的声明式装配层;
|
||||
- 让用户描述装配关系,由 SDK 计算每个零件的最终位姿。
|
||||
|
||||
## 当前实现状态(feat/declarative-constraints-layout)
|
||||
|
||||
当前分支已提供一个可运行的 MVP,核心能力如下:
|
||||
|
||||
- 新增模块:`simplecadapi.constraints`
|
||||
- 新增对象:`Assembly`、`PartHandle`、`PointAnchor`、`AxisAnchor`、`AssemblyResult`
|
||||
- 支持混合范式:
|
||||
- 先命令式预定位(`translate_part` / `rotate_part`)
|
||||
- 再声明式约束求解(`coincident` / `concentric` / `offset` / `distance`)
|
||||
- 支持一维容器语法糖:`stack(...)`
|
||||
- `stack(...)` 新增主轴分布参数:`justify=start|center|end|space-between`
|
||||
- 当需要 `justify=center/end/space-between` 时,可通过 `bounds=(start_anchor, end_anchor)`
|
||||
指定容器主轴边界。
|
||||
|
||||
当前布局实现采用 **BBox-first** 策略:
|
||||
|
||||
- 对齐与分布主要基于 `bbox.*` 锚点(AABB)。
|
||||
- 这与 Flexbox 的盒模型思想一致,但在 3D 下是近似语义:
|
||||
当零件发生旋转时,AABB 会变化,布局结果会随之变化。
|
||||
- 后续可在此基础上增加 OBB/特征面锚点,降低旋转带来的近似误差。
|
||||
- 支持装配树父子关系与局部/世界变换传播
|
||||
|
||||
框架风格约束(函数式)已经被显式化为两类映射:
|
||||
|
||||
1. **Type-1 提升映射**(参数空间 -> CAD对象空间)
|
||||
- 例如:`make_*_rsolid`、`make_assembly_rassembly`
|
||||
2. **Type-2 代数变换映射**(CAD对象空间 -> CAD对象空间/结果空间)
|
||||
- 例如:`translate_part_rassembly`、`constrain_offset_rassembly`、`stack_rassembly`
|
||||
- 求解使用 `solve_assembly_rresult`,保证不修改输入装配对象
|
||||
|
||||
对应的函数式 API(不修改输入)包括:
|
||||
|
||||
- `make_assembly_rassembly`
|
||||
- `clone_assembly_rassembly`
|
||||
- `add_part_rassembly`
|
||||
- `translate_part_rassembly` / `rotate_part_rassembly`
|
||||
- `constrain_coincident_rassembly` / `constrain_concentric_rassembly`
|
||||
- `constrain_offset_rassembly` / `constrain_distance_rassembly`
|
||||
- `stack_rassembly`
|
||||
- `solve_assembly_rresult`
|
||||
|
||||
函数式管线示例:
|
||||
|
||||
```python
|
||||
import simplecadapi as scad
|
||||
|
||||
asm0 = scad.make_assembly_rassembly([
|
||||
("sleeve", sleeve_solid),
|
||||
("rod", rod_solid),
|
||||
])
|
||||
|
||||
asm1 = scad.translate_part_rassembly(asm0, "rod", (3.0, -2.0, 4.0))
|
||||
asm2 = scad.constrain_concentric_rassembly(
|
||||
asm1,
|
||||
asm1.part("sleeve").axis("z"),
|
||||
asm1.part("rod").axis("z"),
|
||||
)
|
||||
asm3 = scad.constrain_offset_rassembly(
|
||||
asm2,
|
||||
asm2.part("sleeve").anchor("bbox.bottom"),
|
||||
asm2.part("rod").anchor("bbox.bottom"),
|
||||
3.0,
|
||||
axis="z",
|
||||
)
|
||||
|
||||
result = scad.solve_assembly_rresult(asm3)
|
||||
```
|
||||
|
||||
示例(混合使用):
|
||||
|
||||
```python
|
||||
import simplecadapi as scad
|
||||
|
||||
asm = scad.Assembly("demo")
|
||||
sleeve = asm.add_part("sleeve", sleeve_solid)
|
||||
rod = asm.add_part("rod", rod_solid)
|
||||
|
||||
# 命令式预定位
|
||||
asm.translate_part("rod", (3.0, -2.0, 4.0), frame="world")
|
||||
|
||||
# 声明式约束
|
||||
asm.concentric(sleeve.axis("z"), rod.axis("z"))
|
||||
asm.offset(sleeve.anchor("bbox.bottom"), rod.anchor("bbox.bottom"), 3.0, axis="z")
|
||||
|
||||
result = asm.solve()
|
||||
scad.export_step(result.solids(), "assembly.step")
|
||||
```
|
||||
|
||||
## 范围(Scope)
|
||||
|
||||
### In Scope(第一阶段)
|
||||
|
||||
@@ -0,0 +1,485 @@
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
from time import perf_counter
|
||||
from typing import Dict, List, Tuple
|
||||
|
||||
import simplecadapi as scad
|
||||
from gear_case import make_involute_spur_gear_rsolid
|
||||
|
||||
|
||||
def _log(message: str, quiet: bool) -> None:
|
||||
if not quiet:
|
||||
print(f"[progress] {message}", flush=True)
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(
|
||||
description=("使用声明式约束的双齿轮啮合示例。中心距由齿轮参数自动求解。")
|
||||
)
|
||||
parser.add_argument("--teeth-a", type=int, default=16)
|
||||
parser.add_argument("--teeth-b", type=int, default=28)
|
||||
parser.add_argument("--module", type=float, default=2.0)
|
||||
parser.add_argument("--gear-thickness", type=float, default=12.0)
|
||||
parser.add_argument("--plate-gap", type=float, default=44.0)
|
||||
parser.add_argument("--plate-thickness", type=float, default=10.0)
|
||||
parser.add_argument("--shaft-radius", type=float, default=4.0)
|
||||
parser.add_argument("--bearing-height", type=float, default=8.0)
|
||||
parser.add_argument("--mesh-offset", type=float, default=0.0)
|
||||
parser.add_argument("--prefix", default="constraint_gear_mesh")
|
||||
parser.add_argument("--quiet", action="store_true")
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def _bbox_center_xyz(solid: scad.Solid) -> Tuple[float, float, float]:
|
||||
bb = solid.cq_solid.BoundingBox()
|
||||
return (
|
||||
0.5 * (bb.xmin + bb.xmax),
|
||||
0.5 * (bb.ymin + bb.ymax),
|
||||
0.5 * (bb.zmin + bb.zmax),
|
||||
)
|
||||
|
||||
|
||||
def make_parts(
|
||||
teeth_a: int,
|
||||
teeth_b: int,
|
||||
module: float,
|
||||
gear_thickness: float,
|
||||
plate_gap: float,
|
||||
plate_thickness: float,
|
||||
shaft_radius: float,
|
||||
bearing_height: float,
|
||||
quiet: bool,
|
||||
) -> List[Tuple[str, scad.Solid]]:
|
||||
t0 = perf_counter()
|
||||
pitch_radius_a = 0.5 * module * teeth_a
|
||||
pitch_radius_b = 0.5 * module * teeth_b
|
||||
center_distance = pitch_radius_a + pitch_radius_b
|
||||
|
||||
base_w = center_distance + 140.0
|
||||
base_d = 130.0
|
||||
frame_height = plate_gap + plate_thickness
|
||||
shaft_height = frame_height + 20.0
|
||||
bearing_radius = shaft_radius + 5.0
|
||||
|
||||
parts: Dict[str, scad.Solid] = {}
|
||||
|
||||
_log("构建上下板和轴", quiet)
|
||||
|
||||
# 机架上下板(故意先打散摆放)
|
||||
parts["base_plate"] = scad.make_box_rsolid(
|
||||
base_w, base_d, plate_thickness, bottom_face_center=(0.0, 0.0, 0.0)
|
||||
)
|
||||
parts["top_plate"] = scad.make_box_rsolid(
|
||||
base_w,
|
||||
base_d,
|
||||
plate_thickness,
|
||||
bottom_face_center=(32.0, -18.0, frame_height),
|
||||
)
|
||||
|
||||
# 轴(同样先打散摆放)
|
||||
parts["shaft_a"] = scad.make_cylinder_rsolid(
|
||||
shaft_radius,
|
||||
shaft_height,
|
||||
bottom_face_center=(-40.0, 20.0, -6.0),
|
||||
)
|
||||
parts["shaft_b"] = scad.make_cylinder_rsolid(
|
||||
shaft_radius,
|
||||
shaft_height,
|
||||
bottom_face_center=(46.0, -16.0, -4.0),
|
||||
)
|
||||
|
||||
# 参数化渐开线齿轮
|
||||
_log("构建渐开线齿轮 A", quiet)
|
||||
bore_radius = shaft_radius + 0.35
|
||||
parts["gear_a"] = make_involute_spur_gear_rsolid(
|
||||
tooth_count=teeth_a,
|
||||
module=module,
|
||||
thickness=gear_thickness,
|
||||
pressure_angle_deg=20.0,
|
||||
bore_radius=bore_radius,
|
||||
backlash=0.03,
|
||||
profile_points=12,
|
||||
root_arc_points=6,
|
||||
tip_arc_points=6,
|
||||
root_fillet_points=6,
|
||||
root_fillet_strength=0.86,
|
||||
verbose=False,
|
||||
)
|
||||
_log("构建渐开线齿轮 B", quiet)
|
||||
parts["gear_b"] = make_involute_spur_gear_rsolid(
|
||||
tooth_count=teeth_b,
|
||||
module=module,
|
||||
thickness=gear_thickness,
|
||||
pressure_angle_deg=20.0,
|
||||
bore_radius=bore_radius,
|
||||
backlash=0.03,
|
||||
profile_points=12,
|
||||
root_arc_points=6,
|
||||
tip_arc_points=6,
|
||||
root_fillet_points=6,
|
||||
root_fillet_strength=0.86,
|
||||
verbose=False,
|
||||
)
|
||||
|
||||
# 进一步打乱齿轮初始位置
|
||||
parts["gear_a"] = scad.translate_shape(parts["gear_a"], (-15.0, 24.0, 26.0)) # type: ignore[assignment]
|
||||
parts["gear_b"] = scad.translate_shape(parts["gear_b"], (21.0, -21.0, 31.0)) # type: ignore[assignment]
|
||||
|
||||
# 轴承块(下/上)
|
||||
_log("构建轴承与支撑块", quiet)
|
||||
parts["bearing_a_lower"] = scad.make_cylinder_rsolid(
|
||||
bearing_radius,
|
||||
bearing_height,
|
||||
bottom_face_center=(18.0, 10.0, 8.0),
|
||||
)
|
||||
parts["bearing_a_upper"] = scad.make_cylinder_rsolid(
|
||||
bearing_radius,
|
||||
bearing_height,
|
||||
bottom_face_center=(-20.0, -14.0, frame_height - 10.0),
|
||||
)
|
||||
parts["bearing_b_lower"] = scad.make_cylinder_rsolid(
|
||||
bearing_radius,
|
||||
bearing_height,
|
||||
bottom_face_center=(-14.0, 9.0, 6.0),
|
||||
)
|
||||
parts["bearing_b_upper"] = scad.make_cylinder_rsolid(
|
||||
bearing_radius,
|
||||
bearing_height,
|
||||
bottom_face_center=(17.0, -8.0, frame_height - 12.0),
|
||||
)
|
||||
|
||||
# 齿轮 A 旁的电机支架块,用于演示侧向约束
|
||||
parts["motor_block"] = scad.make_box_rsolid(
|
||||
40.0,
|
||||
28.0,
|
||||
20.0,
|
||||
bottom_face_center=(53.0, 34.0, 12.0),
|
||||
)
|
||||
|
||||
# 增加拉杆,提升机架稳定性
|
||||
_log("构建拉杆", quiet)
|
||||
tie_r = 2.6
|
||||
for name, x, y in [
|
||||
("tie_fl", -0.5 * base_w + 12.0, 0.5 * base_d - 12.0),
|
||||
("tie_fr", 0.5 * base_w - 12.0, 0.5 * base_d - 12.0),
|
||||
("tie_rl", -0.5 * base_w + 12.0, -0.5 * base_d + 12.0),
|
||||
("tie_rr", 0.5 * base_w - 12.0, -0.5 * base_d + 12.0),
|
||||
]:
|
||||
parts[name] = scad.make_cylinder_rsolid(
|
||||
tie_r,
|
||||
plate_gap,
|
||||
bottom_face_center=(x + 9.0, y - 11.0, plate_thickness),
|
||||
)
|
||||
|
||||
_log(f"make_parts 完成,用时 {perf_counter() - t0:.2f}s", quiet)
|
||||
return list(parts.items())
|
||||
|
||||
|
||||
def constrain_assembly(
|
||||
assembly: scad.Assembly,
|
||||
teeth_a: int,
|
||||
teeth_b: int,
|
||||
module: float,
|
||||
plate_gap: float,
|
||||
plate_thickness: float,
|
||||
gear_thickness: float,
|
||||
bearing_height: float,
|
||||
mesh_offset: float,
|
||||
quiet: bool,
|
||||
) -> scad.Assembly:
|
||||
t0 = perf_counter()
|
||||
pitch_radius_a = 0.5 * module * teeth_a
|
||||
pitch_radius_b = 0.5 * module * teeth_b
|
||||
target_center_distance = pitch_radius_a + pitch_radius_b + mesh_offset
|
||||
|
||||
asm = assembly
|
||||
|
||||
_log("应用机架约束", quiet)
|
||||
|
||||
# 1) 机架闭合关系
|
||||
asm = scad.constrain_offset_rassembly(
|
||||
asm,
|
||||
asm.part("base_plate").anchor("bbox.top"),
|
||||
asm.part("top_plate").anchor("bbox.bottom"),
|
||||
plate_gap,
|
||||
axis="z",
|
||||
)
|
||||
asm = scad.constrain_offset_rassembly(
|
||||
asm,
|
||||
asm.part("base_plate").anchor("bbox.center"),
|
||||
asm.part("top_plate").anchor("bbox.center"),
|
||||
0.0,
|
||||
axis="x",
|
||||
)
|
||||
asm = scad.constrain_offset_rassembly(
|
||||
asm,
|
||||
asm.part("base_plate").anchor("bbox.center"),
|
||||
asm.part("top_plate").anchor("bbox.center"),
|
||||
0.0,
|
||||
axis="y",
|
||||
)
|
||||
|
||||
# 2) 轴心关系:参数化啮合中心距约束在这里
|
||||
_log("应用轴中心距约束", quiet)
|
||||
asm = scad.constrain_offset_rassembly(
|
||||
asm,
|
||||
asm.part("base_plate").anchor("bbox.center"),
|
||||
asm.part("shaft_a").anchor("bbox.center"),
|
||||
-0.5 * target_center_distance,
|
||||
axis="x",
|
||||
)
|
||||
asm = scad.constrain_offset_rassembly(
|
||||
asm,
|
||||
asm.part("shaft_a").anchor("bbox.center"),
|
||||
asm.part("shaft_b").anchor("bbox.center"),
|
||||
target_center_distance,
|
||||
axis="x",
|
||||
)
|
||||
asm = scad.constrain_offset_rassembly(
|
||||
asm,
|
||||
asm.part("base_plate").anchor("bbox.center"),
|
||||
asm.part("shaft_a").anchor("bbox.center"),
|
||||
0.0,
|
||||
axis="y",
|
||||
)
|
||||
asm = scad.constrain_offset_rassembly(
|
||||
asm,
|
||||
asm.part("base_plate").anchor("bbox.center"),
|
||||
asm.part("shaft_b").anchor("bbox.center"),
|
||||
0.0,
|
||||
axis="y",
|
||||
)
|
||||
asm = scad.constrain_offset_rassembly(
|
||||
asm,
|
||||
asm.part("base_plate").anchor("bbox.bottom"),
|
||||
asm.part("shaft_a").anchor("bbox.bottom"),
|
||||
-6.0,
|
||||
axis="z",
|
||||
)
|
||||
asm = scad.constrain_offset_rassembly(
|
||||
asm,
|
||||
asm.part("base_plate").anchor("bbox.bottom"),
|
||||
asm.part("shaft_b").anchor("bbox.bottom"),
|
||||
-6.0,
|
||||
axis="z",
|
||||
)
|
||||
|
||||
# 3) 同轴约束:每根轴上的齿轮和轴承同轴
|
||||
_log("应用 A/B 轴同轴约束", quiet)
|
||||
for target in ["gear_a", "bearing_a_lower", "bearing_a_upper"]:
|
||||
asm = scad.constrain_concentric_rassembly(
|
||||
asm, asm.part("shaft_a").axis("z"), asm.part(target).axis("z")
|
||||
)
|
||||
for target in ["gear_b", "bearing_b_lower", "bearing_b_upper"]:
|
||||
asm = scad.constrain_concentric_rassembly(
|
||||
asm, asm.part("shaft_b").axis("z"), asm.part(target).axis("z")
|
||||
)
|
||||
|
||||
# 4) 在每根轴上于上下板之间做堆叠约束
|
||||
_log("应用轴承-齿轮-轴承堆叠约束", quiet)
|
||||
asm = scad.stack_rassembly(
|
||||
asm,
|
||||
parts=["bearing_a_lower", "gear_a", "bearing_a_upper"],
|
||||
axis="z",
|
||||
align="center",
|
||||
justify="center",
|
||||
bounds=(
|
||||
asm.part("base_plate").anchor("bbox.top"),
|
||||
asm.part("top_plate").anchor("bbox.bottom"),
|
||||
),
|
||||
)
|
||||
asm = scad.stack_rassembly(
|
||||
asm,
|
||||
parts=["bearing_b_lower", "gear_b", "bearing_b_upper"],
|
||||
axis="z",
|
||||
align="center",
|
||||
justify="center",
|
||||
bounds=(
|
||||
asm.part("base_plate").anchor("bbox.top"),
|
||||
asm.part("top_plate").anchor("bbox.bottom"),
|
||||
),
|
||||
)
|
||||
|
||||
# 保证两齿轮节圆所在平面在 z 方向对齐
|
||||
gear_stack_height = 2.0 * bearing_height + gear_thickness
|
||||
lead_gap = 0.5 * max(0.0, plate_gap - gear_stack_height)
|
||||
asm = scad.constrain_offset_rassembly(
|
||||
asm,
|
||||
asm.part("base_plate").anchor("bbox.top"),
|
||||
asm.part("gear_a").anchor("bbox.bottom"),
|
||||
lead_gap + bearing_height,
|
||||
axis="z",
|
||||
)
|
||||
asm = scad.constrain_offset_rassembly(
|
||||
asm,
|
||||
asm.part("base_plate").anchor("bbox.top"),
|
||||
asm.part("gear_b").anchor("bbox.bottom"),
|
||||
lead_gap + bearing_height,
|
||||
axis="z",
|
||||
)
|
||||
|
||||
# 5) 拉杆约束,稳定上下板关系
|
||||
_log("应用拉杆约束", quiet)
|
||||
for rod_name, x_off, y_off in [
|
||||
("tie_fl", -1.0, 1.0),
|
||||
("tie_fr", 1.0, 1.0),
|
||||
("tie_rl", -1.0, -1.0),
|
||||
("tie_rr", 1.0, -1.0),
|
||||
]:
|
||||
x_anchor = "bbox.left" if x_off < 0 else "bbox.right"
|
||||
y_anchor = "bbox.front" if y_off > 0 else "bbox.back"
|
||||
asm = scad.constrain_offset_rassembly(
|
||||
asm,
|
||||
asm.part("base_plate").anchor(x_anchor),
|
||||
asm.part(rod_name).anchor("bbox.center"),
|
||||
x_off * 8.0,
|
||||
axis="x",
|
||||
)
|
||||
asm = scad.constrain_offset_rassembly(
|
||||
asm,
|
||||
asm.part("base_plate").anchor(y_anchor),
|
||||
asm.part(rod_name).anchor("bbox.center"),
|
||||
y_off * -8.0,
|
||||
axis="y",
|
||||
)
|
||||
asm = scad.constrain_offset_rassembly(
|
||||
asm,
|
||||
asm.part("base_plate").anchor("bbox.top"),
|
||||
asm.part(rod_name).anchor("bbox.bottom"),
|
||||
0.0,
|
||||
axis="z",
|
||||
)
|
||||
|
||||
# 6) 电机块与齿轮 A 的相对关系
|
||||
_log("应用电机块关联约束", quiet)
|
||||
asm = scad.constrain_offset_rassembly(
|
||||
asm,
|
||||
asm.part("gear_a").anchor("bbox.left"),
|
||||
asm.part("motor_block").anchor("bbox.right"),
|
||||
-10.0,
|
||||
axis="x",
|
||||
)
|
||||
asm = scad.constrain_offset_rassembly(
|
||||
asm,
|
||||
asm.part("gear_a").anchor("bbox.center"),
|
||||
asm.part("motor_block").anchor("bbox.center"),
|
||||
0.0,
|
||||
axis="y",
|
||||
)
|
||||
asm = scad.constrain_offset_rassembly(
|
||||
asm,
|
||||
asm.part("base_plate").anchor("bbox.top"),
|
||||
asm.part("motor_block").anchor("bbox.bottom"),
|
||||
6.0,
|
||||
axis="z",
|
||||
)
|
||||
|
||||
_log(f"constrain_assembly 完成,用时 {perf_counter() - t0:.2f}s", quiet)
|
||||
return asm
|
||||
|
||||
|
||||
def print_report(prefix: str, report: scad.SolveReport) -> None:
|
||||
print(
|
||||
f"[{prefix}] converged={report.converged}, "
|
||||
f"iterations={report.iterations}, max_delta={report.max_delta:.6g}"
|
||||
)
|
||||
for item in report.diagnostics:
|
||||
print(f"[{prefix}] diagnostic: {item}")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
args = parse_args()
|
||||
total_t0 = perf_counter()
|
||||
if args.teeth_a < 8 or args.teeth_b < 8:
|
||||
raise ValueError("--teeth-a 和 --teeth-b 必须 >= 8")
|
||||
if args.module <= 0:
|
||||
raise ValueError("--module 必须 > 0")
|
||||
if args.plate_gap <= 0 or args.plate_thickness <= 0:
|
||||
raise ValueError("--plate-gap 和 --plate-thickness 必须 > 0")
|
||||
|
||||
pitch_radius_a = 0.5 * args.module * args.teeth_a
|
||||
pitch_radius_b = 0.5 * args.module * args.teeth_b
|
||||
target_center_distance = pitch_radius_a + pitch_radius_b + args.mesh_offset
|
||||
|
||||
_log("开始构建零件", args.quiet)
|
||||
parts = make_parts(
|
||||
teeth_a=args.teeth_a,
|
||||
teeth_b=args.teeth_b,
|
||||
module=args.module,
|
||||
gear_thickness=args.gear_thickness,
|
||||
plate_gap=args.plate_gap,
|
||||
plate_thickness=args.plate_thickness,
|
||||
shaft_radius=args.shaft_radius,
|
||||
bearing_height=args.bearing_height,
|
||||
quiet=args.quiet,
|
||||
)
|
||||
|
||||
_log("构建初始装配", args.quiet)
|
||||
asm_seed = scad.make_assembly_rassembly(parts, name="gear_mesh_seed")
|
||||
|
||||
_log("求解初始装配(未加约束)", args.quiet)
|
||||
t_before = perf_counter()
|
||||
before = scad.solve_assembly_rresult(asm_seed)
|
||||
_log(f"未约束求解完成,用时 {perf_counter() - t_before:.2f}s", args.quiet)
|
||||
|
||||
_log("应用声明式约束", args.quiet)
|
||||
asm_constrained = constrain_assembly(
|
||||
asm_seed,
|
||||
teeth_a=args.teeth_a,
|
||||
teeth_b=args.teeth_b,
|
||||
module=args.module,
|
||||
plate_gap=args.plate_gap,
|
||||
plate_thickness=args.plate_thickness,
|
||||
gear_thickness=args.gear_thickness,
|
||||
bearing_height=args.bearing_height,
|
||||
mesh_offset=args.mesh_offset,
|
||||
quiet=args.quiet,
|
||||
)
|
||||
|
||||
_log("求解约束后装配", args.quiet)
|
||||
t_after = perf_counter()
|
||||
after = scad.solve_assembly_rresult(asm_constrained)
|
||||
_log(f"约束后求解完成,用时 {perf_counter() - t_after:.2f}s", args.quiet)
|
||||
|
||||
out_dir = Path(__file__).resolve().parent
|
||||
before_step = out_dir / f"{args.prefix}_before.step"
|
||||
before_stl = out_dir / f"{args.prefix}_before.stl"
|
||||
after_step = out_dir / f"{args.prefix}_constrained.step"
|
||||
after_stl = out_dir / f"{args.prefix}_constrained.stl"
|
||||
|
||||
_log("导出约束前 STEP", args.quiet)
|
||||
scad.export_step(before.solids(), str(before_step))
|
||||
_log("导出约束前 STL", args.quiet)
|
||||
scad.export_stl(before.solids(), str(before_stl))
|
||||
_log("导出约束后 STEP", args.quiet)
|
||||
scad.export_step(after.solids(), str(after_step))
|
||||
_log("导出约束后 STL", args.quiet)
|
||||
scad.export_stl(after.solids(), str(after_stl))
|
||||
|
||||
shaft_a_center = _bbox_center_xyz(after.get_solid("shaft_a"))
|
||||
shaft_b_center = _bbox_center_xyz(after.get_solid("shaft_b"))
|
||||
solved_center_distance = (
|
||||
(shaft_b_center[0] - shaft_a_center[0]) ** 2
|
||||
+ (shaft_b_center[1] - shaft_a_center[1]) ** 2
|
||||
) ** 0.5
|
||||
|
||||
if not args.quiet:
|
||||
print_report("before", before.report)
|
||||
print_report("after", after.report)
|
||||
print(f"[mesh] 节圆半径 A/B = {pitch_radius_a:.3f}/{pitch_radius_b:.3f}")
|
||||
print(
|
||||
"[mesh] 目标中心距 = "
|
||||
f"{target_center_distance:.3f} (mesh_offset={args.mesh_offset:.3f})"
|
||||
)
|
||||
print(f"[mesh] 求解中心距 = {solved_center_distance:.3f}")
|
||||
print(f"[mesh] 偏差 = {solved_center_distance - target_center_distance:.6f}")
|
||||
|
||||
print(f"OK: {before_step}")
|
||||
print(f"OK: {before_stl}")
|
||||
print(f"OK: {after_step}")
|
||||
print(f"OK: {after_stl}")
|
||||
_log(f"总耗时 {perf_counter() - total_t0:.2f}s", args.quiet)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,67 +0,0 @@
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
|
||||
import simplecadapi as scad
|
||||
from simplecad_self_evolve_cases.evolve import make_involute_spur_gear_rsolid
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(description="Generate involute spur gear STEP/STL")
|
||||
parser.add_argument("--tooth-count", type=int, default=28)
|
||||
parser.add_argument("--module", type=float, default=1.8)
|
||||
parser.add_argument("--thickness", type=float, default=10.0)
|
||||
parser.add_argument("--pressure-angle-deg", type=float, default=20.0)
|
||||
parser.add_argument("--bore-radius", type=float, default=5.0)
|
||||
parser.add_argument("--backlash", type=float, default=0.04)
|
||||
parser.add_argument("--addendum-coeff", type=float, default=1.0)
|
||||
parser.add_argument("--dedendum-coeff", type=float, default=1.25)
|
||||
parser.add_argument("--profile-points", type=int, default=16)
|
||||
parser.add_argument("--root-arc-points", type=int, default=6)
|
||||
parser.add_argument("--tip-arc-points", type=int, default=6)
|
||||
parser.add_argument("--root-fillet-points", type=int, default=8)
|
||||
parser.add_argument("--root-fillet-strength", type=float, default=0.85)
|
||||
parser.add_argument("--step", default="gear.step")
|
||||
parser.add_argument("--stl", default="gear.stl")
|
||||
parser.add_argument("--quiet", action="store_true")
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
args = parse_args()
|
||||
out_dir = Path(__file__).resolve().parent
|
||||
|
||||
if not args.quiet:
|
||||
print("[main] start involute gear generation...")
|
||||
|
||||
gear = make_involute_spur_gear_rsolid(
|
||||
tooth_count=args.tooth_count,
|
||||
module=args.module,
|
||||
thickness=args.thickness,
|
||||
pressure_angle_deg=args.pressure_angle_deg,
|
||||
bore_radius=args.bore_radius,
|
||||
backlash=args.backlash,
|
||||
addendum_coeff=args.addendum_coeff,
|
||||
dedendum_coeff=args.dedendum_coeff,
|
||||
profile_points=args.profile_points,
|
||||
root_arc_points=args.root_arc_points,
|
||||
tip_arc_points=args.tip_arc_points,
|
||||
root_fillet_points=args.root_fillet_points,
|
||||
root_fillet_strength=args.root_fillet_strength,
|
||||
verbose=not args.quiet,
|
||||
)
|
||||
|
||||
step_path = out_dir / args.step
|
||||
stl_path = out_dir / args.stl
|
||||
if not args.quiet:
|
||||
print("[main] export STEP...")
|
||||
scad.export_step(gear, str(step_path))
|
||||
if not args.quiet:
|
||||
print("[main] export STL...")
|
||||
scad.export_stl(gear, str(stl_path))
|
||||
|
||||
print(f"OK: gear created -> {step_path}")
|
||||
print(f"OK: gear created -> {stl_path}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+25
-25
@@ -14,33 +14,33 @@ def make_involute_spur_gear_rsolid(
|
||||
root_fillet_strength: float = 0.85,
|
||||
verbose: bool = False,
|
||||
):
|
||||
"""Create an involute spur gear solid."""
|
||||
"""创建一个渐开线直齿轮实体。"""
|
||||
import math
|
||||
import simplecadapi as scad
|
||||
|
||||
if tooth_count < 8:
|
||||
raise ValueError("tooth_count must be >= 8")
|
||||
raise ValueError("tooth_count 必须 >= 8")
|
||||
if module <= 0:
|
||||
raise ValueError("module must be > 0")
|
||||
raise ValueError("module 必须 > 0")
|
||||
if thickness <= 0:
|
||||
raise ValueError("thickness must be > 0")
|
||||
raise ValueError("thickness 必须 > 0")
|
||||
if not 10.0 <= pressure_angle_deg <= 35.0:
|
||||
raise ValueError("pressure_angle_deg must be within [10, 35]")
|
||||
raise ValueError("pressure_angle_deg 必须位于 [10, 35]")
|
||||
if profile_points < 8:
|
||||
raise ValueError("profile_points must be >= 8")
|
||||
raise ValueError("profile_points 必须 >= 8")
|
||||
if root_arc_points < 4:
|
||||
raise ValueError("root_arc_points must be >= 4")
|
||||
raise ValueError("root_arc_points 必须 >= 4")
|
||||
if tip_arc_points < 4:
|
||||
raise ValueError("tip_arc_points must be >= 4")
|
||||
raise ValueError("tip_arc_points 必须 >= 4")
|
||||
if root_fillet_points < 3:
|
||||
raise ValueError("root_fillet_points must be >= 3")
|
||||
raise ValueError("root_fillet_points 必须 >= 3")
|
||||
if addendum_coeff <= 0 or dedendum_coeff <= 0:
|
||||
raise ValueError("addendum_coeff and dedendum_coeff must be > 0")
|
||||
raise ValueError("addendum_coeff 和 dedendum_coeff 必须 > 0")
|
||||
if root_fillet_strength <= 0:
|
||||
raise ValueError("root_fillet_strength must be > 0")
|
||||
raise ValueError("root_fillet_strength 必须 > 0")
|
||||
|
||||
if verbose:
|
||||
print("[gear] compute base geometry...")
|
||||
print("[gear] 计算基础几何参数...")
|
||||
|
||||
pressure_angle = math.radians(pressure_angle_deg)
|
||||
pitch_radius = 0.5 * module * tooth_count
|
||||
@@ -52,15 +52,15 @@ def make_involute_spur_gear_rsolid(
|
||||
base_radius = pitch_radius * math.cos(pressure_angle)
|
||||
|
||||
if root_radius <= 0:
|
||||
raise ValueError("invalid geometry: root_radius <= 0")
|
||||
raise ValueError("几何无效:root_radius <= 0")
|
||||
if bore_radius < 0 or bore_radius >= root_radius:
|
||||
raise ValueError("bore_radius must be >= 0 and < root_radius")
|
||||
raise ValueError("bore_radius 必须 >= 0 且 < root_radius")
|
||||
|
||||
half_tooth_angle = (math.pi / (2.0 * tooth_count)) - (
|
||||
backlash / (2.0 * pitch_radius)
|
||||
)
|
||||
if half_tooth_angle <= 0:
|
||||
raise ValueError("backlash is too large for current pitch radius")
|
||||
raise ValueError("在当前节圆半径下,backlash 过大")
|
||||
|
||||
inv_pitch = math.tan(pressure_angle) - pressure_angle
|
||||
r_start = max(root_radius, base_radius)
|
||||
@@ -78,20 +78,20 @@ def make_involute_spur_gear_rsolid(
|
||||
tooth_thickness_pitch = 2.0 * pitch_radius * half_tooth_angle
|
||||
tooth_thickness_tip = 2.0 * tip_radius * beta_tip
|
||||
print(
|
||||
"[gear] radii rp/rb/rf/ra = "
|
||||
"[gear] 半径 rp/rb/rf/ra = "
|
||||
f"{pitch_radius:.4f}/{base_radius:.4f}/{root_radius:.4f}/{tip_radius:.4f}"
|
||||
)
|
||||
print(
|
||||
"[gear] flank angle root->tip (deg) = "
|
||||
"[gear] 齿廓角 root->tip (deg) = "
|
||||
f"{math.degrees(beta_root):.4f} -> {math.degrees(beta_tip):.4f}"
|
||||
)
|
||||
print(
|
||||
"[gear] tooth thickness pitch->tip = "
|
||||
"[gear] 齿厚 pitch->tip = "
|
||||
f"{tooth_thickness_pitch:.4f} -> {tooth_thickness_tip:.4f}"
|
||||
)
|
||||
|
||||
if verbose:
|
||||
print("[gear] sample involute flanks...")
|
||||
print("[gear] 采样渐开线齿廓...")
|
||||
|
||||
rs = [
|
||||
r_start + (tip_radius - r_start) * i / (profile_points - 1)
|
||||
@@ -193,7 +193,7 @@ def make_involute_spur_gear_rsolid(
|
||||
|
||||
if verbose and root_radius < r_start - 1e-8:
|
||||
print(
|
||||
"[gear] root fillet blend enabled: "
|
||||
"[gear] 启用齿根圆角过渡:"
|
||||
f"clearance={r_start - root_radius:.4f}, "
|
||||
f"points={root_fillet_points}, strength={root_fillet_strength:.3f}"
|
||||
)
|
||||
@@ -204,7 +204,7 @@ def make_involute_spur_gear_rsolid(
|
||||
return (point[0] * c - point[1] * s, point[0] * s + point[1] * c)
|
||||
|
||||
if verbose:
|
||||
print("[gear] build full 2D tooth profile...")
|
||||
print("[gear] 构建完整 2D 齿形轮廓...")
|
||||
|
||||
tooth_pitch_angle = 2.0 * math.pi / tooth_count
|
||||
full_profile: list[tuple[float, float]] = []
|
||||
@@ -240,10 +240,10 @@ def make_involute_spur_gear_rsolid(
|
||||
cleaned.pop()
|
||||
|
||||
if len(cleaned) < 3:
|
||||
raise ValueError("generated profile has too few points")
|
||||
raise ValueError("生成的轮廓点数量过少")
|
||||
|
||||
if verbose:
|
||||
print(f"[gear] extrude profile with {len(cleaned)} points...")
|
||||
print(f"[gear] 使用 {len(cleaned)} 个点拉伸轮廓...")
|
||||
|
||||
profile_pts = [(x, y, 0.0) for (x, y) in cleaned]
|
||||
profile_wire = scad.make_polyline_rwire(profile_pts, closed=True)
|
||||
@@ -251,10 +251,10 @@ def make_involute_spur_gear_rsolid(
|
||||
|
||||
if bore_radius > 0:
|
||||
if verbose:
|
||||
print("[gear] cut center bore...")
|
||||
print("[gear] 切出中心孔...")
|
||||
bore = scad.make_cylinder_rsolid(bore_radius, thickness)
|
||||
gear = scad.cut_rsolidlist(gear, bore)[0]
|
||||
|
||||
if verbose:
|
||||
print("[gear] done.")
|
||||
print("[gear] 完成。")
|
||||
return gear
|
||||
|
||||
@@ -1,201 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Car Shock Absorber Model - Fixed Version
|
||||
"""
|
||||
|
||||
import simplecadapi as scad
|
||||
import os
|
||||
from typing import cast
|
||||
from simplecadapi import (
|
||||
Solid,
|
||||
make_cylinder_rsolid,
|
||||
make_circle_rwire,
|
||||
helical_sweep_rsolid,
|
||||
translate_shape,
|
||||
export_step,
|
||||
export_stl,
|
||||
)
|
||||
|
||||
|
||||
def create_shock_absorber():
|
||||
print("=" * 50)
|
||||
print("Creating Car Shock Absorber Model (Fixed)")
|
||||
print("=" * 50)
|
||||
|
||||
parts = []
|
||||
|
||||
cylinder_bottom_z = 0.0
|
||||
cylinder_height = 80.0
|
||||
cylinder_top_z = cylinder_bottom_z + cylinder_height
|
||||
|
||||
rod_bottom_z = 10.0
|
||||
rod_height = 90.0
|
||||
|
||||
bottom_seat_bottom_z = 5.0
|
||||
seat_height = 3.0
|
||||
spring_bottom_z = bottom_seat_bottom_z + seat_height
|
||||
spring_height = 86.0
|
||||
top_seat_bottom_z = spring_bottom_z + spring_height
|
||||
|
||||
# =====================
|
||||
# 1. Top Connection (Mounting Eye)
|
||||
# =====================
|
||||
print("\n[1/7] Creating top connection (mounting eye)...")
|
||||
|
||||
top_mount_outer = make_cylinder_rsolid(
|
||||
radius=8.0, height=5.0, bottom_face_center=(0, 0, 100)
|
||||
)
|
||||
top_mount_inner = make_cylinder_rsolid(
|
||||
radius=4.0, height=6.0, bottom_face_center=(0, 0, 99.5)
|
||||
)
|
||||
top_mount = scad.cut_rsolidlist([top_mount_outer, top_mount_inner])[0]
|
||||
parts.append(("top_mount", top_mount, top_mount.get_volume()))
|
||||
print(f" - Top mount: volume = {top_mount.get_volume():.2f}")
|
||||
|
||||
# =====================
|
||||
# 2. Top Spring Seat
|
||||
# =====================
|
||||
print("\n[2/7] Creating top spring seat...")
|
||||
top_seat = make_cylinder_rsolid(
|
||||
radius=12.0, height=seat_height, bottom_face_center=(0, 0, top_seat_bottom_z)
|
||||
)
|
||||
parts.append(("top_seat", top_seat, top_seat.get_volume()))
|
||||
print(f" - Top seat: volume = {top_seat.get_volume():.2f}")
|
||||
|
||||
# =====================
|
||||
# 3. Spring (Coil)
|
||||
# =====================
|
||||
print("\n[3/7] Creating coil spring...")
|
||||
spring_profile = make_circle_rwire(center=(0, 0, 0), radius=1.5)
|
||||
spring = cast(
|
||||
Solid,
|
||||
translate_shape(
|
||||
helical_sweep_rsolid(
|
||||
spring_profile, pitch=8.0, height=spring_height, radius=10.0
|
||||
),
|
||||
(0, 0, spring_bottom_z),
|
||||
),
|
||||
)
|
||||
parts.append(("spring", spring, spring.get_volume()))
|
||||
print(f" - Spring: volume = {spring.get_volume():.2f}")
|
||||
|
||||
# =====================
|
||||
# 4. Bottom Spring Seat
|
||||
# =====================
|
||||
print("\n[4/7] Creating bottom spring seat...")
|
||||
bottom_seat = make_cylinder_rsolid(
|
||||
radius=12.0,
|
||||
height=seat_height,
|
||||
bottom_face_center=(0, 0, bottom_seat_bottom_z),
|
||||
)
|
||||
parts.append(("bottom_seat", bottom_seat, bottom_seat.get_volume()))
|
||||
print(f" - Bottom seat: volume = {bottom_seat.get_volume():.2f}")
|
||||
|
||||
# =====================
|
||||
# 5. Hydraulic Cylinder Body (Hollow)
|
||||
# =====================
|
||||
print("\n[5/7] Creating hydraulic cylinder (outer tube, hollow)...")
|
||||
|
||||
# Outer cylinder
|
||||
cylinder_outer = make_cylinder_rsolid(
|
||||
radius=10.0,
|
||||
height=cylinder_height,
|
||||
bottom_face_center=(0, 0, cylinder_bottom_z),
|
||||
)
|
||||
# Inner hole (to make it hollow)
|
||||
cylinder_inner = make_cylinder_rsolid(
|
||||
radius=5.5,
|
||||
height=cylinder_height + 2.0,
|
||||
bottom_face_center=(0, 0, cylinder_bottom_z - 1.0),
|
||||
)
|
||||
hydraulic_cylinder = scad.cut_rsolidlist([cylinder_outer, cylinder_inner])[0]
|
||||
parts.append(
|
||||
("hydraulic_cylinder", hydraulic_cylinder, hydraulic_cylinder.get_volume())
|
||||
)
|
||||
print(
|
||||
f" - Hydraulic cylinder (hollow): volume = {hydraulic_cylinder.get_volume():.2f}"
|
||||
)
|
||||
|
||||
# =====================
|
||||
# 6. Hydraulic Rod (Piston Rod) - extends above cylinder top
|
||||
# =====================
|
||||
print("\n[6/7] Creating hydraulic rod (piston rod)...")
|
||||
hydraulic_rod = make_cylinder_rsolid(
|
||||
radius=5.0, height=rod_height, bottom_face_center=(0, 0, rod_bottom_z)
|
||||
)
|
||||
parts.append(("hydraulic_rod", hydraulic_rod, hydraulic_rod.get_volume()))
|
||||
print(f" - Hydraulic rod: volume = {hydraulic_rod.get_volume():.2f}")
|
||||
|
||||
# =====================
|
||||
# 7. Bottom Connection
|
||||
# =====================
|
||||
print("\n[7/7] Creating bottom connection (mounting point)...")
|
||||
bottom_mount_outer = make_cylinder_rsolid(
|
||||
radius=8.0, height=5.0, bottom_face_center=(0, 0, -5)
|
||||
)
|
||||
bottom_mount_inner = make_cylinder_rsolid(
|
||||
radius=4.0, height=6.0, bottom_face_center=(0, 0, -5.5)
|
||||
)
|
||||
bottom_mount = scad.cut_rsolidlist([bottom_mount_outer, bottom_mount_inner])[0]
|
||||
parts.append(("bottom_mount", bottom_mount, bottom_mount.get_volume()))
|
||||
print(f" - Bottom mount: volume = {bottom_mount.get_volume():.2f}")
|
||||
|
||||
# =====================
|
||||
# Check volumes before export
|
||||
# =====================
|
||||
print("\n" + "=" * 50)
|
||||
print("Component Summary (before export):")
|
||||
total_vol = 0
|
||||
for name, part, vol in parts:
|
||||
print(f" {name:20s}: {vol:10.2f}")
|
||||
total_vol += vol
|
||||
print(f" {'TOTAL':20s}: {total_vol:10.2f}")
|
||||
|
||||
# =====================
|
||||
# Keep solids separated and export as positioned assembly
|
||||
# =====================
|
||||
print("\n" + "=" * 50)
|
||||
print("Preparing assembly parts...")
|
||||
|
||||
final_parts = [
|
||||
top_mount,
|
||||
top_seat,
|
||||
hydraulic_cylinder,
|
||||
hydraulic_rod,
|
||||
bottom_mount,
|
||||
bottom_seat,
|
||||
spring,
|
||||
]
|
||||
|
||||
print(f" - Cylinder top Z: {cylinder_top_z:.1f}")
|
||||
print(f" - Rod top Z: {rod_bottom_z + rod_height:.1f}")
|
||||
print(
|
||||
f" - Spring range Z: {spring_bottom_z:.1f} -> {spring_bottom_z + spring_height:.1f}"
|
||||
)
|
||||
print(f" - Total parts for export: {len(final_parts)}")
|
||||
|
||||
output_dir = "/Users/lildino/Project/ocws/SimpleCADAPI/sandbox"
|
||||
assembly_step_path = os.path.join(output_dir, "shock_absorber_assembly.step")
|
||||
assembly_stl_path = os.path.join(output_dir, "shock_absorber_assembly.stl")
|
||||
|
||||
print("\nExporting assembled model to STEP format...")
|
||||
export_step(final_parts, assembly_step_path)
|
||||
print(
|
||||
f" - Saved: {os.path.basename(assembly_step_path)} ({len(final_parts)} solids in one file)"
|
||||
)
|
||||
|
||||
print("\nExporting assembled model to STL format...")
|
||||
export_stl(final_parts, assembly_stl_path)
|
||||
print(
|
||||
f" - Saved: {os.path.basename(assembly_stl_path)} ({len(final_parts)} solids in one file)"
|
||||
)
|
||||
|
||||
print("\n" + "=" * 50)
|
||||
print("DONE!")
|
||||
print("=" * 50)
|
||||
|
||||
return final_parts
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parts = create_shock_absorber()
|
||||
-135
@@ -1,135 +0,0 @@
|
||||
import math
|
||||
import cadquery as cq
|
||||
import simplecadapi as scad
|
||||
|
||||
part_1 = None
|
||||
edges_1 = []
|
||||
edges_1.append(scad.make_three_point_arc_redge((20, 62, 0), (0, 12, 0), (53, 4, 0)))
|
||||
edges_1.append(scad.make_three_point_arc_redge((53, 4, 0), (49, 7, 0), (46, 10, 0)))
|
||||
edges_1.append(scad.make_three_point_arc_redge((46, 10, 0), (8, 17, 0), (21, 53, 0)))
|
||||
edges_1.append(scad.make_three_point_arc_redge((21, 53, 0), (20, 58, 0), (20, 62, 0)))
|
||||
wire_1 = cq.Wire.combine([e.cq_edge for e in edges_1])[0]
|
||||
face_1_grp = scad.Face(cq.Face.makeFromWires(wire_1))
|
||||
solid_extr_1 = scad.extrude_rsolid(face_1_grp, (0, 0, 1), 17) # along +Z
|
||||
solid_extr_1 = scad.translate_shape(solid_extr_1, (-95, -86, -8))
|
||||
part_1 = (
|
||||
solid_extr_1 if part_1 is None else scad.union_rsolidlist(part_1, solid_extr_1)[0]
|
||||
)
|
||||
edges_2 = []
|
||||
edges_2.append(scad.make_segment_redge((20, 71, 0), (20, 62, 0)))
|
||||
edges_2.append(scad.make_three_point_arc_redge((20, 62, 0), (60, 47, 0), (53, 4, 0)))
|
||||
edges_2.append(scad.make_segment_redge((53, 4, 0), (61, 0, 0)))
|
||||
edges_2.append(scad.make_three_point_arc_redge((61, 0, 0), (95, 27, 0), (130, 0, 0)))
|
||||
edges_2.append(scad.make_segment_redge((130, 0, 0), (138, 4, 0)))
|
||||
edges_2.append(scad.make_three_point_arc_redge((138, 4, 0), (131, 47, 0), (171, 62, 0)))
|
||||
edges_2.append(scad.make_segment_redge((171, 62, 0), (171, 71, 0)))
|
||||
edges_2.append(
|
||||
scad.make_three_point_arc_redge((171, 71, 0), (130, 87, 0), (136, 131, 0))
|
||||
)
|
||||
edges_2.append(
|
||||
scad.make_three_point_arc_redge((136, 131, 0), (133, 133, 0), (129, 135, 0))
|
||||
)
|
||||
edges_2.append(
|
||||
scad.make_three_point_arc_redge((129, 135, 0), (95, 109, 0), (62, 135, 0))
|
||||
)
|
||||
edges_2.append(scad.make_segment_redge((62, 135, 0), (54, 131, 0)))
|
||||
edges_2.append(scad.make_three_point_arc_redge((54, 131, 0), (61, 87, 0), (20, 71, 0)))
|
||||
wire_2 = cq.Wire.combine([e.cq_edge for e in edges_2])[0]
|
||||
edges_3 = []
|
||||
wire_3 = cq.Wire.assembleEdges([cq.Edge.makeCircle(25, cq.Vector(95, 67, 0))])
|
||||
face_3_grp = scad.Face(cq.Face.makeFromWires(wire_2, [wire_3]))
|
||||
solid_extr_3 = scad.extrude_rsolid(face_3_grp, (0, 0, 1), 17) # along +Z
|
||||
solid_extr_3 = scad.translate_shape(solid_extr_3, (-95, -86, -8))
|
||||
part_1 = (
|
||||
solid_extr_3 if part_1 is None else scad.union_rsolidlist(part_1, solid_extr_3)[0]
|
||||
)
|
||||
edges_4 = []
|
||||
edges_4.append(scad.make_three_point_arc_redge((20, 62, 0), (20, 58, 0), (21, 53, 0)))
|
||||
edges_4.append(scad.make_three_point_arc_redge((21, 53, 0), (51, 42, 0), (46, 10, 0)))
|
||||
edges_4.append(scad.make_three_point_arc_redge((46, 10, 0), (49, 7, 0), (53, 4, 0)))
|
||||
edges_4.append(scad.make_three_point_arc_redge((53, 4, 0), (60, 47, 0), (20, 62, 0)))
|
||||
wire_4 = cq.Wire.combine([e.cq_edge for e in edges_4])[0]
|
||||
face_4_grp = scad.Face(cq.Face.makeFromWires(wire_4))
|
||||
solid_extr_4 = scad.extrude_rsolid(face_4_grp, (0, 0, 1), 17) # along +Z
|
||||
solid_extr_4 = scad.translate_shape(solid_extr_4, (-95, -86, -8))
|
||||
part_1 = (
|
||||
solid_extr_4 if part_1 is None else scad.union_rsolidlist(part_1, solid_extr_4)[0]
|
||||
)
|
||||
edges_5 = []
|
||||
edges_5.append(
|
||||
scad.make_three_point_arc_redge((62, 135, 0), (95, 109, 0), (129, 135, 0))
|
||||
)
|
||||
edges_5.append(
|
||||
scad.make_three_point_arc_redge((129, 135, 0), (125, 137, 0), (120, 139, 0))
|
||||
)
|
||||
edges_5.append(
|
||||
scad.make_three_point_arc_redge((120, 139, 0), (95, 118, 0), (71, 139, 0))
|
||||
)
|
||||
edges_5.append(
|
||||
scad.make_three_point_arc_redge((71, 139, 0), (66, 137, 0), (62, 135, 0))
|
||||
)
|
||||
wire_5 = cq.Wire.combine([e.cq_edge for e in edges_5])[0]
|
||||
face_5_grp = scad.Face(cq.Face.makeFromWires(wire_5))
|
||||
solid_extr_5 = scad.extrude_rsolid(face_5_grp, (0, 0, 1), 17) # along +Z
|
||||
solid_extr_5 = scad.translate_shape(solid_extr_5, (-95, -86, -8))
|
||||
part_1 = (
|
||||
solid_extr_5 if part_1 is None else scad.union_rsolidlist(part_1, solid_extr_5)[0]
|
||||
)
|
||||
edges_6 = []
|
||||
edges_6.append(
|
||||
scad.make_three_point_arc_redge((62, 135, 0), (66, 137, 0), (71, 139, 0))
|
||||
)
|
||||
edges_6.append(
|
||||
scad.make_three_point_arc_redge((71, 139, 0), (95, 168, 0), (120, 139, 0))
|
||||
)
|
||||
edges_6.append(
|
||||
scad.make_three_point_arc_redge((120, 139, 0), (125, 137, 0), (129, 135, 0))
|
||||
)
|
||||
edges_6.append(
|
||||
scad.make_three_point_arc_redge((129, 135, 0), (95, 178, 0), (62, 135, 0))
|
||||
)
|
||||
wire_6 = cq.Wire.combine([e.cq_edge for e in edges_6])[0]
|
||||
face_6_grp = scad.Face(cq.Face.makeFromWires(wire_6))
|
||||
solid_extr_6 = scad.extrude_rsolid(face_6_grp, (0, 0, 1), 17) # along +Z
|
||||
solid_extr_6 = scad.translate_shape(solid_extr_6, (-95, -86, -8))
|
||||
part_1 = (
|
||||
solid_extr_6 if part_1 is None else scad.union_rsolidlist(part_1, solid_extr_6)[0]
|
||||
)
|
||||
edges_7 = []
|
||||
edges_7.append(scad.make_three_point_arc_redge((138, 4, 0), (141, 7, 0), (145, 10, 0)))
|
||||
edges_7.append(
|
||||
scad.make_three_point_arc_redge((145, 10, 0), (139, 42, 0), (170, 53, 0))
|
||||
)
|
||||
edges_7.append(
|
||||
scad.make_three_point_arc_redge((170, 53, 0), (171, 58, 0), (171, 62, 0))
|
||||
)
|
||||
edges_7.append(scad.make_three_point_arc_redge((171, 62, 0), (131, 47, 0), (138, 4, 0)))
|
||||
wire_7 = cq.Wire.combine([e.cq_edge for e in edges_7])[0]
|
||||
face_7_grp = scad.Face(cq.Face.makeFromWires(wire_7))
|
||||
solid_extr_7 = scad.extrude_rsolid(face_7_grp, (0, 0, 1), 17) # along +Z
|
||||
solid_extr_7 = scad.translate_shape(solid_extr_7, (-95, -86, -8))
|
||||
part_1 = (
|
||||
solid_extr_7 if part_1 is None else scad.union_rsolidlist(part_1, solid_extr_7)[0]
|
||||
)
|
||||
edges_8 = []
|
||||
edges_8.append(scad.make_three_point_arc_redge((138, 4, 0), (191, 12, 0), (171, 62, 0)))
|
||||
edges_8.append(
|
||||
scad.make_three_point_arc_redge((171, 62, 0), (171, 58, 0), (170, 53, 0))
|
||||
)
|
||||
edges_8.append(
|
||||
scad.make_three_point_arc_redge((170, 53, 0), (183, 17, 0), (145, 10, 0))
|
||||
)
|
||||
edges_8.append(scad.make_three_point_arc_redge((145, 10, 0), (141, 7, 0), (138, 4, 0)))
|
||||
wire_8 = cq.Wire.combine([e.cq_edge for e in edges_8])[0]
|
||||
face_8_grp = scad.Face(cq.Face.makeFromWires(wire_8))
|
||||
solid_extr_8 = scad.extrude_rsolid(face_8_grp, (0, 0, 1), 17) # along +Z
|
||||
solid_extr_8 = scad.translate_shape(solid_extr_8, (-95, -86, -8))
|
||||
part_1 = (
|
||||
solid_extr_8 if part_1 is None else scad.union_rsolidlist(part_1, solid_extr_8)[0]
|
||||
)
|
||||
result = part_1
|
||||
|
||||
|
||||
# 导出 STEP(可选)
|
||||
scad.export_step(result, "result_simplecad.step")
|
||||
print("OK: simplecadapi inline 版本完成")
|
||||
@@ -82,6 +82,29 @@ from .evolve import (
|
||||
make_threaded_rod_rsolid,
|
||||
)
|
||||
|
||||
from .constraints import (
|
||||
# 声明式装配约束
|
||||
make_assembly_rassembly,
|
||||
clone_assembly_rassembly,
|
||||
add_part_rassembly,
|
||||
clear_constraints_rassembly,
|
||||
translate_part_rassembly,
|
||||
rotate_part_rassembly,
|
||||
constrain_coincident_rassembly,
|
||||
constrain_concentric_rassembly,
|
||||
constrain_offset_rassembly,
|
||||
constrain_distance_rassembly,
|
||||
stack_rassembly,
|
||||
solve_assembly_rresult,
|
||||
Assembly,
|
||||
AssemblyResult,
|
||||
SolveReport,
|
||||
PartHandle,
|
||||
PointAnchor,
|
||||
AxisAnchor,
|
||||
stack,
|
||||
)
|
||||
|
||||
__author__ = "SimpleCAD API Team"
|
||||
__description__ = "Simplified CAD modeling Python API based on CADQuery"
|
||||
|
||||
@@ -202,6 +225,26 @@ __all__ = [
|
||||
"make_n_hole_flange_rsolid",
|
||||
"make_naca_propeller_blade_rsolid",
|
||||
"make_threaded_rod_rsolid",
|
||||
# 声明式装配约束
|
||||
"make_assembly_rassembly",
|
||||
"clone_assembly_rassembly",
|
||||
"add_part_rassembly",
|
||||
"clear_constraints_rassembly",
|
||||
"translate_part_rassembly",
|
||||
"rotate_part_rassembly",
|
||||
"constrain_coincident_rassembly",
|
||||
"constrain_concentric_rassembly",
|
||||
"constrain_offset_rassembly",
|
||||
"constrain_distance_rassembly",
|
||||
"stack_rassembly",
|
||||
"solve_assembly_rresult",
|
||||
"Assembly",
|
||||
"AssemblyResult",
|
||||
"SolveReport",
|
||||
"PartHandle",
|
||||
"PointAnchor",
|
||||
"AxisAnchor",
|
||||
"stack",
|
||||
# 别名
|
||||
"create_angle_arc",
|
||||
"create_angle_arc_wire",
|
||||
|
||||
@@ -19,6 +19,7 @@ PROJECT_ROOT = Path(__file__).resolve().parents[3]
|
||||
DEFAULT_SOURCES: tuple[Path, ...] = (
|
||||
PROJECT_ROOT / "src/simplecadapi/operations.py",
|
||||
PROJECT_ROOT / "src/simplecadapi/evolve.py",
|
||||
PROJECT_ROOT / "src/simplecadapi/constraints.py",
|
||||
)
|
||||
DEFAULT_OUTPUT_DIRS: tuple[Path, ...] = (PROJECT_ROOT / "docs/api",)
|
||||
|
||||
@@ -218,6 +219,7 @@ class APIDocumentGenerator:
|
||||
"导出功能": [],
|
||||
"高级特征": [],
|
||||
"自进化": [],
|
||||
"声明式装配约束": [],
|
||||
"其他": [],
|
||||
}
|
||||
|
||||
@@ -228,6 +230,10 @@ class APIDocumentGenerator:
|
||||
categories["自进化"].append(api)
|
||||
continue
|
||||
|
||||
if api.source_file == "constraints.py":
|
||||
categories["声明式装配约束"].append(api)
|
||||
continue
|
||||
|
||||
if name.startswith("make_"):
|
||||
categories["基础图形创建"].append(api)
|
||||
elif name.startswith(("translate_", "rotate_", "mirror_")):
|
||||
@@ -250,7 +256,7 @@ class APIDocumentGenerator:
|
||||
md_lines: List[str] = [
|
||||
"# SimpleCAD API 文档索引",
|
||||
"",
|
||||
"本文档包含了 SimpleCAD API (来自 `operations.py` 和 `evolve.py`) 的所有函数说明。",
|
||||
"本文档包含了 SimpleCAD API (来自 `operations.py`、`evolve.py`、`constraints.py`) 的所有函数说明。",
|
||||
"",
|
||||
]
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -810,6 +810,244 @@ class TestNewFunctionIntegration(unittest.TestCase):
|
||||
self.skipTest("Alias functions not fully exported")
|
||||
|
||||
|
||||
class TestDeclarativeConstraints(unittest.TestCase):
|
||||
"""测试声明式约束与命令式混合装配。"""
|
||||
|
||||
def test_concentric_and_offset_mix_with_imperative(self):
|
||||
sleeve = scad.make_cylinder_rsolid(5.0, 20.0, bottom_face_center=(0, 0, 0))
|
||||
rod = scad.make_cylinder_rsolid(2.0, 12.0, bottom_face_center=(8, 1, 0))
|
||||
|
||||
asm = scad.Assembly("shock_like")
|
||||
sleeve_p = asm.add_part("sleeve", sleeve)
|
||||
rod_p = asm.add_part("rod", rod)
|
||||
|
||||
# 先命令式预定位,再声明式精定位
|
||||
asm.translate_part(rod_p, (3.0, -2.0, 4.0), frame="world")
|
||||
asm.concentric(sleeve_p.axis("z"), rod_p.axis("z"))
|
||||
asm.offset(
|
||||
sleeve_p.anchor("bbox.bottom"),
|
||||
rod_p.anchor("bbox.bottom"),
|
||||
3.0,
|
||||
axis="z",
|
||||
)
|
||||
|
||||
result = asm.solve()
|
||||
self.assertTrue(result.report.converged)
|
||||
|
||||
sleeve_bb = result.get_solid("sleeve").cq_solid.BoundingBox()
|
||||
rod_bb = result.get_solid("rod").cq_solid.BoundingBox()
|
||||
|
||||
sleeve_cx = 0.5 * (sleeve_bb.xmin + sleeve_bb.xmax)
|
||||
sleeve_cy = 0.5 * (sleeve_bb.ymin + sleeve_bb.ymax)
|
||||
rod_cx = 0.5 * (rod_bb.xmin + rod_bb.xmax)
|
||||
rod_cy = 0.5 * (rod_bb.ymin + rod_bb.ymax)
|
||||
|
||||
self.assertAlmostEqual(rod_cx, sleeve_cx, places=6)
|
||||
self.assertAlmostEqual(rod_cy, sleeve_cy, places=6)
|
||||
self.assertAlmostEqual(rod_bb.zmin, sleeve_bb.zmin + 3.0, places=6)
|
||||
|
||||
def test_stack_layout(self):
|
||||
a = scad.make_box_rsolid(4.0, 2.0, 2.0, bottom_face_center=(0, 0, 0))
|
||||
b = scad.make_box_rsolid(3.0, 3.0, 1.0, bottom_face_center=(5, -3, 0))
|
||||
c = scad.make_box_rsolid(2.0, 4.0, 3.0, bottom_face_center=(-4, 2, 0))
|
||||
|
||||
asm = scad.Assembly("stack")
|
||||
pa = asm.add_part("a", a)
|
||||
pb = asm.add_part("b", b)
|
||||
pc = asm.add_part("c", c)
|
||||
|
||||
scad.stack(asm, [pa, pb, pc], axis="z", gap=1.5, align="center")
|
||||
result = asm.solve()
|
||||
self.assertTrue(result.report.converged)
|
||||
|
||||
bb_a = result.get_solid("a").cq_solid.BoundingBox()
|
||||
bb_b = result.get_solid("b").cq_solid.BoundingBox()
|
||||
bb_c = result.get_solid("c").cq_solid.BoundingBox()
|
||||
|
||||
self.assertAlmostEqual(bb_b.zmin, bb_a.zmax + 1.5, places=6)
|
||||
self.assertAlmostEqual(bb_c.zmin, bb_b.zmax + 1.5, places=6)
|
||||
|
||||
cx_a = 0.5 * (bb_a.xmin + bb_a.xmax)
|
||||
cy_a = 0.5 * (bb_a.ymin + bb_a.ymax)
|
||||
cx_b = 0.5 * (bb_b.xmin + bb_b.xmax)
|
||||
cy_b = 0.5 * (bb_b.ymin + bb_b.ymax)
|
||||
cx_c = 0.5 * (bb_c.xmin + bb_c.xmax)
|
||||
cy_c = 0.5 * (bb_c.ymin + bb_c.ymax)
|
||||
|
||||
self.assertAlmostEqual(cx_b, cx_a, places=6)
|
||||
self.assertAlmostEqual(cy_b, cy_a, places=6)
|
||||
self.assertAlmostEqual(cx_c, cx_a, places=6)
|
||||
self.assertAlmostEqual(cy_c, cy_a, places=6)
|
||||
|
||||
def test_parent_child_transform_propagation(self):
|
||||
parent_solid = scad.make_box_rsolid(2.0, 2.0, 2.0, bottom_face_center=(0, 0, 0))
|
||||
child_solid = scad.make_box_rsolid(1.0, 1.0, 1.0, bottom_face_center=(0, 0, 0))
|
||||
|
||||
asm = scad.Assembly("tree")
|
||||
parent = asm.add_part("parent", parent_solid)
|
||||
asm.add_part(
|
||||
"child",
|
||||
child_solid,
|
||||
parent=parent,
|
||||
local_transform=np.array(
|
||||
[
|
||||
[1.0, 0.0, 0.0, 3.0],
|
||||
[0.0, 1.0, 0.0, 0.0],
|
||||
[0.0, 0.0, 1.0, 0.0],
|
||||
[0.0, 0.0, 0.0, 1.0],
|
||||
]
|
||||
),
|
||||
)
|
||||
|
||||
asm.translate_part("parent", (10.0, 0.0, 0.0), frame="world")
|
||||
result = asm.solve()
|
||||
|
||||
bb_parent = result.get_solid("parent").cq_solid.BoundingBox()
|
||||
bb_child = result.get_solid("child").cq_solid.BoundingBox()
|
||||
|
||||
center_parent_x = 0.5 * (bb_parent.xmin + bb_parent.xmax)
|
||||
center_child_x = 0.5 * (bb_child.xmin + bb_child.xmax)
|
||||
|
||||
self.assertAlmostEqual(center_parent_x, 10.0, places=6)
|
||||
self.assertAlmostEqual(center_child_x, 13.0, places=6)
|
||||
|
||||
def test_stack_justify_center_with_bounds(self):
|
||||
container = scad.make_box_rsolid(6.0, 6.0, 10.0, bottom_face_center=(0, 0, 0))
|
||||
a = scad.make_box_rsolid(2.0, 2.0, 2.0, bottom_face_center=(4, 0, 0))
|
||||
b = scad.make_box_rsolid(1.0, 3.0, 1.0, bottom_face_center=(-3, 1, 0))
|
||||
|
||||
asm = scad.Assembly("justify_center")
|
||||
c = asm.add_part("container", container)
|
||||
pa = asm.add_part("a", a)
|
||||
pb = asm.add_part("b", b)
|
||||
|
||||
scad.stack(
|
||||
asm,
|
||||
[pa, pb],
|
||||
axis="z",
|
||||
gap=1.0,
|
||||
align="center",
|
||||
justify="center",
|
||||
bounds=(c.anchor("bbox.bottom"), c.anchor("bbox.top")),
|
||||
)
|
||||
|
||||
result = asm.solve()
|
||||
self.assertTrue(result.report.converged)
|
||||
|
||||
bb_a = result.get_solid("a").cq_solid.BoundingBox()
|
||||
bb_b = result.get_solid("b").cq_solid.BoundingBox()
|
||||
bb_c = result.get_solid("container").cq_solid.BoundingBox()
|
||||
|
||||
# 容器高10,(2 + 1 + gap1)=4,居中后首件底部应在z=3
|
||||
self.assertAlmostEqual(bb_a.zmin, bb_c.zmin + 3.0, places=6)
|
||||
self.assertAlmostEqual(bb_b.zmin, bb_a.zmax + 1.0, places=6)
|
||||
self.assertAlmostEqual(bb_c.zmax - bb_b.zmax, 3.0, places=6)
|
||||
|
||||
def test_stack_justify_space_between_with_bounds(self):
|
||||
container = scad.make_box_rsolid(5.0, 5.0, 11.0, bottom_face_center=(0, 0, 0))
|
||||
p1 = scad.make_box_rsolid(1.0, 1.0, 1.0, bottom_face_center=(2, 0, 0))
|
||||
p2 = scad.make_box_rsolid(1.0, 1.0, 1.0, bottom_face_center=(-2, 0, 0))
|
||||
p3 = scad.make_box_rsolid(1.0, 1.0, 1.0, bottom_face_center=(0, 2, 0))
|
||||
|
||||
asm = scad.Assembly("justify_space_between")
|
||||
c = asm.add_part("container", container)
|
||||
h1 = asm.add_part("p1", p1)
|
||||
h2 = asm.add_part("p2", p2)
|
||||
h3 = asm.add_part("p3", p3)
|
||||
|
||||
scad.stack(
|
||||
asm,
|
||||
[h1, h2, h3],
|
||||
axis="z",
|
||||
align="center",
|
||||
justify="space-between",
|
||||
bounds=(c.anchor("bbox.bottom"), c.anchor("bbox.top")),
|
||||
)
|
||||
|
||||
result = asm.solve()
|
||||
self.assertTrue(result.report.converged)
|
||||
|
||||
bb1 = result.get_solid("p1").cq_solid.BoundingBox()
|
||||
bb2 = result.get_solid("p2").cq_solid.BoundingBox()
|
||||
bb3 = result.get_solid("p3").cq_solid.BoundingBox()
|
||||
bbc = result.get_solid("container").cq_solid.BoundingBox()
|
||||
|
||||
# 总高11,三个高度各1 => gap=(11-3)/2=4
|
||||
self.assertAlmostEqual(bb1.zmin, bbc.zmin, places=6)
|
||||
self.assertAlmostEqual(bb2.zmin, bb1.zmax + 4.0, places=6)
|
||||
self.assertAlmostEqual(bb3.zmin, bb2.zmax + 4.0, places=6)
|
||||
self.assertAlmostEqual(bb3.zmax, bbc.zmax, places=6)
|
||||
|
||||
def test_unconstrained_part_diagnostic(self):
|
||||
a = scad.make_box_rsolid(1.0, 1.0, 1.0)
|
||||
b = scad.make_box_rsolid(1.0, 1.0, 1.0, bottom_face_center=(3, 0, 0))
|
||||
c = scad.make_box_rsolid(1.0, 1.0, 1.0, bottom_face_center=(6, 0, 0))
|
||||
|
||||
asm = scad.Assembly("diag")
|
||||
pa = asm.add_part("a", a)
|
||||
pb = asm.add_part("b", b)
|
||||
asm.add_part("c", c)
|
||||
|
||||
asm.offset(pa.anchor("bbox.right"), pb.anchor("bbox.left"), 0.5, axis="x")
|
||||
result = asm.solve()
|
||||
|
||||
diagnostics_text = "\n".join(result.report.diagnostics)
|
||||
self.assertIn("未被任何约束引用", diagnostics_text)
|
||||
self.assertIn("'c'", diagnostics_text)
|
||||
|
||||
def test_functional_wrappers_do_not_mutate_input(self):
|
||||
a = scad.make_box_rsolid(1.0, 1.0, 1.0, bottom_face_center=(0, 0, 0))
|
||||
b = scad.make_box_rsolid(1.0, 1.0, 1.0, bottom_face_center=(0, 0, 0))
|
||||
|
||||
base = scad.make_assembly_rassembly([("a", a), ("b", b)], name="base")
|
||||
moved = scad.translate_part_rassembly(base, "b", (5.0, 0.0, 0.0), frame="world")
|
||||
|
||||
base_result = scad.solve_assembly_rresult(base)
|
||||
moved_result = scad.solve_assembly_rresult(moved)
|
||||
|
||||
bb_base_b = base_result.get_solid("b").cq_solid.BoundingBox()
|
||||
bb_moved_b = moved_result.get_solid("b").cq_solid.BoundingBox()
|
||||
|
||||
base_cx = 0.5 * (bb_base_b.xmin + bb_base_b.xmax)
|
||||
moved_cx = 0.5 * (bb_moved_b.xmin + bb_moved_b.xmax)
|
||||
|
||||
self.assertAlmostEqual(base_cx, 0.0, places=6)
|
||||
self.assertAlmostEqual(moved_cx, 5.0, places=6)
|
||||
|
||||
def test_make_assembly_parent_resolution_from_params(self):
|
||||
parent = scad.make_box_rsolid(2.0, 2.0, 2.0, bottom_face_center=(0, 0, 0))
|
||||
child = scad.make_box_rsolid(1.0, 1.0, 1.0, bottom_face_center=(0, 0, 0))
|
||||
|
||||
asm = scad.make_assembly_rassembly(
|
||||
[
|
||||
("child", child),
|
||||
("parent", parent),
|
||||
],
|
||||
name="param_build",
|
||||
parents={"child": "parent"},
|
||||
local_transforms={
|
||||
"child": np.array(
|
||||
[
|
||||
[1.0, 0.0, 0.0, 2.0],
|
||||
[0.0, 1.0, 0.0, 0.0],
|
||||
[0.0, 0.0, 1.0, 0.0],
|
||||
[0.0, 0.0, 0.0, 1.0],
|
||||
]
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
result = scad.solve_assembly_rresult(asm)
|
||||
bb_parent = result.get_solid("parent").cq_solid.BoundingBox()
|
||||
bb_child = result.get_solid("child").cq_solid.BoundingBox()
|
||||
|
||||
center_parent_x = 0.5 * (bb_parent.xmin + bb_parent.xmax)
|
||||
center_child_x = 0.5 * (bb_child.xmin + bb_child.xmax)
|
||||
|
||||
self.assertAlmostEqual(center_parent_x, 0.0, places=6)
|
||||
self.assertAlmostEqual(center_child_x, 2.0, places=6)
|
||||
|
||||
|
||||
def run_comprehensive_tests():
|
||||
"""运行全面测试"""
|
||||
print("SimpleCAD API 全面单元测试")
|
||||
@@ -831,6 +1069,7 @@ def run_comprehensive_tests():
|
||||
TestExport,
|
||||
TestComplexExamples,
|
||||
TestErrorHandling,
|
||||
TestDeclarativeConstraints,
|
||||
]
|
||||
|
||||
for test_class in test_classes:
|
||||
|
||||
Reference in New Issue
Block a user