-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmake_bricks.py
More file actions
224 lines (198 loc) · 8.91 KB
/
make_bricks.py
File metadata and controls
224 lines (198 loc) · 8.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Generate LEGO text bricks (STL) from a CSV using OpenSCAD.
- CSV headers: Vorname, Nachname, OE
- Imports only brick() from LEGOTextBrick-v2p1.scad via `use <...>`
- Defines local make*Text() modules so they see our variables
- Font fixed to: Roboto:style=Black
- Text is recessed on all sides
- Filename: safe_name(org, ln, fn)
"""
import csv
import re
import sys
import subprocess
from pathlib import Path
def esc_scad_string(s: str) -> str:
return '"' + (s or "").replace('\\', '\\\\').replace('"', '\\"') + '"'
def safe_name(*parts):
base = "_".join([p for p in parts if p]).strip()
base = re.sub(r"[^\w\-.]+", "_", base, flags=re.UNICODE)
return base.strip("_") or "output"
# Fixed per project
PROJECT_CFG = {
"brickLength": 8,
"brickWidth": 4,
"brickHeight": 3,
"withStuds": "yes",
"withUnderStuds": "no",
"frontTextScale": 1.0,
"frontTextType": "recessed",
"backTextScale": 1.0,
"backTextType": "recessed",
"leftTextScale": 1.0,
"leftTextType": "recessed",
"rightTextScale": 1.0,
"rightTextType": "recessed",
# Advanced (from template)
"tolerance": 0.00,
"textSize": 5.5,
"letterSpacing": 1.05,
"textZShift": 2.0,
"textDepth": 0.8,
"numberFragments": 50,
# LEGO dims
"UNIT_LENGTH": 8,
"PLATE_HEIGHT": 3.2,
"ROOF_THICKNESS": 1.0,
"WALL_THICKNESS": 1.5,
"STUD_DIAMETER": 4.8,
"STUD_HEIGHT": 1.8,
"UNDERTUBE_OUTER_DIAMETER": 6.41,
"UNDERTUBE_INNER_DIAMETER": 4.8,
"UNDERSTUD_DIAMETER": 1.6,
"PLAY": 0.2,
# Hidden helper
"fudge": 0.01,
}
def write_wrapper(scad_wrapper: Path, template: Path, row: dict):
# CSV fields (German headers)
fn = (row.get("Vorname") or "").strip()
ln = (row.get("Nachname") or "").strip()
org = (row.get("OE") or "").strip()
if not (fn and ln and org):
raise ValueError(f"Incomplete row: {row}")
q = esc_scad_string
cfg = PROJECT_CFG
lines = []
# Import ONLY modules from the template; globals won't leak across files (by design)
lines.append(f'use <{template.resolve().as_posix()}>;')
# Our variables (these MUST live in the same file as the make*Text() modules)
lines += [
f'brickLength = {cfg["brickLength"]};',
f'brickWidth = {cfg["brickWidth"]};',
f'brickHeight = {cfg["brickHeight"]};',
f'withStuds = {q(cfg["withStuds"])};',
f'withUnderStuds = {q(cfg["withUnderStuds"])};',
'createStuds = (withStuds=="yes") ? true : false;',
'createUnderStuds = (withUnderStuds=="yes") ? true : false;',
f'frontText = {q(fn)};',
f'frontTextScale = {cfg["frontTextScale"]};',
f'frontTextType = {q(cfg["frontTextType"])};',
f'backText = {q(ln)};',
f'backTextScale = {cfg["backTextScale"]};',
f'backTextType = {q(cfg["backTextType"])};',
f'leftText = {q(org)};',
f'leftTextScale = {cfg["leftTextScale"]};',
f'leftTextType = {q(cfg["leftTextType"])};',
f'rightText = {q(org)};',
f'rightTextScale = {cfg["rightTextScale"]};',
f'rightTextType = {q(cfg["rightTextType"])};',
f'tolerance = {cfg["tolerance"]};',
f'textSize = {cfg["textSize"]};',
f'letterSpacing = {cfg["letterSpacing"]};',
f'textZShift = {cfg["textZShift"]};',
f'textDepth = {cfg["textDepth"]};',
f'numberFragments = {cfg["numberFragments"]};',
'$fn = numberFragments;',
f'UNIT_LENGTH = {cfg["UNIT_LENGTH"]};',
f'PLATE_HEIGHT = {cfg["PLATE_HEIGHT"]};',
f'ROOF_THICKNESS = {cfg["ROOF_THICKNESS"]};',
f'WALL_THICKNESS = {cfg["WALL_THICKNESS"]};',
f'STUD_DIAMETER = {cfg["STUD_DIAMETER"]};',
f'STUD_HEIGHT = {cfg["STUD_HEIGHT"]};',
f'UNDERTUBE_OUTER_DIAMETER = {cfg["UNDERTUBE_OUTER_DIAMETER"]};',
f'UNDERTUBE_INNER_DIAMETER = {cfg["UNDERTUBE_INNER_DIAMETER"]};',
f'UNDERSTUD_DIAMETER = {cfg["UNDERSTUD_DIAMETER"]};',
f'PLAY = {cfg["PLAY"]};',
f'fudge = {cfg["fudge"]};',
# FIXED FONT — exactly as requested
'selectedFont = "Roboto:style=Black";',
# Back offsets based on text type (from template)
'frontTextBack = (frontTextType == "raised") ? 0 : textDepth;',
'backTextBack = (backTextType == "raised") ? 0 : textDepth;',
'leftTextBack = (leftTextType == "raised") ? 0 : textDepth;',
'rightTextBack = (rightTextType == "raised") ? 0 : textDepth;',
]
# Local copies of text modules so they can SEE our variables (use <...> can’t share globals)
lines += [
'module makeFrontText () {',
' translate([0, -brickWidth/2*UNIT_LENGTH+frontTextBack+PLAY/2+tolerance, textZShift]) rotate([90, 0, 0])',
' linear_extrude(textDepth+fudge) text(frontText, font=selectedFont, size=textSize*frontTextScale, halign="center", spacing=letterSpacing);',
'}',
'module makeBackText () {',
' translate([0, brickWidth/2*UNIT_LENGTH-backTextBack-PLAY/2-tolerance, textZShift]) rotate([90, 0, 180])',
' linear_extrude(textDepth+fudge) text(backText, font=selectedFont, size=textSize*backTextScale, halign="center", spacing=letterSpacing);',
'}',
'module makeLeftText () {',
' translate([-brickLength/2*UNIT_LENGTH+leftTextBack+PLAY/2+tolerance, 0, textZShift]) rotate([90, 0, 270])',
' linear_extrude(textDepth+fudge) text(leftText, font=selectedFont, size=textSize*leftTextScale, halign="center", spacing=letterSpacing);',
'}',
'module makeRightText () {',
' translate([brickLength/2*UNIT_LENGTH-rightTextBack-PLAY/2-tolerance, 0, textZShift]) rotate([90, 0, 90])',
' linear_extrude(textDepth+fudge) text(rightText, font=selectedFont, size=textSize*rightTextScale, halign="center", spacing=letterSpacing);',
'}',
]
# Top-level geometry (copied, unchanged)
lines += [
'difference() {',
' union() {',
' translate([-brickLength/2*UNIT_LENGTH, -brickWidth/2*UNIT_LENGTH, 0])',
' brick (brickLength, brickWidth, brickHeight);',
' if (frontTextType == "raised") makeFrontText();',
' if (backTextType == "raised") makeBackText();',
' if (leftTextType == "raised") makeLeftText();',
' if (rightTextType == "raised") makeRightText();',
' }',
' if (frontTextType == "recessed") makeFrontText();',
' if (backTextType == "recessed") makeBackText();',
' if (leftTextType == "recessed") makeLeftText();',
' if (rightTextType == "recessed") makeRightText();',
'}',
]
scad_wrapper.write_text("\n".join(lines), encoding="utf-8")
def main():
import argparse
ap = argparse.ArgumentParser(description="Generate LEGO text brick STLs from a CSV using OpenSCAD.")
ap.add_argument("--csv", required=True, help="CSV with columns: Vorname,Nachname,OE")
ap.add_argument("--template", required=True, help="Path to LEGOTextBrick-v2p1.scad")
ap.add_argument("--outdir", required=True, help="Output directory for STL files")
ap.add_argument("--openscad", default="openscad", help="Path to OpenSCAD executable (prefer openscad.com on Windows)")
ap.add_argument("--keep-scad", action="store_true", help="Keep generated wrapper .scad files")
args = ap.parse_args()
csv_path = Path(args.csv)
template = Path(args.template)
outdir = Path(args.outdir); outdir.mkdir(parents=True, exist_ok=True)
wrapdir = outdir / "_wrappers"; wrapdir.mkdir(parents=True, exist_ok=True)
with csv_path.open(newline="", encoding="utf-8-sig") as f:
reader = csv.DictReader(f)
required = {"Vorname", "Nachname", "OE"}
missing = required - set(reader.fieldnames or [])
if missing:
sys.exit(f"CSV missing columns: {', '.join(sorted(missing))}")
for row in reader:
fn = (row.get("Vorname") or "").strip()
ln = (row.get("Nachname") or "").strip()
org = (row.get("OE") or "").strip()
if not (fn and ln and org):
print(f"Skipping incomplete row: {row}", file=sys.stderr)
continue
basename = safe_name(org, ln, fn)
wrapper = wrapdir / f"{basename}.scad"
write_wrapper(wrapper, template, row)
out_stl = outdir / f"{basename}.stl"
try:
# On Windows, using openscad.com is recommended for CLI usage.
subprocess.run([str(args.openscad), "-o", str(out_stl), str(wrapper)], check=True)
print(f"OK: {out_stl}")
if not args.keep_scad:
try: wrapper.unlink()
except OSError: pass
except subprocess.CalledProcessError as e:
print(f"OpenSCAD failed for {basename}: {e}", file=sys.stderr)
if not args.keep_scad:
try: wrapdir.rmdir()
except OSError: pass
if __name__ == "__main__":
main()