File: markers.py

package info (click to toggle)
python-vispy 0.16.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 9,112 kB
  • sloc: python: 61,648; javascript: 6,800; ansic: 2,104; makefile: 141; sh: 6
file content (1088 lines) | stat: -rw-r--r-- 37,679 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) Vispy Development Team. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
# -----------------------------------------------------------------------------
"""Marker Visual and shader definitions."""
import numpy as np

from ..color import ColorArray
from ..gloo import VertexBuffer
from .shaders import Function, Variable
from .visual import Visual
from ..util.event import Event


_VERTEX_SHADER = """
uniform float u_antialias;
uniform float u_px_scale;
uniform bool u_scaling;
uniform bool u_spherical;
uniform float u_canvas_size_min;
uniform float u_canvas_size_max;

attribute vec3 a_position;
attribute vec4 a_fg_color;
attribute vec4 a_bg_color;
attribute float a_edgewidth;
attribute float a_size;
attribute float a_symbol;

varying vec4 v_fg_color;
varying vec4 v_bg_color;
varying float v_edgewidth;
varying float v_total_size;
varying float v_depth_middle;
varying float v_alias_ratio;
varying float v_symbol;

float big_float = 1e10; // prevents numerical imprecision

void main (void) {
    v_fg_color  = a_fg_color;
    v_bg_color  = a_bg_color;
    // fluctuations can mess "fake integers" up, so we do +0.5 and floor to make sure it's right
    v_symbol = a_symbol + 0.5;

    // Set up v_texcoord (hook may do nothing for points mode)
    $setup_texcoord();

    vec4 pos = vec4(a_position, 1);
    vec4 fb_pos = $visual_to_framebuffer(pos);
    vec4 x;
    vec4 size_vec;

    // NOTE: gl_stuff uses framebuffer coords!
    if (u_scaling) {
        // scaling == "scene": scale marker using entire visual -> framebuffer set of transforms
        // scaling == "visual": scale marker using only the Visual's transform
        pos = $framebuffer_to_scene_or_visual(fb_pos);
        x = $framebuffer_to_scene_or_visual(fb_pos + vec4(big_float, 0, 0, 0));
        x = (x - pos);
        // multiply that direction by the size and add it to the position
        // this gives us the position of the edge of the point, which we convert in screen space
        size_vec = $scene_or_visual_to_framebuffer(pos + normalize(x) * a_size);
        // divide by `w` for perspective, and subtract pos
        // this gives us the actual screen-space size of the point
        $v_size = size_vec.x / size_vec.w - fb_pos.x / fb_pos.w;
        v_edgewidth = ($v_size / a_size) * a_edgewidth;
    }
    else {
        // scaling == "fixed": marker is always the same number of pixels
        $v_size = a_size * u_px_scale;
        v_edgewidth = a_edgewidth * u_px_scale;
    }

    // Optional canvas size clamping
    float original_size = $v_size;
    if (u_canvas_size_min >= 0.0) {
        $v_size = max($v_size, u_canvas_size_min);
    }
    if (u_canvas_size_max >= 0.0) {
        $v_size = min($v_size, u_canvas_size_max);
    }
    // Update edge width proportionally if size was clamped
    if ($v_size != original_size) {
        v_edgewidth = v_edgewidth * ($v_size / original_size);
        // Floor: ensure edge is visible even when markers are clamped at max size
        if (u_canvas_size_min >= 0.0) {
            v_edgewidth = max(v_edgewidth, u_canvas_size_min * 0.5);
        }
        // Cap: prevent edge from exploding or dominating the marker when clamped at min size
        v_edgewidth = min(v_edgewidth, $v_size * 0.5);
    }

    // Total size including edge and antialiasing
    float total_size = $v_size + 4. * (v_edgewidth + 1.5 * u_antialias);
    v_total_size = total_size;

    // Apply offset and set position (hook handles differences between modes)
    vec4 final_fb_pos = $apply_offset(fb_pos, total_size);
    gl_Position = $framebuffer_to_render(final_fb_pos);
    gl_PointSize = total_size;  // Used for GL_POINTS, ignored for triangles

    if (u_spherical == true) {
        // similar as above for scaling, but in towards the screen direction
        // Get the framebuffer z direction relative to this sphere in visual coords
        vec4 z = $framebuffer_to_scene_or_visual(fb_pos + vec4(0, 0, big_float, 0));
        z = (z - pos);
        // Get the depth of the sphere in its middle point on the screen
        // size/2 because we need the radius, not the diameter
        vec4 depth_z_vec = $scene_or_visual_to_framebuffer(pos + normalize(z) * a_size / 2);
        v_depth_middle = depth_z_vec.z / depth_z_vec.w - fb_pos.z / fb_pos.w;
        // size ratio between aliased and non-aliased, needed for correct depth
        v_alias_ratio = total_size / $v_size;
    }
}
"""


