-
Notifications
You must be signed in to change notification settings - Fork 6
/
importAltCSG.py
1528 lines (1408 loc) · 52.7 KB
/
importAltCSG.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
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf8 -*-
#***************************************************************************
#* *
#* Copyright (c) 2012 Keith Sloan <[email protected]> *
#* *
#* This program is free software; you can redistribute it and/or modify *
#* it under the terms of the GNU Lesser General Public License (LGPL) *
#* as published by the Free Software Foundation; either version 2 of *
#* the License, or (at your option) any later version. *
#* for detail see the LICENCE text file. *
#* *
#* This program is distributed in the hope that it will be useful, *
#* but WITHOUT ANY WARRANTY; without even the implied warranty of *
#* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
#* GNU Library General Public License for more details. *
#* *
#* You should have received a copy of the GNU Library General Public *
#* License along with this program; if not, write to the Free Software *
#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
#* USA *
#* *
#* Acknowledgements : *
#* *
#* Thanks to shoogen on the FreeCAD forum and Peter Li *
#* for programming advice and some code. *
#* *
#* *
#***************************************************************************
__title__="FreeCAD OpenSCAD Workbench - CSG importer"
__author__ = "Keith Sloan <[email protected]>"
__url__ = ["http://www.sloan-home.co.uk/ImportCSG"]
import FreeCAD, Part, Draft, io, os, sys, xml.sax
if FreeCAD.GuiUp:
import FreeCADGui
gui = True
else:
print("FreeCAD Gui not present.")
gui = False
# Save the native open function to avoid collisions
if open.__module__ in ['__builtin__', 'io']:
pythonopen = open
import ply.lex as lex
import ply.yacc as yacc
import Part
import random
import OpenSCADFeatures
import OpenSCADUtils
import OpenSCADHull
import OpenSCADMinkowski
params = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/OpenSCAD")
printverbose = params.GetBool('printverbose',False)
print(f'Verbose = {printverbose}')
#print(params.GetContents())
#printverbose = True
# Get the token map from the lexer. This is required.
import tokrules
from tokrules import tokens
try:
from PySide import QtGui
_encoding = QtGui.QApplication.UnicodeUTF8
def translate(context, text):
"convenience function for Qt translator"
from PySide import QtGui
return QtGui.QApplication.translate(context, text, None, _encoding)
except AttributeError:
def translate(context, text):
"convenience function for Qt translator"
from PySide import QtGui
return QtGui.QApplication.translate(context, text, None)
def num(string) :
try :
v = int(string)
except :
v = float(string)
return v
def open(filename):
"called when freecad opens a file."
global doc
global pathName
FreeCAD.Console.PrintMessage('Processing : '+filename+'\n')
docname = os.path.splitext(os.path.basename(filename))[0]
doc = FreeCAD.newDocument(docname)
if filename.lower().endswith('.scad'):
from OpenSCADUtils import callopenscad, workaroundforissue128needed
print('Calling OpenSCAD')
tmpfile=callopenscad(filename)
if workaroundforissue128needed():
pathName = '' #https://github.com/openscad/openscad/issues/128
#pathName = os.getcwd() #https://github.com/openscad/openscad/issues/128
else:
pathName = os.path.dirname(os.path.normpath(filename))
processCSG(doc, tmpfile)
try:
os.unlink(tmpfile)
except OSError:
pass
else:
pathName = os.path.dirname(os.path.normpath(filename))
processCSG(doc, filename)
return doc
def insert(filename,docname):
"called when freecad imports a file"
global doc
global pathName
groupname = os.path.splitext(os.path.basename(filename))[0]
try:
doc=FreeCAD.getDocument(docname)
except NameError:
doc=FreeCAD.newDocument(docname)
#importgroup = doc.addObject("App::DocumentObjectGroup",groupname)
if filename.lower().endswith('.scad'):
from OpenSCADUtils import callopenscad, workaroundforissue128needed
tmpfile=callopenscad(filename)
if workaroundforissue128needed():
pathName = '' #https://github.com/openscad/openscad/issues/128
#pathName = os.getcwd() #https://github.com/openscad/openscad/issues/128
else:
pathName = os.path.dirname(os.path.normpath(filename))
print('Processing : '+filename)
processCSG(doc, tmpfile)
try:
os.unlink(tmpfile)
except OSError:
pass
else:
pathName = os.path.dirname(os.path.normpath(filename))
processCSG(doc, filename)
def processCSG(docSrc, filename, fnmax_param = None):
global doc
global fnmax
if fnmax_param is None:
fnmax = FreeCAD.ParamGet(\
"User parameter:BaseApp/Preferences/Mod/OpenSCAD").\
GetInt('useMaxFN', 16)
else:
fnmax = fnmax_param
doc = docSrc
print('Using Alternate OpenSCAD Importer')
print(f"Doc {doc.Name} useMaxFn {fnmax}")
#import tokrules
#from tokrules import tokens
#print(f"tokens {tokens}")
if printverbose: print ('ImportCSG Version 0.6a')
# Build the lexer
if printverbose: print('Start Lex')
lex.lex(module=tokrules)
if printverbose: print('End Lex')
# Build the parser
if printverbose: print('Load Parser')
# No debug out otherwise Linux has protection exception
parser = yacc.yacc(debug=False, write_tables=False)
if printverbose: print('Parser Loaded')
# Give the lexer some input
#f=open('test.scad', 'r')
f = io.open(filename, 'r', encoding="utf8")
#lexer.input(f.read())
if printverbose: print('Start Parser')
# Swap statements to enable Parser debugging
#result = parser.parse(f.read(),debug=1)
result = parser.parse(f.read())
f.close()
if printverbose:
print('End Parser')
print(result)
FreeCAD.Console.PrintMessage('End processing CSG file\n')
doc.recompute()
def p_block_list_(p):
'''
block_list : statement
| block_list statement
| statementwithmod
| block_list statementwithmod
'''
#if printverbose: print("Block List")
#if printverbose: print(p[1])
if(len(p) > 2) :
if printverbose: print(p[2])
p[0] = p[1] + p[2]
else :
p[0] = p[1]
#if printverbose: print("End Block List")
def p_render_action(p):
'render_action : render LPAREN keywordargument_list RPAREN OBRACE block_list EBRACE'
if printverbose: print("Render (ignored)")
p[0] = p[6]
def p_group_action1(p):
'group_action1 : group LPAREN RPAREN OBRACE block_list EBRACE'
if printverbose: print(f"Group : {p[5]}")
# Test if need for implicit fuse
if p[5] is None:
p[0] = []
return
if (len(p[5]) > 1) :
if printverbose: print('Fuse Group')
for obj in p[5]:
checkObjShape(obj)
p[0] = [fuse(p[5],"Group")]
else :
if printverbose: print(f"Group {p[5]} type {type(p[5])}")
checkObjShape(p[5])
p[0] = p[5]
def p_group_action2(p) :
'group_action2 : group LPAREN RPAREN SEMICOL'
if printverbose: print("Group2 Empty")
p[0] = []
def p_boolean(p) :
'''
boolean : true
| false
'''
p[0] = p[1]
#def p_string(p):
# 'string : QUOTE ID QUOTE'
# p[0] = p[2]
def p_stripped_string(p):
'stripped_string : STRING'
p[0] = p[1].strip('"')
def p_statement(p):
'''statement : part
| operation
| multmatrix_action
| group_action1
| group_action2
| color_action
| render_action
| not_supported
'''
p[0] = p[1]
def p_anymodifier(p):
'''anymodifier : MODIFIERBACK
| MODIFIERDEBUG
| MODIFIERROOT
| MODIFIERDISABLE
'''
#just return the plain modifier for now
#has to be changed when the modifiers are implemented
#please note that disabled objects usually are stripped of the CSG output during compilation
p[0] = p[1]
def p_statementwithmod(p):
'''statementwithmod : anymodifier statement'''
#ignore the modifiers but add them to the label
modifier = p[1]
obj = p[2]
if hasattr(obj,'Label'):
obj.Label = modifier + obj.Label
p[0] = obj
def p_part(p):
'''
part : sphere_action
| cylinder_action
| cube_action
| circle_action
| square_action
| text_action
| polygon_action_nopath
| polygon_action_plus_path
| polyhedron_action
'''
p[0] = p[1]
def p_2d_point(p):
'2d_point : OSQUARE NUMBER COMMA NUMBER ESQUARE'
global points_list
if printverbose: print("2d Point")
p[0] = [float(p[2]),float(p[4])]
def p_points_list_2d(p):
'''
points_list_2d : 2d_point COMMA
| points_list_2d 2d_point COMMA
| points_list_2d 2d_point
'''
if p[2] == ',' :
#if printverbose:
# print("Start List")
# print(p[1])
p[0] = [p[1]]
else :
if printverbose:
print(p[1])
print(p[2])
p[1].append(p[2])
p[0] = p[1]
#if printverbose: print(p[0])
def p_3d_point(p):
'3d_point : OSQUARE NUMBER COMMA NUMBER COMMA NUMBER ESQUARE'
global points_list
if printverbose: print("3d point")
p[0] = [p[2],p[4],p[6]]
def p_points_list_3d(p):
'''
points_list_3d : 3d_point COMMA
| points_list_3d 3d_point COMMA
| points_list_3d 3d_point
'''
if p[2] == ',' :
if printverbose: print("Start List")
if printverbose: print(p[1])
p[0] = [p[1]]
else :
if printverbose: print(p[1])
if printverbose: print(p[2])
p[1].append(p[2])
p[0] = p[1]
if printverbose: print(p[0])
def p_path_points(p):
'''
path_points : NUMBER COMMA
| path_points NUMBER COMMA
| path_points NUMBER
'''
#if printverbose: print("Path point")
if p[2] == ',' :
#if printverbose: print('Start list')
#if printverbose: print(p[1])
p[0] = [int(p[1])]
else :
#if printverbose: print(p[1])
#if printverbose: print(len(p[1]))
#if printverbose: print(p[2])
p[1].append(int(p[2]))
p[0] = p[1]
#if printverbose: print(p[0])
def p_path_list(p):
'path_list : OSQUARE path_points ESQUARE'
#if printverbose: print('Path List ')
#if printverbose: print(p[2])
p[0] = p[2]
def p_path_set(p) :
'''
path_set : path_list
| path_set COMMA path_list
'''
#if printverbose: print('Path Set')
#if printverbose: print(len(p))
if len(p) == 2 :
p[0] = [p[1]]
else :
p[1].append(p[3])
p[0] = p[1]
#if printverbose: print(p[0])
def p_operation(p):
'''
operation : difference_action
| intersection_action
| union_action
| rotate_extrude_action
| linear_extrude_with_transform
| rotate_extrude_file
| import_file1
| surface_action
| projection_action
| hull_action
| minkowski_action
| offset_action
| resize_action
'''
p[0] = p[1]
def placeholder(name,children,arguments):
from OpenSCADFeatures import OpenSCADPlaceholder
newobj=doc.addObject("Part::FeaturePython",name)
OpenSCADPlaceholder(newobj,children,str(arguments))
if gui:
if FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/OpenSCAD").\
GetBool('useViewProviderTree'):
from OpenSCADFeatures import ViewProviderTree
ViewProviderTree(newobj.ViewObject)
else:
newobj.ViewObject.Proxy = 0
#don't hide the children
return newobj
def CGALFeatureObj(name,children,arguments=[]):
myobj=doc.addObject("Part::FeaturePython",name)
from OpenSCADFeatures import CGALFeature
CGALFeature(myobj,name,children,str(arguments))
if gui:
for subobj in children:
subobj.ViewObject.hide()
if FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/OpenSCAD").\
GetBool('useViewProviderTree'):
from OpenSCADFeatures import ViewProviderTree
ViewProviderTree(myobj.ViewObject)
else:
myobj.ViewObject.Proxy = 0
return myobj
def p_offset_action(p):
'offset_action : offset LPAREN keywordargument_list RPAREN OBRACE block_list EBRACE'
# print('Offset Action')
# print(len(p))
# print(f'p6 : {p[6]}')
if len(p[6]) == 0:
newobj = placeholder('group',[],'{}')
elif (len(p[6]) == 1 ): #single object
subobj = p[6][0]
else:
subobj = fuse(p[6],"Offset Union")
if 'r' in p[3] :
offset = float(p[3]['r'])
if 'delta' in p[3] :
offset = float(p[3]['delta'])
#print(subobj.Shape)
#print(dir(subobj.Shape))
#print(subobj.Shape.ShapeType)
checkObjShape(subobj)
if subobj.Shape.Volume == 0 :
newobj=doc.addObject("Part::Offset2D",'Offset2D')
newobj.Source = subobj
newobj.Value = offset
if 'r' in p[3] :
newobj.Join = 0
else :
newobj.Join = 2
else :
newobj=doc.addObject("Part::Offset",'offset')
newobj.Shape = subobj[0].Shape.makeOffset(offset)
newobj.Document.recompute()
if gui:
subobj.ViewObject.hide()
# if FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/OpenSCAD").\
# GetBool('useViewProviderTree'):
# from OpenSCADFeatures import ViewProviderTree
# ViewProviderTree(newobj.ViewObject)
# else:
# newobj.ViewObject.Proxy = 0
p[0] = [newobj]
def checkObjShape(obj) :
if printverbose: print('Check Object Shape')
if hasattr(obj, 'Shape'):
if obj.Shape.isNull() == True :
if printverbose: print('Shape is Null - recompute')
obj.recompute()
if (obj.Shape.isNull() == True):
print(f'Recompute failed : {obj.Name}')
else:
if hasattr(obj, 'Name'):
print(f"obj {obj.Name} has no Shape")
else:
print(f"obj {obj} has no Name & Shape")
def checkObjType2D(obj) :
if obj.TypeId == 'Part::Part2DObject' :
if printverbose: print('2D')
return True
if obj.TypeId == 'Part::Cut' or obj.TypeId == 'Part::Fuse' or \
obj.TypeId == 'Part::Common' or obj.TypeId == 'Part::MultiFuse' :
if checkObjType2D(obj.Base) and checkObjType2D(obj.Tool) :
return True
return False
def planeFromNormalPoints(a,b) :
#dir = FreeCAD.Vector(a[0]-b[0], a[1]-b[1], a[2]-b[2])
d3 = FreeCAD.Vector(1/(a[0]-b[0]), 1/(a[1]-b[1]), 1/(a[2]-b[2]))
print('a cross b : '+str(a.cross(b)))
#d2 = a.cross(b)
#d2 = FreeCAD.Vector(0.0, 0.0, 1.0)
#d2 = FreeCAD.Vector(1.0,0.0,0.0)
d2 = FreeCAD.Vector(0.0,1.0,0.0)
print('d2 : '+str(d2))
return Part.makePlane(200,50,a,d2)
def hullColour() :
return(random.random(),random.random(),0.5+random.random()/2)
def setObjectColour(obj, col) :
if obj.TypeId == 'Part::Cut' or obj.TypeId == 'Part::Fuse' or \
obj.TypeId == 'Part::Common' or obj.TypeId == 'Part::MultiFuse' :
if hasattr(obj,'Tool') :
setObjectColour(obj.Base, col)
setObjectColour(obj.Tool, col)
else :
if hasattr(obj,'ViewObject') :
if hasattr(obj.ViewObject,'ShapeColor') :
obj.ViewObject.ShapeColor = col
def p_hull_action(p):
'hull_action : hull LPAREN RPAREN OBRACE block_list EBRACE'
#printverbose=True
if printverbose: print('hull function')
from OpenSCADHull import makeHull
myHull = makeHull(p[5],True)
p[0] = [myHull]
return
col = hullColour()
for i in p[5] :
setObjectColour(i,col)
#myloft = doc.addObject("App::DocumentObjectGroup", "Hull")
#myloft.addObjects(p[5])
#p[0] =[myloft]
from OpenSCADHull import makeHull
myHull = makeHull(p[5],True)
p[0] = [myHull]
def p_minkowski_action(p):
'''
minkowski_action : minkowski LPAREN keywordargument_list RPAREN OBRACE block_list EBRACE'''
from OpenSCADMinkowski import minkowski
p[0] = [minkowski(p)]
def p_resize_action(p):
'''
resize_action : resize LPAREN keywordargument_list RPAREN OBRACE block_list EBRACE '''
import Draft
print(p[3])
new_size = p[3]['newsize']
auto = p[3]['auto']
print(new_size)
print(auto)
p[6][0].recompute()
old_bbox = p[6][0].Shape.BoundBox
print ("Old bounding box: " + str(old_bbox))
old_size = [old_bbox.XLength, old_bbox.YLength, old_bbox.ZLength]
for r in range(0,3) :
if auto[r] == '1' :
new_size[r] = new_size[0]
if new_size[r] == '0' :
new_size[r] = '1'
print(new_size)
# Calculate a transform matrix from the current bounding box to the new one:
transform_matrix = FreeCAD.Matrix()
#new_part.Shape = part.Shape.transformGeometry(transform_matrix)
scale = FreeCAD.Vector(float(new_size[0])/old_size[0],
float(new_size[1])/old_size[1],
float(new_size[2])/old_size[2])
transform_matrix.scale(scale)
new_part=doc.addObject("Part::FeaturePython",'Matrix Deformation')
new_part.Shape = p[6][0].Shape.transformGeometry(transform_matrix)
if gui:
if FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/OpenSCAD").\
GetBool('useViewProviderTree'):
from OpenSCADFeatures import ViewProviderTree
ViewProviderTree(new_part.ViewObject)
else:
new_part.ViewObject.Proxy = 0
p[6][0].ViewObject.hide()
p[0] = [new_part]
def p_not_supported(p):
'''
not_supported : glide LPAREN keywordargument_list RPAREN OBRACE block_list EBRACE
| subdiv LPAREN keywordargument_list RPAREN OBRACE block_list EBRACE
'''
if gui and not FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/OpenSCAD").\
GetBool('usePlaceholderForUnsupported'):
from PySide import QtGui
QtGui.QMessageBox.critical(None, translate('OpenSCAD',p[1]+" : Unsupported Function"),translate('OpenSCAD',"Press OK"))
else:
p[0] = [placeholder(p[1],p[6],p[3])]
def p_size_vector(p):
'size_vector : OSQUARE NUMBER COMMA NUMBER COMMA NUMBER ESQUARE'
if printverbose: print("size vector")
p[0] = [p[2],p[4],p[6]]
def p_keywordargument(p):
'''keywordargument : ID EQ boolean
| ID EQ NUMBER
| ID EQ size_vector
| ID EQ vector
| ID EQ 2d_point
| text EQ stripped_string
| ID EQ stripped_string
'''
p[0] = (p[1],p[3])
if printverbose: print(p[0])
def p_keywordargument_list(p):
'''
keywordargument_list : keywordargument
| keywordargument_list COMMA keywordargument
'''
if len(p) == 2:
p[0] = {p[1][0] : p[1][1]}
else:
p[1][p[3][0]] = p[3][1]
p[0]=p[1]
def p_color_action(p):
'color_action : color LPAREN vector RPAREN OBRACE block_list EBRACE'
import math
if printverbose: print("Color")
color = tuple([float(f) for f in p[3][:3]]) #RGB
transp = 100 - int(math.floor(100*float(p[3][3]))) #Alpha
if gui:
for obj in p[6]:
obj.ViewObject.ShapeColor =color
obj.ViewObject.Transparency = transp
p[0] = p[6]
# Error rule for syntax errors
def p_error(p):
if printverbose: print("Syntax error in input!")
if printverbose: print(p)
def fuse(lst,name):
global doc
if printverbose:
print("Fuse")
print(lst)
for obj in lst :
print(obj.Label)
if len(lst) == 0:
myfuse = placeholder('group',[],'{}')
elif len(lst) == 1:
return lst[0]
# Is this Multi Fuse
elif len(lst) > 2:
if printverbose: print("Multi Fuse")
myfuse = doc.addObject('Part::MultiFuse',name)
myfuse.Shapes = lst
for s in myfuse.Shapes:
checkObjShape(s)
if gui:
for subobj in myfuse.Shapes:
subobj.ViewObject.hide()
else:
if printverbose: print("Single Fuse")
myfuse = doc.addObject('Part::Fuse',name)
myfuse.Base = lst[0]
myfuse.Tool = lst[1]
checkObjShape(myfuse.Base)
checkObjShape(myfuse.Tool)
myfuse.Shape = myfuse.Base.Shape.fuse(myfuse.Tool.Shape)
myfuse.Placement = FreeCAD.Placement()
if gui:
myfuse.Base.ViewObject.hide()
myfuse.Tool.ViewObject.hide()
return(myfuse)
def p_union_action(p):
'union_action : union LPAREN RPAREN OBRACE block_list EBRACE'
if printverbose: print("union")
print("union")
newpart = fuse(p[5],p[1])
if printverbose: print("Push Union Result")
p[0] = [newpart]
if printverbose: print("End Union")
def p_difference_action(p):
'difference_action : difference LPAREN RPAREN OBRACE block_list EBRACE'
if printverbose: print("difference")
if printverbose: print(len(p[5]))
if printverbose: print(p[5])
if (len(p[5]) == 0 ): #nochild
mycut = placeholder('group',[],'{}')
elif (len(p[5]) == 1 ): #single object
p[0] = p[5]
else:
mycut = doc.addObject('Part::Cut',p[1])
mycut.Base = p[5][0]
checkObjShape(mycut.Base)
if (len(p[5]) > 2 ):
# Need to fuse extra items first
#print(len(p[5][1:]))
mycut.Tool = fuse(p[5][1:],'union')
else:
mycut.Tool = p[5][1]
checkObjShape(mycut.Tool)
if gui:
mycut.Base.ViewObject.hide()
mycut.Tool.ViewObject.hide()
if printverbose: print("Push Resulting Cut")
#print(dir(mycut))
#print(mycut)
#print(mycut.Name)
p[0] = [mycut]
if printverbose: print("End Cut")
def p_intersection_action(p):
'intersection_action : intersection LPAREN RPAREN OBRACE block_list EBRACE'
if printverbose: print("intersection")
# Is this Multi Common
if (len(p[5]) > 2):
if printverbose: print("Multi Common")
mycommon = doc.addObject('Part::MultiCommon',p[1])
mycommon.Shapes = p[5]
for s in mycommon.Shapes:
checkObjShape(s)
if gui:
for subobj in mycommon.Shapes:
subobj.ViewObject.hide()
elif (len(p[5]) == 2):
if printverbose: print("Single Common")
mycommon = doc.addObject('Part::Common',p[1])
mycommon.Base = p[5][0]
mycommon.Tool = p[5][1]
checkObjShape(mycommon.Base)
checkObjShape(mycommon.Tool)
mycommon.Shape = mycommon.Base.Shape.common(mycommon.Tool.Shape)
if gui:
mycommon.Base.ViewObject.hide()
mycommon.Tool.ViewObject.hide()
elif (len(p[5]) == 1):
mycommon = p[5][0]
else : # 1 child
mycommon = placeholder('group',[],'{}')
p[0] = [mycommon]
if printverbose: print("End Intersection")
def process_rotate_extrude(obj,angle):
from OpenSCADFeatures import RefineShape
newobj=doc.addObject("Part::FeaturePython",'RefineRotateExtrude')
RefineShape(newobj,obj)
if gui:
if FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/OpenSCAD").\
GetBool('useViewProviderTree'):
from OpenSCADFeatures import ViewProviderTree
ViewProviderTree(newobj.ViewObject)
else:
newobj.ViewObject.Proxy = 0
obj.ViewObject.hide()
myrev = doc.addObject("Part::Revolution","RotateExtrude")
myrev.Source = newobj
myrev.Axis = (0.00,1.00,0.00)
myrev.Base = (0.00,0.00,0.00)
myrev.Angle = angle
myrev.Placement=FreeCAD.Placement(FreeCAD.Vector(),FreeCAD.Rotation(0,0,90))
if gui:
newobj.ViewObject.hide()
return(myrev)
def process_rotate_extrude_prism(obj, angle, n):
from OpenSCADFeatures import PrismaticToroid
newobj=doc.addObject("Part::FeaturePython",'PrismaticToroid')
PrismaticToroid(newobj, obj, angle, n)
newobj.Placement=FreeCAD.Placement(FreeCAD.Vector(),FreeCAD.Rotation(0,0,90))
if gui:
if FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/OpenSCAD").\
GetBool('useViewProviderTree'):
from OpenSCADFeatures import ViewProviderTree
ViewProviderTree(newobj.ViewObject)
else:
newobj.ViewObject.Proxy = 0
obj.ViewObject.hide()
return(newobj)
def p_rotate_extrude_action(p):
'rotate_extrude_action : rotate_extrude LPAREN keywordargument_list RPAREN OBRACE block_list EBRACE'
if printverbose: print("Rotate Extrude")
angle = 360.0
if 'angle' in p[3]:
angle = float(p[3]['angle'])
n = int(round(float(p[3]['$fn'])))
# Use Global as maybe passed
#fnmax = FreeCAD.ParamGet(\
# "User parameter:BaseApp/Preferences/Mod/OpenSCAD").\
# GetInt('useMaxFN', 16)
if (len(p[6]) > 1) :
part = fuse(p[6],"Rotate Extrude Union")
else :
part = p[6][0]
if n < 3 or fnmax != 0 and n > fnmax:
p[0] = [process_rotate_extrude(part,angle)]
else:
p[0] = [process_rotate_extrude_prism(part,angle,n)]
if printverbose: print("End Rotate Extrude")
def p_rotate_extrude_file(p):
'rotate_extrude_file : rotate_extrude LPAREN keywordargument_list RPAREN SEMICOL'
if printverbose: print("Rotate Extrude File")
angle = 360.0
if 'angle' in p[3]:
angle = float(p[3]['angle'])
filen,ext =p[3]['file'] .rsplit('.',1)
obj = process_import_file(filen,ext,p[3]['layer'])
n = int(round(float(p[3]['$fn'])))
#fnmax = FreeCAD.ParamGet(\
# "User parameter:BaseApp/Preferences/Mod/OpenSCAD").\
# GetInt('useMaxFN', 16)
if n < 3 or fnmax != 0 and n > fnmax:
p[0] = [process_rotate_extrude(obj,angle)]
else:
p[0] = [process_rotate_extrude_prism(obj,angle,n)]
if printverbose: print("End Rotate Extrude File")
def process_linear_extrude(obj,h) :
#if gui:
from OpenSCADFeatures import RefineShape
newobj=doc.addObject("Part::FeaturePython",'RefineLinearExtrude')
RefineShape(newobj,obj)#mylinear)
if gui:
if FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/OpenSCAD").\
GetBool('useViewProviderTree'):
from OpenSCADFeatures import ViewProviderTree
ViewProviderTree(newobj.ViewObject)
else:
newobj.ViewObject.Proxy = 0
obj.ViewObject.hide()
#mylinear.ViewObject.hide()
mylinear = doc.addObject("Part::Extrusion","LinearExtrude")
mylinear.Base = newobj #obj
mylinear.Dir = (0,0,h)
mylinear.Placement=FreeCAD.Placement()
# V17 change to False mylinear.Solid = True
mylinear.Solid = False
if gui:
newobj.ViewObject.hide()
return(mylinear)
def process_linear_extrude_with_transform(base,height,twist,scale) :
from OpenSCADFeatures import Twist
newobj=doc.addObject("Part::FeaturePython",'twist_extrude')
Twist(newobj,base,height,-twist,scale) #base is an FreeCAD Object, height and twist are floats
if gui:
if FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/OpenSCAD").\
GetBool('useViewProviderTree'):
from OpenSCADFeatures import ViewProviderTree
ViewProviderTree(newobj.ViewObject)
else:
newobj.ViewObject.Proxy = 0
#import ViewProviderTree from OpenSCADFeatures
#ViewProviderTree(obj.ViewObject)
return(newobj)
def p_linear_extrude_with_transform(p):
'linear_extrude_with_transform : linear_extrude LPAREN keywordargument_list RPAREN OBRACE block_list EBRACE'
if printverbose: print("Linear Extrude With Transform")
h = float(p[3]['height'])
s = 1.0
t = 0.0
if printverbose: print("Twist : ",p[3])
if 'scale' in p[3]:
if isinstance(p[3]['scale'], str):
s = [float(p[3]['scale']), float(p[3]['scale'])]
else:
s = [float(p[3]['scale'][0]), float(p[3]['scale'][1])]
#print('Scale: '+str(s))
if 'twist' in p[3]:
t = float(p[3]['twist'])
# Test if null object like from null text
if (len(p[6]) == 0) :
p[0] = []
return
if (len(p[6]) > 1) :
obj = fuse(p[6],"Linear Extrude Union")
else :
obj = p[6][0]
checkObjShape(obj)
if t != 0.0 or s != 1.0:
newobj = process_linear_extrude_with_transform(obj,h,t,s)
else:
newobj = process_linear_extrude(obj,h)
if 'center' in p[3]:
if p[3]['center']=='true' :
center(newobj,0,0,h)
p[0] = [newobj]
if gui:
obj.ViewObject.hide()
if printverbose: print("End Linear Extrude with twist")
def p_import_file1(p):
'import_file1 : import LPAREN keywordargument_list RPAREN SEMICOL'
if printverbose: print("Import File")
filen,ext =p[3]['file'].rsplit('.',1)
if 'layer' in p[3]:
layerName = p[3]['layer']
if layerName == '':
layerName = None
# Should not occur if layer is not set in OpenSCAD csg will have layer =''
else:
layerName = None
#p[0] = [process_import_file(filen,ext,p[3]['layer'])]
p[0] = [process_import_file(filen, ext, layerName)]
if printverbose: print("End Import File")
def p_surface_action(p):
'surface_action : surface LPAREN keywordargument_list RPAREN SEMICOL'
if printverbose: print("Surface")
obj = doc.addObject("Part::Feature",'surface')
obj.Shape,xoff,yoff=makeSurfaceVolume(p[3]['file'])
if p[3]['center']=='true' :
center(obj,xoff,yoff,0.0)
p[0] = [obj]
if printverbose: print("End surface")
def process_import_file(fname, ext, layer):
from OpenSCADUtils import reverseimporttypes
if printverbose: print("Importing : "+fname+"."+ext+" Layer : "+layer)
if ext.lower() in reverseimporttypes()['Mesh']:
obj=process_mesh_file(fname, ext)
elif ext.lower() == 'dxf':
obj=processDXF(fname, layer)
elif ext.lower() == 'svg':
obj=processSVG(fname, ext)
else:
raise ValueError("Unsupported file extension %s" % ext)
return(obj)
def processSVG(fname, ext):
from importSVG import svgHandler
print("SVG Handler")
doc = FreeCAD.ActiveDocument
docSVG = FreeCAD.newDocument(fname+'_tmp')
FreeCAD.ActiveDocument = docSVG
# Set up the parser
parser = xml.sax.make_parser()
parser.setFeature(xml.sax.handler.feature_external_ges, False)
parser.setContentHandler(svgHandler())
parser._cont_handler.doc = docSVG
# pathName is a Global
filename = os.path.join(pathName,fname+'.'+ext)
# Use the native Python open which was saved as `pythonopen`
parser.parse(pythonopen(filename))
#combine SVG objects into one
shapes = []
for obj in FreeCAD.ActiveDocument.Objects:
print(obj.Name)
print(obj.Shape)
shapes.append(obj.Shape)
#compoundSVG = Part.makeCompound(shapes)
#compoundSVG = Draft.join(objects)
FreeCAD.closeDocument(docSVG.Name)
FreeCAD.ActiveDocument=doc
obj=doc.addObject('Part::Feature',fname)
obj.Shape=Part.Compound(shapes)
return obj
def process_mesh_file(fname, ext):
import Mesh,Part
fullname = fname+'.'+ext
filename = os.path.join(pathName,fullname)
objname = os.path.split(fname)[1]
mesh1 = doc.getObject(objname) #reuse imported object
if not mesh1:
Mesh.insert(filename)
mesh1=doc.getObject(objname)
if mesh1 is not None:
if gui:
mesh1.ViewObject.hide()
sh=Part.Shape()
sh.makeShapeFromMesh(mesh1.Mesh.Topology,0.1)
solid = Part.Solid(sh)
obj=doc.addObject('Part::Feature',"Mesh")
#ImportObject(obj,mesh1) #This object is not mutable from the GUI
#ViewProviderTree(obj.ViewObject)
solid=solid.removeSplitter()
if solid.Volume < 0:
#sh.reverse()
#sh = sh.copy()
solid.complement()
obj.Shape=solid#.removeSplitter()
else: #mesh1 is None