66 lines
3.0 KiB
Python
66 lines
3.0 KiB
Python
import math
|
|
|
|
from build123d import FilletPolyline, Polyline, Side, extrude, make_face, offset
|
|
|
|
|
|
def _turn_signs(points):
|
|
"""对每个中间转折点算一次叉积,判断这一处转弯是朝哪个方向拐——这决定了
|
|
"points给定的这个表面"在这一个转角处到底是内侧(凹面)还是外侧(凸面)。
|
|
真实踩过的坑:Z字形这种两处转角方向相反的路径,同一个表面在两处转角上
|
|
的内/外側身份是会互换的,不是固定不变的,必须逐个转角单独判断。"""
|
|
signs = []
|
|
for i in range(1, len(points) - 1):
|
|
a, b, c = points[i - 1], points[i], points[i + 1]
|
|
v1 = (b[0] - a[0], b[1] - a[1])
|
|
v2 = (c[0] - b[0], c[1] - b[1])
|
|
signs.append(v1[0] * v2[1] - v1[1] * v2[0])
|
|
return signs
|
|
|
|
|
|
def validate(context, target, params):
|
|
errors = []
|
|
points = params["points"]
|
|
if len(points) < 2:
|
|
errors.append("TOO_FEW_POINTS: points 至少需要2个点才能定义一条边")
|
|
return errors
|
|
|
|
if len(points) > 2 and params["bend_radius"] > 0:
|
|
radius = params["bend_radius"]
|
|
for i in range(1, len(points) - 1):
|
|
a, b, c = points[i - 1], points[i], points[i + 1]
|
|
len_ab = math.dist(a, b)
|
|
len_bc = math.dist(b, c)
|
|
if radius >= min(len_ab, len_bc):
|
|
errors.append(
|
|
f"BEND_RADIUS_TOO_LARGE: 折弯圆角半径{radius}mm太大,"
|
|
f"覆盖了顶点{b}处相邻的直边(长度{min(len_ab, len_bc):.1f}mm)"
|
|
)
|
|
return errors
|
|
|
|
|
|
def run(context, target, params):
|
|
points = [tuple(p) for p in params["points"]]
|
|
thickness = params["thickness"]
|
|
width = params["width"]
|
|
radius = params.get("bend_radius", 0)
|
|
|
|
if len(points) > 2 and radius > 0:
|
|
# 【重要,真实踩过的坑】bend_radius说的是每一处折弯自己的真实内侧半径
|
|
# (跟真实钣金图纸标注习惯一致——每一处折弯单独标注,不管Z字形两处折弯
|
|
# 方向是不是相反)。如果直接把points当成一个固定不变的表面、整条路径
|
|
# 统一套用同一个半径再整体偏移thickness,会导致其中一处折弯的内侧半径
|
|
# 被动算成"radius-thickness"(而不是精确等于声明的radius),板厚较大时
|
|
# 甚至会退化成尖角。正确做法:先判断points在每一处转角到底是内侧还是
|
|
# 外側,是外侧的转角就在points自己身上先烧成"radius+thickness",这样
|
|
# 整条路径偏移thickness之后,两处折弯的内侧半径都会精确等于声明的
|
|
# bend_radius,不会再有一侧被动打折的问题。
|
|
signs = _turn_signs(points)
|
|
per_vertex_radius = [radius + thickness if s > 0 else radius for s in signs]
|
|
path = FilletPolyline(*points, radius=per_vertex_radius)
|
|
else:
|
|
path = Polyline(*points)
|
|
|
|
strip_curve = offset(path, amount=thickness, side=Side.LEFT, closed=True)
|
|
face = make_face(strip_curve.edges())
|
|
return extrude(face, amount=width)
|