_FRAGMENT_SHADER = """#version 120
uniform vec3 u_light_position;
uniform vec3 u_light_color;
uniform float u_light_ambient;
uniform float u_alpha;
uniform float u_antialias;
uniform bool u_spherical;

varying vec4 v_fg_color;
varying vec4 v_bg_color;
varying float v_edgewidth;
varying float v_total_size;
varying float v_depth_middle;
varying float v_alias_ratio;
varying float v_symbol;


bool isnan(float val) {
  return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true;
}

bool isinf(float val) {
    return (val != 0.0 && val * 2.0 == val) ? true : false;
}

// provides `apply_lighting` and `write_depth` functions
$lighting_functions

void main()
{
    // Discard plotting marker body and edge if zero-size or nan/inf.
    // Sometimes edgewidth becomes nan/inf even if size is not exactly zero here due to float
    // imprecision. We really are checking for `a_size == 0`, but this is the fragment shader proxy
    if ($v_size <= 0. || isnan($v_size) || isinf($v_size) || isnan(v_edgewidth) || isinf(v_edgewidth))
        discard;

    float edgealphafactor = min(v_edgewidth, 1.0);

    float size = $v_size + 4.*(v_edgewidth + 1.5*u_antialias);
    // factor 6 for acute edge angles that need room as for star marker

    // The marker function needs to be linked with this shader
    vec2 pointcoord = $pointcoord;
    float r = $marker(pointcoord, v_total_size, int(v_symbol));

    // it takes into account an antialising layer
    // of size u_antialias inside the edge
    // r:
    // [-e/2-a, -e/2+a] antialising face-edge
    // [-e/2+a, e/2-a] core edge (center 0, diameter e-2a = 2t)
    // [e/2-a, e/2+a] antialising edge-background
    // use max because we don't want negative transition zone
    float t = max(0.5*v_edgewidth - u_antialias, 0);
    float d = abs(r) - t;

    if (r > 0.5*v_edgewidth + u_antialias)
    {
        // out of the marker (beyond the outer edge of the edge
        // including transition zone due to antialiasing)
        discard;
    }

    vec4 facecolor = apply_lighting(pointcoord, v_bg_color);
    vec4 edgecolor = apply_lighting(pointcoord, vec4(v_fg_color.rgb, edgealphafactor*v_fg_color.a));

    if (d < 0.0)
    {
        // inside the width of the edge
        // (core, out of the transition zone for antialiasing)
        gl_FragColor = edgecolor;
    }
    else if (v_edgewidth == 0.)
    {// no edge
        if (r > -u_antialias)
        {// outside
            float alpha = 1.0 + r/u_antialias;
            alpha = exp(-alpha*alpha);
            gl_FragColor = vec4(facecolor.rgb, alpha*facecolor.a);
        }
        else
        {// inside
            gl_FragColor = facecolor;
        }
    }
    else
    {// non-zero edge
        float alpha = d/u_antialias;
        alpha = exp(-alpha*alpha);
        if (r > 0.)
        {
            // outer part of the edge: fade out into the background...
            gl_FragColor = vec4(edgecolor.rgb, alpha*edgecolor.a);
        }
        else
        {
            // inner part of the edge: fade into the face color
            gl_FragColor = mix(facecolor, edgecolor, alpha);
        }
    }

    // Apply depth change if spherical mode is active
    write_depth(pointcoord);
}
"""

_SPHERICAL_LIGHTING = """
vec4 apply_lighting(vec2 pointcoord, vec4 color) {
    // multiply by alias_ratio and then clamp, so we're back to non-alias coordinates
    // and the aliasing ring has the same coordinates as the point just inside,
    // which is important for lighting
    vec2 texcoord = (pointcoord * 2 - 1) * v_alias_ratio;
    float x = clamp(texcoord.x, -1, 1);
    float y = clamp(texcoord.y, -1, 1);
    float z = sqrt(clamp(1 - x*x - y*y, 0, 1));
    vec3 normal = vec3(x, y, z);

    // Diffuse color
    float diffuse = dot(u_light_position, normal);
    // clamp, because 0 < theta < pi/2
    diffuse = clamp(diffuse, 0, 1);
    vec3 diffuse_color = u_light_ambient + u_light_color * diffuse;

    // Specular color
    //   reflect light wrt normal for the reflected ray, then
    //   find the angle made with the eye
    vec3 eye = vec3(0, 0, -1);
    float specular = dot(reflect(u_light_position, normal), eye);
    specular = clamp(specular, 0, 1);
    // raise to the material's shininess, multiply with a
    // small factor for spread
    specular = pow(specular, 80);
    vec3 specular_color = u_light_color * specular;

    return vec4(color.rgb * diffuse_color + specular_color, color.a * u_alpha);
}

void write_depth(vec2 pointcoord) {
    // Compute depth change and write modified depth for spherical lighting
    vec2 texcoord = (pointcoord * 2 - 1) * v_alias_ratio;
    float x = clamp(texcoord.x, -1, 1);
    float y = clamp(texcoord.y, -1, 1);
    float z = sqrt(clamp(1 - x*x - y*y, 0, 1));
    // TODO: figure out why this 0.5 is needed, despite already having the radius, not diameter
    float depth_change = -0.5 * z * v_depth_middle;
    gl_FragDepth = gl_FragCoord.z + depth_change;
}
"""

