-
Notifications
You must be signed in to change notification settings - Fork 15
/
index.js
1149 lines (953 loc) · 29.4 KB
/
index.js
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
'use strict'
const rgba = require('color-normalize')
const getBounds = require('array-bounds')
const extend = require('object-assign')
const pick = require('pick-by-alias')
const flatten = require('flatten-vertex-data')
const triangulate = require('earcut')
const normalize = require('array-normalize')
const { float32, fract32 } = require('to-float32')
const WeakMap = require('es6-weak-map')
const parseRect = require('parse-rect')
const findIndex = require('array-find-index')
const rectVert = `
precision highp float;
attribute vec2 aCoord, bCoord, aCoordFract, bCoordFract;
attribute vec4 color;
attribute float lineEnd, lineTop;
uniform vec2 scale, scaleFract, translate, translateFract;
uniform float thickness, pixelRatio, id, depth;
uniform vec4 viewport;
varying vec4 fragColor;
varying vec2 tangent;
vec2 project(vec2 position, vec2 positionFract, vec2 scale, vec2 scaleFract, vec2 translate, vec2 translateFract) {
// the order is important
return position * scale + translate
+ positionFract * scale + translateFract
+ position * scaleFract
+ positionFract * scaleFract;
}
void main() {
float lineStart = 1. - lineEnd;
float lineOffset = lineTop * 2. - 1.;
vec2 diff = (bCoord + bCoordFract - aCoord - aCoordFract);
tangent = normalize(diff * scale * viewport.zw);
vec2 normal = vec2(-tangent.y, tangent.x);
vec2 position = project(aCoord, aCoordFract, scale, scaleFract, translate, translateFract) * lineStart
+ project(bCoord, bCoordFract, scale, scaleFract, translate, translateFract) * lineEnd
+ thickness * normal * .5 * lineOffset / viewport.zw;
gl_Position = vec4(position * 2.0 - 1.0, depth, 1);
fragColor = color / 255.;
}
`
const rectFrag =`
precision highp float;
uniform float dashLength, pixelRatio, thickness, opacity, id;
uniform sampler2D dashTexture;
varying vec4 fragColor;
varying vec2 tangent;
void main() {
float alpha = 1.;
float t = fract(dot(tangent, gl_FragCoord.xy) / dashLength) * .5 + .25;
float dash = texture2D(dashTexture, vec2(t, .5)).r;
gl_FragColor = fragColor;
gl_FragColor.a *= alpha * opacity * dash;
}
`
const fillVert = `
precision highp float;
attribute vec2 position, positionFract;
uniform vec4 color;
uniform vec2 scale, scaleFract, translate, translateFract;
uniform float pixelRatio, id;
uniform vec4 viewport;
uniform float opacity;
varying vec4 fragColor;
const float MAX_LINES = 256.;
void main() {
float depth = (MAX_LINES - 4. - id) / (MAX_LINES);
vec2 position = position * scale + translate
+ positionFract * scale + translateFract
+ position * scaleFract
+ positionFract * scaleFract;
gl_Position = vec4(position * 2.0 - 1.0, depth, 1);
fragColor = color / 255.;
fragColor.a *= opacity;
}
`
const fillFrag = `
precision highp float;
varying vec4 fragColor;
void main() {
gl_FragColor = fragColor;
}
`
const milterVert = `
precision highp float;
attribute vec2 aCoord, bCoord, nextCoord, prevCoord;
attribute vec4 aColor, bColor;
attribute float lineEnd, lineTop;
uniform vec2 scale, translate;
uniform float thickness, pixelRatio, id, depth;
uniform vec4 viewport;
uniform float miterLimit, miterMode;
varying vec4 fragColor;
varying vec4 startCutoff, endCutoff;
varying vec2 tangent;
varying vec2 startCoord, endCoord;
varying float enableStartMiter, enableEndMiter;
const float REVERSE_THRESHOLD = -.875;
const float MIN_DIFF = 1e-6;
// TODO: possible optimizations: avoid overcalculating all for vertices and calc just one instead
// TODO: precalculate dot products, normalize things beforehead etc.
// TODO: refactor to rectangular algorithm
float distToLine(vec2 p, vec2 a, vec2 b) {
vec2 diff = b - a;
vec2 perp = normalize(vec2(-diff.y, diff.x));
return dot(p - a, perp);
}
bool isNaN( float val ){
return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true;
}
void main() {
vec2 aCoord = aCoord, bCoord = bCoord, prevCoord = prevCoord, nextCoord = nextCoord;
vec2 adjustedScale;
adjustedScale.x = (abs(scale.x) < MIN_DIFF) ? MIN_DIFF : scale.x;
adjustedScale.y = (abs(scale.y) < MIN_DIFF) ? MIN_DIFF : scale.y;
vec2 scaleRatio = adjustedScale * viewport.zw;
vec2 normalWidth = thickness / scaleRatio;
float lineStart = 1. - lineEnd;
float lineBot = 1. - lineTop;
fragColor = (lineStart * aColor + lineEnd * bColor) / 255.;
if (isNaN(aCoord.x) || isNaN(aCoord.y) || isNaN(bCoord.x) || isNaN(bCoord.y)) return;
if (aCoord == prevCoord) prevCoord = aCoord + normalize(bCoord - aCoord);
if (bCoord == nextCoord) nextCoord = bCoord - normalize(bCoord - aCoord);
vec2 prevDiff = aCoord - prevCoord;
vec2 currDiff = bCoord - aCoord;
vec2 nextDiff = nextCoord - bCoord;
vec2 prevTangent = normalize(prevDiff * scaleRatio);
vec2 currTangent = normalize(currDiff * scaleRatio);
vec2 nextTangent = normalize(nextDiff * scaleRatio);
vec2 prevNormal = vec2(-prevTangent.y, prevTangent.x);
vec2 currNormal = vec2(-currTangent.y, currTangent.x);
vec2 nextNormal = vec2(-nextTangent.y, nextTangent.x);
vec2 startJoinDirection = normalize(prevTangent - currTangent);
vec2 endJoinDirection = normalize(currTangent - nextTangent);
// collapsed/unidirectional segment cases
// FIXME: there should be more elegant solution
vec2 prevTanDiff = abs(prevTangent - currTangent);
vec2 nextTanDiff = abs(nextTangent - currTangent);
if (max(prevTanDiff.x, prevTanDiff.y) < MIN_DIFF) {
startJoinDirection = currNormal;
}
if (max(nextTanDiff.x, nextTanDiff.y) < MIN_DIFF) {
endJoinDirection = currNormal;
}
if (aCoord == bCoord) {
endJoinDirection = startJoinDirection;
currNormal = prevNormal;
currTangent = prevTangent;
}
tangent = currTangent;
//calculate join shifts relative to normals
float startJoinShift = dot(currNormal, startJoinDirection);
float endJoinShift = dot(currNormal, endJoinDirection);
float startMiterRatio = abs(1. / startJoinShift);
float endMiterRatio = abs(1. / endJoinShift);
vec2 startJoin = startJoinDirection * startMiterRatio;
vec2 endJoin = endJoinDirection * endMiterRatio;
vec2 startTopJoin, startBotJoin, endTopJoin, endBotJoin;
startTopJoin = sign(startJoinShift) * startJoin * .5;
startBotJoin = -startTopJoin;
endTopJoin = sign(endJoinShift) * endJoin * .5;
endBotJoin = -endTopJoin;
vec2 aTopCoord = aCoord + normalWidth * startTopJoin;
vec2 bTopCoord = bCoord + normalWidth * endTopJoin;
vec2 aBotCoord = aCoord + normalWidth * startBotJoin;
vec2 bBotCoord = bCoord + normalWidth * endBotJoin;
//miter anti-clipping
float baClipping = distToLine(bCoord, aCoord, aBotCoord) / dot(normalize(normalWidth * endBotJoin), normalize(normalWidth.yx * vec2(-startBotJoin.y, startBotJoin.x)));
float abClipping = distToLine(aCoord, bCoord, bTopCoord) / dot(normalize(normalWidth * startBotJoin), normalize(normalWidth.yx * vec2(-endBotJoin.y, endBotJoin.x)));
//prevent close to reverse direction switch
bool prevReverse = dot(currTangent, prevTangent) <= REVERSE_THRESHOLD && abs(dot(currTangent, prevNormal)) * min(length(prevDiff), length(currDiff)) < length(normalWidth * currNormal);
bool nextReverse = dot(currTangent, nextTangent) <= REVERSE_THRESHOLD && abs(dot(currTangent, nextNormal)) * min(length(nextDiff), length(currDiff)) < length(normalWidth * currNormal);
if (prevReverse) {
//make join rectangular
vec2 miterShift = normalWidth * startJoinDirection * miterLimit * .5;
float normalAdjust = 1. - min(miterLimit / startMiterRatio, 1.);
aBotCoord = aCoord + miterShift - normalAdjust * normalWidth * currNormal * .5;
aTopCoord = aCoord + miterShift + normalAdjust * normalWidth * currNormal * .5;
}
else if (!nextReverse && baClipping > 0. && baClipping < length(normalWidth * endBotJoin)) {
//handle miter clipping
bTopCoord -= normalWidth * endTopJoin;
bTopCoord += normalize(endTopJoin * normalWidth) * baClipping;
}
if (nextReverse) {
//make join rectangular
vec2 miterShift = normalWidth * endJoinDirection * miterLimit * .5;
float normalAdjust = 1. - min(miterLimit / endMiterRatio, 1.);
bBotCoord = bCoord + miterShift - normalAdjust * normalWidth * currNormal * .5;
bTopCoord = bCoord + miterShift + normalAdjust * normalWidth * currNormal * .5;
}
else if (!prevReverse && abClipping > 0. && abClipping < length(normalWidth * startBotJoin)) {
//handle miter clipping
aBotCoord -= normalWidth * startBotJoin;
aBotCoord += normalize(startBotJoin * normalWidth) * abClipping;
}
vec2 aTopPosition = (aTopCoord) * adjustedScale + translate;
vec2 aBotPosition = (aBotCoord) * adjustedScale + translate;
vec2 bTopPosition = (bTopCoord) * adjustedScale + translate;
vec2 bBotPosition = (bBotCoord) * adjustedScale + translate;
//position is normalized 0..1 coord on the screen
vec2 position = (aTopPosition * lineTop + aBotPosition * lineBot) * lineStart + (bTopPosition * lineTop + bBotPosition * lineBot) * lineEnd;
startCoord = aCoord * scaleRatio + translate * viewport.zw + viewport.xy;
endCoord = bCoord * scaleRatio + translate * viewport.zw + viewport.xy;
gl_Position = vec4(position * 2.0 - 1.0, depth, 1);
enableStartMiter = step(dot(currTangent, prevTangent), .5);
enableEndMiter = step(dot(currTangent, nextTangent), .5);
//bevel miter cutoffs
if (miterMode == 1.) {
if (enableStartMiter == 1.) {
vec2 startMiterWidth = vec2(startJoinDirection) * thickness * miterLimit * .5;
startCutoff = vec4(aCoord, aCoord);
startCutoff.zw += vec2(-startJoinDirection.y, startJoinDirection.x) / scaleRatio;
startCutoff = startCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;
startCutoff += viewport.xyxy;
startCutoff += startMiterWidth.xyxy;
}
if (enableEndMiter == 1.) {
vec2 endMiterWidth = vec2(endJoinDirection) * thickness * miterLimit * .5;
endCutoff = vec4(bCoord, bCoord);
endCutoff.zw += vec2(-endJoinDirection.y, endJoinDirection.x) / scaleRatio;
endCutoff = endCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;
endCutoff += viewport.xyxy;
endCutoff += endMiterWidth.xyxy;
}
}
//round miter cutoffs
else if (miterMode == 2.) {
if (enableStartMiter == 1.) {
vec2 startMiterWidth = vec2(startJoinDirection) * thickness * abs(dot(startJoinDirection, currNormal)) * .5;
startCutoff = vec4(aCoord, aCoord);
startCutoff.zw += vec2(-startJoinDirection.y, startJoinDirection.x) / scaleRatio;
startCutoff = startCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;
startCutoff += viewport.xyxy;
startCutoff += startMiterWidth.xyxy;
}
if (enableEndMiter == 1.) {
vec2 endMiterWidth = vec2(endJoinDirection) * thickness * abs(dot(endJoinDirection, currNormal)) * .5;
endCutoff = vec4(bCoord, bCoord);
endCutoff.zw += vec2(-endJoinDirection.y, endJoinDirection.x) / scaleRatio;
endCutoff = endCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;
endCutoff += viewport.xyxy;
endCutoff += endMiterWidth.xyxy;
}
}
}
`
const milterFrag = `
precision highp float;
uniform float dashLength, pixelRatio, thickness, opacity, id, miterMode;
uniform sampler2D dashTexture;
varying vec4 fragColor;
varying vec2 tangent;
varying vec4 startCutoff, endCutoff;
varying vec2 startCoord, endCoord;
varying float enableStartMiter, enableEndMiter;
float distToLine(vec2 p, vec2 a, vec2 b) {
vec2 diff = b - a;
vec2 perp = normalize(vec2(-diff.y, diff.x));
return dot(p - a, perp);
}
void main() {
float alpha = 1., distToStart, distToEnd;
float cutoff = thickness * .5;
//bevel miter
if (miterMode == 1.) {
if (enableStartMiter == 1.) {
distToStart = distToLine(gl_FragCoord.xy, startCutoff.xy, startCutoff.zw);
if (distToStart < -1.) {
discard;
return;
}
alpha *= min(max(distToStart + 1., 0.), 1.);
}
if (enableEndMiter == 1.) {
distToEnd = distToLine(gl_FragCoord.xy, endCutoff.xy, endCutoff.zw);
if (distToEnd < -1.) {
discard;
return;
}
alpha *= min(max(distToEnd + 1., 0.), 1.);
}
}
// round miter
else if (miterMode == 2.) {
if (enableStartMiter == 1.) {
distToStart = distToLine(gl_FragCoord.xy, startCutoff.xy, startCutoff.zw);
if (distToStart < 0.) {
float radius = length(gl_FragCoord.xy - startCoord);
if(radius > cutoff + .5) {
discard;
return;
}
alpha -= smoothstep(cutoff - .5, cutoff + .5, radius);
}
}
if (enableEndMiter == 1.) {
distToEnd = distToLine(gl_FragCoord.xy, endCutoff.xy, endCutoff.zw);
if (distToEnd < 0.) {
float radius = length(gl_FragCoord.xy - endCoord);
if(radius > cutoff + .5) {
discard;
return;
}
alpha -= smoothstep(cutoff - .5, cutoff + .5, radius);
}
}
}
float t = fract(dot(tangent, gl_FragCoord.xy) / dashLength) * .5 + .25;
float dash = texture2D(dashTexture, vec2(t, .5)).r;
gl_FragColor = fragColor;
gl_FragColor.a *= alpha * opacity * dash;
}
`
module.exports = Line2D
/** @constructor */
function Line2D (regl, options) {
if (!(this instanceof Line2D)) return new Line2D(regl, options)
if (typeof regl === 'function') {
if (!options) options = {}
options.regl = regl
}
else {
options = regl
}
if (options.length) options.positions = options
regl = options.regl
if (!regl.hasExtension('ANGLE_instanced_arrays')) {
throw Error('regl-error2d: `ANGLE_instanced_arrays` extension should be enabled');
}
// persistent variables
this.gl = regl._gl
this.regl = regl
// list of options for lines
this.passes = []
// cached shaders instance
this.shaders = Line2D.shaders.has(regl) ? Line2D.shaders.get(regl) : Line2D.shaders.set(regl, Line2D.createShaders(regl)).get(regl)
// init defaults
this.update(options)
}
Line2D.dashMult = 2
Line2D.maxPatternLength = 256
Line2D.precisionThreshold = 3e6
Line2D.maxPoints = 1e4
Line2D.maxLines = 2048
// cache of created draw calls per-regl instance
Line2D.shaders = new WeakMap()
// create static shaders once
Line2D.createShaders = function (regl) {
let offsetBuffer = regl.buffer({
usage: 'static',
type: 'float',
data: [0,1, 0,0, 1,1, 1,0]
})
let shaderOptions = {
primitive: 'triangle strip',
instances: regl.prop('count'),
count: 4,
offset: 0,
uniforms: {
miterMode: (ctx, prop) => prop.join === 'round' ? 2 : 1,
miterLimit: regl.prop('miterLimit'),
scale: regl.prop('scale'),
scaleFract: regl.prop('scaleFract'),
translateFract: regl.prop('translateFract'),
translate: regl.prop('translate'),
thickness: regl.prop('thickness'),
dashTexture: regl.prop('dashTexture'),
opacity: regl.prop('opacity'),
pixelRatio: regl.context('pixelRatio'),
id: regl.prop('id'),
dashLength: regl.prop('dashLength'),
viewport: (c, p) => [p.viewport.x, p.viewport.y, c.viewportWidth, c.viewportHeight],
depth: regl.prop('depth')
},
blend: {
enable: true,
color: [0,0,0,0],
equation: {
rgb: 'add',
alpha: 'add'
},
func: {
srcRGB: 'src alpha',
dstRGB: 'one minus src alpha',
srcAlpha: 'one minus dst alpha',
dstAlpha: 'one'
}
},
depth: {
enable: (c, p) => {
return !p.overlay
}
},
stencil: {enable: false},
scissor: {
enable: true,
box: regl.prop('viewport')
},
viewport: regl.prop('viewport')
}
// simplified rectangular line shader
let drawRectLine = regl(extend({
vert: rectVert,
frag: rectFrag,
attributes: {
// if point is at the end of segment
lineEnd: {
buffer: offsetBuffer,
divisor: 0,
stride: 8,
offset: 0
},
// if point is at the top of segment
lineTop: {
buffer: offsetBuffer,
divisor: 0,
stride: 8,
offset: 4
},
// beginning of line coordinate
aCoord: {
buffer: regl.prop('positionBuffer'),
stride: 8,
offset: 8,
divisor: 1
},
// end of line coordinate
bCoord: {
buffer: regl.prop('positionBuffer'),
stride: 8,
offset: 16,
divisor: 1
},
aCoordFract: {
buffer: regl.prop('positionFractBuffer'),
stride: 8,
offset: 8,
divisor: 1
},
bCoordFract: {
buffer: regl.prop('positionFractBuffer'),
stride: 8,
offset: 16,
divisor: 1
},
color: {
buffer: regl.prop('colorBuffer'),
stride: 4,
offset: 0,
divisor: 1
}
}
}, shaderOptions))
// create regl draw
let drawMiterLine
try {
drawMiterLine = regl(extend({
// culling removes polygon creasing
cull: {
enable: true,
face: 'back'
},
vert: milterVert,
frag: milterFrag,
attributes: {
// is line end
lineEnd: {
buffer: offsetBuffer,
divisor: 0,
stride: 8,
offset: 0
},
// is line top
lineTop: {
buffer: offsetBuffer,
divisor: 0,
stride: 8,
offset: 4
},
// left color
aColor: {
buffer: regl.prop('colorBuffer'),
stride: 4,
offset: 0,
divisor: 1
},
// right color
bColor: {
buffer: regl.prop('colorBuffer'),
stride: 4,
offset: 4,
divisor: 1
},
prevCoord: {
buffer: regl.prop('positionBuffer'),
stride: 8,
offset: 0,
divisor: 1
},
aCoord: {
buffer: regl.prop('positionBuffer'),
stride: 8,
offset: 8,
divisor: 1
},
bCoord: {
buffer: regl.prop('positionBuffer'),
stride: 8,
offset: 16,
divisor: 1
},
nextCoord: {
buffer: regl.prop('positionBuffer'),
stride: 8,
offset: 24,
divisor: 1
}
}
}, shaderOptions))
} catch (e) {
// IE/bad Webkit fallback
drawMiterLine = drawRectLine
}
// fill shader
let drawFill = regl({
primitive: 'triangle',
elements: (ctx, prop) => prop.triangles,
offset: 0,
vert: fillVert,
frag: fillFrag,
uniforms: {
scale: regl.prop('scale'),
color: regl.prop('fill'),
scaleFract: regl.prop('scaleFract'),
translateFract: regl.prop('translateFract'),
translate: regl.prop('translate'),
opacity: regl.prop('opacity'),
pixelRatio: regl.context('pixelRatio'),
id: regl.prop('id'),
viewport: (ctx, prop) => [prop.viewport.x, prop.viewport.y, ctx.viewportWidth, ctx.viewportHeight]
},
attributes: {
position: {
buffer: regl.prop('positionBuffer'),
stride: 8,
offset: 8
},
positionFract: {
buffer: regl.prop('positionFractBuffer'),
stride: 8,
offset: 8
}
},
blend: shaderOptions.blend,
depth: { enable: false },
scissor: shaderOptions.scissor,
stencil: shaderOptions.stencil,
viewport: shaderOptions.viewport
})
return {
fill: drawFill, rect: drawRectLine, miter: drawMiterLine
}
}
// used to for new lines instances
Line2D.defaults = {
dashes: null,
join: 'miter',
miterLimit: 1,
thickness: 10,
cap: 'square',
color: 'black',
opacity: 1,
overlay: false,
viewport: null,
range: null,
close: false,
fill: null
}
Line2D.prototype.render = function (...args) {
if (args.length) {
this.update(...args)
}
this.draw()
}
Line2D.prototype.draw = function (...args) {
// render multiple polylines via regl batch
(args.length ? args : this.passes).forEach((s, i) => {
// render array pass as a list of passes
if (s && Array.isArray(s)) return this.draw(...s)
if (typeof s === 'number') s = this.passes[s]
if (!(s && s.count > 1 && s.opacity)) return
this.regl._refresh()
if (s.fill && s.triangles && s.triangles.length > 2) {
this.shaders.fill(s)
}
if (!s.thickness) return
// high scale is only available for rect mode with precision
if (s.scale[0] * s.viewport.width > Line2D.precisionThreshold || s.scale[1] * s.viewport.height > Line2D.precisionThreshold) {
this.shaders.rect(s)
}
// thin this.passes or too many points are rendered as simplified rect shader
else if (s.join === 'rect' || (!s.join && (s.thickness <= 2 || s.count >= Line2D.maxPoints))) {
this.shaders.rect(s)
}
else {
this.shaders.miter(s)
}
})
return this
}
Line2D.prototype.update = function (options) {
if (!options) return
if (options.length != null) {
if (typeof options[0] === 'number') options = [{positions: options}]
}
// make options a batch
else if (!Array.isArray(options)) options = [options]
let { regl, gl } = this
// process per-line settings
options.forEach((o, i) => {
let state = this.passes[i]
if (o === undefined) return
// null-argument removes pass
if (o === null) {
this.passes[i] = null
return
}
if (typeof o[0] === 'number') o = {positions: o}
// handle aliases
o = pick(o, {
positions: 'positions points data coords',
thickness: 'thickness lineWidth lineWidths line-width linewidth width stroke-width strokewidth strokeWidth',
join: 'lineJoin linejoin join type mode',
miterLimit: 'miterlimit miterLimit',
dashes: 'dash dashes dasharray dash-array dashArray',
color: 'color colour stroke colors colours stroke-color strokeColor',
fill: 'fill fill-color fillColor',
opacity: 'alpha opacity',
overlay: 'overlay crease overlap intersect',
close: 'closed close closed-path closePath',
range: 'range dataBox',
viewport: 'viewport viewBox',
hole: 'holes hole hollow',
splitNull: 'splitNull'
})
// init state
if (!state) {
this.passes[i] = state = {
id: i,
scale: null,
scaleFract: null,
translate: null,
translateFract: null,
count: 0,
hole: [],
depth: 0,
dashLength: 1,
dashTexture: regl.texture({
channels: 1,
data: new Uint8Array([255]),
width: 1,
height: 1,
mag: 'linear',
min: 'linear'
}),
colorBuffer: regl.buffer({
usage: 'dynamic',
type: 'uint8',
data: new Uint8Array()
}),
positionBuffer: regl.buffer({
usage: 'dynamic',
type: 'float',
data: new Uint8Array()
}),
positionFractBuffer: regl.buffer({
usage: 'dynamic',
type: 'float',
data: new Uint8Array()
})
}
o = extend({}, Line2D.defaults, o)
}
if (o.thickness != null) state.thickness = parseFloat(o.thickness)
if (o.opacity != null) state.opacity = parseFloat(o.opacity)
if (o.miterLimit != null) state.miterLimit = parseFloat(o.miterLimit)
if (o.overlay != null) {
state.overlay = !!o.overlay
if (i < Line2D.maxLines) {
state.depth = 2 * (Line2D.maxLines - 1 - i % Line2D.maxLines) / Line2D.maxLines - 1.;
}
}
if (o.join != null) state.join = o.join
if (o.hole != null) state.hole = o.hole
if (o.fill != null) state.fill = !o.fill ? null : rgba(o.fill, 'uint8')
if (o.viewport != null) state.viewport = parseRect(o.viewport)
if (!state.viewport) {
state.viewport = parseRect([
gl.drawingBufferWidth,
gl.drawingBufferHeight
])
}
if (o.close != null) state.close = o.close
// reset positions
if (o.positions === null) o.positions = []
if (o.positions) {
let positions, count
// if positions are an object with x/y
if (o.positions.x && o.positions.y) {
let xPos = o.positions.x
let yPos = o.positions.y
count = state.count = Math.max(
xPos.length,
yPos.length
)
positions = new Float64Array(count * 2)
for (let i = 0; i < count; i++) {
positions[i * 2] = xPos[i]
positions[i * 2 + 1] = yPos[i]
}
}
else {
positions = flatten(o.positions, 'float64')
count = state.count = Math.floor(positions.length / 2)
}
let bounds = state.bounds = getBounds(positions, 2)
// create fill positions
// FIXME: fill positions can be set only along with positions
if (state.fill) {
let pos = []
// filter bad vertices and remap triangles to ensure shape
let ids = {}
let lastId = 0
for (let i = 0, ptr = 0, l = state.count; i < l; i++) {
let x = positions[i*2]
let y = positions[i*2 + 1]
if (isNaN(x) || isNaN(y) || x == null || y == null) {
x = positions[lastId*2]
y = positions[lastId*2 + 1]
ids[i] = lastId
}
else {
lastId = i
}
pos[ptr++] = x
pos[ptr++] = y
}
// split the input into multiple polygon at Null/NaN
if(o.splitNull){
// use "ids" to track the boundary of segment
// the keys in "ids" is the end boundary of a segment, or split point
// make sure there is at least one segment
if(!(state.count-1 in ids)) ids[state.count] = state.count-1
let splits = Object.keys(ids).map(Number).sort((a, b) => a - b)
let split_triangles = []
let base = 0
// do not split holes
let hole_base = state.hole != null ? state.hole[0] : null
if(hole_base != null){
let last_id = findIndex(splits, (e)=>e>=hole_base)
splits = splits.slice(0,last_id)
splits.push(hole_base)
}
for (let i = 0; i < splits.length; i++)
{
// create temporary pos array with only one segment and all the holes
let seg_pos = pos.slice(base*2, splits[i]*2).concat(
hole_base ? pos.slice(hole_base*2) : []
)
let hole = (state.hole || []).map((e) => e-hole_base+(splits[i]-base) )
let triangles = triangulate(seg_pos, hole)
// map triangle index back to the original pos buffer
triangles = triangles.map(
(e)=> e + base + ((e + base < splits[i]) ? 0 : hole_base - splits[i])
)
split_triangles.push(...triangles)
// skip split point
base = splits[i] + 1
}
for (let i = 0, l = split_triangles.length; i < l; i++) {
if (ids[split_triangles[i]] != null) split_triangles[i] = ids[split_triangles[i]]
}
state.triangles = split_triangles
}
else {
// treat the wholw input as a single polygon
let triangles = triangulate(pos, state.hole || [])
for (let i = 0, l = triangles.length; i < l; i++) {
if (ids[triangles[i]] != null) triangles[i] = ids[triangles[i]]
}
state.triangles = triangles
}
}
// update position buffers
let npos = new Float64Array(positions)
normalize(npos, 2, bounds)
let positionData = new Float64Array(count * 2 + 6)
// rotate first segment join
if (state.close) {
if (positions[0] === positions[count*2 - 2] &&
positions[1] === positions[count*2 - 1]) {
positionData[0] = npos[count*2 - 4]
positionData[1] = npos[count*2 - 3]
}
else {
positionData[0] = npos[count*2 - 2]
positionData[1] = npos[count*2 - 1]
}
}
else {
positionData[0] = npos[0]
positionData[1] = npos[1]
}
positionData.set(npos, 2)
// add last segment
if (state.close) {
// ignore coinciding start/end
if (positions[0] === positions[count*2 - 2] &&
positions[1] === positions[count*2 - 1]) {
positionData[count*2 + 2] = npos[2]
positionData[count*2 + 3] = npos[3]
state.count -= 1
}
else {
positionData[count*2 + 2] = npos[0]
positionData[count*2 + 3] = npos[1]