anycad 0.0.0-stage → 1.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +24 -0
- package/LICENSE +21 -0
- package/README.md +40 -2
- package/install.ps1 +41 -0
- package/package.json +16 -4
- package/runtime/assembly_plan.py +166 -0
- package/runtime/build_model.py +87 -0
- package/runtime/cad_help.py +174 -0
- package/runtime/cad_primitives.py +110 -0
- package/runtime/native_plan.py +138 -0
- package/runtime/plan.py +146 -0
- package/runtime/write_source.py +87 -0
- package/showcase/anycad-preview.png +0 -0
- package/showcase/dovetail-0mm.step +3514 -0
- package/showcase/dovetail-plus10mm.step +3514 -0
- package/showcase/dovetail-preview.png +0 -0
- package/showcase/dovetail-prompt.md +3 -0
- package/showcase/rounded-bolt-block.step +987 -0
- package/src/cad-construct.ts +232 -0
- package/src/cad-plan.ts +43 -0
- package/src/cad-tools.ts +115 -0
- package/src/extension.ts +328 -0
- package/src/runtime.ts +10 -0
- package/vendor/text-to-cad/package.json +7 -0
- package/vendor/text-to-cad/skills/cad/LICENSE +21 -0
- package/vendor/text-to-cad/skills/cad/SKILL.md +241 -0
- package/vendor/text-to-cad/skills/cad/agents/openai.yaml +4 -0
- package/vendor/text-to-cad/skills/cad/references/2d-profiles-and-dxf.md +197 -0
- package/vendor/text-to-cad/skills/cad/references/animation.md +115 -0
- package/vendor/text-to-cad/skills/cad/references/build123d-modeling.md +206 -0
- package/vendor/text-to-cad/skills/cad/references/environments.md +44 -0
- package/vendor/text-to-cad/skills/cad/references/exports.md +249 -0
- package/vendor/text-to-cad/skills/cad/references/inspection-and-validation.md +383 -0
- package/vendor/text-to-cad/skills/cad/references/kinematics.md +478 -0
- package/vendor/text-to-cad/skills/cad/references/manufacturing-cnc.md +127 -0
- package/vendor/text-to-cad/skills/cad/references/manufacturing-injection-molding.md +133 -0
- package/vendor/text-to-cad/skills/cad/references/manufacturing-printing.md +129 -0
- package/vendor/text-to-cad/skills/cad/references/manufacturing-review.md +144 -0
- package/vendor/text-to-cad/skills/cad/references/manufacturing-sheet-metal.md +167 -0
- package/vendor/text-to-cad/skills/cad/references/model-contract.md +281 -0
- package/vendor/text-to-cad/skills/cad/references/positioning.md +94 -0
- package/vendor/text-to-cad/skills/cad/references/project-layout.md +79 -0
- package/vendor/text-to-cad/skills/cad/references/snapshot-review.md +203 -0
- package/workflow.md +15 -0
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""Reusable dimensions-first helpers over the installed build123d solids."""
|
|
2
|
+
|
|
3
|
+
import build123d as bd
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def stock(width, depth, height, bottom=0, x=0, y=0):
|
|
7
|
+
return bd.Pos(x, y, bottom + height / 2) * bd.Box(width, depth, height)
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def block(x0, x1, y0, y1, z0, z1):
|
|
11
|
+
return stock(x1 - x0, y1 - y0, z1 - z0, z0, (x0 + x1) / 2, (y0 + y1) / 2)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def cylinder_z(diameter, z0, z1, x=0, y=0):
|
|
15
|
+
return bd.Pos(x, y, (z0 + z1) / 2) * bd.Cylinder(diameter / 2, z1 - z0)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def cylinder_y(diameter, y0, y1, x=0, z=0):
|
|
19
|
+
return bd.Pos(x, (y0 + y1) / 2, z) * bd.Rot(90, 0, 0) * bd.Cylinder(diameter / 2, y1 - y0)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def cylinder_x(diameter, x0, x1, y=0, z=0):
|
|
23
|
+
return bd.Pos((x0 + x1) / 2, y, z) * bd.Rot(0, 90, 0) * bd.Cylinder(diameter / 2, x1 - x0)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def drill_through_z(body, diameter, x=0, y=0):
|
|
27
|
+
bounds = body.bounding_box()
|
|
28
|
+
return body.cut(cylinder_z(diameter, bounds.min.Z - 1, bounds.max.Z + 1, x, y))
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def drill_through_y(body, diameter, x=0, z=0):
|
|
32
|
+
bounds = body.bounding_box()
|
|
33
|
+
return body.cut(cylinder_y(diameter, bounds.min.Y - 1, bounds.max.Y + 1, x, z))
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def drill_through_x(body, diameter, y=0, z=0):
|
|
37
|
+
bounds = body.bounding_box()
|
|
38
|
+
return body.cut(cylinder_x(diameter, bounds.min.X - 1, bounds.max.X + 1, y, z))
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def round_all(body, radius):
|
|
42
|
+
return bd.fillet(body.edges(), radius)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def round_vertical(body, radius):
|
|
46
|
+
return bd.fillet(body.edges().filter_by(bd.Axis.Z), radius)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def rounded_prism(width, depth, radius, z0, z1):
|
|
50
|
+
return bd.Pos(0, 0, z0) * bd.extrude(bd.RectangleRounded(width, depth, radius), amount=z1 - z0)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def slot_y(overall_length, width, x, y, z0, z1):
|
|
54
|
+
outline = bd.SlotOverall(overall_length, width, rotation=90)
|
|
55
|
+
return bd.Pos(x, y, z0) * bd.extrude(outline, amount=z1 - z0)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def drill_pattern_z(body, diameter, x_centers, y_centers):
|
|
59
|
+
bounds = body.bounding_box()
|
|
60
|
+
cutters = [cylinder_z(diameter, bounds.min.Z - 1, bounds.max.Z + 1, x, y)
|
|
61
|
+
for x in x_centers for y in y_centers]
|
|
62
|
+
return body.cut(*cutters)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def counterbore_z(body, diameter, floor, x=0, y=0):
|
|
66
|
+
return body.cut(cylinder_z(diameter, floor, body.bounding_box().max.Z + 1, x, y))
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def drill_from_positive_x(body, diameter, stop, y, z):
|
|
70
|
+
end = body.bounding_box().max.X + 1
|
|
71
|
+
return body.cut(cylinder_x(diameter, stop, end, y, z))
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def drill_pattern_y(body, diameter, x_centers, z_centers):
|
|
75
|
+
bounds = body.bounding_box()
|
|
76
|
+
cutters = [cylinder_y(diameter, bounds.min.Y - 1, bounds.max.Y + 1, x, z)
|
|
77
|
+
for x in x_centers for z in z_centers]
|
|
78
|
+
return body.cut(*cutters)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def cut_slots_y(body, overall_length, width, x_centers, y_centers, z0, z1):
|
|
82
|
+
cutters = [slot_y(overall_length, width, x, y, z0, z1)
|
|
83
|
+
for x in x_centers for y in y_centers]
|
|
84
|
+
return body.cut(*cutters)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def prism_x(yz_points, x0, x1):
|
|
88
|
+
wire = bd.Wire.make_polygon([(x0, y, z) for y, z in yz_points], close=True)
|
|
89
|
+
return bd.extrude(bd.Face(wire), amount=x1 - x0, dir=(1, 0, 0))
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def half_z(body, plane_z, upper):
|
|
93
|
+
keep = bd.Keep.TOP if upper else bd.Keep.BOTTOM
|
|
94
|
+
return body.split(bd.Plane.XY.offset(plane_z), keep=keep)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def assembly(**parts):
|
|
98
|
+
for label, part in parts.items():
|
|
99
|
+
part.label = label
|
|
100
|
+
return bd.Compound(children=list(parts.values()))
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def checked(body, *, solids=1, material=(), void=()):
|
|
104
|
+
occurrences = list(body.solids())
|
|
105
|
+
assert body.is_valid and len(occurrences) == solids, "Invalid geometry or unexpected solid count"
|
|
106
|
+
for point in material:
|
|
107
|
+
assert any(part.is_inside(point) for part in occurrences), f"Expected material at {point}"
|
|
108
|
+
for point in void:
|
|
109
|
+
assert not any(part.is_inside(point) for part in occurrences), f"Expected void at {point}"
|
|
110
|
+
return body
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"""Compile a workflow-authored plan to a normal editable text-to-CAD source."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from itertools import product
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import shutil
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
from plan import compile_source
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def fused_plan(plan):
|
|
13
|
+
stocks = []
|
|
14
|
+
supplied = plan["stocks"]
|
|
15
|
+
if isinstance(supplied, dict):
|
|
16
|
+
supplied = list(supplied.values())
|
|
17
|
+
for stock in supplied:
|
|
18
|
+
if plan.get("corner_default") and stock["op"] == "rounded_prism":
|
|
19
|
+
radius = round(min(stock["width"], stock["depth"]) / 10, 3)
|
|
20
|
+
print(f"Default vertical corner radius: {radius:g} mm.")
|
|
21
|
+
stocks.append({**stock, "radius": radius})
|
|
22
|
+
elif stock["op"] == "symmetric_prisms_x":
|
|
23
|
+
half = stock["thickness"] / 2
|
|
24
|
+
stocks.extend({"op": "prism_x", "yz_points": stock["yz_points"],
|
|
25
|
+
"x0": center - half, "x1": center + half}
|
|
26
|
+
for center in stock["x_centers"])
|
|
27
|
+
else:
|
|
28
|
+
stocks.append(stock)
|
|
29
|
+
steps = [{"name": f"stock_{index}", **stock} for index, stock in enumerate(stocks)]
|
|
30
|
+
last = steps[0]["name"]
|
|
31
|
+
if len(steps) > 1:
|
|
32
|
+
steps.append({"name": "joined", "op": "fuse", "body": last,
|
|
33
|
+
"items": [step["name"] for step in steps[1:]]})
|
|
34
|
+
last = "joined"
|
|
35
|
+
cuts = plan["cuts"]
|
|
36
|
+
probes = list(plan.get("void", []))
|
|
37
|
+
if plan.get("centered_bore"):
|
|
38
|
+
if len(stocks) != 1 or stocks[0]["op"] not in ("stock", "rounded_prism", "block"):
|
|
39
|
+
raise ValueError("A centered through-hole needs one block or rounded stock.")
|
|
40
|
+
stock = stocks[0]
|
|
41
|
+
x = (stock["x0"] + stock["x1"]) / 2 if stock["op"] == "block" else 0
|
|
42
|
+
y = (stock["y0"] + stock["y1"]) / 2 if stock["op"] == "block" else 0
|
|
43
|
+
cuts = [{**cut, "x_centers": [x], "y_centers": [y]} for cut in cuts]
|
|
44
|
+
if "clearance" in plan:
|
|
45
|
+
diameter = plan["clearance"]
|
|
46
|
+
cuts = [{**cut, "diameter": diameter} for cut in cuts]
|
|
47
|
+
print(f"Centered through-hole diameter: {diameter:g} mm including bolt clearance.")
|
|
48
|
+
stock_roles = plan["stocks"] if isinstance(plan["stocks"], dict) else {}
|
|
49
|
+
base = stock_roles.get("base") or stock_roles.get("foot")
|
|
50
|
+
if not base and len(stocks) == 1 and stocks[0]["op"] in ("stock", "block", "rounded_prism"):
|
|
51
|
+
base = stocks[0]
|
|
52
|
+
upright = stock_roles.get("upright")
|
|
53
|
+
if base:
|
|
54
|
+
if base["op"] == "stock":
|
|
55
|
+
base_middle = base.get("bottom", 0) + base["height"] / 2
|
|
56
|
+
else:
|
|
57
|
+
base_middle = (base["z0"] + base["z1"]) / 2
|
|
58
|
+
else:
|
|
59
|
+
base_middle = None
|
|
60
|
+
if isinstance(cuts, dict):
|
|
61
|
+
axial = cuts.get("axial_bore")
|
|
62
|
+
side = cuts.get("positive_x_port")
|
|
63
|
+
if axial and side and "stop" not in side:
|
|
64
|
+
cuts = {
|
|
65
|
+
**cuts,
|
|
66
|
+
"positive_x_port": {**side, "stop": axial["x"]},
|
|
67
|
+
}
|
|
68
|
+
cuts = list(cuts.values())
|
|
69
|
+
for index, cut in enumerate(cuts):
|
|
70
|
+
name = f"cut_{index}"
|
|
71
|
+
if cut["op"] == "rounded_prism":
|
|
72
|
+
tool = f"tool_{index}"
|
|
73
|
+
steps.append({"name": tool, **cut})
|
|
74
|
+
steps.append({"name": name, "op": "cut", "body": last, "items": [tool]})
|
|
75
|
+
else:
|
|
76
|
+
steps.append({"name": name, "body": last, **cut})
|
|
77
|
+
if cut["op"] in ("drill_pattern_z", "cut_slots_y") and base_middle is not None:
|
|
78
|
+
probes.extend([x, y, base_middle] for x, y in product(cut["x_centers"], cut["y_centers"]))
|
|
79
|
+
if cut["op"] == "drill_pattern_y" and upright:
|
|
80
|
+
middle_y = (upright["y0"] + upright["y1"]) / 2
|
|
81
|
+
probes.extend([x, middle_y, z] for x, z in product(cut["x_centers"], cut["z_centers"]))
|
|
82
|
+
last = name
|
|
83
|
+
return {**plan, "steps": steps, "result": last, "void": [list(point) for point in dict.fromkeys(map(tuple, probes))]}
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def write_centered_brief(path, plan):
|
|
87
|
+
stock, hole = plan["steps"]
|
|
88
|
+
if stock["op"] == "block":
|
|
89
|
+
width, depth = stock["x1"] - stock["x0"], stock["y1"] - stock["y0"]
|
|
90
|
+
else:
|
|
91
|
+
width, depth = stock["width"], stock["depth"]
|
|
92
|
+
if stock["op"] == "stock":
|
|
93
|
+
z0 = stock.get("bottom", 0)
|
|
94
|
+
z1 = z0 + stock["height"]
|
|
95
|
+
else:
|
|
96
|
+
z0, z1 = stock["z0"], stock["z1"]
|
|
97
|
+
x, y = hole["x_centers"][0], hole["y_centers"][0]
|
|
98
|
+
profile = f" with R{stock['radius']:g} vertical corners" if stock["op"] == "rounded_prism" else ""
|
|
99
|
+
path.write_text(
|
|
100
|
+
"# CAD design brief\n\n"
|
|
101
|
+
"A flat-based block with one centered through bore.\n\n"
|
|
102
|
+
"## Dimensions and feature order\n\n"
|
|
103
|
+
f"1. Build {width:g} × {depth:g} × {z1 - z0:g} mm stock{profile}. "
|
|
104
|
+
f"The bore axis is X={x:g}, Y={y:g} mm.\n"
|
|
105
|
+
f"2. Drill a Ø{hole['diameter']:g} mm through bore along Z from {z0:g} to {z1:g} mm.\n\n"
|
|
106
|
+
"## Assumptions and checks\n\n"
|
|
107
|
+
"- Z is vertical and the bottom face is the resting surface.\n"
|
|
108
|
+
"- The build checks that the result is one valid solid and that its bore centerline is open.\n"
|
|
109
|
+
"- Inspect the dimensions and export the verified model to STEP.\n",
|
|
110
|
+
encoding="utf-8",
|
|
111
|
+
)
|
|
112
|
+
print("Saved the resolved design brief in src/design.md.")
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def main():
|
|
116
|
+
root = Path.cwd()
|
|
117
|
+
path = root / "geometry-plan.json"
|
|
118
|
+
plan = json.loads(path.read_text(encoding="utf-8"))
|
|
119
|
+
if "stocks" in plan:
|
|
120
|
+
plan = fused_plan(plan)
|
|
121
|
+
number_of_solids = plan.get("solids", 1)
|
|
122
|
+
if type(number_of_solids) is not int or number_of_solids < 1:
|
|
123
|
+
raise ValueError("solids must be a positive whole number")
|
|
124
|
+
code = compile_source(plan, number_of_solids)
|
|
125
|
+
target = root / "src/model.py"
|
|
126
|
+
target.parent.mkdir(exist_ok=True)
|
|
127
|
+
if plan.get("design_brief"):
|
|
128
|
+
write_centered_brief(target.with_name("design.md"), plan)
|
|
129
|
+
shutil.copyfile(Path(__file__).with_name("cad_primitives.py"), target.with_name("cad_primitives.py"))
|
|
130
|
+
target.write_text(code, encoding="utf-8")
|
|
131
|
+
print(f"Saved src/model.py with {len(plan['steps'])} features and {number_of_solids} expected solids.")
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
if __name__ == "__main__":
|
|
135
|
+
try:
|
|
136
|
+
main()
|
|
137
|
+
except (OSError, ValueError) as error:
|
|
138
|
+
sys.exit(str(error))
|
package/runtime/plan.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""Translate a model-authored CAD operation plan into editable build123d source."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import keyword
|
|
5
|
+
import math
|
|
6
|
+
import re
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
OPERATIONS = {
|
|
10
|
+
"stock": ("width depth height", "bottom x y"),
|
|
11
|
+
"block": ("x0 x1 y0 y1 z0 z1", ""),
|
|
12
|
+
"cylinder_z": ("diameter z0 z1", "x y"),
|
|
13
|
+
"cylinder_y": ("diameter y0 y1", "x z"),
|
|
14
|
+
"cylinder_x": ("diameter x0 x1", "y z"),
|
|
15
|
+
"round_all": ("body radius", ""),
|
|
16
|
+
"round_vertical": ("body radius", ""),
|
|
17
|
+
"drill_through_z": ("body diameter", "x y"),
|
|
18
|
+
"drill_through_y": ("body diameter", "x z"),
|
|
19
|
+
"drill_through_x": ("body diameter", "y z"),
|
|
20
|
+
"drill_pattern_z": ("body diameter x_centers y_centers", ""),
|
|
21
|
+
"counterbore_z": ("body diameter floor", "x y"),
|
|
22
|
+
"drill_from_positive_x": ("body diameter stop y z", ""),
|
|
23
|
+
"drill_pattern_y": ("body diameter x_centers z_centers", ""),
|
|
24
|
+
"cut_slots_y": ("body overall_length width x_centers y_centers z0 z1", ""),
|
|
25
|
+
"rounded_prism": ("width depth radius z0 z1", ""),
|
|
26
|
+
"slot_y": ("overall_length width x y z0 z1", ""),
|
|
27
|
+
"prism_x": ("yz_points x0 x1", ""),
|
|
28
|
+
"half_z": ("body plane_z upper", ""),
|
|
29
|
+
"cut": ("body items", ""),
|
|
30
|
+
"fuse": ("body items", ""),
|
|
31
|
+
"assembly": ("parts", ""),
|
|
32
|
+
"translate": ("body dx dy dz", ""),
|
|
33
|
+
}
|
|
34
|
+
def identifier(name):
|
|
35
|
+
return isinstance(name, str) and re.fullmatch(r"[a-z][a-z0-9_]*", name) and not keyword.iskeyword(name)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def number(value):
|
|
39
|
+
return type(value) in (float, int) and math.isfinite(value)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def expression(value, known):
|
|
43
|
+
if isinstance(value, str) and value in known:
|
|
44
|
+
return value
|
|
45
|
+
if value is True or value is False or number(value):
|
|
46
|
+
return repr(value)
|
|
47
|
+
if isinstance(value, list):
|
|
48
|
+
return "[" + ", ".join(expression(item, known) for item in value) + "]"
|
|
49
|
+
raise ValueError(f"Unknown reference or invalid argument {value!r}.")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def points(value):
|
|
53
|
+
if not isinstance(value, list) or not all(
|
|
54
|
+
isinstance(point, list) and len(point) == 3 and all(number(coordinate) for coordinate in point)
|
|
55
|
+
for point in value
|
|
56
|
+
):
|
|
57
|
+
raise ValueError("Check points must be lists of three numbers.")
|
|
58
|
+
return [tuple(point) for point in value]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def references(value, known):
|
|
62
|
+
if isinstance(value, str):
|
|
63
|
+
return {value} if value in known else set()
|
|
64
|
+
if isinstance(value, dict):
|
|
65
|
+
value = list(value.values())
|
|
66
|
+
return set().union(*(references(item, known) for item in value)) if isinstance(value, list) else set()
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def read_plan(answer):
|
|
70
|
+
start = answer.find("{")
|
|
71
|
+
if start < 0:
|
|
72
|
+
raise ValueError("Pi did not return a JSON plan.")
|
|
73
|
+
return json.JSONDecoder().raw_decode(answer[start:])[0]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def compile_source(plan, expected_solids):
|
|
77
|
+
if not isinstance(plan, dict) or not isinstance(plan.get("steps"), list):
|
|
78
|
+
raise ValueError("Pi's plan must contain a steps array.")
|
|
79
|
+
known = set()
|
|
80
|
+
dependencies = {}
|
|
81
|
+
lines = ["import build123d as bd", "from cad import model",
|
|
82
|
+
"import cad_primitives as shapes", ""]
|
|
83
|
+
parameter = plan.get("parameter")
|
|
84
|
+
if parameter is not None:
|
|
85
|
+
if not (isinstance(parameter, dict) and identifier(parameter.get("name")) and number(parameter.get("default"))):
|
|
86
|
+
raise ValueError("The parameter needs a Python name and numeric default.")
|
|
87
|
+
name = parameter["name"]
|
|
88
|
+
known.add(name)
|
|
89
|
+
lines += [f"{name} = model.param({name!r}, {parameter['default']!r}, unit='mm')", ""]
|
|
90
|
+
lines += ["", "def geometry():"]
|
|
91
|
+
for step in plan["steps"]:
|
|
92
|
+
if not isinstance(step, dict):
|
|
93
|
+
raise ValueError("Each step needs an object with a name, op and named arguments.")
|
|
94
|
+
name, operation = step.get("name"), step.get("op")
|
|
95
|
+
if not identifier(name) or name in known or name in ("model", "bd", "shapes"):
|
|
96
|
+
raise ValueError(f"Invalid or duplicate step name {name!r}.")
|
|
97
|
+
if not isinstance(operation, str) or operation not in OPERATIONS:
|
|
98
|
+
raise ValueError(f"Unknown operation {operation!r}.")
|
|
99
|
+
mandatory, optional = (set(names.split()) for names in OPERATIONS[operation])
|
|
100
|
+
arguments = {key: value for key, value in step.items() if key not in ("name", "op")}
|
|
101
|
+
missing, extra = mandatory - arguments.keys(), arguments.keys() - (mandatory | optional)
|
|
102
|
+
if missing or extra:
|
|
103
|
+
raise ValueError(f"{operation} is missing {sorted(missing)} and has unknown fields {sorted(extra)}.")
|
|
104
|
+
if operation == "assembly":
|
|
105
|
+
labels = arguments["parts"]
|
|
106
|
+
if not isinstance(labels, dict) or not labels or not all(
|
|
107
|
+
isinstance(label, str) and label.strip() for label in labels
|
|
108
|
+
):
|
|
109
|
+
raise ValueError("Assembly takes a nonempty object mapping part labels to step names.")
|
|
110
|
+
entries = ", ".join(f"{label!r}: {expression(reference, known)}"
|
|
111
|
+
for label, reference in labels.items())
|
|
112
|
+
code = "shapes.assembly(**{" + entries + "})"
|
|
113
|
+
elif operation in ("cut", "fuse"):
|
|
114
|
+
body = expression(arguments["body"], known)
|
|
115
|
+
items = arguments["items"]
|
|
116
|
+
if not isinstance(items, list) or not items:
|
|
117
|
+
raise ValueError("cut and fuse use a nonempty items array of step names.")
|
|
118
|
+
cutters = ", ".join(expression(item, known) for item in items)
|
|
119
|
+
code = f"{body}.{operation}({cutters})"
|
|
120
|
+
elif operation == "translate":
|
|
121
|
+
body = expression(arguments["body"], known)
|
|
122
|
+
shift = ", ".join(expression(arguments[axis], known) for axis in ("dx", "dy", "dz"))
|
|
123
|
+
code = f"bd.Pos({shift}) * {body}"
|
|
124
|
+
else:
|
|
125
|
+
args = [f"{key}={expression(value, known)}" for key, value in arguments.items()]
|
|
126
|
+
code = f"shapes.{operation}({', '.join(args)})"
|
|
127
|
+
lines.append(f" {name} = {code}")
|
|
128
|
+
dependencies[name] = references(arguments, known)
|
|
129
|
+
known.add(name)
|
|
130
|
+
|
|
131
|
+
result = expression(plan.get("result"), known)
|
|
132
|
+
if result not in dependencies:
|
|
133
|
+
raise ValueError("The result must be the name of a geometry step.")
|
|
134
|
+
used = {result}
|
|
135
|
+
for name in reversed(dependencies):
|
|
136
|
+
if name in used:
|
|
137
|
+
used.update(dependencies[name])
|
|
138
|
+
unused = [name for name in dependencies if name not in used]
|
|
139
|
+
if unused:
|
|
140
|
+
raise ValueError("Connect these unused steps to the final result: " + ", ".join(unused))
|
|
141
|
+
void = points(plan.get("void", []))
|
|
142
|
+
material = points(plan.get("material", []))
|
|
143
|
+
lines += [f" return shapes.checked({result}, solids={expected_solids}, material={material!r}, void={void!r})",
|
|
144
|
+
"", "", "@model", "def part():", " return geometry()", "", "",
|
|
145
|
+
'if __name__ == "__main__":', " part()", ""]
|
|
146
|
+
return "\n".join(lines)
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Write a model with AnyCAD's standard build123d entry point."""
|
|
2
|
+
|
|
3
|
+
import ast
|
|
4
|
+
import json
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import sys
|
|
7
|
+
import textwrap
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def is_main_guard(node):
|
|
11
|
+
return isinstance(node, ast.If) and ast.unparse(node.test) in (
|
|
12
|
+
"__name__ == '__main__'", "'__main__' == __name__",
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def is_model_invocation(node, names):
|
|
17
|
+
value = getattr(node, "value", None)
|
|
18
|
+
return isinstance(value, ast.Call) and isinstance(value.func, ast.Name) and value.func.id in names
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def model_body(code):
|
|
22
|
+
tree = ast.parse(code)
|
|
23
|
+
if any(isinstance(node, ast.Return) for node in tree.body):
|
|
24
|
+
return "", code, "part"
|
|
25
|
+
defined = [node for node in tree.body if isinstance(node, ast.FunctionDef)]
|
|
26
|
+
preferred = [node for node in defined if node.name == "part"
|
|
27
|
+
or any(ast.unparse(item) == "model" for item in node.decorator_list)]
|
|
28
|
+
functions = preferred or defined
|
|
29
|
+
if len(functions) != 1:
|
|
30
|
+
return "", code, "part"
|
|
31
|
+
function = functions[0]
|
|
32
|
+
if function.args.posonlyargs or function.args.args or function.args.kwonlyargs:
|
|
33
|
+
raise ValueError("The CAD model function needs zero arguments.")
|
|
34
|
+
support = [
|
|
35
|
+
node for node in tree.body
|
|
36
|
+
if node is not function and not is_main_guard(node)
|
|
37
|
+
and not is_model_invocation(node, {function.name})
|
|
38
|
+
]
|
|
39
|
+
lines = code.splitlines()
|
|
40
|
+
body = textwrap.dedent("\n".join(lines[function.body[0].lineno - 1:function.body[-1].end_lineno]))
|
|
41
|
+
if function.body[0].lineno == function.lineno:
|
|
42
|
+
body = "\n".join(map(ast.unparse, function.body))
|
|
43
|
+
return ast.unparse(ast.Module(body=support, type_ignores=[])), body, function.name
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def check_apis(tree, verified):
|
|
47
|
+
missing = set()
|
|
48
|
+
for node in ast.walk(tree):
|
|
49
|
+
if not isinstance(node, ast.Call) or not isinstance(node.func, (ast.Name, ast.Attribute)):
|
|
50
|
+
continue
|
|
51
|
+
name = ast.unparse(node.func)
|
|
52
|
+
operation = name.rsplit(".", 1)[-1]
|
|
53
|
+
if name.startswith(("bd.", "build123d.")):
|
|
54
|
+
if name.split(".", 1)[1] not in verified:
|
|
55
|
+
missing.add(name)
|
|
56
|
+
elif name.startswith("model.") and name not in verified:
|
|
57
|
+
missing.add(name)
|
|
58
|
+
elif (operation == "export" or operation.startswith("export_")) and name not in verified:
|
|
59
|
+
missing.add(name)
|
|
60
|
+
if missing:
|
|
61
|
+
raise ValueError("Call cad_syntax for these unverified operations or let AnyCAD export STEP: " + ", ".join(sorted(missing)))
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def main():
|
|
65
|
+
payload = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8"))
|
|
66
|
+
code = textwrap.dedent(payload["body"]).strip("\n")
|
|
67
|
+
extra, body, name = model_body(code)
|
|
68
|
+
setup = ast.parse("\n\n".join(filter(None, (payload.get("setup"), extra))))
|
|
69
|
+
future = [node for node in setup.body if isinstance(node, ast.ImportFrom) and node.module == "__future__"]
|
|
70
|
+
support = [node for node in setup.body if node not in future and not is_main_guard(node)
|
|
71
|
+
and not is_model_invocation(node, {name, "part"})]
|
|
72
|
+
source = "\n\n\n".join(filter(None, (
|
|
73
|
+
"\n".join(map(ast.unparse, future)),
|
|
74
|
+
"import build123d as bd\nfrom cad import model",
|
|
75
|
+
ast.unparse(ast.Module(body=support, type_ignores=[])),
|
|
76
|
+
"@model\ndef part():\n" + textwrap.indent(body, " "),
|
|
77
|
+
'if __name__ == "__main__":\n part()\n',
|
|
78
|
+
)))
|
|
79
|
+
output = Path("src/model.py")
|
|
80
|
+
compile(source, str(output), "exec")
|
|
81
|
+
check_apis(ast.parse(source), set(payload.get("verifiedApis", [])))
|
|
82
|
+
output.parent.mkdir(exist_ok=True)
|
|
83
|
+
output.write_text(source, encoding="utf-8")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
if __name__ == "__main__":
|
|
87
|
+
main()
|
|
Binary file
|