_FLAT_LIGHTING = """
vec4 apply_lighting(vec2 pointcoord, vec4 color) {
    return color;
}

void write_depth(vec2 pointcoord) {
    // No-op: leave gl_FragDepth unmodified for early-Z optimization
}
"""

disc = """
float r = length((pointcoord.xy - vec2(0.5,0.5))*size);
r -= $v_size/2.;
return r;
"""


arrow = """
const float sqrt2 = sqrt(2.);
float half_size = $v_size/2.;
float ady = abs(pointcoord.y -.5)*size;
float dx = (pointcoord.x -.5)*size;
float r1 = abs(dx) + ady - half_size;
float r2 = dx + 0.25*$v_size + ady - half_size;
float r = max(r1,-r2);
return r/sqrt2;//account for slanted edge and correct for width
"""


ring = """
float r1 = length((pointcoord.xy - vec2(0.5,0.5))*size) - $v_size/2.;
float r2 = length((pointcoord.xy - vec2(0.5,0.5))*size) - $v_size/4.;
float r = max(r1,-r2);
return r;
"""

clobber = """
const float sqrt3 = sqrt(3.);
const float PI = 3.14159265358979323846264;
const float t1 = -PI/2;
float circle_radius = 0.32 * $v_size;
float center_shift = 0.36/sqrt3 * $v_size;
//total size (horizontal) = 2*circle_radius + sqrt3*center_shirt = $v_size
vec2  c1 = vec2(cos(t1),sin(t1))*center_shift;
const float t2 = t1+2*PI/3;
vec2  c2 = vec2(cos(t2),sin(t2))*center_shift;
const float t3 = t2+2*PI/3;
vec2  c3 = vec2(cos(t3),sin(t3))*center_shift;
//xy is shift to center marker vertically
vec2 xy = (pointcoord.xy-vec2(0.5,0.5))*size + vec2(0.,-0.25*center_shift);
float r1 = length(xy - c1) - circle_radius;
float r2 = length(xy - c2) - circle_radius;
float r3 = length(xy - c3) - circle_radius;
float r = min(min(r1,r2),r3);
return r;
"""


square = """
float r = max(abs(pointcoord.x -.5)*size, abs(pointcoord.y -.5)*size);
r -= $v_size/2.;
return r;
"""

x = """
vec2 rotcoord = vec2((pointcoord.x + pointcoord.y - 1.) / sqrt(2.),
 (pointcoord.y - pointcoord.x) / sqrt(2.));
//vbar
float r1 = abs(rotcoord.x)*size - $v_size/6.;
float r2 = abs(rotcoord.y)*size - $v_size/2.;
float vbar = max(r1,r2);
//hbar
float r3 = abs(rotcoord.y)*size - $v_size/6.;
float r4 = abs(rotcoord.x)*size - $v_size/2.;
float hbar = max(r3,r4);
return min(vbar, hbar);
"""


diamond = """
float r = abs(pointcoord.x -.5)*size + abs(pointcoord.y -.5)*size;
r -= $v_size/2.;
return r / sqrt(2.);//account for slanted edge and correct for width
"""


vbar = """
float r1 = abs(pointcoord.x - 0.5)*size - $v_size/6.;
float r3 = abs(pointcoord.y - 0.5)*size - $v_size/2.;
float r = max(r1,r3);
return r;
"""

hbar = """
float r2 = abs(pointcoord.y - 0.5)*size - $v_size/6.;
float r3 = abs(pointcoord.x - 0.5)*size - $v_size/2.;
float r = max(r2,r3);
return r;
"""

cross = """
//vbar
float r1 = abs(pointcoord.x - 0.5)*size - $v_size/6.;
float r2 = abs(pointcoord.y - 0.5)*size - $v_size/2.;
float vbar = max(r1,r2);
//hbar
float r3 = abs(pointcoord.y - 0.5)*size - $v_size/6.;
float r4 = abs(pointcoord.x - 0.5)*size - $v_size/2.;
float hbar = max(r3,r4);
return min(vbar, hbar);
"""


