-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.py
executable file
·676 lines (637 loc) · 21 KB
/
main.py
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
#!/usr/bin/env python3
# OPENSCAD_PATH = "P:/Program Files/OpenSCAD/openscad.com"
# If you keep OpenSCAD in an unusual location, uncomment the above line of code and
# set it to the full path to the openscad executable.
# Note: Windows/python now support forward-slash characters in paths, so please use
# those instead of backslashes which create a lot of confusion in code strings.
# do not edit below unless you know what you are doing!
import os
import configparser
import platform
from shutil import copy, rmtree
import shlex
import random as rd
import time
import numpy as np
import math
import re
from PIL import Image
import subprocess as sp
skip = -1 # debug: skip all shells up to here (0 to n to enable)
halt = -1 # debug: terminate skipping this shell (0 to n to enable)
USE_SCAD_THREAD_TRAVERSAL = False
STL_DIR = "_files"#name gets tacked on later...
PREV_DIR = "maze_previews"
#tries to get the path to openscad
def openscad():
try:
if OPENSCAD_PATH:
return OPENSCAD_PATH
except NameError:
pass
if os.getenv("OPENSCAD_PATH"):
return os.getenv("OPENSCAD_PATH")
if platform.system() == "Darwin":
return "/Applications/OpenSCAD.app/Contents/MacOS/OpenSCAD"
if platform.system() == "Windows":
# Note: Windows allows forward slashes now
return "C:/Program Files/OpenSCAD/openscad.com"
# Default to linux-friendly CLI program name
return "openscad"
#prepares folders
def prepwd():
# Linux and other systems that use PATH variables don't need an absolute path configured.
# if os.path.exists(openscad_exe) == False:
# input("ERROR: openscad path not found.")
# exit()
if os.path.exists(STL_DIR):
rmtree(STL_DIR)
os.mkdir(STL_DIR) # Default perms: world-writable
if os.path.exists(PREV_DIR):
rmtree(PREV_DIR)
os.mkdir(PREV_DIR) # Default perms: world-writable
#checks threading availability
def has_scad_threading():
cmd = [openscad(), "--help"]
out = str(sp.check_output(cmd)).lower()
if "--parallelism" in out:
return True
return False
#checks version
def scad_version():
cmd = [openscad(), "--version"]
ver=sp.Popen(cmd,stdout=sp.PIPE).stdout.readline().decode("utf-8")
ver=ver.replace("\r","").replace("\n","").replace("-",".").replace("OpenSCAD version ","").split(".")
for v in range(len(ver)):
ver[v]=re.sub('[^0-9]','', ver[v])
return int(ver[0]) if ver else ()
#runs the scad
def execscad(threadid=0):
global ext
print("Executing OpenSCAD script...")
cmd = [openscad()]
if USE_SCAD_THREAD_TRAVERSAL:
cmd.append("--enable=thread-traversal")
cmd.extend(
[
"-o",
os.path.join(os.getcwd(), STL_DIR, name + "_" + str(shell + 1) + "." + ext),
os.path.join(os.getcwd(), "make_shells.scad"),
]
)
sp.run(cmd)
#updates the possible ways to cut the maze
def udnbers(n, vi, nc, mw, mh, stag):
#with every tile
for y in range(0, mh):
for x in range(0, mw):
#shift the vertical edge
x3 = int((x + stag[y]) % mw)
#next tile coords
x2 = [x - 1, x + 1, x, x]
y2 = [y, y, y - 1, y + 1]
#look arround
for i in range(0, 4):
#did we shift the edge?
if stag[y] % mw > 0:
#shift the next tile coords too
x2[i] = int((x2[i] + mw) % mw)
else:
#constrain to bounds otherwise
if x2[i] < 0:
x2[i] = 0
if x2[i] > mw - 1:
x2[i] = mw - 1
#is this cuttable and not out of bounds?
if (
not ((x3 == 0 and i == 0) or (x3 == mh - 1 and i == 1))
and y2[i] > -1
and y2[i] < mh
):
#mark cuttable if we have not been there
n[x, y, i] = vi[int(x2[i]), int(y2[i])] == 0
else:
#mark not cuttable
n[x, y, i] = 0
#update count of cuttable tiles
nc[x, y] = len(np.argwhere(n[x, y].astype("int")))
#makes a maze
def genmaze(mw, mh, stag):
#where we have cut a path already
visited = np.zeros(mw * mh)
#number of possible ways to cut
nbercount = np.zeros(mw * mh)
#possible ways to cut
nbers = np.ones(mw * mh * 4)
#walls of the maze tiles
# walls are: 0=L 1=R 2=U 3=D
walls = np.ones(mw * mh * 4,dtype="int")
#start here
r = rd.randint(0, mw*mh-1)
#mark start as visited
#number of places we have cut a path already
vcount = 1
visited[r] = 1
#to make things easier
visited = visited.reshape([mw, mh])
nbers = nbers.reshape([mw, mh, 4])
nbercount = nbercount.reshape([mw, mh])
walls = walls.reshape([mw, mh, 4])
#update the possible ways to cut
udnbers(nbers, visited, nbercount, mw, mh, stag)
#loop until maze is completed
while vcount < (mw * mh):
#all places we can continue cutting
v = np.transpose(np.nonzero(np.logical_and(visited == 1, nbercount > 0)))
# choose a tile to cut from
if len(v) < 2:
r=0
else:
r = rd.randint(0, len(v) - 1)
c = v[r]
#keep cutting until can't or min_branch is reached
for i in range(min_branch):
# choose wall to cut
r = rd.randint(0, nbercount[c[0], c[1]] - 1)
n = np.argwhere(nbers[c[0], c[1]])[r]
# cut the wall
walls[c[0], c[1], n] = 0
#temp for the tile we are cutting
c2 = c
#the other side of the wall
if n == 0:
n2 = 1
c2[0] = c[0] - 1
elif n == 1:
n2 = 0
c2[0] = c[0] + 1
elif n == 2:
n2 = 3
c2[1] = c[1] - 1
else:
n2 = 2
c2[1] = c[1] + 1
#wrap horizontally
c2[0] = int((c2[0] + mw) % mw)
#mark as visited
visited[c2[0], c2[1]] = 1
#cut the other side
walls[c2[0], c2[1], n2] = 0
#update the possible ways to cut again
udnbers(nbers, visited, nbercount, mw, mh, stag)
#update the number of places we have cut a path already
vcount = np.sum(visited,dtype="int")
#prepare cut again...
c=c2
#...if we can. otherwise break the for.
if nbercount[c[0],c[1]]==0:
break
return walls
#makes and writes the preview image
def preview(maze):
#a new image
im = Image.new("L", [2 * mw + 1, 2 * mh + 1], 0)
#start and end
im.putpixel((1 + ex * 2, 0), 255)#end
im.putpixel((1 + st * 2, mh * 2), 255)#start
for y in range(0, mh):
for x in range(0, mw):
#tile pos
imx = 1 + x * 2
imy = 1 + y * 2
#wall pixel coords
imnx = [imx - 1, imx + 1, imx, imx]
imny = [imy, imy, imy - 1, imy + 1]
#center of tile
im.putpixel((imx, imy), 255)
#check walls
for idx in range(0, 4):
#no wall?
if maze[x, y, idx] == 0:
#cut a hole!
im.putpixel((imnx[idx], imny[idx]), 255)
#fill in answer key
ans=ans_solver(maze,st,ex)
for y in range(0, mh):
for x in range(0, mw):
imx = 1 + x * 2
imy = 1 + y * 2
if [x,y] in ans:
im.putpixel((imx, imy), 128)
else:
im.putpixel((imx, imy), 255)
#transition shell maze 2?
if tpp == 2:
#save as maze 2
im.save(os.path.join(os.getcwd(), PREV_DIR, str(shell + 1) + "a.png"))
else:
#save as maze 1
im.save(os.path.join(os.getcwd(), PREV_DIR, str(shell + 1) + ".png"))
#for ans key in previews
def ans_solver(maze,s,e):
ret=[[s,mh],[s,mh-1]]
direction=1#r,u,l,d
x=s
y=mh-1
direction2wall=[1,2,0,3]#r,u,l,d -> l,r,u,d
direction2xy=[[1,0],[0,-1],[-1,0],[0,1]]#r,u,l,d
while x!=e or y>0:
#walls at x,y in the maze
here=maze[x,y]
#print(x,y,direction,4-np.sum(here))
if here[direction2wall[(direction+3)%4]]==0:
direction=(direction+3)%4
#change direction until no wall in case of front wall
if here[direction2wall[direction]]==1:
while here[direction2wall[direction]]==1:
#change direction
#print(direction,here[direction2wall[direction]])
direction=(direction+1)%4
x=(x+direction2xy[direction][0]+mw)%mw
y=y+direction2xy[direction][1]
#are we backtracking?
if x==ret[-2][0] and y==ret[-2][1]:
ret=ret[0:-1]
#print("backtracking")
else:
ret.append([x,y])
#print(ret)
return ret[1:]
#finds the lengths from a start to all ends of a maze
def solver(maze,s):
#start here
branches=[[s,mh-1,0,0,4]]#x,y,length,downcnt,last
#return value
ret=[]
#loop until return value is full
while len(ret)<mw:
#temporarlily store new branches here
temp=[]
#loop through all current branches
for branch in branches:
x=branch[0]
y=branch[1]
length=branch[2]
#count for how many times we go down toward start
downcnt=branch[3]
#must not back track.
last=branch[4]
#walls at x,y in the maze
here=maze[x,y]
#how many openings at x,y in maze
opencnt=4-np.sum(here)
#is this a posible end?
if y==0:
#include this length in return value.
ret.append(length)
#can we move on?
if opencnt>0:
#move on but do not bactrack.
if here[0]==0 and last!=0:
#left
temp.append([(x+mw-1)%mw,y,length+1,downcnt,1])
if here[1]==0 and last!=1:
#right
temp.append([(x+1)%mw,y,length+1,downcnt,0])
if here[2]==0 and last!=2:
#up
temp.append([x,y-1,length+1,downcnt,3])
if here[3]==0 and last!=3:
#down
temp.append([x,y+1,length+1,downcnt+1,2])
#copy the new branches over the old branches
branches=temp.copy()
return ret
#chooses a maze path (start and end) based on difficulty
def choose_path(maze):
global st
global ex
#get path lengths...
lengths=[]
for s in range(mw):
#find the lengths from this start to all ends
lengths.append(solver(maze,s))
#get sorted indexes
sortedlengthidxs=np.argsort(np.asarray(lengths).flatten())
#choose one
chosen=sortedlengthidxs[int(difficulty/101*len(sortedlengthidxs))]
#assign start and end
st=chosen//mw#start
ex=chosen%mw#end
#make and write preview image
preview(maze)
#makes parts
def gen():
global shell
global d2
global mh
global mw
global i
global tpp
global maze_data
#are we done yet?
if shell < shells:
#debug halt
if shell >= halt and halt > -1:
return True
#is the next shell the transition?
if shell + 1 < shells and shell + 1 == tp and tpp < 1:
tpp = -1
#part status
if tpp < 1:
print("part: " + str(shell + 1))
#wall thickness
wt = mwt
#are we not in transitioning stage 2?
if tpp < 1:
#is this the first?
if shell == 0:
#set the diameter
d = (mw * us * p) / np.pi / 2 - wt - marge * 2
print("diameter:",d)
else:
#are we transitioning?
if shell == tp:
#keep the diameter the same
d = d2
elif (shell+1 == shells and shells==2):
d = d2 + us * td / 2 + wt + marge * 2
else:
#set the diameter
d = d2 + us * td + wt + marge * 2
print("diameter:",d)
#is the maze on the outside?
if i == 0:
#set the maze width
mw = int(math.ceil((d + us) * np.pi / us / p))
else:
#set the maze width
mw = int(math.ceil((d + us) * np.pi / us / p ))
#fix for tpp=1 (maze outside to inside)
if (shell!=tp or i==1):
#increase maze height
mh += 1
#extra height for lid
if shell+1==shells:
mh += 1
else:
#set the diameter
d = d2 + us * td + wt + marge * 2
print("diameter:",d)
#set the maze width
mw = int(math.ceil((d + us) * np.pi / us / p))
#fix for tpp=1 (maze outside to inside)
if tpp==2:
#increase maze height
mh += 1
# shift
stag = np.zeros(mh)
#is it a random shift?
if stagmode in (1, 2):
#loop through y
for y in range(0, mh):
#are we at end or shift mode is random?
if y == 0 or stagmode == 1:
#random shift
stag[y] = rd.randint(0, mh - 1)
else:
#random shift offset
stag[y] = stag[y - 1] + rd.randint(0, mh - 1)
#is it a twist shift?
elif stagmode == 3:
#twist it!
stag = np.multiply(np.arange(0, mh), stagconst).astype("int")
#do we even have a maze with this part?
if ((i == 0 and shell < shells - 1) or (i == 1 and shell > 0)) and tpp != 1:
# maze
marr = genmaze(int(mw), int(mh), stag)
#get the path we want
choose_path(marr)
#convert to string
matrix = []
for y in range(0, mh):
row = []
for x in range(0, mw * p):
x2 = x % mw
r = marr[x2, y, 1] == 0
u = marr[x2, y, 3] == 0
if u and r:
row.append("3")
elif u:
row.append("2")
elif r:
row.append("1")
else:
row.append("0")
matrix.append(",".join(row))
s = "[["+"],[".join(matrix)+"]];"
else:
#empty maze
s="[];"
#write the maze
if tpp < 1:
maze_num = 1
maze_data="\n".join(["maze"+str(maze_num)+"="+s,
"h"+str(maze_num)+"="+str(mh)+";",
"w"+str(maze_num)+"="+str(mw*p)+";",
"st"+str(maze_num)+"="+str(st)+";",
"ex"+str(maze_num)+"="+str(ex)+";",
""])
else:
maze_num = 2
maze_data+="\n".join(["maze"+str(maze_num)+"="+s,
"h"+str(maze_num)+"="+str(mh)+";",
"w"+str(maze_num)+"="+str(mw*p)+";",
"st"+str(maze_num)+"="+str(st)+";",
"ex"+str(maze_num)+"="+str(ex)+";",
""])
#non lid
base = 1
lid = 0
#is it the lid?
if shell > shells - 2:
#lid
lid = 1
base = 0
#no more to go
#how many are left to go
mos = shells - shell - 2
with open("shell_data.scad", "w") as shell_data:
shell_data.write(opt+"\n".join(["p="+str(p)+";",
"tpp="+str(tpp)+";",
"is="+str(shell)+";",
"os="+str(mos)+";",
"lid="+str(lid)+";",
"base="+str(base)+";",
"iw="+str(wt)+";",
"id="+str(d)+";",
"s="+str(us)+";",
"td="+str(td)+";",
"i="+str(i)+";",
"bd="+str(d + wt * 2 + us * td * 2)+";",
"m="+str(marge)+";",
""])+maze_data
)
#save diameter of this one for later
if shell < shells - 2:
d2 = d
#was this the transition shell?
if shell > 0 and shell < shells-1 and shell == tp and tpp < 1:
#get ready for transition stage 2
if i == 0: # double nub transition
tpp = 1
i = 1
else: # double maze transition
tpp = 2
i = 0
else:
tpp = 0
#are we done with this shell?
if tpp < 1:
#make it!
#debug skip
if shell >= skip or skip < 0:
execscad()
#on to the next
shell = shell + 1
#not done making parts
return False
else:
#all done!
return True
#reads opt.ini
def readOpt():
global shells
global marge
global us
global mh
global mw
global mwt
global i
global p
global tp
global STL_DIR
global stagmode
global stagconst
global difficulty
global min_branch
global ext
global name
global opt
global td
config = configparser.ConfigParser()
config.read("opt.ini")
if "DEFAULT" not in config or "MAZE" not in config:
print("ERROR: No DEFAULT and/or MAZE section in opt.ini; Must have both.\n")
exit(1)
mazeconfig=config["MAZE"]
looksconfig=config["LOOKS"]
embossconfig=config["EMBOSS"]
config = config["DEFAULT"]
version = scad_version()
if config.getboolean("o3mf") and version>=2019:
ext="3mf"
else:
ext="stl"
p = abs(config.getint("nubs")-2) + 2
shells = config.getint("levels") + 1
marge = config.getfloat("tolerance")
i = int(config.getboolean("maze_inside"))
us = config.getfloat("spacing")
td = config.getfloat("td")
if td<1.0:
td=1.0
if td>2.0:
td=2.0
mh = config.getint("units_tall")
mw = config.getint("units_wide")
mwt = config.getfloat("wall_thickness")
name = config.get("name")
STL_DIR=name+STL_DIR
#maze options
#seeding...
seed=mazeconfig.get("seed").replace("\r","").replace("\n","")
if not seed.isnumeric() or "\\" in seed or "." in seed:
# Make sure we have a fresh random seed
rd.seed()
else:
#use seed from ini
rd.seed(int(seed))
difficulty=abs(mazeconfig.getfloat("diff",100.0))
if difficulty>100:
difficulty=100
min_branch=mazeconfig.getint("min_branch",5)
if min_branch<1:
min_branch=5
stagmode = mazeconfig.getint("shift",1)
stagconst = 0
if stagmode == 3:
stagconst = abs(mazeconfig.getint("twist",1))
#options
opt=""
if looksconfig.getboolean("oldnubs",True):
opt+="oldnubs=1;\n"
else:
opt+="oldnubs=0;\n"
bs=looksconfig.getint("bs",10)
if bs<3:
bs=3
opt+="bs="+str(bs)+";\n"
bversion=abs(looksconfig.getint("bversion",2))%3
opt+="bversion="+str(bversion)+";\n"
if looksconfig.getboolean("lefty",True):
opt+="lefty=1;\n"
else:
opt+="lefty=0;\n"
#emboss
if embossconfig.getboolean("ense",True):
opt+="ense=1;\n"
else:
opt+="ense=0;\n"
opt+='se="'+embossconfig.get("se").replace('"','')+'";\n'
be=embossconfig.get("be").replace('"','')
if embossconfig.getboolean("enbe",True):
opt+="enbe=1;\n"
shells=len(be)
if embossconfig.getboolean("emboss_inside_only",True):
shells+=2
if shells==0:
shells+=2
if shells==1:
shells+=1
else:
opt+="enbe=0;\n"
opt+='be="'+be+'";\n'
tp = config.getint("transition_shell")
if tp > shells-1 or tp < 1:
tp = -1
if __name__ == "__main__":
#read opt.ini
opt=""
readOpt()
try:
#prep folders
prepwd()
# get scad version:
version = scad_version()
if version < 2015:
print("ERROR: invalid scad version. must be at least 2015.xx.xx .\n")
exit(1)
#do we have threading?
if has_scad_threading():
USE_SCAD_THREAD_TRAVERSAL = (
input("multi-threading available. use it(y/n)?").lower() == "y"
)
except FileNotFoundError:
print("ERROR: Could not find OpenSCAD: " + openscad()+"\n")
exit(1)
#init vars
st=0
ex=0
d2 = 0
shell = 0
tpp = 0
# make parts:
while not gen():
continue
print("done!")