-
Notifications
You must be signed in to change notification settings - Fork 20
/
fiziko.mp
2612 lines (2438 loc) · 104 KB
/
fiziko.mp
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
% fiziko 0.2.1
% MetaPost library for physics textbook illustrations
% Copyright 2023 Sergey Slyusarev
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.
% https://github.com/jemmybutton/fiziko
%
% Here we define some things of general interest
%
pi := 3.1415926;
radian := 180/pi;
vardef sin primary x = (sind(x*radian)) enddef;
vardef cos primary x = (cosd(x*radian)) enddef;
vardef log (expr n, b) =
save rv;
numeric rv;
if n > 0:
rv := (mlog(n)/mlog(b));
else:
rv := 0;
fi;
rv
enddef;
vardef arcsind primary x = angle((1+-+x,x)) enddef;
vardef arccosd primary x = angle((x,1+-+x)) enddef;
vardef arcsin primary x = ((arcsind(x))/radian) enddef;
vardef arccos primary x = ((arccosd(x))/radian) enddef;
vardef angleRad primary x = angle(x)/radian enddef;
vardef dirRad primary x = dir(x*radian) enddef;
% used here and there.
vardef sign (expr x)=
if x > 0: 1 fi
if x < 0: -1 fi
if x = 0: 1 fi
enddef;
% This is inverted `clip`
primarydef i maskedWith p =
begingroup
save q, invertedmask, resultimage, breakpoint;
pair q[];
path invertedmask;
picture resultimage;
resultimage := i;
q1 := ulcorner(i) shifted (-1, 1);
q3 := lrcorner(i) shifted (1, -1);
q2 := (xpart(q3), ypart(q1));
q4 := (xpart(q1), ypart(q3));
breakpoint := ypart((ulcorner(p)--llcorner(p)) firstIntersectionTimes p);
invertedmask := (subpath (breakpoint, length(p) + breakpoint) of p) -- q1 -- q2 -- q3 -- q4 -- q1 -- cycle;
clip resultimage to invertedmask;
resultimage
endgroup
enddef;
%
% Since metapost is somewhat unpredictable in determining where paths intersect, here's macro
% that returns first intersection times with first path (ray) priority.
% Actually, it is so in most cases, but sometimes second path can take precedence,
% so the macro just checks whether reversing 'q' changes something
%
primarydef p firstIntersectionTimes q =
begingroup
save t;
pair t[];
t1 := p intersectiontimes q;
t2 := p intersectiontimes reverse(q);
if xpart(t1) < xpart(t2):
t3 := t1;
else:
t3 := (xpart(t2), length(q) - ypart(t2));
fi;
if xpart(t1) < 0: t3 := t2; fi;
t3
endgroup
enddef;
% This checks if point a is inside of closed path p
primarydef a isInside p =
begingroup
save ang, v, i, rv, pp;
boolean rv;
pair pp[];
ang := 0;
for i := 0 step 1/4 until (length(p)):
pp1 := (point i of p) - a;
pp2 := (point i + 1/4 of p) - a;
if (pp1 <> (0, 0)) and (pp2 <> (0, 0)):
v := angle(pp1) - angle(pp2);
if v > 180: v := v - 360; fi; if v < -180: v := v + 360; fi;
ang := ang + v;
fi;
endfor;
if abs(ang) > 355:
rv := true;
else:
rv := false;
fi;
rv
endgroup
enddef;
% rotation in radians
primarydef somethingToRotate radRotated radAngle =
somethingToRotate rotated ((radAngle/pi)*180)
enddef;
%
% some 3D stuff
%
% this one's from byrne.mp
primarydef colorone dotprodXYZ colortwo =
begingroup
save xp, yp, zp;
numeric xp[], yp[], zp[];
xp1 := (redpart colorone);
yp1 := (greenpart colorone);
zp1 := (bluepart colorone);
xp2 := (redpart colortwo);
yp2 := (greenpart colortwo);
zp2 := (bluepart colortwo);
xp1*xp2 + yp1*yp2 + zp1*zp2
endgroup
enddef;
%
% sometimes it's useful to put some arrows along the path. this macro puts them
% in the middles of the segments that have length no less than midArrowLimit;
%
midArrowLimit := 1cm;
def drawmidarrow (expr p) text t =
begingroup
save i, j, q;
path q;
j := 0;
for i := 1 upto length(p):
if arclength(subpath(i-1, i) of p) >= midArrowLimit:
q := subpath(j, i - 1/2) of p;
j := i - 1/2;
draw q t;
filldraw arrowhead q t;
fi;
endfor;
draw subpath(j, length(p)) of p t;
endgroup
enddef;
% This macro marks angles, unsurprisingly
def markAngle (expr a, o, b) (text t) =
begingroup
save p, an, d;
numeric an[], d[];
pair p;
an1 := angle(a-o);
an2 := angle(b-o) - an1;
if (an2 < 0): an2 := an2 + 360; fi;
an3 := an1 + 1/2an2;
p := center(t);
d1 := abs(ulcorner(t)-lrcorner(t));
if (an2 < 90) and (an2 > 0):
d2 := max(1/3cm, (d1/(abs(sind(an2))*1/3cm))*1/3cm);
else:
d2 := 1/3cm;
fi;
draw subpath (0, 8an2/360) of fullcircle scaled 2d2 rotated an1 shifted o withpen thinpen;
draw (t) shifted -p shifted o shifted (dir(an3)*(d2 + d1));
endgroup
enddef;
%
% Here we define some auxilary global variables
%
% Offset path algorithm can subdivide original path in order to be more precise
offsetPathSteps := 4;
% The following macro sets all the values related to minimal stroke width at once.
% It can be used to easily redefine all of them.
def defineMinStrokeWidth (expr msw) =
% We don't want to display strokes that are too thin to print. Default value
% is subject to change when needed.
minStrokeWidth := msw;
maxShadingStrokeWidth := 3/2minStrokeWidth;
% At some point it's useless to display even dashes
minDashStrokeWidth := 1/3minStrokeWidth;
% this value corresponds to particular dashing algorithm and is subject to change whenever this algorithm changes
minDashStrokeLength := 6minStrokeWidth;
dashStrokeWidthStep := (minStrokeWidth - minDashStrokeWidth)/16;
% all the shading algorithms need to know how close lines should be packed
shadingDensity := 3maxShadingStrokeWidth;
stippleSize := 3/2minStrokeWidth;
minStippleStep := 1/2stippleSize;
stippleShadingDensity := 3minStippleStep;
minStippleStrokeWidth := 1/20stippleSize;
% here are some pens
pen thinpen, thickpen, fatpen, stipplepen;
thinpen := pencircle scaled minStrokeWidth;
thickpen := pencircle scaled 3minStrokeWidth;
fatpen := pencircle scaled 6minStrokeWidth;
stipplepen := pencircle scaled stippleSize;
enddef;
defineMinStrokeWidth(1/5pt);
% here we set global light direction
def defineLightDirection (expr ldx, ldy) =
pair lightDirection;
color lightDirectionVectorXYZ;
lightDirection := (ldx, ldy);
lightDirectionVectorXYZ := (0, 0, 1);
lightDirectionVectorXYZ := rotateXYZaround.x(lightDirectionVectorXYZ, ldy);
lightDirectionVectorXYZ := rotateXYZaround.y(lightDirectionVectorXYZ, ldx);
enddef;
vardef rotateXYZaround@# (expr p, a) =
save partProj, rv;
pair partProj;
color rv;
if str @# = "x":
partProj := (greenpart(p), bluepart(p)) radRotated -a;
rv := (redpart(p), xpart(partProj), ypart(partProj));
elseif str @# = "y":
partProj := (redpart(p), bluepart(p)) radRotated -a;
rv := (xpart(partProj), greenpart(p), ypart(partProj));
elseif str @# = "z":
partProj := (redpart(p), greenpart(p)) radRotated -a;
rv := (xpart(partProj), ypart(partProj), bluepart(p));
else:
errmessage("What axis is " & str @# & "?");
fi;
rv
enddef;
defineLightDirection(-1/8pi, 1/8pi);
boolean shadowsEnabled;
shadowsEnabled := false;
%
% To simplify further calculations we need subdivided original path
%
vardef pathSubdivideBase (expr p, subdivideStep, i) =
save returnPath, sp;
path returnPath, sp;
returnPath := point i of p;
if i<length(p):
sp := subpath(i, i + subdivideStep) of p;
returnPath := returnPath .. controls (postcontrol 0 of sp) and (precontrol 1 of sp) .. pathSubdivideBase (p, subdivideStep, i + subdivideStep);
fi;
if (i = 0) and (cycle p):
(subpath(0, length(returnPath)-1) of returnPath) .. controls (postcontrol length(returnPath)-1 of returnPath) and (precontrol length(returnPath) of returnPath) .. cycle
else:
returnPath
fi
enddef;
vardef offsetPathSubdivide (expr p) =
pathSubdivideBase(p, 1/offsetPathSteps, 0)
enddef;
vardef pathSubdivide (expr p, n) =
pathSubdivideBase(p, 1/n, 0)
enddef;
%
% This macro creates a template offset path to a straight line, so we can correct angles
% It might appear as if we need to calculate derivative of the function somehow, instead of mocking it
% but this function might be anything, function of coordinates of distance to some point etc.,
% so consider this a lazy way to do the right thing.
%
% either offsetPathTime or offsetPathLength are intended to be used as arguments. offsetPathTime is for time and offsetPathLength is for distance
%
vardef offsetPathTemplate (expr p, i) (text offsetFunction) =
save returnPath, offsetPathTime, offsetPathLength, instantDirection, nextDirection;
numeric offsetPathTime, offsetPathLength, currentAngle;
pair instantDirection, nextDirection;
path returnPath;
if (i <= length(p)):
offsetPathTime := i;
else:
offsetPathTime := length(p);
fi;
if (arclength(p) > 0):
offsetPathLength := arclength(subpath (0, i) of p)/arclength(p);
else:
offsetPathLength := 0;
fi;
returnPath := (arclength(subpath (0, i) of p), offsetFunction);
if (i < length(p)):
% this thing is glitchy, but should be more accurate
%if (arclength(subpath (0, i) of p) < arclength(subpath (0, i + 1/4) of p)):
% offsetPathTime := i + 1/4;
% offsetPathLength := arclength(subpath (0, i + 1/4) of p)/arclength(p);
% instantDirection := unitvector((arclength(subpath (0, i + 1/4) of p), offsetFunction) - point 0 of returnPath);
% offsetPathTime := i + 1;
% offsetPathLength := arclength(subpath (0, i + 1) of p)/arclength(p);
% nextDirection := (arclength(subpath (0, i + 1) of p), offsetFunction);
% offsetPathTime := i + 3/4;
% offsetPathLength := arclength(subpath (0, i + 3/4) of p)/arclength(p);
% nextDirection := unitvector(nextDirection - (arclength(subpath (0, i + 3/4) of p), offsetFunction));
% returnPath := returnPath{instantDirection} .. {nextDirection}offsetPathTemplate(p, i + 1)(offsetFunction);
% returnPath := returnPath -- offsetPathTemplate(p, i + 1)(offsetFunction);
%else:
returnPath := returnPath -- offsetPathTemplate(p, i + 1)(offsetFunction);
%fi;
fi;
returnPath
enddef;
%
% This macro creates offset path p based on previously built template q, instead of function itself
% It is loosely based on something called Tiller-Hanson heuristic as described here:
% http://math.stackexchange.com/questions/465782/control-points-of-offset-bezier-curve
%
vardef offsetPathGenerate (expr p, q, i) =
save returnPath, c, d, a, pl, ps;
path returnPath, pl[];
pair c[], d[];
numeric a[];
c1 := precontrol i of p;
c2 := point i of p;
c3 := postcontrol i of p;
if abs(c1-c2) = 0:
c1 := c2 shifted (c2-c3);
fi;
if abs(c3-c2) = 0:
c3 := c2 shifted (c2-c1);
fi;
if (abs(c1-c2) > 0) and (abs(c2-c3) > 0):
d1 := unitvector(c1-c2) rotated -90;
d2 := unitvector(c2-c3) rotated -90;
pl1 := (unitvector(c2-c1)--unitvector(c1-c2))
scaled arclength(subpath (i - 1/2, i + 1/2) of p)
shifted (point i of p shifted (d1 scaled ypart(point i of q)));
pl2 := (unitvector(c2-c3)--unitvector(c3-c2))
scaled arclength(subpath (i - 1/2, i + 1/2) of p)
shifted (point i of p shifted (d2 scaled ypart(point i of q)));
if (abs(angle(d1) - angle(d2)) > 2) and (xpart(pl1 intersectiontimes pl2) > 0):
c4 := pl1 intersectionpoint pl2;
else:
c4 := c2 shifted (d1 scaled ypart(point i of q));
fi;
returnPath := c4;
else:
returnPath := c2 shifted (unitvector( (point i-1 of p) - (point i+1 of p) rotated -90) scaled ypart (point i of q));
fi;
if i < length(p):
path ps;
ps := subpath (i, i + 1) of p;
c1 := point 0 of ps;
c2 := postcontrol 0 of ps;
c3 := precontrol 1 of ps;
c4 := point 1 of ps;
c5 := point 0 of returnPath;
if (abs(c3-c4)>0)
and (abs(c1-c2)>0)
and (abs(c1-c4)>0)
and (abs(direction i of q) > 0):
c6 := c4 shifted (unitvector(c4 - c3) rotated 90 scaled ypart(point i + 1 of q));
%if abs(direction i of q) > 0:
a1 := angle(direction i of q);
%else:
% a1 := angle((point (i + 1/10) of q) - (point (i - 1/10) of q));
%fi;
%if abs(direction i + 1 of q) > 0:
a2 := angle(direction i + 1 of q);
%else:
% a2 := angle((point (i + 1 + 1/10) of q) - (point (i + 1 - 1/10) of q));
%fi;
c7 := (c2 - c1) scaled (abs(c5-c6)/abs(c1-c4)) rotated a1 shifted c5;
c8 := (c3 - c4) scaled (abs(c5-c6)/abs(c1-c4)) rotated a2 shifted c6;
returnPath := returnPath .. controls c7 and c8 .. offsetPathGenerate (p, q, i + 1);
else:
returnPath := returnPath -- offsetPathGenerate (p, q, i + 1);
fi;
fi;
returnPath
enddef;
%
% Frontend for offsetPathGenerate and offsetPathTemplate
%
vardef offsetPath (expr p)(text offsetFunction) =
offsetPathGenerate (p, offsetPathTemplate(p, 0)(offsetFunction), 0)
enddef;
%
% Brush macro. It draws line with brush of variable width.
% For parts thicker than minStrokeWidth it uses offsetPath functions'
% results, for thiner parts it draws dashed lines of fixed width
%
def brushGenerate (expr p, q, i) =
begingroup
save w, brushPath, bt, t;
numeric w[], t[];
path brushPath[], bt;
bt := q;
w0 := (ypart(urcorner(bt)));
w1 := (ypart(lrcorner(bt)));
t := cutPathTime(bt, minStrokeWidth);
if ((w0 > minStrokeWidth)
and (w1 < minStrokeWidth)
and (t > 0)
and (t < length(p))
and (arclength(p) > minDashStrokeLength)
and (i < 10)):
brushGenerate (subpath (0, t) of p, subpath (0, t) of q, i + 1);
brushGenerate (subpath (t, length(p)) of p, subpath (t, length(q)) of q, i + 1);
elseif (arclength(p) > 0):
if (w0 > 99/100minStrokeWidth)
and (w1 > 99/100minStrokeWidth):
brushPath1 := offsetPathGenerate (p, q yscaled 1/2, 0);
brushPath2 := offsetPathGenerate (p, q yscaled -1/2, 0);
fill brushPath1 -- reverse(brushPath2) -- cycle;
elseif (w0 < 101/100minStrokeWidth) and (w1 < 101/100minStrokeWidth):
thinBrushGenerate (p, q, 0)
fi;
fi;
endgroup
enddef;
%
% macro for thin lines which are actually dashed
%
vardef thinBrushGenerate@#(expr p, q, i) =
begingroup
save w, brushPath, bt, t, h, minLength, minWidth, dashPatternImage;
numeric w[], t[];
path brushPath[], bt;
picture dashPatternImage;
if (str @# = "") or (str @# = "hatches"):
minLength := minDashStrokeLength;
minWidth := minDashStrokeWidth;
elseif str @# = "stipples":
minLength := minStippleStep;
minWidth := minStippleStrokeWidth;
fi;
bt := q;
w0 := ypart(urcorner(bt));
w1 := ypart(lrcorner(bt));
if (w0 > minWidth + 1/100):
if (w1 > minWidth - 1/100):
w2 := floor((1/2(w0 + w1) - minWidth)/dashStrokeWidthStep)*dashStrokeWidthStep + minWidth;
else:
w2 := minWidth;
fi;
t := cutPathTime(bt, w2);
brushPath1 := subpath (0, t) of p;
brushPath2 := subpath (t, length(p)) of p;
if (((w0 - w1) >= dashStrokeWidthStep) and (i < 15))
and ((arclength(brushPath1) > minLength)
or (arclength(brushPath2) > minLength))
and (t > 1/100) and (t < length(p) - 1/100):
thinBrushGenerate@#(brushPath1, subpath (0, t) of q, i + 1);
thinBrushGenerate@#(brushPath2, subpath (t, length(q)) of q, i + 1);
else:
if (str @# = "") or (str @# = "hatches"):
if (w2 > minStrokeWidth):
w2 := minStrokeWidth;
fi;
if (w2 >= minWidth) and (arclength(p) > 0):
if (w2 < minStrokeWidth) and (arclength(p) > minLength):
draw p withpen thinpen dashed thinBrushPattern(w2, arclength(p));
else:
draw p withpen thinpen;
fi;
fi;
elseif str @# = "stipples":
begingroup
interim linecap := rounded;
save stippleSizeVar;
stippleSizeVar := stippleSize;
save stippleSize;
w2 := 1/3w2;
if (w2 >= minWidth) and (arclength(p) > 0):
stippleSize := stippleSizeVar * (0.9 + uniformdeviate(0.3));
dashPatternImage := stipplesBrushPattern(w2, arclength(p));
if urcorner(dashPatternImage) <> (0,0):
brushPath1 := offsetPathGenerate (p, (q yscaled 0) shifted (0, 1/3stippleShadingDensity), 0);
draw brushPath1 withpen (pencircle scaled stippleSize) dashed dashPatternImage;
fi;
stippleSize := stippleSizeVar * (0.9 + uniformdeviate(0.3));
dashPatternImage := stipplesBrushPattern(w2, arclength(p));
if urcorner(dashPatternImage) <> (0,0):
brushPath2 := offsetPathGenerate (p, (q yscaled 0) shifted (0, -1/3stippleShadingDensity), 0);
draw brushPath2 withpen (pencircle scaled stippleSize) dashed dashPatternImage;
fi;
stippleSize := stippleSizeVar * (0.9 + uniformdeviate(0.3));
dashPatternImage := stipplesBrushPattern(w2, arclength(p));
if urcorner(dashPatternImage) <> (0,0):
draw p withpen (pencircle scaled stippleSize) dashed dashPatternImage;
fi;
fi;
endgroup
fi;
fi;
fi;
endgroup
enddef;
%
% this macro returns path as a shaded edge
%
vardef shadedEdge (expr p) =
image(
brushGenerate (p,
offsetPathTemplate (p, 0) (
1/2minStrokeWidth + 2*minStrokeWidth
* normalVectorToLightness(
sphereAnglesToNormalVector(
(angleRad(point offsetPathTime of p), arcsin(1/2))
), 0, point offsetPathTime of p
)
), 0);
)
enddef;
%
% Whenever we have brush thinner than minStrokeWidth we call this dash pattern macro
%
vardef thinBrushPattern (expr w, l) =
save d;
numeric d[];
d0 := w;
if d0 > minStrokeWidth: d0 := minStrokeWidth; fi;
% d1 is a result of some arbitrary function of line width
% we do not use simple linear function because minimal dash length
% also shouldn't be less than minStrokeWidth.
% After we get d1 other measurements are calculated,
% so filled area per unit length remains adequate and dashes are aligned
% with segments
% d1*mSW = (d1*w + d2*w) -> d2=d1(mSW-w)/w
d1 := (1/2minDashStrokeLength) + (((d0/minStrokeWidth)**(5/2))*1/2minDashStrokeLength);
d1 := d1 + 1/2uniformdeviate(d1);
d2 := (minStrokeWidth - d0)*(d1/d0);
d3 := round(l/(d2 + d1));
if (d3 < 1): d3 := 1; fi;
d4 := (l/d3)/(d2 + d1);
d1 := d1*d4;
d2 := d2*d4;
if (uniformdeviate(2) > 1):
dashpattern (on d1/2 off d2 on d1/2)
else:
dashpattern (off d2/2 on d1 off d2/2)
fi
enddef;
%
% Stipples are also dashes
%
vardef stipplesBrushPattern (expr w, l) =
save d, n, rn, rv, ss;
ss := 1/1000;
numeric d[];
picture rv;
%if w > stippleSize:
% d0 := minStippleStep;
%else:
n := (w*l)/(stippleSize**2);
rn := floor(n);
if rn > 0:
d0 := l/rn;
fi;
%fi;
if rn > 0:
d1 := uniformdeviate(d0);
d2 := d0-d1;
if rn >=3:
d3 := uniformdeviate(d0);
d4 := d0-d3;
%if uniformdeviate(2) > 1:
% d5 := uniformdeviate(d0);
% d6 := d0-d5;
% rv := dashpattern (off d1 on ss off (d2+d5)-ss on ss off (d4+d6)-ss on ss off d3-ss);
%else:
rv := dashpattern (off d1 on ss off (d2+d3)-ss on ss off d4-ss);
%fi;
else:
rv := dashpattern (off d1 on ss off d2-ss);
fi;
else:
if uniformdeviate(1) < n:
rv := dashpattern (off uniformdeviate(l-ss) on ss off l);
else:
rv := image();
fi;
fi;
rv
enddef;
%
% macro that actually draws line of variable width
%
vardef brush (expr p) (text offsetFunction) =
image(
brushGenerate (p, offsetPathTemplate(p, 0)(offsetFunction), 0);
)
enddef;
%
% same, but only for thin brushes
%
vardef thinBrush@#(expr p) (text offsetFunction) =
image(
thinBrushGenerate@#(p, offsetPathTemplate(p, 0)(offsetFunction), 0);
)
enddef;
%
% This macro generates tube between paths p and q, of variable width d
% Tube is subdivided into segments in such a way that within every segment
% we need 2**n lines to generate even fill
%
vardef tubeGenerate@#(expr p, q, d, i) =
save w, bw, k, t, tubeWidth, sp, currentPath, currentTubePath, currentDepth, lineDensity;
numeric w[], bw[], t, currentDepth;
path tubeWidth, sp, currentPath, currentTubePath;
tubeWidth := d yscaled 2;
if (str @# = "") or (str @# = "hatches"):
lineDensity := shadingDensity;
elseif (str @# = "stipples"):
lineDensity := stippleShadingDensity;
fi;
w0 := (ypart(urcorner(tubeWidth))) - 1/1000;
w1 := (ypart(lrcorner(tubeWidth))) + 1/1000;
w2 := ceiling(log(w0/lineDensity, 2));
w3 := ceiling(log(w1/lineDensity, 2));
if ((w2 > w3) and (i<20)):
t := cutPathTime(tubeWidth, lineDensity*(2**(w2-1)));
tubeGenerate@#(subpath (0, t) of p, subpath (0, t) of q, subpath (0, t) of d, i + 1);
tubeGenerate@#(subpath (t, length(p)) of p, subpath (t, length(q)) of q, subpath (t, length(d)) of d, i + 1);
else:
if (arclength(p) > 0) and (arclength(q) > 0):
bw1 := 2**w2;
currentTubePath := interpath (1/2, q, p);
for k := 0 upto bw1:
currentPath := interpath (k/bw1, q, p);
angleOnTube := arcsin(((k/bw1)*2) - 1);
currentDepth := -abs((1-sin(angleOnTube + 1/2pi))*w0);
if shadowsEnabled:
currentPath := shadowCut(currentPath, currentDepth);
fi;
if (str @# = "") or (str @# = "hatches"):
brushGenerate (currentPath,
offsetPathTemplate(currentPath, 0)(
maxShadingStrokeWidth
if odd (k): * (abs(ypart(point offsetPathTime of tubeWidth)/bw1) - 1/2lineDensity) fi
* normalVectorToLightness(
tubeAnglesToNormalVector((
angleOnTube,
angleRad(direction offsetPathTime of currentTubePath),
angleRad(direction offsetPathTime of (tubeWidth yscaled 1/2))
)), currentDepth, point offsetPathTime of currentPath)
), 0);
elseif (str @# = "stipples"):
begingroup
save stippleShadingDensity;
if w2 > 0:
stippleShadingDensity := 2w0/(2**w2); % When the distance between the lines changes, wtipples should spread further apart
else:
stippleShadingDensity := w0;
fi;
thinBrushGenerate.@#(currentPath,
offsetPathTemplate(currentPath, 0)(
stippleSize
if odd (k): * (abs(ypart(point offsetPathTime of tubeWidth)/bw1) - 1/2lineDensity) fi
* normalVectorToLightness(
tubeAnglesToNormalVector((
angleOnTube,
angleRad(direction offsetPathTime of currentTubePath),
angleRad(direction offsetPathTime of (tubeWidth yscaled 1/2))
)), currentDepth, point offsetPathTime of currentPath)
), 0);
endgroup
fi;
endfor;
fi;
fi;
enddef;
%
% This macro is analogous to tubeGenerate, but draws transverse strokes
% result is somewhat suboptimal for now, but in simple cases it works ok
%
def tubeGenerateAlt (expr p, q, d) =
begingroup
save spth, lpth, currentPath, pos, t, pthdir, corr, o, l, i, j, k, tubeAngle, pathAngle, scorr, dt;
numeric l[];
path spth, lpth, currentPath;
pos := 0;
j := 0;
forever:
dt := (xpart(point pos of d) + 1/2shadingDensity);
scorr := cosd(angle(direction xpart(d intersectiontimes ((dt, ypart(lrcorner(d))) -- (dt, ypart(urcorner(d))))) of d));
t1 := arctime ((arclength(subpath(0, pos) of p)) + shadingDensity/scorr) of p;
t2 := arctime ((arclength(subpath(0, pos) of q)) + shadingDensity/scorr) of q;
if (arclength(subpath(pos, t1) of p) < arclength(subpath(pos, t1) of q)):
pthdir := -1;
t3 := t1;
else:
pthdir := 1;
t3 := t2;
fi;
corr := round(arclength(subpath(pos, t3) of if pthdir = 1: p else: q fi)/(shadingDensity/scorr));
if (corr < 1): corr := 1; fi;
corr := (arclength(subpath(pos, t3) of if pthdir = 1: p else: q fi) - (corr*(shadingDensity/scorr)))/corr;
t3 := arctime (arclength(subpath(0, t3) of if pthdir = 1: q else: p fi) - 1/3corr) of if pthdir = 1: q else: p fi;
spth := subpath(pos, t3) of if pthdir = 1: q else: p fi;
lpth := subpath(pos, t3) of if pthdir = 1: p else: q fi;
tubeAngle := angleRad(direction 1/2[pos, t3] of d);
pathAngle := angleRad(direction 1/2 of interpath (1/2, spth, lpth));
pos := t3;
l1 := round(arclength(lpth)/(shadingDensity/scorr));
if (l1 < 1): l1 := 1; fi;
l2 := arclength(lpth)/(l1*(shadingDensity/scorr));
for i := 0 upto l1 - 1:
j := j + 1;
k := i*(arclength(lpth)/l1);
currentPath := point (arctime k of lpth) of spth -- point (arctime k of lpth) of lpth;
currentPath := offsetPathSubdivide(currentPath);
brushGenerate (
currentPath,
offsetPathTemplate(currentPath, 0)(
maxShadingStrokeWidth
* orderFade(offsetPathLength[1/l1, l2], j)
* normalVectorToLightness(
tubeAnglesToNormalVector((
arcsin(pthdir*((offsetPathLength*2)-1)),
pathAngle,
tubeAngle)
), -2(1/2arclength(currentPath))+sqrt(1 - (2offsetPathLength - 1)**2)*(1/2arclength(currentPath)), point offsetPathTime of currentPath)
)
, 0);
endfor;
exitif pos >= length(p);
endfor;
endgroup
enddef;
%
% This macro converts some measurements of point on tube to absolute angle.
% Since there are three such measurements, macro gets them as as a single
% argument of "color" type, in case it would eventually appear as a result
% of some other macro.
%
% redpart is the angle on the tube's circumference
% greenpart is the angle of the tube path
% bluepart is the angle of the tube's outline
%
vardef tubeAnglesToNormalVector (expr p) =
save normalVector;
color normalVector;
normalVector := (0, 0, 1);
normalVector := rotateXYZaround.y(normalVector, -bluepart(p));
normalVector := rotateXYZaround.x(normalVector, redpart(p));
normalVector := rotateXYZaround.z(normalVector, -greenpart(p));
normalVector
enddef;
%
% frontend to simplify tube drawing. tubeOutline variable changes on every call
% of the function and can be used afterwards.
%
path tubeOutline;
boolean drawTubeEnds;
drawTubeEnds := true;
vardef tube@#(expr p)(text offsetFunction)=
save q, respic;
path q[];
picture respic;
q0 := offsetPathSubdivide(p);
q1 := offsetPathTemplate(q0, 0)(offsetFunction);
q2 := offsetPathGenerate (q0, q1, 0);
q3 := offsetPathGenerate (q0, q1 yscaled -1, 0);
tubeOutline := q3--reverse(q2)--cycle;
if str @# = "e":
if not drawTubeEnds:
image(
draw q2 withpen thinpen;
draw q3 withpen thinpen;
)
else:
tubeOutline
fi
else:
image(
if str @# = "l":
respic := image(tubeGenerate (q2, q3, q1, 0););
elseif str @# = "s":
respic := image(tubeGenerate.stipples(q2, q3, q1, 0);)
elseif str @# = "t":
respic := image(tubeGenerateAlt (q2, q3, q1););
fi;
if (cycle p) or (not drawTubeEnds):
draw q2 withpen thinpen;
draw q3 withpen thinpen;
else:
draw q2--reverse(q3)--cycle withpen thinpen;
fi;
clip respic to (q2--reverse(q3)--cycle);
draw respic;
)
fi
enddef;
%
% Sphere can be used as a cap for a tube, so it has same 2**n lines.
%
vardef sphere@#(expr d) =
save currentCircle, origCircle, currentRadius, currentDepth, order, circleThickness, lineDensity, shadingPicture;
path currentCircle, origCircle;
numeric currentRadius, currentDepth, order;
picture shadingPicture;
if (str @# = "") or (str @# = "c"):
lineDensity := shadingDensity;
elseif (str @# = "s"):
lineDensity := stippleShadingDensity;
fi;
origCircle := fullcircle;
order := 2**ceiling(log((1/2d)/lineDensity, 2));
image(
draw fullcircle scaled d withpen thinpen;
shadingPicture := image(
for i := 1 upto order:
currentRadius := i/order;
currentCircle := origCircle scaled (currentRadius*d) rotated uniformdeviate (1/4pi);
if odd(i):
circleThickness := maxShadingStrokeWidth * ((abs(d - (lineDensity*order)))/order);
else:
circleThickness := maxShadingStrokeWidth;
fi;
currentDepth:= -(1-sqrt(1-currentRadius**2))*(1/2d);
if shadowsEnabled:
currentCircle := shadowCut(currentCircle, currentDepth);
fi;
if (str @# = "") or (str @# = "c"):
brushGenerate (currentCircle,
offsetPathTemplate (currentCircle, 0) (
circleThickness
* normalVectorToLightness(
sphereAnglesToNormalVector(
(angleRad(point offsetPathTime of currentCircle), arcsin(currentRadius))
), currentDepth, point offsetPathTime of currentCircle
)
), 0);
elseif (str @# = "s"):
begingroup
save stippleShadingDensity;
if order > 0:
stippleShadingDensity := d/order; % When the distance between the lines changes, wtipples should spread further ap
else:
stippleShadingDensity := 1/2d;
fi;
thinBrushGenerate.stipples(currentCircle,
offsetPathTemplate (currentCircle, 0) (
circleThickness
* normalVectorToLightness(
sphereAnglesToNormalVector(
(angleRad(point offsetPathTime of currentCircle), arcsin(currentRadius))
), currentDepth, point offsetPathTime of currentCircle
)
), 0);
endgroup
fi;
endfor;
);
clip shadingPicture to (fullcircle scaled d);
draw shadingPicture;
)
enddef;
%
% Alternative sphere macro. It's all about latitudinal strokes.
% The idea is: when we have a sphere with evenly distributed parallel strokes
% we know how their density rises towards edge in a projection,
% so all we need to do is to fade lines correspondingly
%
vardef sphereLat (expr d, lat) =
save p, a, x, y, sphlat, latrad, n, c, currentPath, nline, tlat;
path p[], currentPath, currentArc;
sphlat := 0;
nline := 0;
latrad := (2pi*lat/360);
n := ceiling((pi*1/2d)/shadingDensity);
if (cosd(lat) <> 0): tlat := (sind(lat)/cosd(lat)); fi;
image(
draw fullcircle scaled d withpen thinpen;
p0 := fullcircle rotated 90;
for nline := 1 upto n-1:
sphlat := nline*(pi/n);
if (sphlat + latrad < pi) and (sphlat + latrad > 0):
if (cosd(lat) <> 0):
if (sin(sphlat) <> 0):
x := tlat*(cos(sphlat)/sin(sphlat));
else:
x := 0;
fi;
else:
if ((sphlat > 1/2pi) and (lat > 0)) or ((sphlat < 1/2pi) and (lat < 0)):
x := -2;
else:
x := 2;
fi;
fi;
if (abs(x) <= 1):
y := arcsin(x);
p1 := subpath(6 + 8y/2pi, 2 - 8y/2pi) of p0;
else:
p1 := p0;
fi;
if (x > -1) and (arclength(p1) > 0):
currentPath := (p1 scaled (d*sin(sphlat)) yscaled sind(lat)) shifted (0, 1/2d*cos(sphlat)*cosd(lat));
currentPath := offsetPathSubdivide(currentPath);
brushGenerate(currentPath,
offsetPathTemplate(currentPath, 0)(
maxShadingStrokeWidth * orderFade(
sqrt(1 -
abs(
ypart(point offsetPathTime of currentPath)/(1/2d),
1 - abs(
1 - abs(
xpart(point offsetPathTime of currentPath)
/(1/2d)
)
)**abs(sind(lat))
)**2)
, nline)
* normalVectorToLightness(
sphereAnglesToNormalVector((
(
if (abs(point offsetPathTime of currentPath) > 0):
angleRad(point offsetPathTime of currentPath)
else:
0
fi
), arcsin(2abs(point offsetPathTime of currentPath)/(d+1)))
), 0, point offsetPathTime of currentPath)
), 0);
fi;