tailed_arrow = """
const float sqrt2 = sqrt(2.);
float half_size = $v_size/2.;
float ady = abs(pointcoord.y -.5)*size;
float dx = (pointcoord.x -.5)*size;
float r1 = abs(dx) + ady - half_size;
float r2 = dx + 0.25*$v_size + ady - half_size;
float arrow = max(r1,-r2);
//hbar
float upper_bottom_edges = ady - $v_size/8./sqrt2;
float left_edge = -dx - half_size;
float right_edge = dx + ady - half_size;
float hbar = max(upper_bottom_edges, left_edge);
float scale = 1.; //rescaling for slanted edge
if (right_edge >= hbar)
{
hbar = right_edge;
scale = sqrt2;
}
if (arrow <= hbar)
{
return arrow / sqrt2;//account for slanted edge and correct for width
}
else
{
return hbar / scale;
}
"""


triangle_up = """
float height = $v_size*sqrt(3.)/2.;
float bottom = ((pointcoord.y - 0.5)*size - height/2.);
float rotated_y = sqrt(3.)/2. * (pointcoord.x - 0.5) * size
  - 0.5 * ((pointcoord.y - 0.5)*size - height/6.) + height/6.;
float right_edge = (rotated_y - height/2.);
float cc_rotated_y = -sqrt(3.)/2. * (pointcoord.x - 0.5)*size
  - 0.5 * ((pointcoord.y - 0.5)*size - height/6.) + height/6.;
float left_edge = (cc_rotated_y - height/2.);
float slanted_edges = max(right_edge, left_edge);
return max(slanted_edges, bottom);
"""

triangle_down = """
float height = -$v_size*sqrt(3.)/2.;
float bottom = -((pointcoord.y - 0.5)*size - height/2.);
float rotated_y = sqrt(3.)/2. * (pointcoord.x - 0.5) * size
- 0.5 * ((pointcoord.y - 0.5)*size - height/6.) + height/6.;
float right_edge = -(rotated_y - height/2.);
float cc_rotated_y = -sqrt(3.)/2. * (pointcoord.x - 0.5)*size
- 0.5 * ((pointcoord.y - 0.5)*size - height/6.) + height/6.;
float left_edge = -(cc_rotated_y - height/2.);
float slanted_edges = max(right_edge, left_edge);
return max(slanted_edges, bottom);
"""


star = """
float star = -10000.;
const float PI2_5 = 3.141592653589*2./5.;
const float PI2_20 = 3.141592653589/10.;  //PI*2/20
// downwards shift to that the marker center is halfway vertically
// between the top of the upward spike (y = -v_size/2.)
// and the bottom of one of two downward spikes
// (y = +v_size/2.*cos(2.*pi/10.) approx +v_size/2.*0.8)
// center is at -v_size/2.*0.1
float shift_y = -0.05*$v_size;
// first spike upwards,
// rotate spike by 72 deg four times to complete the star
for (int i = 0; i <= 4; i++)
{
//if not the first spike, rotate it upwards
float x = (pointcoord.x - 0.5)*size;
float y = (pointcoord.y - 0.5)*size;
float spike_rot_angle = float(i) * PI2_5;
float cosangle = cos(spike_rot_angle);
float sinangle = sin(spike_rot_angle);
float spike_x = x;
float spike_y = y + shift_y;
if (i > 0)
{
spike_x = cosangle * x - sinangle * (y + shift_y);
spike_y = sinangle * x + cosangle * (y + shift_y);
}
// in the frame where the spike is upwards:
// rotate 18 deg the zone x < 0 around the top of the star
// (point whose coords are -s/2, 0 where s is the size of the marker)
// compute y coordonates as well because
// we do a second rotation to put the spike at its final position
float rot_center_y = -$v_size/2.;
float rot18x = cos(PI2_20) * spike_x
- sin(PI2_20) * (spike_y - rot_center_y);
//rotate -18 deg the zone x > 0 arount the top of the star
float rot_18x = cos(PI2_20) * spike_x
+ sin(PI2_20) * (spike_y - rot_center_y);
float bottom = spike_y - $v_size/10.;
// max(left edge, right edge)
float spike = max(bottom, max(rot18x, -rot_18x));
if (i == 0)
{// first spike, skip the rotation
star = spike;
}
else // i > 0
{
star = min(star, spike);
}
}
return star;
"""

cross_lines = """
//vbar
float r1 = abs(pointcoord.x - 0.5)*size;
float r2 = abs(pointcoord.y - 0.5)*size - $v_size/2;
float vbar = max(r1,r2);
//hbar
float r3 = abs(pointcoord.y - 0.5)*size;
float r4 = abs(pointcoord.x - 0.5)*size - $v_size/2;
float hbar = max(r3,r4);
return min(vbar, hbar);
"""

