forked from journeymanoc/ltdcc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1892 lines (1521 loc) · 60.6 KB
/
main.py
File metadata and controls
1892 lines (1521 loc) · 60.6 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
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
################################################################################
# #
# Parameters -- Feel free to customize these as desired! #
# #
# The syntax of the comments is as follows: #
# # [unit] (interval of acceptable values) #
# # description #
# #
################################################################################
# Switches (`True` or `False`)
lock_only = False # Output only the model of the lock chamber
show_cage = True # Show the cage part
show_base = True # Show the base part
offset_parts = False # Offset parts so that they are easier to manipulate in other programs
fast_ellipse = True # Whether to use an cheaper approximation of SDFs for ellipses
# [-] [0, 1]
# resulting model quality, 0.0 = best, 0.5 = good, 1.0 = poor
model_quality = 0.0
# [mm] (0, +Inf)
# diameter
base_ring_thickness = 7
# [mm] (0, +Inf)
# the diameter of the base ring, can be calculated from circumference
base_ring_inner_diameter = 52
# [-] [2/3, 3/2]
# width:height ratio of the base ring
base_ring_inner_aspect_ratio = 1.00
# [mm] (-Inf, +Inf)
# base ring offset along the vertical axis to create a gap
base_ring_gap = -1
# [mm] (-Inf, +Inf)
# base ring offset along the X axis
base_ring_offset_x = -3
# [-] `True` or `False`
# enable the testicle separator
separator_enable = True
# [0, +Inf)
# the length of the testicle separator
separator_length = 30
# [-] [1, 2]
# the relative size of the sphere at the end of the testicle separator
separator_sphere_size = 1.25
# [degrees] [0, 180]
# the angle at which the separator is connected to the base ring
separator_tilt = 90
# [mm] (0, +Inf)
# the radius of the separator's curve
separator_radius = 18
# [mm] (0, +Inf)
# the diameter of cage bars
cage_thickness = 5
# [mm] (0, +Inf)
# the diameter of the free space within the cage, can be calculated from circumference
cage_inner_diameter = 30
# [mm] (0, +Inf)
# the length of the length of the cage
cage_length = 55
# [-] (4, +Inf)
# the number of lateral bars
cage_bars = 10
# [mm] (0, +Inf)
# the radius of the cage curve; lower = more curved
cage_curve_radius = 34
# [degrees] [0, 90)
# the angle of the cage at the beginning, relative to the base ring
cage_tilt = 10.0
# [mm] (0, +Inf) or `None`
# the distance between the main lateral bars (excluding their thickness); set to `None` for uniform spacing of lateral bars
cage_slit_width = 6
# [mm] (0, +Inf) or `None`
# the extra space between the shaft and each of the reinforcements at the base
# part of the shaft cage, to relieve blood flow
cage_ring_reliefs = [5, 4, 3, 1.5, 2, 5]
# [-] `True` or `False`
# whether each cage ring relief should be an elliptic arc (`True`) or a circular arc (`False`);
# circular arcs close to the lock compartment will most likely cause crashes (FIXME)
cage_ring_reliefs_elliptic = [True, True, False]
# [-] [1, +Inf)
# the width of the lock compartment
connection_width = 2
# [mm] (0, +Inf)
# the length of the lock compartment
connection_length = 20
# [mm] (-Inf, +Inf)
# the offset of the inner radius of the lock compartment (the cut out part)
connection_radius_offset_inner = 2
# [mm] (-Inf, +Inf)
# the offset of the outer radius of the lock compartment (height)
connection_radius_offset_outer = 14
# [-] [0, +Inf)
# the smoothness of the lock compartment itself
connection_smoothness = 2.0
# [mm] (-Inf, +Inf)
# offset of the cut radius to make sure the base ring or the cage ring are not cut
connection_cut_offset = 2.15
# [-] [0, +Inf)
# the smoothness of the cut
connection_cut_smoothness = 0.5
# [mm] [0, +Inf)
# the height of the top part of the lock compartment on top of which the
# optional symbol is placed.
connection_reinforcement_height = 4.5
# `0`, `1`, or `None`
# the type of the symbol or `None` for no symbol
connection_symbol_index = 0
# [-] [0, +Inf)
# the size of the symbol
connection_symbol_scale = 7 #4
# [-] [0, +Inf)
# the stroke thickness of the symbol
connection_symbol_thickness = 0.3
# [-] [0, +Inf)
# the outline stroke thickness of the symbol
connection_symbol_outline_thickness = 0.2
# [degrees] (-Inf, +Inf)
# rotation angle of the symbol
connection_symbol_angle = 0 #-60
# [mm] (-Inf, +Inf)
# position offset of the symbol and its outline
connection_symbol_offset = (-3, 0, 0) #(-4, 0, 0)
# [mm] (-Inf, +Inf)
# z offset of the symbol
connection_symbol_offset_z = -connection_reinforcement_height * 0.8
# [mm] (-Inf, +Inf)
# z offset of the symbol's outline
connection_symbol_outline_offset_z = -connection_reinforcement_height * 0.8
# [mm] (-Inf, +Inf)
# the depth of the symbol
connection_symbol_depth = -(1.5 + connection_reinforcement_height * 0.8)
# [mm] (-Inf, +Inf)
# the depth of the symbol's outline
connection_symbol_outline_depth = 0 #-(0.0 + connection_reinforcement_height * 0.8)
# [mm] [0, +Inf)
# the thickness of the condom slit
connection_condom_slit_thickness = 4
# [mm] (-Inf, +Inf)
# the position of the condom slit along the connection/lock compartment
connection_condom_slit_position = 12
# [mm] [0, +Inf)
# the smoothness of the condom slit
connection_condom_slit_smoothness = 1.0
# [degrees] (-Inf, +Inf)
# the rotation angle of the lock chamber within the lock compartment
lock_chamber_angle = 10
# [-] (0, +Inf)^n
# how many lateral bars does each top reinforcement connect, in a list; add more numbers to add more reinforcements
reinforcements_top_widths = [1]
# [mm] (0, +Inf)
# distance between the top reinforcements (including their thickness)
reinforcements_top_spacing = 5.5
# [mm] (0, +Inf)
# distance of the top reinforcements from the cap
reinforcements_top_offset = 0
# [-] (0, 1)
# how curved the top reinforcements should be to relieve blood flow
reinforcements_top_curve = [0.35, 0.7]
# [mm] (0, +Inf) or `None`
# inner height of elliptical reinforcements or `None` for circular reinforcements (note that with circular reinforcements and customized `cage_slit_width`, the reinforcements may not be uniformly tall)
reinforcements_top_relief = [1.25, 2.5]
# [-] (0, +Inf)^n
# how many lateral bars does each bottom reinforcement connect, in a list; add more numbers to add more reinforcements
reinforcements_bottom_widths = []
# [mm] (0, +Inf)
# distance between the bottom reinforcements (including their thickness)
reinforcements_bottom_spacing = 20
# [mm] (0, +Inf)
# distance of the bottom reinforcements from the cap
reinforcements_bottom_offset = 0
# [-] (0, 1)
# how curved the bottom reinforcements should be to relieve blood flow
reinforcements_bottom_curve = 0
# [mm] (0, +Inf) or `None`
# inner height of elliptical reinforcements or `None` for circular reinforcements (note that with circular reinforcements and customized `cage_slit_width`, the reinforcements may not be uniformly tall)
reinforcements_bottom_relief = None
# [mm] (0, 1]
# if your lock fits too tightly in the casing, add some space around it here
lock_margin = 0.15
# [mm] (0, 1]
# if the two parts fit too tightly, add some space between them here
part_margin = 0.15
# [mm] (-Inf, +Inf)
lock_chamber_adjustment_x = -7.0
# [mm] (-Inf, +Inf)
lock_chamber_adjustment_y = 12.0
################################################################################
# #
# End of parameter customization, implementation logic follows. #
# Be advised not to edit past this point unless you know what you are doing. #
# #
################################################################################
# Input validation
assert cage_bars % 2 == 0
assert isinstance(reinforcements_top_widths, list)
assert isinstance(reinforcements_bottom_widths, list)
# MagicLocker measurements
lock_measurements_length = 18.7
lock_measurements_stationary_cuboid_width = 2.8
lock_measurements_stationary_length = 12.5
lock_measurements_stationary_diameter = 6
lock_measurements_stationary_height = 10.3
lock_measurements_rotary_cuboid_width = 2
lock_measurements_rotary_cuboid_length_min = 3
lock_measurements_rotary_cuboid_length_max = 5
lock_measurements_rotary_diameter = 5.5
lock_measurements_rotary_height = 8.8
lock_measurements_rotary_angle = 45
lock_wall_width = 2.0
import math
from enum import Enum
from math import asin, sin, acos, atan2, radians, degrees, sqrt
import studio
from libfive.shape import Shape
import libfive as libfive
# Derived parameters
show_cage_shaft = not lock_only
lock_measurements_stationary_radius = lock_measurements_stationary_diameter / 2
lock_measurements_rotary_length = lock_measurements_length - lock_measurements_stationary_length
lock_measurements_rotary_radius = lock_measurements_rotary_diameter / 2
lock_length = lock_measurements_length + lock_margin # margin applied only once because only one side is adjacent to a wall
lock_height = lock_measurements_stationary_height + 2 * lock_margin
lock_stationary_radius = lock_measurements_stationary_radius + lock_margin
lock_stationary_cuboid_height = lock_measurements_stationary_height - lock_measurements_stationary_diameter + lock_stationary_radius
lock_stationary_cuboid_width = lock_measurements_stationary_cuboid_width + 2 * lock_margin
lock_rotary_radius = lock_measurements_rotary_radius + lock_margin
lock_rotary_cuboid_height = lock_measurements_rotary_height - lock_measurements_rotary_diameter + lock_rotary_radius
lock_rotary_cuboid_width = lock_measurements_rotary_cuboid_width + 2 * lock_margin
lock_rotary_cuboid_length_min = lock_measurements_rotary_cuboid_length_min + 2 * lock_margin # not perpendicular margin, but good enough
lock_rotary_cuboid_length_max = lock_measurements_rotary_cuboid_length_max + 2 * lock_margin # not perpendicular margin, but good enough
# Adjustment for the width of the cuboid
lock_rotary_radius_radius = (lock_rotary_radius**2 + (lock_rotary_cuboid_width / 2)**2)**0.5
lock_rotary_cuboid_height_radius = (lock_rotary_cuboid_height**2 + (lock_rotary_cuboid_width / 2)**2)**0.5
base_ring_r = base_ring_thickness / 2
base_ring_inner_diameter_1 = base_ring_inner_diameter / ((base_ring_inner_aspect_ratio - 1) / 2 + 1)
base_ring_inner_diameter_2 = base_ring_inner_diameter * ((base_ring_inner_aspect_ratio - 1) / 2 + 1)
base_ring_inner_radius_1 = base_ring_inner_diameter_1 / 2
base_ring_inner_radius_2 = base_ring_inner_diameter_2 / 2
base_ring_R1 = base_ring_inner_radius_1 + base_ring_r
base_ring_R2 = base_ring_inner_radius_2 + base_ring_r
base_ring_gap_angle = degrees(asin(base_ring_gap / cage_curve_radius))
cage_r = cage_thickness / 2
cage_inner_radius = cage_inner_diameter / 2
cage_R = cage_inner_radius + cage_r
cage_bars_half = cage_bars // 2
base_ring_offset = base_ring_offset_x + base_ring_R1 - base_ring_r + cage_r - (cage_ring_reliefs[0] if isinstance(cage_ring_reliefs, list) else cage_ring_reliefs)
if cage_slit_width is None:
cage_bar_offset_angle = 180 / cage_bars
cage_bar_offset_x = cage_R * sin(radians(cage_bar_offset_angle))
else:
cage_bar_offset_x = cage_r + cage_slit_width / 2
cage_bar_offset_angle = degrees(asin(cage_bar_offset_x / cage_R))
cage_bar_spacing_angle = (180 - 2 * cage_bar_offset_angle) / (cage_bars_half - 1)
cage_offset = cage_curve_radius * sin(radians(cage_tilt))
cage_curve_angle = degrees((cage_length - cage_R + cage_r) / cage_curve_radius) - base_ring_gap_angle
cage_curve_angle_start = degrees(asin(cage_offset / cage_curve_radius))
cage_curve_angle_end = cage_curve_angle_start + cage_curve_angle
shaft_alignment = sqrt((cage_curve_radius + cage_R)**2 - cage_offset**2)
shaft_alignment_offset = shaft_alignment - sqrt((cage_curve_radius + cage_R)**2 - max(0, cage_offset - base_ring_gap)**2)
connection_condom_slit_radius = connection_condom_slit_thickness / 2
# Rendering settings
studio.set_bounds([-200, -200, -200], [200, 200, 200])
studio.set_quality(9)
studio.set_resolution(10 * 10**(-model_quality))
Shape.transform = lambda self, vec: self.remap(*vec.destructure())
Shape.map = lambda self, map: map(self)
def nanfill(x, value):
if isinstance(x, Shape):
return x.nanfill(value)
elif math.isnan(x):
return value
else:
return x
def abs(x):
if isinstance(x, Shape):
return x.abs()
else:
return __builtins__['abs'](x)
def signum(x, nf=0):
if not isinstance(x, Shape) and x == 0:
return nf
else:
return nanfill(x / abs(x), nf)
# returns 1 for x <= 0, 0 otherwise
def piecewise_coefficient(x):
return signum(x, nf=-1) * (-0.5) + 0.5
def piecewise(x, inside, outside):
c = piecewise_coefficient(x)
return inside * c + outside * (1 - c)
def sin(x):
if isinstance(x, Shape):
return x.sin()
else:
return math.sin(x)
def cos(x):
if isinstance(x, Shape):
return x.cos()
else:
return math.cos(x)
def min(a, b):
if isinstance(a, Shape) or isinstance(b, Shape):
return Shape.min(a, b)
else:
return __builtins__['min'](a, b)
def max(a, b):
if isinstance(a, Shape) or isinstance(b, Shape):
return Shape.max(a, b)
else:
return __builtins__['max'](a, b)
def clamp(x, lower_bound, upper_bound, shape=False):
return max(lower_bound, min(upper_bound, x))
def dot(a, b):
return a.dot(b)
class Vec2:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def clone(self):
return Vec2(self.x, self.y)
@staticmethod
def symbolic():
return Vec2(Shape.X(), Shape.Y())
@staticmethod
def from_iter(iterable):
iterator = iter(iterable)
return Vec2(next(iterator), next(iterator))
def into_vec3(self, z=0):
return Vec3(self.x, self.y, z)
def atan2(self):
if isinstance(self.x, Shape) or isinstance(self.y, Shape):
return Shape.wrap(self.y).atan2(self.x)
else:
return math.atan2(self.y, self.x)
def destructure(self):
return self.x, self.y
def abs(self):
return Vec2(self.x.abs(), self.y.abs())
def __repr__(self):
return 'Vec2({}, {})'.format(self.x, self.y)
def __getitem__(self, index):
if index == 0:
return self.x
elif index == 1:
return self.y
def __setitem__(self, index, item):
if index == 0:
self.x = item
elif index == 1:
self.y = item
def __neg__(self):
return Vec2(-self.x, -self.y)
def __add__(self, other):
return Vec2(
self.x + other.x,
self.y + other.y,
)
def __sub__(self, other):
return Vec2(
self.x - other.x,
self.y - other.y,
)
def __mul__(self, other):
if isinstance(other, Vec2):
return Vec2(
self.x * other.x,
self.y * other.y,
)
else:
return Vec2(
self.x * other,
self.y * other,
)
def __rmul__(self, other):
return self * other
def __truediv__(self, other):
if isinstance(other, Vec2):
return Vec2(
self.x / other.x,
self.y / other.y,
)
else:
return Vec2(
self.x / other,
self.y / other,
)
def map(self, map):
return Vec2(
map(self.x),
map(self.y),
)
def recip(self):
return self.map(lambda x: 1 / x)
def normalize(self, p=2):
return self / self.norm(p=p)
def norm_squared(self, p=2):
if p == float("inf"):
return max(abs(self.x), abs(self.y))
return abs(self.x)**p + abs(self.y)**p
def norm(self, p=2):
norm_squared = self.norm_squared(p=p)
if p == float("inf"):
return norm_squared
if isinstance(norm_squared, Shape):
return norm_squared.nth_root(p)
else:
return norm_squared ** (1 / p)
def dot(self, other):
return self.x * other.x + self.y * other.y
class Vec3:
def __init__(self, x=0, y=0, z=0):
self.x = x
self.y = y
self.z = z
def clone(self):
return Vec3(self.x, self.y, self.z)
@staticmethod
def symbolic():
return Vec3(Shape.X(), Shape.Y(), Shape.Z())
@staticmethod
def from_iter(iterable):
iterator = iter(iterable)
return Vec3(next(iterator), next(iterator), next(iterator))
def destructure(self):
return self.x, self.y, self.z
def abs(self):
return Vec3(self.x.abs(), self.y.abs(), self.z.abs())
def __repr__(self):
return 'Vec3({}, {}, {})'.format(self.x, self.y, self.z)
def __getitem__(self, index):
if index == 0:
return self.x
elif index == 1:
return self.y
elif index == 2:
return self.z
def __setitem__(self, index, item):
if index == 0:
self.x = item
elif index == 1:
self.y = item
elif index == 2:
self.z = item
def __neg__(self):
return Vec3(-self.x, -self.y, -self.z)
def __add__(self, other):
return Vec3(
self.x + other.x,
self.y + other.y,
self.z + other.z,
)
def __sub__(self, other):
return Vec3(
self.x - other.x,
self.y - other.y,
self.z - other.z,
)
def __mul__(self, other):
if isinstance(other, Vec3):
return Vec3(
self.x * other.x,
self.y * other.y,
self.z * other.z,
)
else:
return Vec3(
self.x * other,
self.y * other,
self.z * other,
)
def __rmul__(self, other):
return self * other
def __truediv__(self, other):
if isinstance(other, Vec3):
return Vec3(
self.x / other.x,
self.y / other.y,
self.z / other.z,
)
else:
return Vec3(
self.x / other,
self.y / other,
self.z / other,
)
def map(self, map):
return Vec3(
map(self.x),
map(self.y),
map(self.z),
)
def recip(self):
return self.map(lambda x: 1 / x)
def xy(self):
return Vec2(self.x, self.y)
def normalize(self, p=2):
return self / self.norm(p=p)
def norm_squared(self, p=2):
if p == float("inf"):
return max(abs(self.x), abs(self.y), abs(self.z))
return abs(self.x)**p + abs(self.y)**p + abs(self.z)**p
def norm(self, p=2):
norm_squared = self.norm_squared(p=p)
if p == float("inf"):
return norm_squared
if isinstance(norm_squared, Shape):
return norm_squared.nth_root(p)
else:
return norm_squared ** (1 / p)
def dot(self, other):
return self.x * other.x + self.y * other.y + self.z * other.z
def vec(x=0.0, y=0.0, z=None):
if z is None:
return Vec2(x, y)
else:
return Vec3(x, y, z)
class Coords:
def __init__(self, transform=None):
assert callable(transform) or transform is None
self.transform = transform if transform is not None else lambda vec: vec
def eval(self):
return self.transform(Vec3.symbolic())
def __mul__(self, other):
return Coords(lambda vec: self.transform(other.transform(vec)))
def sqrt(x):
if type(x) == int or type(x) == float:
return x**(0.5)
else:
return x.sqrt()
def blend_extremes(generic_smoothness, shapes):
"""
Returns a max-combinator for generic_smoothness = +Inf;
and a min-combinator for generic_smoothness = -Inf.
For other values of generic_smoothness, returns `None`.
"""
combinator = None
if generic_smoothness == float("inf"):
combinator = Shape.max
elif generic_smoothness == float("-inf"):
combinator = Shape.min
if combinator is not None:
result = None;
for shape in shapes:
if result is None:
result = shape
else:
result = combinator(result, shape)
return result
else:
return None
def p_norm(p, shapes):
"""
The p-norm is suitable for blending UNSIGNED distance fields.
The result can be then transformed into a signed distance field.
It results in the nicest, smooth blending.
"""
combination = blend_extremes(p, shapes)
if combination is not None:
return combination
elif int(p) == p:
p = int(p)
sum = 0
for shape in shapes:
d = 1
for i in range(p):
d = d * shape
sum += d.abs()
return sum.nth_root(p)
else:
# For some reason, `pow(x)` is broken, so we use `nth_root(1/x)`
# instead.
sum = 0
for shape in shapes:
sum += shape.abs().nth_root(1.0/p)
return sum.nth_root(p)
def log_sum_exp(alpha, shapes):
"""
The LogSumExp is suitable for blending any distance fields.
It propagates the discontinuities inherent to distance fields and if
the absolute value of the blending parameter is set too high, it may result
in noticeable sharp edges.
"""
combination = blend_extremes(alpha, shapes)
if combination is not None:
return combination
else:
sum = 0
for shape in shapes:
sum += (shape * alpha).exp()
return (1 / alpha) * sum.log()
def blend(smoothness: float, shapes):
assert isinstance(smoothness, float)
alpha = None
if smoothness != 0:
alpha = 1 / smoothness
else:
sign = math.copysign(1, smoothness);
alpha = sign * float("inf")
return log_sum_exp(alpha, shapes)
def union(shapes, smoothness=0.0):
if len(shapes) == 0:
return float("inf")
smoothness = float(smoothness)
assert smoothness >= 0.0
smoothness = abs(smoothness)
return blend(-smoothness, shapes)
def intersect(shapes, smoothness=0.0):
if len(shapes) == 0:
return float("-inf")
smoothness = float(smoothness)
assert smoothness >= 0.0
smoothness = abs(smoothness)
return blend(smoothness, shapes)
def half_space(normal, point=Vec3()):
coords = Vec3.symbolic()
coords = coords - point
return coords.dot(normal)
def plane(normal, point=Vec3()):
return half_space(normal, point=point).abs()
def box(axes=None, center=Vec3(), half_axes=None):
if axes is None and half_axes is None:
raise 'Missing axes'
elif axes is not None and half_axes is not None:
raise 'Duplicate axes'
elif half_axes is None:
half_axes = axes * 0.5
coords = None
if isinstance(half_axes, Vec2):
coords = Vec3.symbolic().xy()
if isinstance(center, Vec3):
center = center.xy()
elif isinstance(half_axes, Vec3):
coords = Vec3.symbolic()
else:
raise 'Invalid type'
return ((coords - center) / half_axes).norm(p=float("inf")) - 1
def sphere(r, center=Vec3()):
if isinstance(center, Vec3):
coords = Vec3.symbolic()
coords = coords - center
return coords.norm() - r
elif isinstance(center, Vec2):
coords = Vec3.symbolic().xy()
coords = coords - center
return coords.norm() - r
else:
raise 'Invalid center type'
# Inigo Quilez' ellipsoid bound
def ellipsoid(axes):
r = axes
p = Vec3.symbolic()
min_axis = None
if isinstance(axes, Vec2):
p = p.xy()
min_axis = min(axes.x, axes.y)
elif isinstance(axes, Vec3):
min_axis = min(axes.x, axes.y, axes.z)
else:
raise "Wrong axes type"
k0 = (p/r).norm()
k1 = (p/(r*r)).norm()
return (k0*(k0-1.0)/k1).nanfill(min_axis)
# https://github.com/0xfaded/ellipse_demo/issues/1
def ellipse(axes):
global fast_ellipse
if fast_ellipse:
return ellipsoid(axes)
p = Vec3.symbolic().xy()
pAbs = p.abs()
ei = axes.recip()
e2 = axes * axes
ve = ei * Vec2(e2.x - e2.y, e2.y - e2.x)
t = Vec2(Shape.wrap(0.70710678118654752), Shape.wrap(0.70710678118654752))
for i in range(3):
v = ve*t*t*t
u = (pAbs - v).normalize() * (t * axes - v).norm()
w = ei * (v + u)
t = w.map(lambda x: clamp(x, 0.0, 1.0, shape=True)).normalize()
# return Shape.wrap(0)
nearestAbs = t * axes
dist = (pAbs - nearestAbs).norm()
return signum((dot(pAbs, pAbs) - dot(nearestAbs, nearestAbs))) * dist
def ellipsoid2(axes):
p = Vec3.symbolic()
px = p.x.abs()
py = p.y.abs()
a = axes.x
b = axes.y
tx = 0.707
ty = 0.707
for x in range(0, 3):
x = a * tx
y = b * ty
ex = (a*a - b*b) * tx**3 / a
ey = (b*b - a*a) * ty**3 / b
rx = x - ex
ry = y - ey
qx = px - ex
qy = py - ey
r = math.hypot(ry, rx)
q = math.hypot(qy, qx)
tx = min(1, max(0, (qx * r / q + ex) / a))
ty = min(1, max(0, (qy * r / q + ey) / b))
t = math.hypot(ty, tx)
tx /= t
ty /= t
return (Vec2(x, y) - Vec2(px, py)).norm()
def elliptical_arc(R1, R2, r, start, end, capped=False, z=0.0, debug_cut=False):
arc = p_norm(2, [
ellipse(Vec2(R1, R2)),
Vec3.symbolic().z - z,
]) - r
if end - start >= math.tau:
return arc
# cutoff_angle_start = atan2((2 / R2) * sin(start), (2 / R1) * cos(start))
# cutoff_angle_end = atan2((2 / R2) * sin(end), (2 / R1) * cos(end))
cutoff_normal_start = -Vec2(-(2 / R2) * sin(start), (2 / R1) * cos(start))
cutoff_normal_end = Vec2(-(2 / R2) * sin(end), (2 / R1) * cos(end))
cutoff_point_start = Vec2(R1 * cos(start), R2 * sin(start))
cutoff_point_end = Vec2(R1 * cos(end), R2 * sin(end))
R1_gte_R2 = nanfill(((R1 - R2) / abs(R1 - R2)), 1) * 0.5 + 0.5
lateral_cut_normal = Vec3(1 - R1_gte_R2, R1_gte_R2, 0)
# lateral_cut_tangent = Vec3(-lateral_cut_normal.y, lateral_cut_normal.x, 0)
# invert = piecewise(
# -dot(cutoff_point_start_pre, lateral_cut_normal) * dot(cutoff_point_end_pre, lateral_cut_normal),
# -((end - start) - math.pi),
# 1,
# )
# cutoff_normal_start = piecewise(invert, cutoff_normal_end_pre, cutoff_normal_start_pre)
# cutoff_normal_end = piecewise(invert, cutoff_normal_start_pre, cutoff_normal_end_pre)
# cutoff_point_start = piecewise(invert, cutoff_point_end_pre, cutoff_point_start_pre)
# cutoff_point_end = piecewise(invert, cutoff_point_start_pre, cutoff_point_end_pre)
# print('invert:', invert)
# if R1 >= R2:
# lateral_cut_normal = Vec3(0, 1, 0)
# else:
# lateral_cut_normal = Vec3(1, 0, 0)
top_cut = intersect([
half_space(-lateral_cut_normal),
union([
-dot(cutoff_point_start, lateral_cut_normal),
-dot(cutoff_point_end, lateral_cut_normal),
]),
union([
intersect([
half_space(cutoff_normal_start.into_vec3(0), cutoff_point_start.into_vec3(0)),
-dot(cutoff_point_start, lateral_cut_normal),
]),
dot(cutoff_point_start, lateral_cut_normal),
]),
union([
intersect([
half_space(cutoff_normal_end.into_vec3(0), cutoff_point_end.into_vec3(0)),
-dot(cutoff_point_end, lateral_cut_normal),
]),
dot(cutoff_point_end, lateral_cut_normal),
]),
])
bottom_cut = intersect([
half_space(lateral_cut_normal),
union([
dot(cutoff_point_start, lateral_cut_normal),
dot(cutoff_point_end, lateral_cut_normal),
]),
union([
intersect([
half_space(cutoff_normal_start.into_vec3(0), cutoff_point_start.into_vec3(0)),
dot(cutoff_point_start, lateral_cut_normal),
]),
-dot(cutoff_point_start, lateral_cut_normal),
]),
union([
intersect([
half_space(cutoff_normal_end.into_vec3(0), cutoff_point_end.into_vec3(0)),
dot(cutoff_point_end, lateral_cut_normal),
]),
-dot(cutoff_point_end, lateral_cut_normal),
]),
])
"""
top_cut = None
bottom_cut = None
if dot(cutoff_point_start, lateral_cut_normal) >= 0:
top_cut = intersect([
top_cut if top_cut is not None else half_space(-lateral_cut_normal),
half_space(cutoff_normal_start.into_vec3(0), cutoff_point_start.into_vec3(0)),
])
else:
bottom_cut = intersect([
bottom_cut if bottom_cut is not None else half_space(lateral_cut_normal),
half_space(cutoff_normal_start.into_vec3(0), cutoff_point_start.into_vec3(0)),
])
if dot(cutoff_point_end, lateral_cut_normal) >= 0:
top_cut = intersect([
top_cut if top_cut is not None else half_space(-lateral_cut_normal),
half_space(cutoff_normal_end.into_vec3(0), cutoff_point_end.into_vec3(0)),
])
else: