forked from Joshua-Nti/Topography_Automation
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_00all.py
More file actions
310 lines (259 loc) · 9.76 KB
/
_00all.py
File metadata and controls
310 lines (259 loc) · 9.76 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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
# _00all.py
import sys
import os
import time
import shutil
from _01analysestl import analyseSTL
from _02cutstl import cutSTL
from _03refinemesh import refineMesh
from _04transformstl import transformSTL
from _05execslicer import execSlicer
from _06transformgcode import transformGCode
from _07combine import combineGCode
from _08movegcode import moveGCode
from _10config import (
make_folder_dict,
GEOMETRY_CONFIG,
PIPELINE_CONFIG,
ANALYSE_STL,
)
# default entry if user doesn't pass an STL
# You can override this via ANALYSE_STL['input_stl'] in _10config.py
in_file = ANALYSE_STL.get("input_stl", "test.stl")
def sliceTransform(folder, filename, bottom=False, top=False, transform_flag=True):
"""
Process a single STL part file:
- refine mesh
- apply transform if tf_surface exists
- slice with SuperSlicer
- backtransform/slowdown G-code if nonplanar OR if config says so
"""
base_no_ext, ext = os.path.splitext(filename)
if ext.lower() == ".stl":
part_name = base_no_ext
elif ext == "":
part_name = filename
else:
print(f"skip {filename}: not an STL")
return
stl_parts_path = os.path.join(folder["stl_parts"], part_name + ".stl")
tf_surfaces_path = os.path.join(folder["tf_surfaces"], part_name + ".stl")
stl_tf_path = os.path.join(folder["stl_tf"], part_name + ".stl")
gcode_tf_path = os.path.join(folder["gcode_tf"], part_name + ".gcode")
gcode_parts_path = os.path.join(folder["gcode_parts"], part_name + ".gcode")
# A part is considered "nonplanar" if it is marked in cuts.txt (transform_flag)
# AND there is a matching transform surface STL.
is_nonplanar = bool(transform_flag) and os.path.exists(tf_surfaces_path)
# Step 1: refine mesh if we are going to transform
# (We keep the same logic you had: refine only for nonplanar parts,
# because planar parts don't need dense tessellation.)
if is_nonplanar:
print(" refining mesh:", stl_parts_path)
refineMesh(stl_parts_path, GEOMETRY_CONFIG["refine_edge_length_mm"])
# Step 2: apply nonplanar transform
print(" transforming STL using tf_surface:", tf_surfaces_path)
transformSTL(stl_parts_path, tf_surfaces_path, folder["stl_tf"])
# Step 3: slice transformed STL -> gcode_tf
print(" slicing transformed part:", part_name)
execSlicer(
in_file=stl_tf_path,
out_file=gcode_tf_path,
bottom_stl=bottom,
top_stl=top,
transformed=True,
)
# Step 4: backtransform & slowdown -> gcode_parts
print(" backtransform + slowdown:", part_name)
_backtransform_and_slowdown(
gcode_tf_path,
tf_surfaces_path,
folder["gcode_parts"],
stl_parts_path,
)
else:
# Planar path
print(" slicing planar part:", part_name)
execSlicer(
in_file=stl_parts_path,
out_file=gcode_parts_path,
bottom_stl=bottom,
top_stl=top,
transformed=False,
)
# Optionally also run backtransform/slowdown for planar parts if requested
if PIPELINE_CONFIG["apply_backtransform_to_planar"]:
print(" (config) also applying slowdown to planar part:", part_name)
_backtransform_and_slowdown(
gcode_parts_path, # input is already planar G-code
tf_surfaces_path, # might not exist for planar -> you’d adapt if needed
folder["gcode_parts"],
coarse_stl_path,
)
def _backtransform_and_slowdown(
gcode_in,
tf_surface_stl,
out_dir,
coarse_surface_for_slowdown,
):
"""
Helper to call transformGCode() using GEOMETRY_CONFIG.
This wraps all those numeric knobs in one place.
"""
max_seg_len = GEOMETRY_CONFIG["maximal_segment_length_mm"]
down_angle = GEOMETRY_CONFIG["downward_angle_deg"]
slow_feed = GEOMETRY_CONFIG["slow_feedrate_mm_per_min"]
medium_feed = GEOMETRY_CONFIG["medium_feedrate_mm_per_min"]
z_min = GEOMETRY_CONFIG["z_desired_min_mm"]
xy_shift_x, xy_shift_y = GEOMETRY_CONFIG["xy_backtransform_shift_mm"]
transformGCode(
in_file=gcode_in,
in_transform_for_interp=tf_surface_stl,
out_dir=out_dir,
surface_for_slowdown=coarse_surface_for_slowdown,
maximal_length=max_seg_len,
x_shift=xy_shift_x,
y_shift=xy_shift_y,
z_desired=z_min,
downward_angle_deg=down_angle,
slow_feedrate=slow_feed,
medium_feedrate=medium_feed
)
def sliceAll(folder, segments_to_transform=None):
"""
Go through all stl_parts/*.stl in sort order.
Mark first as bottom=True, last as top=True,
pass flags forward.
"""
parts = [
f for f in os.listdir(folder["stl_parts"])
if f.lower().endswith(".stl") and not f.startswith(".")
]
parts.sort()
if not parts:
print("No STL parts found.")
return
for idx, stlfile in enumerate(parts):
bottom_flag = (idx == 0)
top_flag = (idx == len(parts) - 1)
seg_index = idx + 1 # segments are numbered 1..N in cuts.txt
# Decide whether this segment should be treated as nonplanar
if segments_to_transform is None:
transform_flag = True
else:
transform_flag = str(seg_index) in segments_to_transform
print(
"Processing:", stlfile,
"| index =", seg_index,
"| bottom =", bottom_flag,
"| top =", top_flag,
"| transform =", transform_flag,
)
sliceTransform(
folder,
stlfile,
bottom=bottom_flag,
top=top_flag,
transform_flag=transform_flag,
)
def read_segments_to_transform(cuts_file):
"""Read cuts.txt and return list of segment IDs where flag == '1'.
Expected file format per line:
<segment_index> <flag> <z_value>
Example:
1 0 20.0000
2 1 30.0000
3 1 37.6410
4 1 45.3000
5 1 TOP
"""
segments = []
if not os.path.exists(cuts_file):
print(f"[read_segments_to_transform] WARNING: file not found: {cuts_file}")
return segments
with open(cuts_file, "r") as f:
for line in f:
parts = line.split()
if len(parts) >= 2 and parts[1] == "1":
segments.append(parts[0])
print(f"[read_segments_to_transform] Segments to transform: {segments}")
return segments
def createFoldersIfMissing(folder_dict):
"""
Ensure all working directories exist.
"""
for key in folder_dict:
p = folder_dict[key]
if not os.path.exists(p):
os.makedirs(p, exist_ok=True)
def main(input_stl):
"""
Full pipeline:
1. Build folder layout
2. Analyse STL -> cuts.txt
3. Copy STL into work dir, run cutSTL() to produce stl_parts
4. sliceAll() -> slice each part (nonplanar or planar)
5. combineGCode() merges all part G-codes
6. moveGCode() shifts final merged toolpath on the bed (optional)
"""
base_name = os.path.splitext(os.path.basename(input_stl))[0]
folders = make_folder_dict(base_name)
print("Create folders if missing …")
t0 = time.time()
createFoldersIfMissing(folders)
cuts_txt_path = os.path.join(folders["root"], "cuts.txt")
working_input_stl = os.path.join(folders["root"], base_name + ".stl")
# Analyse STL (if we don't have cuts already)
if not os.path.exists(cuts_txt_path):
print("Analyse STL to determine cut heights …")
analyseSTL(input_stl, cuts_txt_path)
# Copy the input STL into working root (if config says so)
if PIPELINE_CONFIG["copy_input_to_work"]:
print("Copy input STL into working root …")
shutil.copy(input_stl, working_input_stl)
stl_for_cutting = working_input_stl
else:
stl_for_cutting = input_stl
# Cut STL into individual vertical segments -> stl_parts/
print("Cut STL into vertical parts …")
cutSTL(
in_stl=stl_for_cutting,
cuts_file=cuts_txt_path,
out_folder=folders["stl_parts"],
)
# Determine which segments should be transformed (from cuts.txt)
print("Read segments to transform from cuts.txt …")
segments_to_transform = read_segments_to_transform(cuts_txt_path)
# Slice all parts (and transform/backtransform where needed)
print("Slice all parts …")
sliceAll(folders, segments_to_transform=segments_to_transform)
# Combine final segments' G-code into one combined file
combined_gcode_path = os.path.join(folders["root"], base_name + ".gcode")
print("Combine G-code parts …")
combineGCode(
in_folder=folders["gcode_parts"],
out_file=combined_gcode_path,
)
# Optionally apply final XY shift
if PIPELINE_CONFIG["apply_final_shift"]:
print("Apply final XY shift to merged G-code …")
x_off, y_off = PIPELINE_CONFIG["final_shift_xy_mm"]
# place the shifted file in the SAME directory as the input STL (one level above 'test/')
project_root = os.path.dirname(folders["root"])
shifted_gcode_path = os.path.join(project_root, base_name + "_moved.gcode")
moveGCode(
in_file=combined_gcode_path,
out_file=shifted_gcode_path,
x_off=x_off,
y_off=y_off,
)
print("Shifted G-code:", shifted_gcode_path)
else:
print("Skipping final XY shift (config).")
dt = time.time() - t0
print("Pipeline finished in {:.1f}s".format(dt))
print("Combined (unshifted):", combined_gcode_path)
if __name__ == "__main__":
stl_arg = in_file
if len(sys.argv) > 1:
stl_arg = sys.argv[1]
main(stl_arg)