symbol_shaders = {
    'disc': disc,
    'arrow': arrow,
    'ring': ring,
    'clobber': clobber,
    'square': square,
    'x': x,
    'diamond': diamond,
    'vbar': vbar,
    'hbar': hbar,
    'cross': cross,
    'tailed_arrow': tailed_arrow,
    'triangle_up': triangle_up,
    'triangle_down': triangle_down,
    'star': star,
    'cross_lines': cross_lines,
}

# combine all the symbol shaders in a big if-else statement
symbol_func = f"""
float symbol(vec2 pointcoord, float size, int symbol) {{
   {' else'.join(
    f''' if (symbol == {i}) {{
        // {name}
        {shader}
    }}'''
    for i, (name, shader) in enumerate(symbol_shaders.items())
    )}
}}"""

# aliases
symbol_aliases = {
    'o': 'disc',
    '+': 'cross',
    '++': 'cross_lines',
    's': 'square',
    '-': 'hbar',
    '|': 'vbar',
    '->': 'tailed_arrow',
    '>': 'arrow',
    '^': 'triangle_up',
    'v': 'triangle_down',
    '*': 'star',
}

symbol_shader_values = {name: i for i, name in enumerate(symbol_shaders)}
symbol_shader_values.update({
    **{alias: symbol_shader_values[name] for alias, name in symbol_aliases.items()},
})


