-
Notifications
You must be signed in to change notification settings - Fork 3
/
platesjoinery.py
9086 lines (8588 loc) · 605 KB
/
platesjoinery.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
"""
Module for Timber Plate Joinery from Digital Fabrication to Robotic Assembly
Classes:
- PlateModel : adjacency, topology, insertion vectors, assembly sequence...
- Module : inherits from model, sub-sequence, insertion vectors...
- Plate : thickness, contour, plane, normal...
- ToolBox : geometry function for rhino objects
TO DO LIST:
- Discard SS connections which are not sharing an edge
- add an option to convert a datatree of objects to a sequence
- Check plate faces orientation before playing with it
- Check potential problem in set attributes components
- Make it work for half lap joints if the contact volume cut plate faces in two
- Plates that are two contacts with the same neighbors
- joints ideas: common dovetail, butterfly, tusked tenon
"""
__author__ = "Nicolas Rogeau"
__laboratory__ = "IBOIS, Laboratory for Timber Construction"
__university__ = "EPFL, Ecole Polytechnique Federale de Lausanne"
__funding__ = "NCCR Digital Fabrication, ETH Zurich"
__version__ = "2021.09.23"
import rhinoscriptsyntax as rs
import Rhino.Geometry as rg
from ghpythonlib import components as gh
from Grasshopper import DataTree
from Grasshopper.Kernel.Data import GH_Path
import scriptcontext
import math
import copy
import ast
import rhinoscriptsyntax as rs
import Rhino.Geometry as rg
from ghpythonlib import components as gh
from Grasshopper import DataTree
from Grasshopper.Kernel.Data import GH_Path
import scriptcontext
import math
import copy
import ast
yes = True
if yes:
if yes:
#Model -----------------------------------------------------------------------
class PlateModel:
def __init__(self, breps, sequence=0, constraints=[None,None,None,None,None], discard=[]):
# INITIALIZATION -------------------------------------
self.temp = []
self.log = []
self.count = len(breps)
self.sequence = self.__set_sequence(sequence)
self.breps = self.__reorder_breps(breps)
self.sequence = self.__reorder_sequence(self.sequence)
self.plates = self.__get_plates_from_breps()
# TOPOLOGY -------------------------------------------
self.discard = discard
self.contact_ids = self.__get_contact_ids()
self.contact_pairs = self.__get_contact_pairs()
self.contact_breps = self.__get_contact_breps()
self.contact_zones= self.__get_contact_zones()
self.contact_types = self.__get_contact_types()
self.contact_strings = self.__get_contact_strings()
self.contact_centers= self.__get_contact_centers()
self.contact_normals = self.__get_contact_normals()
self.contact_planes= self.__get_contact_planes()
self.contact_spheres = self.__get_contact_spheres(constraints)
# ASSEMBLY -------------------------------------------
self.contact_vectors = []
self.modules = self.__get_modules_from_sequence()
self.assembly_vectors = []
self.assembly_spaces = []
self.assembly_relatives = []
self.__get_assembly_vectors()
# STRUCTURAL ANALYSIS --------------------------------
self.FEM_joints = []
self.FEM_plates = [plate.mid_contour for plate in self.plates]
# MODEL INITIALIZATION ---------------------------------------
def __set_sequence(self, sequence):
"""return the default sequence if incorrect input is provided"""
if sequence == 0 or sequence == [] or sequence == None:
self.log.append('Sequence set to default : '+ str(range(self.count)))
return str(range(self.count))
else:
if type(sequence) is str:
Toolbox.Data.test_seq(sequence)
try: test = ast.literal_eval(sequence)
except: raise Exception(' An error occured when trying to convert sequence text to list of lists.')
self.log.append('Sequence set to custom : '+ str(sequence))
return sequence
else: raise Exception(' Sequence input should be expressed as a string.')
def __reorder_breps(self, breps):
seq = ast.literal_eval(self.sequence)
return Toolbox.Data.sort_list_sync(breps, Toolbox.Data.flatten_integer_list(seq))
def __reorder_sequence(self, sequence):
new_sequence = Toolbox.Data.reorder_sequence(sequence)
if new_sequence != sequence:
self.log.append('Breps and sequence have been reordered: '+ str(new_sequence))
return new_sequence
def __get_plates_from_breps(self):
plates=[]
for i in range(len(self.breps)):
# plate object creation
plates.append(Plate(self.breps[i], i))
return plates
def __get_modules_from_sequence(self):
# create sub_sequence list
seq = ast.literal_eval(self.sequence)
steps = Toolbox.Data.seq_to_steps(seq)
steps = Toolbox.Data.order_sequence(steps)
sub_seq = []
sub_steps = []
for i in range(len(steps)):
if steps[i] in Toolbox.Data.deepest_steps(seq): pass
else:
sub_steps.append(steps[i])
sub_seq.append(Toolbox.Data.get_item_from_path(seq, steps[i]))
sub_seq.append(seq)
sub_steps.append(['Model'])
# fill parent list
parents = []
for sub_step in sub_steps:
if sub_step == ['Model']: parents.append([])
elif len(sub_step) == 1 : parents.append(['Model'])
else: parents.append(sub_step[0:len(sub_step)-1])
# fill children list
children = Toolbox.Data.list_of_empty_lists(len(parents))
for i in range(len(parents)):
for j in range(len(sub_steps)):
if parents[i] == sub_steps[j]:
children[j].append(sub_steps[i])
# module creation
modules = []
for i in range(len(sub_seq)):
modules.append(PlateModule(self, i, sub_steps[i], str(sub_seq[i]), parents[i], children[i]))
return modules
# MODEL TOPOLOGY ---------------------------------------------
def __get_contact_ids(self):
mylist = []
for i in range(self.count):
sub = []
for j in range(self.count):
if i != j:
#discard
if ('('+str(i)+','+str(j)+')' == self.discard) or ('('+str(i)+','+str(j)+')' in self.discard) or ('('+str(j)+','+str(i)+')' == self.discard) or ('('+str(j)+','+str(i)+')' in self.discard):
self.log.append("pair "+str(i)+","+str(j)+" skipped")
else:
intersect = rs.IntersectBreps(self.breps[i],self.breps[j])
if intersect != None:
if len(intersect) == 1:
if rs.IsCurveClosed(intersect) is True:
if rs.IsCurvePlanar(intersect) is True:
sub.append(j)
else:
# if plate contours are intersecting the surfaces of the other plate
if rs.CurveBrepIntersect(self.plates[i].top_contour,self.plates[j].top_face) != None:
if rs.CurveBrepIntersect(self.plates[i].top_contour,self.plates[j].bottom_face) != None:
if rs.CurveBrepIntersect(self.plates[i].bottom_contour,self.plates[j].top_face) != None:
if rs.CurveBrepIntersect(self.plates[i].bottom_contour,self.plates[j].bottom_face) != None:
sub.append(j)
mylist.append(sub)
return mylist
def __get_contact_pairs(self):
mylist = []
for i in range(self.count):
sub = []
for j in range(len(self.contact_ids[i])):
brep_id = self.contact_ids[i][j]
sub.append( '(' + str(i) + ',' + str(brep_id) + ')' )
mylist.append(sub)
return mylist
def __get_contact_breps(self):
mylist = []
for i in range(self.count):
sub = []
for j in range(len(self.contact_ids[i])):
brep_id = self.contact_ids[i][j]
brep = rs.coercebrep(rs.CopyObject(self.breps[brep_id]))
sub.append(brep)
mylist.append(sub)
return mylist
def __get_contact_zones(self):
mylist = []
for i in range(self.count):
sub = []
for j in range(len(self.contact_ids[i])):
brep_id = self.contact_ids[i][j]
pi = copy.deepcopy(self.plates[i])
pj = copy.deepcopy(self.plates[brep_id])
intersect = rs.IntersectBreps(pi.brep,pj.brep)
if intersect != None:
if len(intersect) == 1:
if rs.IsCurveClosed(intersect) is True:
if rs.IsCurvePlanar(intersect) is True:
zone = rs.coercegeometry(rs.AddPlanarSrf(intersect)[0])
sub.append(zone)
# intersecting breps
else:
# if plate contours are intersecting the surfaces of the other plate
if rs.CurveBrepIntersect(pi.top_contour, pj.top_face) != None:
if rs.CurveBrepIntersect(pi.top_contour, pj.bottom_face) != None:
if rs.CurveBrepIntersect(pi.bottom_contour, pj.top_face) != None:
if rs.CurveBrepIntersect(pi.bottom_contour, pj.bottom_face) != None:
volume = rg.Brep.CreateBooleanIntersection(pi.brep,pj.brep,0.1)[0]
edges = Toolbox.Breps.brep_edges(volume)
edges.sort(key=rs.CurveLength)
edges.reverse()
vec_dir = Toolbox.Vectors.round_vector(rs.VectorUnitize(Toolbox.Vectors.cross(pi.top_normal, pj.top_normal)),6)
four_edges = []
for edge in edges:
vec_line = Toolbox.Vectors.round_vector(rs.VectorUnitize(Toolbox.Vectors.line_to_vec(edge)),6)
if vec_dir == vec_line or vec_dir == rs.VectorReverse(vec_line):
four_edges.append(edge)
if len(four_edges) == 4: break
mids = [rs.CurveMidPoint(four_edges[k]) for k in range(4)]
center = Toolbox.Points.average_point(mids)
proj = rs.coerce3dpointlist([rs.EvaluateCurve(four_edges[l],rs.CurveClosestPoint(four_edges[l],center)) for l in range(4)])
poly = rs.AddPolyline(rs.PolylineVertices(gh.ConvexHull(proj, rs.PlaneFitFromPoints(proj))[0]))
zone = rs.coercegeometry(rs.AddPlanarSrf(poly)[0])
#orient surface normal
current_normal = rs.SurfaceNormal(zone,[0,0])
new_vec = Toolbox.Vectors.line_to_vec(four_edges[0],True)
test_point = rs.CurveStartPoint(four_edges[0])
test1 = rs.IsPointOnCurve(pi.top_contour, test_point)
test2 = rs.IsPointOnCurve(pi.bottom_contour, test_point)
if test1 is True or test2 is True:
new_vec =rs.VectorReverse(new_vec)
if rs.IsVectorParallelTo(current_normal, new_vec) == -1:
rs.FlipSurface(zone,True)
sub.append(zone)
mylist.append(sub)
return mylist
def __get_contact_types(self):
mylist = []
for i in range(self.count):
sub = []
for j in range(len(self.contact_ids[i])):
nb = self.contact_ids[i][j]
zone = self.contact_zones[i][j]
zone_normal = rs.SurfaceNormal(zone,[0,0])
plate1_normal = self.plates[i].top_normal
plate2_normal = self.plates[nb].top_normal
cross1 = Toolbox.Vectors.cross(zone_normal,plate1_normal)
cross2 = Toolbox.Vectors.cross(zone_normal,plate2_normal)
if Toolbox.Vectors.isvectornull(cross1) is False and Toolbox.Vectors.isvectornull(cross2) is False :
intersect = rs.IntersectBreps(self.breps[i],self.breps[nb])
if rs.IsCurvePlanar(intersect) is True: sub.append('SS')
else: sub.append('IN')
elif Toolbox.Vectors.isvectornull(cross1) is True and Toolbox.Vectors.isvectornull(cross2) is True :
sub.append('FF')
else:
#edge test:
top_top = Toolbox.Curves.isSharingEdge(self.plates[i].top_contour, self.plates[nb].top_contour)
top_bottom = Toolbox.Curves.isSharingEdge(self.plates[i].top_contour, self.plates[nb].bottom_contour)
bottom_top = Toolbox.Curves.isSharingEdge(self.plates[i].bottom_contour, self.plates[nb].top_contour)
bottom_bottom = Toolbox.Curves.isSharingEdge(self.plates[i].bottom_contour, self.plates[nb].bottom_contour)
if Toolbox.Vectors.isvectornull(cross1) is True and Toolbox.Vectors.isvectornull(cross2) is False :
if top_top == False and top_bottom == False and bottom_top == False and bottom_bottom == False:
sub.append('FS')
else: sub.append('ES')
elif Toolbox.Vectors.isvectornull(cross1) is False and Toolbox.Vectors.isvectornull(cross2) is True :
if top_top == False and top_bottom == False and bottom_top == False and bottom_bottom == False:
sub.append('SF')
else: sub.append('SE')
mylist.append(sub)
return mylist
def __get_contact_strings(self):
mylist = []
for i in range(self.count):
sub = []
for j in range(len(self.contact_ids[i])):
brep_id = self.contact_ids[i][j]
ptype = self.contact_types[i][j]
if ptype == 'SS':
sub.append('Side of plate '+str(i)+' is connected to Side of plate '+str(brep_id))
elif ptype == 'FS':
sub.append('Face of plate '+str(i)+' is connected to Side of plate '+str(brep_id))
elif ptype == 'ES':
sub.append('Edge of plate '+str(i)+' is connected to Side of plate '+str(brep_id))
elif ptype == 'SF':
sub.append('Side of plate '+str(i)+' is connected to Face of plate '+str(brep_id))
elif ptype == 'SE':
sub.append('Side of plate '+str(i)+' is connected to Edge of plate '+str(brep_id))
elif ptype == 'FF':
sub.append('Face of plate '+str(i)+' is connected to Face of plate '+str(brep_id))
elif ptype == 'IN':
sub.append('Volume of plate '+str(i)+' is intersecting volume of plate '+str(brep_id))
mylist.append(sub)
return mylist
def __get_contact_centers(self):
mylist = []
for i in range(self.count):
sub = []
for j in range(len(self.contact_ids[i])):
center = Toolbox.Surfaces.surface_centroid(self.contact_zones[i][j])
sub.append(rs.coerce3dpoint(center))
mylist.append(sub)
return mylist
def __get_contact_normals(self):
mylist = []
for i in range(self.count):
sub = []
for j in range(len(self.contact_ids[i])):
brep_id = self.contact_ids[i][j]
zone = self.contact_zones[i][j]
vec = rs.VectorUnitize(rs.SurfaceNormal(zone,[0,0]))
plate_center = self.plates[i].plate_center
zone_center = Toolbox.Surfaces.surface_centroid(zone)
if self.contact_types[i][j] != "IN":
if Toolbox.Vectors.is_vector_outward(plate_center, zone_center, copy.deepcopy(vec)) is False:
vec=rs.VectorReverse(copy.deepcopy(vec))
sub.append(rs.coerce3dvector(vec))
mylist.append(sub)
return mylist
def __get_contact_planes(self):
mylist = []
for i in range(self.count):
sub = []
for j in range(len(self.contact_ids[i])):
nb = self.contact_ids[i][j]
origin = self.contact_centers[i][j]
zone = Toolbox.Surfaces.get_face_largest_contour(self.contact_zones[i][j])
sides = rs.ExplodeCurves(rs.CopyObject(zone))
longest_side = Toolbox.Curves.sort_curves_by_length(sides)[-1][0]
x_axis = rs.VectorCreate(rs.CurveStartPoint(longest_side), rs.CurveEndPoint(longest_side))
plane = rs.PlaneFromNormal(origin, self.contact_normals[i][j], x_axis)
if self.contact_types[i][j] == 'ES':
if Toolbox.Vectors.is_vector_outward(self.plates[i].mid_plane.Origin, self.contact_centers[i][j], plane.YAxis) is False:
plane = rs.PlaneFromNormal(origin, self.contact_normals[i][j], -x_axis)
if self.contact_types[i][j] == 'SE':
if Toolbox.Vectors.is_vector_outward(self.plates[nb].mid_plane.Origin, self.contact_centers[i][j], plane.YAxis) is True:
plane = rs.PlaneFromNormal(origin, self.contact_normals[i][j], -x_axis)
sub.append(rs.coerceplane(plane))
mylist.append(sub)
return mylist
def __get_contact_spheres(self, constraints):
if constraints.BranchCount != 5: constraints = [[],[],[],[],[]]
else: constraints = Toolbox.Data.datatree_to_list(constraints)
# Create canonic insertion space
sphere = rs.AddSphere((0,0,0),1)
cutter = rs.AddPlanarSrf(rs.AddPolyline([(1,1,0),(1,-1,0),(-1,-1,0),(-1,1,0),(1,1,0)]))
hemisphere = rs.SplitBrep(sphere,cutter)[1]
hemicircle_horizontal = rs.RotateObject(rs.AddArc(rs.WorldZXPlane(),1,180),(0,0,0),-90,(0,1,0))
hemicircle_vertical = rs.RotateObject(rs.AddArc(rs.WorldYZPlane(),1,180),(0,0,0),0,(1,0,0))
normal_point= rs.AddPoint(0,0,1)
# Orient hemisphere on each conctact zone
mylist = []
for i in range(self.count):
sub = []
for j in range(len(self.contact_types[i])):
#face-to-face
if self.contact_types[i][j] == 'FF':
if constraints[0] != []:
insertion_space = constraints[0]
else: insertion_space = hemisphere
#face-to-side
elif (self.contact_types[i][j] == 'FS' or self.contact_types[i][j] == 'SF'):
if constraints[1] != []:
insertion_space = constraints[1]
else: insertion_space = hemicircle_horizontal
#edge-to-side
elif (self.contact_types[i][j] == 'ES' or self.contact_types[i][j] == 'SE'):
if constraints[2] != []:
insertion_space = constraints[2]
else: insertion_space = hemisphere
#side-to-side
elif self.contact_types[i][j] == 'SS':
if constraints[3] != []:
insertion_space = constraints[3]
else: insertion_space = hemicircle_vertical
#intersecting
elif self.contact_types[i][j] == 'IN':
if constraints[4] != []:
insertion_space = constraints[4]
else: insertion_space = normal_point
#Exception for SF/FS where the default constraint is oriented with the male plane
if constraints[1] == [] and (self.contact_types[i][j] == 'FS' or self.contact_types[i][j] == 'SF'):
nb = self.contact_ids[i][j]
if self.contact_types[i][j] == 'SF': male_normal = self.plates[i].top_plane.ZAxis
else: male_normal = self.plates[nb].top_plane.ZAxis
pl_origin = self.contact_planes[i][j].Origin
pl_X = self.contact_planes[i][j].XAxis
pl_Z = rs.VectorCrossProduct(male_normal, pl_X)
proj_plane = rs.PlaneFromNormal(pl_origin, pl_Z, pl_X)
test_point = rs.CopyObject(pl_origin, -self.contact_normals[i][j])
if Toolbox.Vectors.is_vector_outward(test_point, pl_origin, pl_Z) is False:
proj_plane = rs.PlaneFromNormal(pl_origin, -pl_Z, -pl_X)
matrix = rg.Transform.PlaneToPlane(rs.WorldXYPlane(), proj_plane)
insertion_space = rs.TransformObject(insertion_space, matrix,True)
#normal Orientation of all other insertion constraints
else:
matrix = rg.Transform.PlaneToPlane(rs.WorldXYPlane(), self.contact_planes[i][j])
insertion_space = rs.TransformObject(insertion_space, matrix,True)
#Exception for SE/ES where the default constraint is trimmed by plate planes
if constraints[2] == [] and (self.contact_types[i][j] == 'ES' or self.contact_types[i][j] == 'SE'):
test_point = rs.CopyObject(self.contact_centers[i][j], - self.contact_planes[i][j].YAxis)
if self.contact_types[i][j] == 'SE':
trim_plane = self.plates[i].mid_plane
else: trim_plane = self.plates[self.contact_ids[i][j]].mid_plane
trim_plane = rs.MovePlane(trim_plane, self.contact_centers[i][j])
if Toolbox.Vectors.is_vector_outward(test_point, self.contact_centers[i][j], trim_plane.ZAxis) is True:
trim_plane = rs.RotatePlane(trim_plane, 180, trim_plane.XAxis)
insertion_space = rs.TrimBrep(insertion_space, trim_plane)
sub.append(insertion_space)
mylist.append(sub)
return mylist
# MODULES ASSEMBLY -------------------------------------------
def __get_assembly_vectors(self):
adj = self.contact_ids
seq = ast.literal_eval(self.sequence)
steps = Toolbox.Data.seq_to_steps(seq)
steps = Toolbox.Data.order_sequence(steps)
sub_seq = []
for i in range(len(steps)):
if steps[i] in Toolbox.Data.deepest_steps(seq): pass
else: sub_seq.append(Toolbox.Data.get_item_from_path(seq, steps[i]))
sub_seq.append(seq)
# Assembly vectors following modules list
iv = copy.deepcopy(sub_seq)
space = copy.deepcopy(sub_seq)
rel = copy.deepcopy(sub_seq)
for i in range(len(sub_seq)):
for j in range(len(sub_seq[i])):
# first element in subsequence
if j == 0:
iv[i][j] = "gravity"
rel[i][j] = []
space[i][j] = []
else:
# look for all connection between the plate (or a plate of the module) to insert and the plates in place
rel_list = [] #
is_list = [] #insertion spaces
# element in subsequence is a module
if type(sub_seq[i][j]) is list:
plates = Toolbox.Data.flatten_integer_list(sub_seq[i][j])
for plate in plates:
neighbours = adj[plate]
prequel = sub_seq[i][:j]
# find all corespondance between the neighbour group and the prequel group
for k in range(len(neighbours)):
for l in range(len(prequel)):
# element in prequel is a module
if type(prequel[l]) is list:
prequel[l] = Toolbox.Data.flatten_integer_list(prequel[l])
for m in range(len(prequel[l])):
if prequel[l][m] == neighbours[k]:
to_zero = rs.VectorCreate((0,0,0),self.contact_centers[plate][k])
sphere = rs.CopyObject(self.contact_spheres[plate][k],to_zero)
is_list.append(sphere)
rel_list.append(neighbours[k])
# element in prequel is a plate
else:
if prequel[l] == neighbours[k]:
to_zero = rs.VectorCreate((0,0,0),self.contact_centers[plate][k])
sphere = rs.CopyObject(self.contact_spheres[plate][k],to_zero)
is_list.append(sphere)
rel_list.append(neighbours[k])
# element in subsequence is a plate
else:
plate = sub_seq[i][j]
neighbours = adj[plate]
prequel = sub_seq[i][:j]
# find the first corespondance between the neighbour group and the prequel group
for k in range(len(neighbours)):
for l in range(len(prequel)):
# element in prequel is a module
if type(prequel[l]) is list:
for m in range(len(prequel[l])):
if prequel[l][m] == neighbours[k]:
to_zero = rs.VectorCreate((0,0,0),self.contact_centers[plate][k])
sphere = rs.CopyObject(self.contact_spheres[plate][k],to_zero)
is_list.append(sphere)
rel_list.append(neighbours[k])
# element in prequel is a plate
else:
if prequel[l] == neighbours[k]:
to_zero = rs.VectorCreate((0,0,0),self.contact_centers[plate][k])
sphere = rs.CopyObject(self.contact_spheres[plate][k],to_zero)
is_list.append(sphere)
rel_list.append(neighbours[k])
# If plate/module has no contact, add a default vector and a support
if is_list == []:
iv[i][j] = "gravity"
space[i][j] = []
rel[i][j] = []
self.modules[i].needed_supports += 1
# If plate/module has contacts, intersect insertion spheres and take average candidate
else:
try:
inter = self.intersect_insertion_spaces(is_list)
iv[i][j] = inter[0] #average vector
space[i][j] = inter[1] #candidates
rel[i][j] = rel_list
except:
self.temp = is_list
iv[i][j] = "gravity"
space[i][j] = []
rel[i][j] = rel_list
#raise Exception('Insertion space intersection returns no compatible vector for plate(s) '+str(sub_seq[i][j])+' with plates '+str(rel[i][j]))
# if average vector failed or was null, take gravity instead
if iv[i][j] == None: iv[i][j] = "gravity"
# Update modules attributes
for i in range(len(self.modules)):
self.modules[i].assembly_vectors = iv[i]
self.modules[i].assembly_relatives = rel[i]
self.modules[i].assembly_spaces = space[i]
# Assembly vectors following contact list
iv2 = copy.deepcopy(self.contact_planes)
rel2 = copy.deepcopy(self.contact_planes)
# Compare each contact zone...
for i in range(self.count):
for j in range(len(adj[i])):
# ... with each module sequence.
search = True
for k in range(len(self.modules)):
# to retrieve the associated assembly vector
if search is True:
mod_seq = ast.literal_eval(self.modules[k].sequence)
plates_in_sequence = Toolbox.Data.flatten_integer_list(mod_seq)
if (i in plates_in_sequence) and (adj[i][j] in plates_in_sequence):
for l in range(len(mod_seq)):
corresponding_vector = copy.deepcopy(self.modules[k].assembly_vectors[l])
if type(mod_seq[l]) is list:
plates_in_sub_sequence = Toolbox.Data.flatten_integer_list(mod_seq[l])
if i < adj[i][j] and adj[i][j] in plates_in_sub_sequence:
iv2[i][j] = corresponding_vector
rel2[i][j] = adj[i][j]
search = False
elif i > adj[i][j] and i in plates_in_sub_sequence:
iv2[i][j] = rs.VectorReverse(corresponding_vector)
rel2[i][j] = adj[i][j]
search = False
else:
if i < adj[i][j] and mod_seq[l] == adj[i][j]:
iv2[i][j] = corresponding_vector
rel2[i][j] = adj[i][j]
search = False
elif i > adj[i][j] and mod_seq[l] == i:
iv2[i][j] = rs.VectorReverse(corresponding_vector)
rel2[i][j] = adj[i][j]
search = False
#self.assembly_relatives = rel2
self.contact_vectors = iv2
#coerce geometry of contact spheres to avoid guid instance problem.
for i in range(len(self.contact_spheres)):
for j in range(len(self.contact_spheres[i])):
self.contact_spheres[i][j]=rs.coercegeometry(self.contact_spheres[i][j])
#assign model attributes
self.assembly_vectors = self.modules[0].assembly_vectors
self.assembly_spaces = self.modules[0].assembly_spaces
self.assembly_relatives = self.modules[0].assembly_relatives
def intersect_insertion_spaces(self, insertion_spaces):
"""
Hypothesis:
insertion spaces are points, curves and surfaces
pts, crvs and srfs are parts of a sphere of radius 1
crvs are geodesics on that sphere
crvs are smaller than the hemisphere (L = pi.r)
srfs have convex perimeters and no holes
srfs are smaller than the hemisphere (A = 2.pi.r^2)
Method:
we start from the most constraining (point to surface)
we avoid surface intersection using geodesic points
"""
# Sort insertion_spaces
pts,crvs,srfs = [],[],[]
for space in insertion_spaces:
if rs.IsPoint(space) is True:
pts.append(space)
elif rs.IsCurve(space) is True:
crvs.append(space)
elif rs.IsBrep(space) is True:
srfs.append(space)
geodesic_cloud = Toolbox.Points.geodesic_sphere_points()
tol = 0.001 # intersection tolerance
dso = 2 # design space order
candidates = []
# Intersection functions:
def pt_pt(pt1, pt2, tol):
if rs.Distance(pt1,pt2) > tol:
raise Exception('No pt-pt intersection was found')
def pt_crv(pt,crv):
if rs.IsPointOnCurve(crv, pt) is False:
raise Exception('No pt-crv intersection was found')
def pts_crv(pts, crv, warning=True):
new_pts = []
for pt in pts:
if rs.IsPointOnCurve(crv, pt) is True:
new_pts.append(pt)
if new_pts == [] and warning == True:
raise Exception('No pts-crv intersection was found')
else: return new_pts
def pt_srf(pt,srf):
if rs.IsPointOnSurface(srf, pt) is False:
raise Exception('No pt-srf intersection was found')
def pts_srf(pts, srf, tol, warning=True):
new_pts = []
for pt in pts:
srf_pt = rs.BrepClosestPoint(srf,pt)[0]
if rs.Distance(pt,srf_pt) < tol:
new_pts.append(pt)
if new_pts == [] and warning==True:
raise Exception('No pts-srf intersection was found')
else: return new_pts
def crv_crv(crv1, crv2, warning=True):
inter = rs.CurveCurveIntersection(crv1,crv2)
if inter == None and warning == True:
raise Exception('No crv-crv intersection was found')
else: return inter
def crv_srf():
pass
def srf_srf():
pass
def dist_to_srf(srf,pt):
srf_pt = rs.BrepClosestPoint(srf,pt)[0]
return rs.Distance(srf_pt,pt)
def dist_to_crv(crv,pt):
t = rs.CurveClosestPoint(crv,pt)
return rs.Distance(rs.EvaluateCurve(crv,t),pt)
def crv_to_pts(crv):
segments = rs.CurveLength(crv) /0.01
pts = rs.DivideCurve(crv,segments)
return pts
def srf_to_pts(srf,geodesic_cloud,edge=True):
pts=[]
border = rs.DuplicateSurfaceBorder(srf,1)
if edge is True:
border_pts = crv_to_pts(border)
for pt in border_pts:
pts.append(pt)
for pt in geodesic_cloud:
pt = rs.AddPoint(pt)
srf_pt = rs.BrepClosestPoint(srf,pt)[0]
if rs.Distance(srf_pt,pt) < tol:
t =rs.CurveClosestPoint(border,pt)
border_pt = rs.EvaluateCurve(border,t)
if rs.Distance(border_pt,pt) > tol:
pts.append(pt)
return pts
# Start from points
if len(pts) != 0:
dso = 0
candidates.append(pts[0])
#check points
for i in range(len(pts)-1):
pt_pt(candidates[0],pts[i+1],tol)
# check curves
for crv in crvs:
pt_crv(candidates[0],crv)
# check surfaces
for srf in srfs:
pt_srf(candidates[0],srf)
# Start from curves
elif len(crvs) != 0:
dso = 1
candidates = crv_to_pts(crvs[0])
base_crv = crvs[0]
#check curves
for i in range(len(crvs)-1):
if dso == 1:
inter = crv_crv(base_crv,crvs[i+1])[0]
#intersection
if inter[0] == 1:
candidates = [inter[1]]
dso = 0
#overlap
else:
candidates = pts_crv(candidates,crvs[i+1])
new_start=rs.CurveClosestPoint(base_crv,candidates[0])
new_end=rs.CurveClosestPoint(base_crv,candidates[-1])
base_crv=rs.AddSubCrv(base_crv,new_start,new_end)
else: candidates = pts_crv(candidates,crvs[i+1])
# check surfaces
for srf in srfs:
candidates = pts_srf(candidates,srf,tol)
# Start from surfaces
elif len(srfs) != 0:
dso = 2
candidates = srf_to_pts(srfs[0],geodesic_cloud,edge=True)
# check surfaces
for i in range(len(srfs)-1):
candidates = pts_srf(candidates,srfs[i+1],tol,False)
#complete border
border_i = rs.DuplicateSurfaceBorder(srfs[i+1])
border_points = crv_to_pts(border_i)
for j in range(i+1):
border_points = pts_srf(border_points,srfs[j],tol,False)
candidates = candidates + border_points
if candidates == []: raise Exception('No srf-srf intersection was found')
else: raise Exception('Please provide at least one point/curve/surface')
if len(candidates) == 1:
chosen = candidates[0]
elif len(candidates) > 1:
l = len(candidates)
x = 0
y = 0
z = 0
for i in range(len(candidates)):
if rs.IsPoint(candidates[i]) is False:
candidates[i] = rs.AddPoint(candidates[i])
coord = rs.PointCoordinates(candidates[i])
candidates[i] = rs.coercegeometry(candidates[i])
x += coord[0]
y += coord[1]
z += coord[2]
x = x/l
y = y/l
z = z/l
chosen = rs.AddPoint(x,y,z)
vector = rs.VectorUnitize(rs.VectorCreate(chosen,(0,0,0)))
return (vector, candidates)
# Decorator -----------------------------------
def __skip_nones(fun):
"""
Decorator to use default value if parameter is null or is an empty list.
"""
def _(*args, **kwargs):
for a, v in zip(fun.__code__.co_varnames, args):
if v is not None and v!=[]:
kwargs[a] = v
return fun(**kwargs)
return _
# PLATE JOINERY ----------------------------------------------
@__skip_nones
def add_dowels(self,
plates_pairs='all',
dowel_number=1.0,
dowel_radius=0.5,
dowel_tolerance=0.0,
dowel_retreat_1=0.0,
dowel_retreat_2=0.0,
circle_radius=3.0,
circle_rotation=0.0,
dowel_angle_1=0.0,
dowel_angle_2=0.0,
parallel=False,
tile=False):
"""Add dowels on Face-to-Face contact zones."""
#cast plate_pairs to string
if plates_pairs != 'all':
for i in range(len(plates_pairs)):
plates_pairs[i] = str(plates_pairs[i])
#conditional loop
for i in range(self.count):
types = self.contact_types[i]
for j in range(len(types)):
nb = self.contact_ids[i][j]
#specific selection function
if ((plates_pairs == 'all')
or ('('+str(i)+','+str(nb)+')' == plates_pairs)
or ('('+str(i)+','+str(nb)+')' in plates_pairs)):
i_want_a_dowel = True
else: i_want_a_dowel = False
#for all specified Face-to-Face connection
if (types[j] == 'FF') and (nb > i) and (i_want_a_dowel is True):
#prerequisite
if dowel_radius <= 0 : raise Exception(' Dowel_radius must be greater than 0')
if dowel_number <= 0 : raise Exception(' Dowel_number must be greater than 0')
if dowel_tolerance < 0 : raise Exception(' Dowel_tolerance must be greater than 0')
if dowel_retreat_1 >= self.plates[i].thickness : raise Exception(' Dowel_retreat_1 must be smaller than plate '+str(i)+' thickness')
if dowel_retreat_2 >= self.plates[nb].thickness : raise Exception(' Dowel_retreat_2 must be smaller than plate '+str(nb)+' thickness')
if circle_radius <= 0 : raise Exception(' Circle_radius must be greater than 0')
if not (-180.0 <= dowel_angle_1 <= 180.0) : raise Exception(' Dowel_angle_1 must be between -180 and 180')
if not (-45.0 <= dowel_angle_2 <= 45.0) : raise Exception(' Dowel_angle_1 must be between -45 and 45')
#location
plane = self.contact_planes[i][j]
location=[]
if dowel_number == 1:
location.append(plane)
elif dowel_number > 1:
polygon = Toolbox.Curves.create_polygon(plane, circle_radius, dowel_number)
polygon = rs.RotateObject(polygon, plane.Origin, circle_rotation, plane.ZAxis)
vertices = rs.PolylineVertices(polygon)
for k in range(len(vertices)-1):
x_axis = rs.VectorCreate(plane.Origin,vertices[k])
new_plane = rs.PlaneFromNormal(vertices[k], plane.ZAxis, x_axis)
location.append(new_plane)
if tile != False :
tile = scriptcontext.doc.Objects.Add(tile)
for k in range(len(location)):
#construction lines
base_circle = tile
if tile == False :
base_circle = rs.AddCircle(location[k],float(dowel_radius))
else :
x_target = rs.CopyObject(location[k].Origin, location[k].XAxis)
y_target = rs.CopyObject(location[k].Origin, location[k].YAxis)
base_circle = Toolbox.Planes.orient(tile, rs.WorldXYPlane(), rs.RotatePlane(location[k], 90, location[k].ZAxis))
top_circle = rs.CopyObject(base_circle, self.contact_normals[i][j] * (self.plates[nb].thickness - dowel_retreat_2))
bottom_circle = rs.CopyObject(base_circle, -self.contact_normals[i][j] * (self.plates[i].thickness - dowel_retreat_1))
#inclination
if (-180 <= dowel_angle_1 <= 180) and (-45 <= dowel_angle_2 <= 45) :
if parallel is True :
ref = rs.PlaneFromFrame(plane.Origin,plane.XAxis,plane.YAxis)
ref = rs.RotatePlane(ref, dowel_angle_1, ref.ZAxis)
else :
x_axis = rs.VectorCreate(plane.Origin, location[k].Origin)
ref = rs.PlaneFromNormal(location[k].Origin, plane.ZAxis, x_axis)
top_move = (self.plates[nb].thickness - dowel_retreat_2) * math.tan(math.radians(dowel_angle_2)) * ref.XAxis
bottom_move = (self.plates[i].thickness - dowel_retreat_1) * math.tan(math.radians(dowel_angle_2)) * -ref.XAxis
rs.MoveObject(top_circle,top_move)
rs.MoveObject(bottom_circle,bottom_move)
#keys geometry
rail = rs.AddLine(rs.CurveAreaCentroid(bottom_circle)[0],rs.CurveAreaCentroid(top_circle)[0])
cylinder = rs.ExtrudeCurve(bottom_circle, rail)
rs.CapPlanarHoles(cylinder)
self.plates[nb].joints_keys.append(rs.coercebrep(cylinder))
#solid
base_circle_bool = Toolbox.Curves.offset(base_circle, - dowel_tolerance)
rail_top = rs.AddLine(rs.CurveAreaCentroid(base_circle)[0],rs.CurveAreaCentroid(top_circle)[0])
cylinder_top = rs.ExtrudeCurve(base_circle_bool, rail_top)
rail_bottom = rs.AddLine(rs.CurveAreaCentroid(base_circle)[0],rs.CurveAreaCentroid(bottom_circle)[0])
cylinder_bottom = rs.ExtrudeCurve(base_circle_bool, rail_bottom)
rs.CapPlanarHoles(cylinder_top)
rs.CapPlanarHoles(cylinder_bottom)
self.plates[i].joints_negatives.append(rs.coercebrep(cylinder_bottom))
self.plates[nb].joints_negatives.append(rs.coercebrep(cylinder_top))
#fabrication lines
top_poly = rs.ConvertCurveToPolyline(top_circle, 10)
bottom_poly = rs.ConvertCurveToPolyline(bottom_circle, 10)
base_poly = rs.ConvertCurveToPolyline(base_circle, 10)
if dowel_retreat_1 == 0 :
self.plates[i].top_holes.append(rs.coercecurve(base_poly))
self.plates[i].bottom_holes.append(rs.coercecurve(bottom_poly))
else:
self.plates[i].top_holes.append(rs.coercecurve(base_poly))
self.plates[i].bottom_holes.append(rs.coercecurve(bottom_poly))
if dowel_retreat_2 == 0 :
self.plates[nb].top_holes.append(rs.coercecurve(top_poly))
self.plates[nb].bottom_holes.append(rs.coercecurve(base_poly))
else:
self.plates[nb].top_holes.append(rs.coercecurve(top_poly))
self.plates[nb].bottom_holes.append(rs.coercecurve(base_poly))
self.log.append('Dowel joint added bewteen plates '+ str(i)+ ' and '+str(nb))
@__skip_nones
def add_tenons(self,
plates_pairs='all',
tenon_number=1.0,
tenon_length='default',
tenon_width=1.0,
tenon_spacing=1.0,
tenon_shift=0.0,):
"""Add tenon and mortise on Side-to-Face or Face-to-Side contact zones."""
#cast plate_pairs to string
if plates_pairs != 'all':
for i in range(len(plates_pairs)):
plates_pairs[i] = str(plates_pairs[i])
#conditional loop
for i in range(self.count):
types = self.contact_types[i]
for j in range(len(types)):
nb = self.contact_ids[i][j]
#specific selection function
if ((plates_pairs == 'all')
or ('('+str(i)+','+str(nb)+')' == plates_pairs)
or ('('+str(i)+','+str(nb)+')' in plates_pairs)
or ('('+str(nb)+','+str(i)+')' == plates_pairs)
or ('('+str(nb)+','+str(i)+')' in plates_pairs)):
i_want_a_tenon = True
else: i_want_a_tenon = False
#for all specified Side-to-Face connection
if (types[j] in 'SFS') and (nb > i) and i_want_a_tenon is True:
#prerequisite
if tenon_number <= 0 : raise Exception(' Tenon_number must be greater than 0')
if tenon_width <= 0 : raise Exception(' Tenon_width must be greater than 0')
#male-female parameters
if types[j] == 'SF':
male = i
female = nb
plane_zone = rs.PlaneFromFrame(self.contact_planes[i][j].Origin, self.contact_planes[i][j].XAxis, self.contact_planes[i][j].YAxis)
if types[j] == 'FS':
male = nb
female = i
plane_zone = rs.PlaneFromFrame(self.contact_planes[i][j].Origin, self.contact_planes[i][j].YAxis, self.contact_planes[i][j].XAxis)