generated from soypat/go-module-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
operations.go
841 lines (728 loc) · 23.3 KB
/
operations.go
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
package gsdf
import (
"errors"
"fmt"
"github.com/chewxy/math32"
"github.com/soypat/glgl/math/ms2"
"github.com/soypat/glgl/math/ms3"
"github.com/soypat/gsdf/glbuild"
)
// OpUnion is the result of the [Union] operation. Prefer using [Union] to using this type directly.
//
// Normally primitives and results of operations in this package are
// not exported since their concrete type provides relatively little value.
// The result of Union is the exception to the rule since it is the
// most common operation to perform on SDFs and can provide
// several benefits to users seeking to optimize their SDFs
// creatively such as creating sectioned SDFs where conditional evaluation
// may be performed depending on the bounding boxes of the SDFs being evaluated.
//
// By exporting OpUnion users can traverse a [glbuild.Shader3D] tree looking for
// OpUnion elements and checking how heavy their computation cost is and
// evaluating if sectioning their bounding box is effective.
type OpUnion struct {
// joined contains 2 or more 3D SDFs.
// OpUnion methods will panic if joined less than 2 elements.
joined []glbuild.Shader3D
}
// Union joins the shapes of several 3D SDFs into one. Is exact.
// Union aggregates nested Union results into its own. To prevent this behaviour use [OpUnion] directly.
func Union(shaders ...glbuild.Shader3D) glbuild.Shader3D {
if len(shaders) < 2 {
panic("need at least 2 arguments to Union")
}
var U OpUnion
for i, s := range shaders {
if s == nil {
panic(fmt.Sprintf("nil %d argument to Union", i))
}
if subU, ok := s.(*OpUnion); ok {
// Discard nested union elements and join their elements.
// Results in much smaller and readable GLSL code.
U.joined = append(U.joined, subU.joined...)
} else {
U.joined = append(U.joined, s)
}
}
return &U
}
// Bounds returns the union of all joined SDFs. Implements [glbuild.Shader3D] and [gleval.SDF3].
func (u *OpUnion) Bounds() ms3.Box {
u.mustValidate()
bb := u.joined[0].Bounds()
for _, bb2 := range u.joined[1:] {
bb = bb.Union(bb2.Bounds())
}
return bb
}
// ForEachChild implements [glbuild.Shader3D].
func (u *OpUnion) ForEachChild(userData any, fn func(userData any, s *glbuild.Shader3D) error) error {
u.mustValidate()
for i := range u.joined {
err := fn(userData, &u.joined[i])
if err != nil {
return err
}
}
return nil
}
// AppendShaderName implements [glbuild.Shader].
func (u *OpUnion) AppendShaderName(b []byte) []byte {
u.mustValidate()
b = append(b, "union_"...)
// startNames := len(b)
for i := range u.joined {
b = u.joined[i].AppendShaderName(b)
if i < len(u.joined)-1 {
b = append(b, '_')
}
}
return b
}
// AppendShaderBody implements [glbuild.Shader].
func (u *OpUnion) AppendShaderBody(b []byte) []byte {
u.mustValidate()
b = glbuild.AppendDistanceDecl(b, "d", "p", u.joined[0])
for i := range u.joined[1:] {
b = append(b, "d=min(d,"...)
b = u.joined[i+1].AppendShaderName(b)
b = append(b, "(p));\n"...)
}
b = append(b, "return d;"...)
return b
}
// AppendShaderObjects implements [glbuild.Shader]. This method returns the argument buffer with no modifications. See [glbuild.Shader] for more information.
func (u *OpUnion) AppendShaderObjects(objects []glbuild.ShaderObject) []glbuild.ShaderObject {
u.mustValidate()
return objects
}
func (u *OpUnion) mustValidate() {
if len(u.joined) < 2 {
panic("OpUnion must have at least 2 elements. please prefer using gsdf.Union over gsdf.OpUnion")
}
}
// Difference is the SDF difference of a-b. Does not produce a true SDF.
func Difference(a, b glbuild.Shader3D) glbuild.Shader3D {
if a == nil || b == nil {
panic("nil argument to Difference")
}
return &diff{s1: a, s2: b}
}
type diff struct {
s1, s2 glbuild.Shader3D // Performs s1-s2.
}
func (u *diff) Bounds() ms3.Box {
return u.s1.Bounds()
}
func (s *diff) ForEachChild(userData any, fn func(userData any, s *glbuild.Shader3D) error) error {
err := fn(userData, &s.s1)
if err != nil {
return err
}
return fn(userData, &s.s2)
}
func (s *diff) AppendShaderName(b []byte) []byte {
b = append(b, "diff_"...)
b = s.s1.AppendShaderName(b)
b = append(b, '_')
b = s.s2.AppendShaderName(b)
return b
}
func (s *diff) AppendShaderBody(b []byte) []byte {
b = glbuild.AppendDistanceDecl(b, "a", "p", s.s1)
b = glbuild.AppendDistanceDecl(b, "b", "p", s.s2)
b = append(b, "return max(a,-b);"...)
return b
}
func (u *diff) AppendShaderObjects(objects []glbuild.ShaderObject) []glbuild.ShaderObject {
return objects
}
// Intersection is the SDF intersection of a ^ b. Does not produce an exact SDF.
func Intersection(a, b glbuild.Shader3D) glbuild.Shader3D {
if a == nil || b == nil {
panic("nil argument to Difference")
}
return &intersect{s1: a, s2: b}
}
type intersect struct {
s1, s2 glbuild.Shader3D // Performs s1 ^ s2.
}
func (u *intersect) Bounds() ms3.Box {
return u.s1.Bounds().Intersect(u.s2.Bounds())
}
func (s *intersect) ForEachChild(userData any, fn func(userData any, s *glbuild.Shader3D) error) error {
err := fn(userData, &s.s1)
if err != nil {
return err
}
return fn(userData, &s.s2)
}
func (s *intersect) AppendShaderName(b []byte) []byte {
b = append(b, "intersect_"...)
b = s.s1.AppendShaderName(b)
b = append(b, '_')
b = s.s2.AppendShaderName(b)
return b
}
func (s *intersect) AppendShaderBody(b []byte) []byte {
b = append(b, "return max("...)
b = s.s1.AppendShaderName(b)
b = append(b, "(p),"...)
b = s.s2.AppendShaderName(b)
b = append(b, "(p));"...)
return b
}
func (u *intersect) AppendShaderObjects(objects []glbuild.ShaderObject) []glbuild.ShaderObject {
return objects
}
// Xor is the mutually exclusive boolean operation and results in an exact SDF.
func Xor(s1, s2 glbuild.Shader3D) glbuild.Shader3D {
if s1 == nil || s2 == nil {
panic("nil argument to Xor")
}
return &xor{s1: s1, s2: s2}
}
type xor struct {
s1, s2 glbuild.Shader3D
}
func (u *xor) Bounds() ms3.Box {
return u.s1.Bounds().Union(u.s2.Bounds())
}
func (s *xor) ForEachChild(userData any, fn func(userData any, s *glbuild.Shader3D) error) error {
err := fn(userData, &s.s1)
if err != nil {
return err
}
return fn(userData, &s.s2)
}
func (s *xor) AppendShaderName(b []byte) []byte {
b = append(b, "xor_"...)
b = s.s1.AppendShaderName(b)
b = append(b, '_')
b = s.s2.AppendShaderName(b)
return b
}
func (s *xor) AppendShaderBody(b []byte) []byte {
b = glbuild.AppendDistanceDecl(b, "d1", "(p)", s.s1)
b = glbuild.AppendDistanceDecl(b, "d2", "(p)", s.s2)
b = append(b, "return max(min(d1,d2),-max(d1,d2));"...)
return b
}
func (u *xor) AppendShaderObjects(objects []glbuild.ShaderObject) []glbuild.ShaderObject {
return objects
}
// Scale scales s by scaleFactor around the origin.
func Scale(s glbuild.Shader3D, scaleFactor float32) glbuild.Shader3D {
return &scale{s: s, scale: scaleFactor}
}
type scale struct {
s glbuild.Shader3D
scale float32
}
func (u *scale) Bounds() ms3.Box {
b := u.s.Bounds()
return b.Scale(ms3.Vec{X: u.scale, Y: u.scale, Z: u.scale})
}
func (s *scale) ForEachChild(userData any, fn func(userData any, s *glbuild.Shader3D) error) error {
return fn(userData, &s.s)
}
func (s *scale) AppendShaderName(b []byte) []byte {
b = append(b, "scale_"...)
b = s.s.AppendShaderName(b)
return b
}
func (s *scale) AppendShaderBody(b []byte) []byte {
b = glbuild.AppendFloatDecl(b, "s", s.scale)
b = append(b, "return "...)
b = s.s.AppendShaderName(b)
b = append(b, "(p/s)*s;"...)
return b
}
func (u *scale) AppendShaderObjects(objects []glbuild.ShaderObject) []glbuild.ShaderObject {
return objects
}
// Symmetry reflects the SDF around one or more cartesian planes.
func Symmetry(s glbuild.Shader3D, mirrorX, mirrorY, mirrorZ bool) glbuild.Shader3D {
if !mirrorX && !mirrorY && !mirrorZ {
panic("ineffective symmetry")
}
return &symmetry{s: s, xyz: glbuild.NewXYZBits(mirrorX, mirrorY, mirrorZ)}
}
type symmetry struct {
s glbuild.Shader3D
xyz glbuild.XYZBits
}
func (u *symmetry) Bounds() ms3.Box {
box := u.s.Bounds()
if u.xyz.X() {
box.Min.X = minf(box.Min.X, -box.Max.X)
}
if u.xyz.Y() {
box.Min.Y = minf(box.Min.Y, -box.Max.Y)
}
if u.xyz.Z() {
box.Min.Z = minf(box.Min.Z, -box.Max.Z)
}
return box
}
func (s *symmetry) ForEachChild(userData any, fn func(userData any, s *glbuild.Shader3D) error) error {
return fn(userData, &s.s)
}
func (s *symmetry) AppendShaderName(b []byte) []byte {
b = append(b, "symmetry"...)
b = s.xyz.AppendMapped_XYZ(b)
b = append(b, '_')
b = s.s.AppendShaderName(b)
return b
}
func (s *symmetry) AppendShaderBody(b []byte) []byte {
b = append(b, "p."...)
b = s.xyz.AppendMapped_xyz(b)
b = append(b, "=abs(p."...)
b = s.xyz.AppendMapped_xyz(b)
b = append(b, ");\n return "...)
b = s.s.AppendShaderName(b)
b = append(b, "(p);"...)
return b
}
func (u *symmetry) AppendShaderObjects(objects []glbuild.ShaderObject) []glbuild.ShaderObject {
return objects
}
// Transform applies a 4x4 matrix transformation to the argument shader by
// inverting the argument matrix.
func Transform(s glbuild.Shader3D, m ms3.Mat4) (glbuild.Shader3D, error) {
det := m.Determinant()
if math32.Abs(det) < epstol {
return nil, errors.New("singular Mat4")
}
return &transform{s: s, t: m, tInv: m.Inverse()}, nil
}
type transform struct {
s glbuild.Shader3D
// Transformation matrix. Transforms points. We use it
// to transform the bounding box.
t ms3.Mat4 // The actual transformation matrix,
// Inverse transformation matrix needed for SDF.
// The SDF receives points which we must evaluate in
// transformed coordinates, so we must work backwards, thus inverse.
tInv ms3.Mat4
}
func (u *transform) Bounds() ms3.Box {
return u.t.MulBox(u.s.Bounds())
}
func (s *transform) ForEachChild(userData any, fn func(userData any, s *glbuild.Shader3D) error) error {
return fn(userData, &s.s)
}
func (s *transform) AppendShaderName(b []byte) []byte {
b = append(b, "transform"...)
// Hash floats so that name is not too long.
values := s.t.Array()
b = glbuild.AppendFloat(b, 'p', 'n', hashf(values[:]))
b = append(b, '_')
b = s.s.AppendShaderName(b)
return b
}
func (r *transform) AppendShaderBody(b []byte) []byte {
b = glbuild.AppendMat4Decl(b, "invT", r.tInv)
b = append(b, "return "...)
b = r.s.AppendShaderName(b)
b = append(b, "(((invT) * vec4(p,0.0)).xyz);"...)
return b
}
func (u *transform) AppendShaderObjects(objects []glbuild.ShaderObject) []glbuild.ShaderObject {
return objects
}
// Rotate is the rotation of radians angle around an axis vector.
func Rotate(s glbuild.Shader3D, radians float32, axis ms3.Vec) (glbuild.Shader3D, error) {
if axis == (ms3.Vec{}) {
return nil, errors.New("null vector")
}
T := ms3.RotationMat4(radians, axis)
return Transform(s, T)
}
// Translate moves the SDF s in the given direction (dirX, dirY, dirZ) and returns the result.
func Translate(s glbuild.Shader3D, dirX, dirY, dirZ float32) glbuild.Shader3D {
return &translate{s: s, p: ms3.Vec{X: dirX, Y: dirY, Z: dirZ}}
}
type translate struct {
s glbuild.Shader3D
p ms3.Vec
}
func (u *translate) Bounds() ms3.Box {
return u.s.Bounds().Add(u.p)
}
func (s *translate) ForEachChild(userData any, fn func(userData any, s *glbuild.Shader3D) error) error {
return fn(userData, &s.s)
}
func (s *translate) AppendShaderName(b []byte) []byte {
b = append(b, "translate"...)
arr := s.p.Array()
b = glbuild.AppendFloats(b, 0, 'n', 'p', arr[:]...)
b = append(b, '_')
b = s.s.AppendShaderName(b)
return b
}
func (s *translate) AppendShaderBody(b []byte) []byte {
b = glbuild.AppendVec3Decl(b, "t", s.p)
b = append(b, "return "...)
b = s.s.AppendShaderName(b)
b = append(b, "(p-t);"...)
return b
}
func (u *translate) AppendShaderObjects(objects []glbuild.ShaderObject) []glbuild.ShaderObject {
return objects
}
// Offset adds sdfAdd to the entire argument SDF. If sdfAdd is negative this will
// round edges and increase the dimension of flat surfaces of the SDF by the absolute magnitude.
// See [Inigo's youtube video] on the subject.
//
// [Inigo's youtube video]: https://www.youtube.com/watch?v=s5NGeUV2EyU
func Offset(s glbuild.Shader3D, sdfAdd float32) glbuild.Shader3D {
return &offset{s: s, off: sdfAdd}
}
type offset struct {
s glbuild.Shader3D
off float32
}
func (u *offset) Bounds() ms3.Box {
bb := u.s.Bounds()
bb.Max = ms3.AddScalar(-u.off, bb.Max)
bb.Min = ms3.AddScalar(u.off, bb.Min)
return bb.Canon()
}
func (s *offset) ForEachChild(userData any, fn func(userData any, s *glbuild.Shader3D) error) error {
return fn(userData, &s.s)
}
func (s *offset) AppendShaderName(b []byte) []byte {
b = append(b, "offset"...)
b = glbuild.AppendFloat(b, 'n', 'p', s.off)
b = append(b, '_')
b = s.s.AppendShaderName(b)
return b
}
func (s *offset) AppendShaderBody(b []byte) []byte {
b = append(b, "return "...)
b = s.s.AppendShaderName(b)
b = append(b, "(p)+("...)
b = glbuild.AppendFloat(b, '-', '.', s.off)
b = append(b, ')', ';')
return b
}
func (u *offset) AppendShaderObjects(objects []glbuild.ShaderObject) []glbuild.ShaderObject {
return objects
}
// Array is the domain repetition operation. It repeats domain centered around the origin (x,y,z)=(0,0,0).
func Array(s glbuild.Shader3D, spacingX, spacingY, spacingZ float32, nx, ny, nz int) (glbuild.Shader3D, error) {
if nx <= 0 || ny <= 0 || nz <= 0 {
return nil, errors.New("invalid array repeat param")
} else if spacingX <= 0 || spacingY <= 0 || spacingZ <= 0 {
return nil, errors.New("invalid array spacing")
}
return &array{s: s, d: ms3.Vec{X: spacingX, Y: spacingY, Z: spacingZ}, nx: nx, ny: ny, nz: nz}, nil
}
type array struct {
s glbuild.Shader3D
d ms3.Vec
nx, ny, nz int
}
func (u *array) Bounds() ms3.Box {
// TODO(soypat): use more accurate algorithm for bounds calculation.
sbb := u.s.Bounds()
size := ms3.MulElem(u.nvec3(), u.d)
sbb.Max = ms3.Add(sbb.Max, size)
return sbb
}
func (s *array) ForEachChild(userData any, fn func(userData any, s *glbuild.Shader3D) error) error {
return fn(userData, &s.s)
}
func (s *array) AppendShaderName(b []byte) []byte {
b = append(b, "repeat"...)
arr := s.d.Array()
b = glbuild.AppendFloats(b, 'q', 'n', 'p', arr[:]...)
arr = s.nvec3().Array()
b = glbuild.AppendFloats(b, 'q', 'n', 'p', arr[:]...)
b = append(b, '_')
b = s.s.AppendShaderName(b)
return b
}
func (s *array) nvec3() ms3.Vec { return ms3.Vec{X: float32(s.nx), Y: float32(s.ny), Z: float32(s.nz)} }
func (s *array) AppendShaderBody(b []byte) []byte {
sdf := string(s.s.AppendShaderName(nil))
// id is the tile index in 3 directions.
// o is neighbor offset direction (which neighboring tile is closest in 3 directions)
// s is scaling factors in 3 directions.
// rid is the neighboring tile index, which is then corrected for limited repetition using clamp.
b = fmt.Appendf(b, `
vec3 s = vec3(%f,%f,%f);
vec3 n = vec3(%d.,%d.,%d.);
vec3 minlim = vec3(0.,0.,0.);
vec3 id = round(p/s);
vec3 o = sign(p-s*id);
float d = %f;
for( int k=0; k<2; k++ )
for( int j=0; j<2; j++ )
for( int i=0; i<2; i++ )
{
vec3 rid = id + vec3(i,j,k)*o;
// limited repetition
rid = clamp(rid, minlim, n);
vec3 r = p - s*rid;
d = min( d, %s(r) );
}
return d;`, s.d.X, s.d.Y, s.d.Z,
s.nx-1, s.ny-1, s.nz-1,
largenum, sdf)
return b
}
func (u *array) AppendShaderObjects(objects []glbuild.ShaderObject) []glbuild.ShaderObject {
return objects
}
// SmoothUnion joins the shapes of two shaders into one with a smoothing blend.
func SmoothUnion(k float32, s1, s2 glbuild.Shader3D) glbuild.Shader3D {
if s1 == nil || s2 == nil {
panic("nil object")
}
return &smoothUnion{s1: s1, s2: s2, k: k}
}
type smoothUnion struct {
s1, s2 glbuild.Shader3D
k float32
}
func (s *smoothUnion) Bounds() ms3.Box {
return s.s1.Bounds().Union(s.s2.Bounds())
}
func (s *smoothUnion) ForEachChild(userData any, fn func(any, *glbuild.Shader3D) error) error {
err := fn(userData, &s.s1)
if err != nil {
return err
}
return fn(userData, &s.s2)
}
func (s *smoothUnion) AppendShaderName(b []byte) []byte {
b = append(b, "smoothUnion_"...)
b = glbuild.AppendFloat(b, 'n', 'd', s.k)
b = append(b, '_')
b = s.s1.AppendShaderName(b)
b = append(b, '_')
b = s.s2.AppendShaderName(b)
return b
}
func (s *smoothUnion) AppendShaderBody(b []byte) []byte {
b = glbuild.AppendDistanceDecl(b, "d1", "p", s.s1)
b = glbuild.AppendDistanceDecl(b, "d2", "p", s.s2)
b = glbuild.AppendFloatDecl(b, "k", s.k)
b = append(b, `float h = clamp( 0.5 + 0.5*(d2-d1)/k, 0.0, 1.0 );
return mix( d2, d1, h ) - k*h*(1.0-h);`...)
return b
}
func (u *smoothUnion) AppendShaderObjects(objects []glbuild.ShaderObject) []glbuild.ShaderObject {
return objects
}
// SmoothDifference performs the difference of two SDFs with a smoothing parameter.
func SmoothDifference(k float32, s1, s2 glbuild.Shader3D) glbuild.Shader3D {
if s1 == nil || s2 == nil {
panic("nil object")
}
return &smoothDiff{diff: diff{s1: s1, s2: s2}, k: k}
}
type smoothDiff struct {
diff
k float32
}
func (s *smoothDiff) AppendShaderName(b []byte) []byte {
b = append(b, "smoothDiff"...)
b = glbuild.AppendFloat(b, 'n', 'd', s.k)
b = append(b, '_')
b = s.s1.AppendShaderName(b)
b = append(b, '_')
b = s.s2.AppendShaderName(b)
return b
}
func (s *smoothDiff) AppendShaderBody(b []byte) []byte {
b = glbuild.AppendDistanceDecl(b, "d1", "p", s.s1)
b = glbuild.AppendDistanceDecl(b, "d2", "p", s.s2)
b = glbuild.AppendFloatDecl(b, "k", s.k)
b = append(b, `float h = clamp( 0.5 - 0.5*(d2+d1)/k, 0.0, 1.0 );
return mix( d1, -d2, h ) + k*h*(1.0-h);`...)
return b
}
// SmoothIntersect performs the intesection of two SDFs with a smoothing parameter.
func SmoothIntersect(k float32, s1, s2 glbuild.Shader3D) glbuild.Shader3D {
if s1 == nil || s2 == nil {
panic("nil object")
}
return &smoothIntersect{intersect: intersect{s1: s1, s2: s2}, k: k}
}
type smoothIntersect struct {
intersect
k float32
}
func (s *smoothIntersect) AppendShaderName(b []byte) []byte {
b = append(b, "smoothIntersect"...)
b = glbuild.AppendFloat(b, 'n', 'd', s.k)
b = append(b, '_')
b = s.s1.AppendShaderName(b)
b = append(b, '_')
b = s.s2.AppendShaderName(b)
return b
}
func (s *smoothIntersect) AppendShaderBody(b []byte) []byte {
b = glbuild.AppendDistanceDecl(b, "d1", "p", s.s1)
b = glbuild.AppendDistanceDecl(b, "d2", "p", s.s2)
b = glbuild.AppendFloatDecl(b, "k", s.k)
b = append(b, `float h = clamp( 0.5 - 0.5*(d2-d1)/k, 0.0, 1.0 );
return mix( d2, d1, h ) + k*h*(1.0-h);`...)
return b
}
// Elongate "stretches" the SDF in a direction by splitting it on the origin in
// the plane perpendicular to the argument direction. The part of the shape in the negative
// plane is discarded and replaced with the elongated positive part.
//
// Arguments are distances, so zero-valued arguments are no-op.
func Elongate(s glbuild.Shader3D, dirX, dirY, dirZ float32) glbuild.Shader3D {
return &elongate{s: s, h: ms3.Vec{X: dirX, Y: dirY, Z: dirZ}}
}
type elongate struct {
s glbuild.Shader3D
h ms3.Vec
}
func (u *elongate) Bounds() ms3.Box {
box := u.s.Bounds()
// Elongate splits shape around origin and keeps positive bits only.
box.Max = ms3.MaxElem(box.Max, ms3.Vec{})
box.Max = ms3.Add(box.Max, ms3.Scale(0.5, u.h))
box.Min = ms3.Scale(-1, box.Max) // Discard negative side of shape.
return box
}
func (s *elongate) ForEachChild(userData any, fn func(userData any, s *glbuild.Shader3D) error) error {
return fn(userData, &s.s)
}
func (s *elongate) AppendShaderName(b []byte) []byte {
b = append(b, "elongate"...)
arr := s.h.Array()
b = glbuild.AppendFloats(b, 0, 'n', 'p', arr[:]...)
b = append(b, '_')
b = s.s.AppendShaderName(b)
return b
}
func (s *elongate) AppendShaderBody(b []byte) []byte {
b = glbuild.AppendVec3Decl(b, "h", ms3.Scale(0.5, s.h))
b = append(b, "vec3 q=abs(p)-h;"...)
b = glbuild.AppendDistanceDecl(b, "d", "max(q,0.)", s.s)
b = append(b, "return d+min(max(q.x,max(q.y,q.z)),0.);"...)
return b
}
func (u *elongate) AppendShaderObjects(objects []glbuild.ShaderObject) []glbuild.ShaderObject {
return objects
}
// Shell carves the interior of the SDF leaving only the exterior shell of the part.
func Shell(s glbuild.Shader3D, thickness float32) glbuild.Shader3D {
return &shell{s: s, thick: thickness}
}
type shell struct {
s glbuild.Shader3D
thick float32
}
func (u *shell) Bounds() ms3.Box {
bb := u.s.Bounds()
return bb
}
func (s *shell) ForEachChild(userData any, fn func(userData any, s *glbuild.Shader3D) error) error {
return fn(userData, &s.s)
}
func (s *shell) AppendShaderName(b []byte) []byte {
b = append(b, "shell"...)
b = glbuild.AppendFloat(b, 'n', 'p', s.thick)
b = append(b, '_')
b = s.s.AppendShaderName(b)
return b
}
func (s *shell) AppendShaderBody(b []byte) []byte {
b = glbuild.AppendFloatDecl(b, "t", s.thick)
b = append(b, "return t*(abs("...)
b = s.s.AppendShaderName(b)
b = append(b, "(p/t))-t);"...)
return b
}
func (u *shell) AppendShaderObjects(objects []glbuild.ShaderObject) []glbuild.ShaderObject {
return objects
}
// CircularArray is the circular domain repetition operation around the origin (x,y,z)=(0,0,0).
// It repeats the shape numInstances times and the spacing angle is defined by circleDiv such that angle = 2*pi/circleDiv.
// The operation is defined this way so that the argument shape is evaluated only twice per circular array evaluation, regardless of instances.
func CircularArray(s glbuild.Shader3D, numInstances, circleDiv int) (glbuild.Shader3D, error) {
if circleDiv <= 1 || numInstances <= 0 {
return nil, errors.New("invalid circarray repeat param")
} else if s == nil {
return nil, errors.New("nil argument to circarray")
} else if numInstances > circleDiv {
return nil, errors.New("bad circular array instances, must be less than or equal to circleDiv")
}
return &circarray{s: s, circleDiv: circleDiv, nInst: numInstances}, nil
}
type circarray struct {
s glbuild.Shader3D
nInst int
circleDiv int
}
func (ca *circarray) Bounds() ms3.Box {
bb := ca.s.Bounds()
bb2 := ms2.Box{
Min: ms2.Vec{X: bb.Min.X, Y: bb.Min.Y},
Max: ms2.Vec{X: bb.Max.X, Y: bb.Max.Y},
}
verts := bb2.Vertices()
angle := 2 * math32.Pi / float32(ca.circleDiv)
m := ms2.RotationMat2(angle)
for i := 0; i < ca.nInst-1; i++ {
for i := range verts {
verts[i] = ms2.MulMatVec(m, verts[i])
bb2 = bb2.IncludePoint(verts[i])
}
}
bb.Max.X, bb.Max.Y = bb2.Max.X, bb2.Max.Y
bb.Min.X, bb.Min.Y = bb2.Min.X, bb2.Min.Y
return bb
}
func (ca *circarray) ForEachChild(userData any, fn func(userData any, s *glbuild.Shader3D) error) error {
return fn(userData, &ca.s)
}
// func (ca *circarray) angle() float32 { return 2 * math32.Pi / float32(ca.n) }
func (ca *circarray) AppendShaderName(b []byte) []byte {
b = append(b, "circarray"...)
b = glbuild.AppendFloats(b, 0, 'n', 'p', float32(ca.nInst), float32(ca.circleDiv))
b = append(b, '_')
b = ca.s.AppendShaderName(b)
return b
}
func (ca *circarray) AppendShaderBody(b []byte) []byte {
angle := 2 * math32.Pi / float32(ca.circleDiv)
b = glbuild.AppendFloatDecl(b, "ncirc", float32(ca.circleDiv))
b = glbuild.AppendFloatDecl(b, "angle", angle)
b = glbuild.AppendFloatDecl(b, "ninsm1", float32(ca.nInst-1))
b = append(b, `float pangle=atan(p.y, p.x);
float i=floor(pangle/angle);
if (i<0.0) i=ncirc+i;
float i0,i1;
if (i>=ninsm1) {
i0=ninsm1;
i1=0.0;
} else {
i0=i;
i1=i+1.0;
}
float c0 = cos(angle*i0);
float s0 = sin(angle*i0);
vec2 p0 = mat2(c0,-s0,s0,c0)*p.xy;
float c1 = cos(angle*i1);
float s1 = sin(angle*i1);
vec2 p1 = mat2(c1,-s1,s1,c1)*p.xy;
`...)
b = glbuild.AppendDistanceDecl(b, "d0", "vec3(p0.x,p0.y,p.z)", ca.s)
b = glbuild.AppendDistanceDecl(b, "d1", "vec3(p1.x,p1.y,p.z)", ca.s)
b = append(b, "return min(d0, d1);"...)
return b
}
func (u *circarray) AppendShaderObjects(objects []glbuild.ShaderObject) []glbuild.ShaderObject {
return objects
}