class MarkersVisual(Visual):
    """Visual displaying marker symbols.

    Parameters
    ----------
    pos : array
        The array of locations to display each symbol.
    size : float or array
        The symbol size in screen (or data, if scaling is on) px.
    edge_width : float or array or None
        The width of the symbol outline in screen (or data, if scaling is on) px.
        Defaults to 1.0 if None or not provided and ``edge_width_rel`` is not
        provided.
    edge_width_rel : float or array or None
        The width as a fraction of marker size. Can not be specified along with
        edge_width. A ValueError will be raised if both are provided.
    edge_color : Color | ColorArray
        The color used to draw each symbol outline.
    face_color : Color | ColorArray
        The color used to draw each symbol interior.
    symbol : str or array
        The style of symbol used to draw each marker (see Notes).
    scaling : str | bool
        Scaling method of individual markers. If set to "fixed" (default) then
        no scaling is done and markers will always be the same number of
        pixels on the screen. If set to "scene" then the chain of transforms
        from the Visual's transform to the transform mapping to the OpenGL
        framebuffer are used to scaling the marker. This has the effect of the
        marker staying the same size in the "scene" coordinate space and
        changing size as the visualization is zoomed in and out. If set to
        "visual" the marker is scaled only using the transform of the Visual
        and not the rest of the scene/camera. This means that something like
        a camera changing the view will not affect the size of the marker, but
        the user can still scale it using the Visual's transform. For
        backwards compatibility this can be set to the boolean ``False`` for
        "fixed" or ``True`` for "scene".
    alpha : float
        The opacity level of the visual.
    antialias : float
        Antialiasing amount (in px).
    spherical : bool
        Whether to add a spherical effect on the marker using lighting.
    light_color : Color | ColorArray
        The color of the light used to create the spherical effect.
    light_position : array
        The coordinates of the light used to create the spherical effect.
    light_ambient : float
        The amount of ambient light used to create the spherical effect.
    method : str
        Rendering method for markers. Options are:

        * 'points' (default): Use GL_POINTS primitive. Fast but may have
          platform-specific size limitations.
        * 'instanced': Use instanced rendering of quads. Works around point
          size limitations on some platforms.

    Notes
    -----
    Allowed style strings are: disc, arrow, ring, clobber, square, diamond,
    vbar, hbar, cross, tailed_arrow, x, triangle_up, triangle_down,
    and star.
    """

    _shaders = {
        'vertex': _VERTEX_SHADER,
        'fragment': _FRAGMENT_SHADER,
    }
    _symbol_shader_values = symbol_shader_values
    _symbol_shader = symbol_func

    def __init__(self, scaling="fixed", alpha=1, antialias=1, spherical=False,
                 light_color='white', light_position=(1, -1, 1), light_ambient=0.3,
                 method='points', **kwargs):
        self._vbo = VertexBuffer()
        self._quad_vbo = None
        self._data = None
        self._scaling = "fixed"
        self._canvas_size_limits = None

        if method not in ('points', 'instanced'):
            raise ValueError(f"method must be 'points' or 'instanced', got {method!r}")

        self._method = method

        # Set up quad vertices for instanced rendering
        if method == 'instanced':
            # instancing draws a small quad for each marker
            # Use 4 vertices with TRIANGLE_STRIP (no index buffer needed!)
            # TRIANGLE_STRIP automatically forms 2 triangles from 4 vertices
            # Order: bottom-left, bottom-right, top-left, top-right
            # Forms triangles: (0,1,2) and (2,1,3) with auto-reversed winding
            quad_vertices = np.array([
                [-0.5, -0.5],  # 0: bottom-left
                [0.5, -0.5],   # 1: bottom-right
                [-0.5, 0.5],   # 2: top-left
                [0.5, 0.5],    # 3: top-right
            ], dtype=np.float32)
            self._quad_vbo = VertexBuffer(quad_vertices)

        Visual.__init__(self, vcode=self._shaders['vertex'], fcode=self._shaders['fragment'])
        self._symbol_func = Function(self._symbol_shader)
        self.shared_program.frag['marker'] = self._symbol_func
        self._v_size_var = Variable('varying float v_size')
        self.shared_program.vert['v_size'] = self._v_size_var
        self.shared_program.frag['v_size'] = self._v_size_var
        self._symbol_func['v_size'] = self._v_size_var
        self.shared_program['u_canvas_size_min'] = -1.0
        self.shared_program['u_canvas_size_max'] = -1.0

        if method == 'instanced':
            self._draw_mode = 'triangle_strip'

            # instanced mode, use v_texcoord instead of gl_PointCoord
            setup_texcoord_func = Function("""
                void setup_texcoord() {
                    vec2 coord = $a_quad_pos + 0.5;
                    coord.y = 1.0 - coord.y;
                    $v_texcoord = coord;
                }
            """)

            # offset the framebuffer position to match gl_PointSize behavior (but without aliasing)
            apply_offset_func = Function("""
                vec4 apply_offset(vec4 fb_pos, float total_size) {
                    vec2 offset = $a_quad_pos * total_size;
                    return fb_pos + vec4(offset, 0, 0);
                }
            """)

            v_texcoord_var = Variable('varying vec2 v_texcoord')
            setup_texcoord_func['v_texcoord'] = v_texcoord_var
            frag_pointcoord = v_texcoord_var

            setup_texcoord_func['a_quad_pos'] = self._quad_vbo
            apply_offset_func['a_quad_pos'] = self._quad_vbo
        else:
            self._draw_mode = 'points'
            # GL_POINTS mode: noop setup, no offset, use gl_PointCoord for pointcoord
            setup_texcoord_func = Function("void setup_texcoord() {}")
            apply_offset_func = Function("vec4 apply_offset(vec4 fb_pos, float total_size) { return fb_pos; }")

            frag_pointcoord = "gl_PointCoord"

        self.shared_program.vert['setup_texcoord'] = setup_texcoord_func
        self.shared_program.vert['apply_offset'] = apply_offset_func
        self.shared_program.frag['pointcoord'] = frag_pointcoord

        self._setup_lighting_functions(spherical)

        self.set_gl_state(depth_test=True, blend=True,
                          blend_func=('src_alpha', 'one_minus_src_alpha'))

        self.events.add(data_updated=Event)

        if len(kwargs) > 0:
            self.set_data(**kwargs)

        self.scaling = scaling
        self.antialias = antialias
        self.light_color = light_color
        self.light_position = light_position
        self.light_ambient = light_ambient
        self.alpha = alpha
        self.spherical = spherical

        self.freeze()

    def _setup_lighting_functions(self, spherical):
        """Set up lighting and depth functions based on spherical mode."""
        lighting_functions = _SPHERICAL_LIGHTING if spherical else _FLAT_LIGHTING
        self.shared_program.frag['lighting_functions'] = lighting_functions

    def _prepare_edge_width(self, edge_width, edge_width_rel):
        """Validate and return edge width parameters."""
        if edge_width is not None and edge_width_rel is not None:
            raise ValueError("either edge_width or edge_width_rel "
                             "should be provided, not both")

        if edge_width is None and edge_width_rel is None:
            return np.asarray(1.0), None

        if edge_width is not None:
            edge_width = np.asarray(edge_width)
            if np.any(edge_width < 0):
                raise ValueError('edge_width cannot be negative')
            return edge_width, None
        else:
            edge_width_rel = np.asarray(edge_width_rel)
            if np.any(edge_width_rel < 0):
                raise ValueError('edge_width_rel cannot be negative')
            return None, edge_width_rel

    def _prepare_colors(self, edge_color, face_color):
        """Prepare and normalize color arrays."""
        edge_color = ColorArray(edge_color).rgba
        if len(edge_color) == 1:
            edge_color = edge_color[0]

        face_color = ColorArray(face_color).rgba
        if len(face_color) == 1:
            face_color = face_color[0]

        return edge_color, face_color

    def _prepare_symbol_values(self, symbol, n):
        """Convert symbol names to numeric values and broadcast."""
        if symbol is None:
            return np.zeros(n, dtype=np.float32)

        if isinstance(symbol, str):
            symbol = [symbol]

        try:
            symbol_values = np.array([self._symbol_shader_values[x] for x in symbol], dtype=np.float32)
            if len(symbol_values) == 1:
                symbol_values = np.full(n, symbol_values[0], dtype=np.float32)
            return symbol_values
        except KeyError:
            raise ValueError(f'symbols must one of {self.symbols}')

    def _prepare_data_dict(self, pos, size, edge_width, edge_width_rel,
                           edge_color, face_color, symbol):
        """Prepare attribute data as a dictionary."""
        assert (isinstance(pos, np.ndarray) and
                pos.ndim == 2 and pos.shape[1] in (2, 3))

        n = len(pos)

        position = np.zeros((n, 3), dtype=np.float32)
        position[:, :pos.shape[1]] = pos

        symbol_values = self._prepare_symbol_values(symbol, n)

        edgewidth = edge_width if edge_width is not None else size * edge_width_rel

        size_array = _broadcast_scalar(size, n)
        edgewidth_array = _broadcast_scalar(edgewidth, n)
        edge_color_array = _broadcast_color(edge_color, n)
        face_color_array = _broadcast_color(face_color, n)

        return {
            'a_position': position,
            'a_fg_color': edge_color_array,
            'a_bg_color': face_color_array,
            'a_size': size_array,
            'a_edgewidth': edgewidth_array,
            'a_symbol': symbol_values,
        }

    def _upload_data(self, data_dict):
        """Upload data using interleaved buffer for both points and instanced rendering."""
        n = len(data_dict['a_position'])

        # Create a single structured array for all attributes (interleaved layout)
        structured_data = np.zeros(n, dtype=[
            ('a_position', np.float32, 3),
            ('a_fg_color', np.float32, 4),
            ('a_bg_color', np.float32, 4),
            ('a_size', np.float32),
            ('a_edgewidth', np.float32),
            ('a_symbol', np.float32)
        ])

        # Copy attribute data into structured array
        for attr_name, attr_data in data_dict.items():
            structured_data[attr_name] = attr_data

        self._data = structured_data

        # Upload to VBO
        self._vbo.set_data(structured_data)

        # Create views and assign to program
        # For instanced rendering, set divisor=1 on each view
        divisor = 1 if self._method == 'instanced' else None
        for name in structured_data.dtype.names:
            view = self._vbo[name]
            view.divisor = divisor
            self.shared_program[name] = view

    def set_data(self, pos=None, size=10., edge_width=None, edge_width_rel=None,
                 edge_color='black', face_color='white',
                 symbol='o'):
        """Set the data used to display this visual.

        Parameters
        ----------
        pos : array
            The array of locations to display each symbol.
        size : float or array
            The symbol size in screen (or data, if scaling is on) px.
        edge_width : float or array or None
            The width of the symbol outline in screen (or data, if scaling is on) px.
            Defaults to 1.0 if None or not provided and ``edge_width_rel`` is not
        provided.
        edge_width_rel : float or array or None
            The width as a fraction of marker size. Can not be specified along with
            edge_width. A ValueError will be raised if both are provided.
        edge_color : Color | ColorArray
            The color used to draw each symbol outline.
        face_color : Color | ColorArray
            The color used to draw each symbol interior.
        symbol : str or array
            The style of symbol used to draw each marker (see Notes).
        """
        edge_width, edge_width_rel = self._prepare_edge_width(edge_width, edge_width_rel)
        edge_color, face_color = self._prepare_colors(edge_color, face_color)

        if pos is not None and len(pos):
            data_dict = self._prepare_data_dict(
                pos,
                size,
                edge_width,
                edge_width_rel,
                edge_color,
                face_color,
                symbol,
            )

            self._upload_data(data_dict)
        else:
            self._data = None

        self.events.data_updated()
        self.update()

    @property
    def symbols(self):
        return list(self._symbol_shader_values)

    @property
    def symbol(self):
        if self._data is None:
            return None
        value_to_symbol = {v: k for k, v in self._symbol_shader_values.items()}
        return np.vectorize(value_to_symbol.get)(self._data['a_symbol'])

    @symbol.setter
    def symbol(self, value):
        if self._data is not None:
            rec_to_kw = {
                'a_position': 'pos',
                'a_fg_color': 'edge_color',
                'a_bg_color': 'face_color',
                'a_size': 'size',
                'a_edgewidth': 'edge_width',
                'a_symbol': 'symbol',
            }
            kwargs = {kw: self._data[rec] for rec, kw in rec_to_kw.items()}
        else:
            kwargs = {}
        kwargs['symbol'] = value
        self.set_data(**kwargs)

    @property
    def scaling(self):
        """
        If set to True, marker scales when rezooming.
        """
        return self._scaling

    @scaling.setter
    def scaling(self, value):
        scaling_modes = {
            False: "fixed",
            True: "scene",
            "fixed": "fixed",
            "scene": "scene",
            "visual": "visual",
        }
        if value not in scaling_modes:
            possible_options = ", ".join(repr(opt) for opt in scaling_modes)
            raise ValueError(f"Unknown scaling option {value!r}, expected one of: {possible_options}")
        self._scaling = scaling_modes[value]
        self.shared_program['u_scaling'] = self._scaling != "fixed"
        self.update()

    @property
    def antialias(self):
        """
        Antialiasing amount (in px).
        """
        return self._antialias

    @antialias.setter
    def antialias(self, value):
        value = float(value)
        self.shared_program['u_antialias'] = value
        self._antialias = value
        self.update()

    @property
    def light_position(self):
        """
        The coordinates of the light used to create the spherical effect.
        """
        return self._light_position

    @light_position.setter
    def light_position(self, value):
        value = np.array(value)
        self.shared_program['u_light_position'] = value / np.linalg.norm(value)
        self._light_position = value
        self.update()

    @property
    def light_ambient(self):
        """
        The amount of ambient light used to create the spherical effect.
        """
        return self._light_ambient

    @light_ambient.setter
    def light_ambient(self, value):
        self.shared_program['u_light_ambient'] = value
        self._light_ambient = value
        self.update()

    @property
    def light_color(self):
        """
        The color of the light used to create the spherical effect.
        """
        return self._light_color

    @light_color.setter
    def light_color(self, value):
        self.shared_program['u_light_color'] = ColorArray(value).rgb
        self._light_color = value
        self.update()

    @property
    def alpha(self):
        """
        The opacity level of the visual.
        """
        return self._alpha

    @alpha.setter
    def alpha(self, value):
        self.shared_program['u_alpha'] = value
        self._alpha = value
        self.update()

    @property
    def spherical(self):
        """
        Whether to add a spherical effect on the marker using lighting.
        """
        return self._spherical

    @spherical.setter
    def spherical(self, value):
        self.shared_program['u_spherical'] = value
        self._spherical = value
        self._setup_lighting_functions(value)
        self.update()

    @property
    def canvas_size_limits(self):
        """
        Tuple of (min, max) size limits for markers in canvas pixels.

        If set, marker sizes will be clamped to this range. This is useful
        for preventing markers from becoming too large or too small when
        zooming with scene/visual scaling.

        Either min or max can be None to clamp only one side.
        Set to None to disable clamping entirely (default).

        Returns
        -------
        tuple or None
            (min_size, max_size) or None if clamping is disabled.
        """
        return self._canvas_size_limits

    @canvas_size_limits.setter
    def canvas_size_limits(self, value):
        if value is not None:
            if not isinstance(value, (tuple, list)) or len(value) != 2:
                raise ValueError("canvas_size_limits must be a tuple of (min, max) or None")
            min_val, max_val = value
            if min_val is not None and min_val < 0:
                raise ValueError("canvas_size_limits min must be non-negative or None")
            if max_val is not None and max_val < 0:
                raise ValueError("canvas_size_limits max must be non-negative or None")
            if min_val is not None and max_val is not None and min_val > max_val:
                raise ValueError("canvas_size_limits min must be <= max")
        self._canvas_size_limits = value
        self._update_canvas_size_clamping()

    def _update_canvas_size_clamping(self):
        """Update the canvas size clamping uniforms."""
        min_size, max_size = self._canvas_size_limits or (None, None)
        self.shared_program['u_canvas_size_min'] = float(min_size) if min_size is not None else -1.0
        self.shared_program['u_canvas_size_max'] = float(max_size) if max_size is not None else -1.0
        self.update()

    def _prepare_transforms(self, view):
        view.view_program.vert['visual_to_framebuffer'] = view.get_transform('visual', 'framebuffer')
        view.view_program.vert['framebuffer_to_render'] = view.get_transform('framebuffer', 'render')
        scaling = view._scaling if view._scaling != "fixed" else "scene"
        view.view_program.vert['framebuffer_to_scene_or_visual'] = view.get_transform('framebuffer', scaling)
        view.view_program.vert['scene_or_visual_to_framebuffer'] = view.get_transform(scaling, 'framebuffer')

    def _prepare_draw(self, view):
        if self._data is None:
            return False
        view.view_program['u_px_scale'] = view.transforms.pixel_scale

    def _compute_bounds(self, axis, view):
        pos = self._data['a_position']
        if pos is None:
            return None
        if pos.shape[1] > axis:
            return (pos[:, axis].min(), pos[:, axis].max())
        else:
            return (0, 0)


def _broadcast_scalar(value, n, dtype=np.float32):
    """Broadcast scalar or array to length n."""
    array = np.asarray(value, dtype=dtype)
    if array.ndim == 0:
        return np.full(n, array, dtype=dtype)
    return array


def _broadcast_color(color, n, dtype=np.float32):
    """Broadcast color (4,) to (n, 4) or return (n, 4) as-is."""
    array = np.asarray(color, dtype=dtype)
    if array.ndim == 1:
        return np.tile(array, (n, 1))
    return array