summaryrefslogtreecommitdiff
path: root/gsk/gskglshader.c
blob: 13802f6067b4c5edd355120aa9b1fba75b79ceff (plain)
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
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
/* GSK - The GTK Scene Kit
 *
 * Copyright 2020, Red Hat Inc
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library. If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * SECTION:GskGLShader
 * @Title: GskGLShader
 * @Short_description: Fragment shaders for GSK
 *
 * A #GskGLShader is a snippet of GLSL that is meant to run in the
 * fragment shader of the rendering pipeline. A fragment shader
 * gets the coordinates being rendered as input and produces the
 * pixel values for that particular pixel. Additionally, the
 * shader can declare a set of other input arguments, called
 * uniforms (as they are uniform over all the calls to your shader in
 * each instance of use). A shader can also receive up to 4
 * textures that it can use as input when producing the pixel data.
 *
 * The typical way a #GskGLShader is used is as an argument to a
 * #GskGLShaderNode in the rendering hierarchy, and then the textures
 * it gets as input are constructed by rendering the child nodes to
 * textures before rendering the shader node itself. (Although you can
 * also pass texture nodes as children if you want to directly use a
 * texture as input). Note that the #GskGLShaderNode API is a bit
 * lowlevel, and highlevel code normally uses
 * gtk_snapshot_push_glshader() to produce the nodes.
 *
 * The actual shader code is GLSL code that gets combined with
 * some other code into the fragment shader. Since the exact
 * capabilities of the GPU driver differs between different OpenGL
 * drivers and hardware, GTK adds some defines that you can use
 * to ensure your GLSL code runs on as many drivers as it can.
 *
 * If the OpenGL driver is GLES, then the shader language version
 * is set to 100, and GSK_GLES will be defined in the shader.
 *
 * Otherwise, if the OpenGL driver does not support the 3.2 core profile,
 * then the shader will run with language version 110 for GL2 and 130 for GL3,
 * and GSK_LEGACY will be defined in the shader.
 *
 * If the OpenGL driver supports the 3.2 code profile, it will be used,
 * the shader language version is set to 150, and GSK_GL3 will be defined
 * in the shader.
 *
 * The main function the shader should implement is:
 *
 * |[<!-- language="plain" -->
 *  void mainImage(out vec4 fragColor,
 *                 in vec2 fragCoord,
 *                 in vec2 resolution,
 *                 in vec2 uv)
 * ]|
 * 
 * Where the input @fragCoord is the coordinate of the pixel we're
 * currently rendering, relative to the boundary rectangle that was
 * specified in the #GskGLShaderNode, and @resolution is the width and
 * height of that rectangle. This is in the typical GTK coordinate
 * system with the origin in the top left. @uv contains the u and v
 * coordinates that can be used to index a texture at the
 * corresponding point. These coordinates are in the [0..1]x[0..1]
 * region, with 0, 0 being in the lower left cornder (which is typical
 * for OpenGL).
 *
 * The output @fragColor should be a RGBA color (with
 * non-premultiplied alpha) that will be used as the output for the
 * specified pixel location. Note that this output will be
 * automatically clipped to the clip region of the glshader node.
 *
 * In addition to the function arguments the shader can define
 * up to 4 uniforms for tetxures which must be called u_textureN
 * (i.e. u_texture1 to u_texture4) as well as any custom uniforms
 * you want of types int, uint, bool, float, vec2, vec3 or vec4.
 *
 * Note that GTK parses the uniform declarations, so each uniform has to
 * be on a line by itself with no other code, like so:
 *
 * |[<!-- language="plain" -->
 * uniform float u_time;
 * uniform vec3 u_color;
 * uniform sampler2D u_texture1;
 * uniform sampler2D u_texture2;
 * ]|
 *
 * GTK uses the the "gsk" namespace in the symbols it uses in the
 * shader, so your code should not use any symbols with the prefix gsk
 * or GSK. There are some helper functions declared that you can use:
 *
 * |[<!-- language="plain" -->
 * vec4 GskTexture(sampler2D sampler, vec2 texCoords);
 * ]|
 *
 * This samples a texture (e.g. u_texture1) at the specified
 * coordinates, and containes some helper ifdefs to ensure that
 * it works on all OpenGL versions.
 */

#include "config.h"
#include "gskglshader.h"
#include "gskglshaderprivate.h"
#include "gskdebugprivate.h"
#include "gl/gskglrendererprivate.h"

static GskGLUniformType
uniform_type_from_glsl (const char *str)
{
  if (strcmp (str, "int") == 0)
    return GSK_GL_UNIFORM_TYPE_INT;
  if (strcmp (str, "uint") == 0)
    return GSK_GL_UNIFORM_TYPE_UINT;
  if (strcmp (str, "bool") == 0)
    return GSK_GL_UNIFORM_TYPE_BOOL;
  if (strcmp (str, "float") == 0)
    return GSK_GL_UNIFORM_TYPE_FLOAT;
  if (strcmp (str, "vec2") == 0)
    return GSK_GL_UNIFORM_TYPE_VEC2;
  if (strcmp (str, "vec3") == 0)
    return GSK_GL_UNIFORM_TYPE_VEC3;
  if (strcmp (str, "vec4") == 0)
    return GSK_GL_UNIFORM_TYPE_VEC4;

  return  GSK_GL_UNIFORM_TYPE_NONE;
}

static const char *
uniform_type_name (GskGLUniformType type)
{
  switch (type)
    {
    case GSK_GL_UNIFORM_TYPE_FLOAT:
      return "float";

    case GSK_GL_UNIFORM_TYPE_INT:
      return "int";

    case GSK_GL_UNIFORM_TYPE_UINT:
      return "uint";

    case GSK_GL_UNIFORM_TYPE_BOOL:
      return "bool";

    case GSK_GL_UNIFORM_TYPE_VEC2:
      return "vec2";

    case GSK_GL_UNIFORM_TYPE_VEC3:
      return "vec3";

    case GSK_GL_UNIFORM_TYPE_VEC4:
      return "vec4";

    case GSK_GL_UNIFORM_TYPE_NONE:
    default:
      g_assert_not_reached ();
      return NULL;
    }
}

static int
uniform_type_size (GskGLUniformType type)
{
  switch (type)
    {
    case GSK_GL_UNIFORM_TYPE_FLOAT:
      return sizeof (float);

    case GSK_GL_UNIFORM_TYPE_INT:
      return sizeof (gint32);

    case GSK_GL_UNIFORM_TYPE_UINT:
    case GSK_GL_UNIFORM_TYPE_BOOL:
      return sizeof (guint32);

    case GSK_GL_UNIFORM_TYPE_VEC2:
      return sizeof (float) * 2;

    case GSK_GL_UNIFORM_TYPE_VEC3:
      return sizeof (float) * 3;

    case GSK_GL_UNIFORM_TYPE_VEC4:
      return sizeof (float) * 4;

    case GSK_GL_UNIFORM_TYPE_NONE:
    default:
      g_assert_not_reached ();
      return 0;
    }
}

struct _GskGLShader
{
  GObject parent_instance;
  GBytes *bytes;
  char *resource;
  int n_required_textures;
  int uniforms_size;
  GArray *uniforms;
};

G_DEFINE_TYPE (GskGLShader, gsk_gl_shader, G_TYPE_OBJECT)

enum {
  GLSHADER_PROP_0,
  GLSHADER_PROP_BYTES,
  GLSHADER_PROP_RESOURCE,
  GLSHADER_N_PROPS
};
static GParamSpec *gsk_gl_shader_properties[GLSHADER_N_PROPS];

static void
gsk_gl_shader_get_property (GObject    *object,
                            guint       prop_id,
                            GValue     *value,
                            GParamSpec *pspec)
{
  GskGLShader *shader = GSK_GL_SHADER (object);

  switch (prop_id)
    {
    case GLSHADER_PROP_BYTES:
      g_value_set_boxed (value, shader->bytes);
      break;

    case GLSHADER_PROP_RESOURCE:
      g_value_set_string (value, shader->resource);
      break;

    default:
      g_assert_not_reached ();
    }
}

static void
gsk_gl_shader_set_property (GObject      *object,
                            guint         prop_id,
                            const GValue *value,
                            GParamSpec   *pspec)
{
  GskGLShader *shader = GSK_GL_SHADER (object);

  switch (prop_id)
    {
    case GLSHADER_PROP_BYTES:
      g_clear_pointer (&shader->bytes, g_bytes_unref);
      shader->bytes = g_value_dup_boxed (value);
      break;

    case GLSHADER_PROP_RESOURCE:
      {
        GError *error = NULL;
        GBytes *bytes;
        const char *resource;

        resource = g_value_get_string (value);
        if (resource == NULL)
          break;

        bytes = g_resources_lookup_data (resource, 0, &error);
        if (bytes)
          {
            g_clear_pointer (&shader->bytes, g_bytes_unref);
            shader->bytes = bytes;
            shader->resource = g_strdup (resource);
          }
        else
          {
            g_critical ("Unable to load resource %s for glshader: %s", resource, error->message);
            g_error_free (error);
            if (shader->bytes == NULL)
              shader->bytes = g_bytes_new_static ("", 1);
          }
      }
      break;

    default:
      g_assert_not_reached ();
    }
}

static void
gsk_gl_shader_finalize (GObject *object)
{
  GskGLShader *shader = GSK_GL_SHADER (object);

  g_bytes_unref (shader->bytes);
  g_free (shader->resource);
  for (int i = 0; i < shader->uniforms->len; i ++)
    g_free (g_array_index (shader->uniforms, GskGLUniform, i).name);
  g_array_free (shader->uniforms, TRUE);

  G_OBJECT_CLASS (gsk_gl_shader_parent_class)->finalize (object);
}

static GRegex *uniform_regexp = NULL; /* Initialized in class_init */


static void
gsk_gl_shader_add_uniform (GskGLShader     *shader,
                           const char      *name,
                           GskGLUniformType type)
{
  GskGLUniform uniform = {
    g_strdup (name),
    type,
    shader->uniforms_size
  };

  shader->uniforms_size += uniform_type_size (type);

  g_array_append_val (shader->uniforms, uniform);
}

static void
gsk_gl_shader_constructed (GObject *object)
{
  GskGLShader *shader = GSK_GL_SHADER (object);
  gsize string_len;
  const char *string = g_bytes_get_data (shader->bytes, &string_len);
  GMatchInfo *match_info;
  int max_texture_seen = 0;

  g_regex_match_full (uniform_regexp,
                      string, string_len, 0, 0,
                      &match_info, NULL);
  while (g_match_info_matches (match_info))
    {
      char *type = g_match_info_fetch (match_info, 1);
      char *name = g_match_info_fetch (match_info, 2);

      if (strcmp (type, "sampler2D") == 0)
        {
          /* Textures are special cased */

          if (g_str_has_prefix (name, "u_texture") &&
              strlen (name) == strlen ("u_texture")+1)
            {
              char digit = name[strlen("u_texture")];
              if (digit >= '1' && digit <= '9')
                max_texture_seen = MAX(max_texture_seen, digit - '0');
            }
          else
            g_debug ("Unhandled shader texture uniform '%s', use uniforms of name 'u_texture[1..9]'", name);
        }
      else
        {
          GskGLUniformType utype = uniform_type_from_glsl (type);
          g_assert (utype != GSK_GL_UNIFORM_TYPE_NONE); // Shouldn't have matched the regexp
          gsk_gl_shader_add_uniform (shader, name, utype);
        }

      g_free (type);
      g_free (name);

      g_match_info_next (match_info, NULL);
    }

  g_match_info_free (match_info);

  shader->n_required_textures = max_texture_seen;

  if (GSK_DEBUG_CHECK(SHADERS))
    {
      GString *s;

      s = g_string_new ("");
      for (int i = 0; i < shader->uniforms->len; i++)
        {
          GskGLUniform *u = &g_array_index (shader->uniforms, GskGLUniform, i);
          if (i > 0)
            g_string_append (s, ", ");
          g_string_append_printf (s, "%s %s", uniform_type_name (u->type), u->name);
        }
      g_message ("Shader constructed: %d textures, %d uniforms (%s)",
                 shader->n_required_textures, shader->uniforms->len,
                 s->str);
      g_string_free (s, TRUE);
    }
}

#define SPACE_RE "[ \\t]+" // Don't use \s, we don't want to match newlines
#define OPT_SPACE_RE "[ \\t]*"
#define UNIFORM_TYPE_RE "(int|uint|bool|float|vec2|vec3|vec4|sampler2D)"
#define UNIFORM_NAME_RE "([\\w]+)"
#define OPT_INIT_VALUE_RE "[-\\w(),. ]+" // This is a bit simple, but will match most initializers
#define OPT_COMMENT_RE "(//.*)?"
#define OPT_INITIALIZER_RE  "(" OPT_SPACE_RE "=" OPT_SPACE_RE  OPT_INIT_VALUE_RE ")?"
#define UNIFORM_MATCHER_RE "^uniform" SPACE_RE UNIFORM_TYPE_RE SPACE_RE UNIFORM_NAME_RE OPT_INITIALIZER_RE OPT_SPACE_RE ";" OPT_SPACE_RE OPT_COMMENT_RE "$"

static void
gsk_gl_shader_class_init (GskGLShaderClass *klass)
{
   GObjectClass *object_class = G_OBJECT_CLASS (klass);
   uniform_regexp = g_regex_new (UNIFORM_MATCHER_RE,
                                 G_REGEX_MULTILINE | G_REGEX_RAW | G_REGEX_OPTIMIZE,
                                 0, NULL);

  object_class->get_property = gsk_gl_shader_get_property;
  object_class->set_property = gsk_gl_shader_set_property;
  object_class->finalize = gsk_gl_shader_finalize;
  object_class->constructed = gsk_gl_shader_constructed;

  /**
   * GskGLShader:sourcecode:
   *
   * The source code for the shader, as a #GBytes.
   */
  gsk_gl_shader_properties[GLSHADER_PROP_BYTES] =
    g_param_spec_boxed ("bytes",
                        "Bytes",
                        "The sourcecode code for the shader",
                        G_TYPE_BYTES,
                        G_PARAM_READWRITE |
                        G_PARAM_CONSTRUCT_ONLY |
                        G_PARAM_STATIC_STRINGS);

  /**
   * GskGLShader:resource:
   *
   * resource containing the source code for the shader.
   */
  gsk_gl_shader_properties[GLSHADER_PROP_RESOURCE] =
    g_param_spec_string ("resource",
                         "Resources",
                         "Resource path to the source code",
                         NULL,
                         G_PARAM_READWRITE |
                         G_PARAM_CONSTRUCT_ONLY |
                         G_PARAM_STATIC_STRINGS);

  g_object_class_install_properties (object_class, GLSHADER_N_PROPS, gsk_gl_shader_properties);
}

static void
gsk_gl_shader_init (GskGLShader *shader)
{
  shader->uniforms = g_array_new (FALSE, FALSE, sizeof (GskGLUniform));
}

/**
 * gsk_gl_shader_new_from_bytes:
 * @sourcecode: The sourcecode for the shader, as a #GBytes
 *
 * Creates a #GskGLShader that will render pixels using the specified code.
 *
 * Returns: (transfer full): A new #GskGLShader
 */
GskGLShader *
gsk_gl_shader_new_from_bytes (GBytes *sourcecode)
{
  g_return_val_if_fail (sourcecode != NULL, NULL);

  return g_object_new (GSK_TYPE_GL_SHADER,
                       "bytes", sourcecode,
                       NULL);
}

/**
 * gsk_gl_shader_new_from_resource:
 * @resource_path: valid path to a resource that contains the sourcecode for the shader
 *
 * Creates a #GskGLShader that will render pixels using the specified code.
 *
 * Returns: (transfer full): A new #GskGLShader
 */
GskGLShader *
gsk_gl_shader_new_from_resource (const char      *resource_path)
{
  g_return_val_if_fail (resource_path != NULL, NULL);

  return g_object_new (GSK_TYPE_GL_SHADER,
                       "resource", resource_path,
                       NULL);
}

/**
 * gsk_gl_shader_try_compile_for:
 * @shader: A #GskGLShader
 * @renderer: A #GskRenderer
 * @error: Location to store error int
 *
 * Tries to compile the @shader for the given @renderer, and reports
 * %FALSE with an error if there is a problem. You should use this
 * before relying on the shader for rendering and use a fallback with
 * a simpler shader or without shaders if it fails.
 *
 * Note that this will modify the rendering state (for example
 * change the current GL context) and requires the renderer to be
 * set up. This means that the widget has to be realized. Commonly you
 * want to call this from the realize signal of a widget, or during
 * widget snapshot.
 *
 * Returns: %TRUE on success, %FALSE if an error occurred
 */
gboolean
gsk_gl_shader_try_compile_for (GskGLShader      *shader,
                               GskRenderer      *renderer,
                               GError          **error)
{
  if (GSK_IS_GL_RENDERER (renderer))
    return gsk_gl_render_try_compile_gl_shader (GSK_GL_RENDERER (renderer),
                                                shader, error);

  g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
               "The renderer does not support gl shaders");
  return FALSE;
}


/**
 * gsk_gl_shader_get_sourcecode:
 * @shader: A #GskGLShader
 *
 * Get the source code being used to render this shader.
 *
 * Returns: (transfer none): The source code for the shader
 */
GBytes *
gsk_gl_shader_get_bytes (GskGLShader *shader)
{
  return shader->bytes;
}

/**
 * gsk_gl_shader_get_n_required_textures:
 * @shader: A #GskGLShader
 *
 * Returns the number of textures that the shader requires. This can be used
 * to check that the a passed shader works in your usecase. This
 * is determined by looking at the highest u_textureN value that the
 * shader defines.
 *
 * Returns: The nr of texture input this shader requires.
 */
int
gsk_gl_shader_get_n_required_textures (GskGLShader  *shader)
{
  return shader->n_required_textures;
}

/**
 * gsk_gl_shader_get_n_uniforms:
 * @shader: A #GskGLShader
 *
 * Get the number of declared uniforms for this shader.
 *
 * Returns: The nr of declared uniforms
 */
int
gsk_gl_shader_get_n_uniforms (GskGLShader     *shader)
{
  return shader->uniforms->len;
}

/**
 * gsk_gl_shader_get_uniform_name:
 * @shader: A #GskGLShader
 * @idx: A zero-based index of the uniforms
 *
 * Get the name of a declared uniforms for this shader at index @indx.
 *
 * Returns: (transfer none): The name of the declared uniform
 */
const char *
gsk_gl_shader_get_uniform_name (GskGLShader     *shader,
                                int              idx)
{
  return g_array_index (shader->uniforms, GskGLUniform, idx).name;
}

/**
 * gsk_gl_shader_find_uniform_by_name:
 * @shader: A #GskGLShader
 * @name: A uniform name
 *
 * Looks for a uniform by the name @name, and returns the index
 * of the unifor, or -1 if it was not found.
 *
 * Returns: The index of the uniform, or -1
 */
int
gsk_gl_shader_find_uniform_by_name (GskGLShader      *shader,
                                    const char       *name)
{
  for (int i = 0; i < shader->uniforms->len; i++)
    {
      const GskGLUniform *u = &g_array_index (shader->uniforms, GskGLUniform, i);
      if (strcmp (u->name, name) == 0)
        return i;
    }

  return -1;
}

/**
 * gsk_gl_shader_get_uniform_type:
 * @shader: A #GskGLShader
 * @idx: A zero-based index of the uniforms
 *
 * Get the type of a declared uniforms for this shader at index @indx.
 *
 * Returns: The type of the declared uniform
 */
GskGLUniformType
gsk_gl_shader_get_uniform_type (GskGLShader     *shader,
                                int              idx)
{
  return g_array_index (shader->uniforms, GskGLUniform, idx).type;
}

/**
 * gsk_gl_shader_get_uniform_offset:
 * @shader: A #GskGLShader
 * @idx: A zero-based index of the uniforms
 *
 * Get the offset into the data block where data for this uniforms is stored.
 *
 * Returns: The data offset
 */
int
gsk_gl_shader_get_uniform_offset (GskGLShader     *shader,
                                  int              idx)
{
  return g_array_index (shader->uniforms, GskGLUniform, idx).offset;
}

const GskGLUniform *
gsk_gl_shader_get_uniforms (GskGLShader *shader,
                            int         *n_uniforms)
{
  *n_uniforms = shader->uniforms->len;
  return &g_array_index (shader->uniforms, GskGLUniform, 0);
}

/**
 * gsk_gl_shader_get_args_size:
 * @shader: A #GskGLShader
 *
 * Get the size of the data block used to specify arguments for this shader.
 *
 * Returns: The size of the data block
 */
int
gsk_gl_shader_get_args_size (GskGLShader *shader)
{
  return shader->uniforms_size;
}

static const GskGLUniform *
gsk_gl_shader_find_uniform (GskGLShader *shader,
                            const char *name)
{
  for (int i = 0; i < shader->uniforms->len; i++)
    {
      const GskGLUniform *u = &g_array_index (shader->uniforms, GskGLUniform, i);
      if (strcmp (u->name, name) == 0)
        return u;
    }

  return NULL;
}

/**
 * gsk_gl_shader_get_arg_float:
 * @shader: A #GskGLShader
 * @args: The uniform arguments
 * @idx: The index of the uniform
 *
 * Gets the value of the uniform @idx in the @args block.
 * The uniform must be of float type.
 *
 * Returns: The value
 */
float
gsk_gl_shader_get_arg_float (GskGLShader *shader,
                             GBytes       *args,
                             int          idx)
{
  const GskGLUniform *u;
  const guchar *args_src;
  gsize size;
  const guchar *data = g_bytes_get_data (args, &size);

  g_assert (size == shader->uniforms_size);
  g_assert (idx < shader->uniforms->len);
  u = &g_array_index (shader->uniforms, GskGLUniform, idx);
  g_assert (u->type == GSK_GL_UNIFORM_TYPE_FLOAT);

  args_src = data + u->offset;
  return *(float *)args_src;
}

/**
 * gsk_gl_shader_get_arg_int:
 * @shader: A #GskGLShader
 * @args: The uniform arguments
 * @idx: The index of the uniform
 *
 * Gets the value of the uniform @idx in the @args block.
 * The uniform must be of int type.
 *
 * Returns: The value
 */
gint32
gsk_gl_shader_get_arg_int (GskGLShader *shader,
                           GBytes       *args,
                           int          idx)
{
  const GskGLUniform *u;
  const guchar *args_src;
  gsize size;
  const guchar *data = g_bytes_get_data (args, &size);

  g_assert (size == shader->uniforms_size);
  g_assert (idx < shader->uniforms->len);
  u = &g_array_index (shader->uniforms, GskGLUniform, idx);
  g_assert (u->type == GSK_GL_UNIFORM_TYPE_INT);

  args_src = data + u->offset;
  return *(gint32 *)args_src;
}

/**
 * gsk_gl_shader_get_arg_uint:
 * @shader: A #GskGLShader
 * @args: The uniform arguments
 * @idx: The index of the uniform
 *
 * Gets the value of the uniform @idx in the @args block.
 * The uniform must be of uint type.
 *
 * Returns: The value
 */
guint32
gsk_gl_shader_get_arg_uint (GskGLShader *shader,
                            GBytes       *args,
                            int          idx)
{
  const GskGLUniform *u;
  const guchar *args_src;
  gsize size;
  const guchar *data = g_bytes_get_data (args, &size);

  g_assert (size == shader->uniforms_size);
  g_assert (idx < shader->uniforms->len);
  u = &g_array_index (shader->uniforms, GskGLUniform, idx);
  g_assert (u->type == GSK_GL_UNIFORM_TYPE_UINT);

  args_src = data + u->offset;
  return *(guint32 *)args_src;
}

/**
 * gsk_gl_shader_get_arg_bool:
 * @shader: A #GskGLShader
 * @args: The uniform arguments
 * @idx: The index of the uniform
 *
 * Gets the value of the uniform @idx in the @args block.
 * The uniform must be of bool type.
 *
 * Returns: The value
 */
gboolean
gsk_gl_shader_get_arg_bool (GskGLShader *shader,
                            GBytes       *args,
                            int          idx)
{
  const GskGLUniform *u;
  const guchar *args_src;
  gsize size;
  const guchar *data = g_bytes_get_data (args, &size);

  g_assert (size == shader->uniforms_size);
  g_assert (idx < shader->uniforms->len);
  u = &g_array_index (shader->uniforms, GskGLUniform, idx);
  g_assert (u->type == GSK_GL_UNIFORM_TYPE_BOOL);

  args_src = data + u->offset;
  return *(guint32 *)args_src;
}

/**
 * gsk_gl_shader_get_arg_vec2:
 * @shader: A #GskGLShader
 * @args: The uniform arguments
 * @idx: The index of the uniform
 * @out_value: Location to store set the uniform value too
 *
 * Gets the value of the uniform @idx in the @args block.
 * The uniform must be of vec2 type.
 */
void
gsk_gl_shader_get_arg_vec2 (GskGLShader           *shader,
                            GBytes                *args,
                            int                    idx,
                            graphene_vec2_t       *out_value)
{
  const GskGLUniform *u;
  const guchar *args_src;
  gsize size;
  const guchar *data = g_bytes_get_data (args, &size);

  g_assert (size == shader->uniforms_size);
  g_assert (idx < shader->uniforms->len);
  u = &g_array_index (shader->uniforms, GskGLUniform, idx);
  g_assert (u->type == GSK_GL_UNIFORM_TYPE_VEC2);

  args_src = data + u->offset;
  graphene_vec2_init_from_float (out_value, (float *)args_src);
}

/**
 * gsk_gl_shader_get_arg_vec3:
 * @shader: A #GskGLShader
 * @args: The uniform arguments
 * @idx: The index of the uniform
 * @out_value: Location to store set the uniform value too
 *
 * Gets the value of the uniform @idx in the @args block.
 * The uniform must be of vec3 type.
 */
void
gsk_gl_shader_get_arg_vec3 (GskGLShader           *shader,
                                     GBytes                *args,
                                     int                    idx,
                                     graphene_vec3_t       *out_value)
{
  const GskGLUniform *u;
  const guchar *args_src;
  gsize size;
  const guchar *data = g_bytes_get_data (args, &size);

  g_assert (size == shader->uniforms_size);
  g_assert (idx < shader->uniforms->len);
  u = &g_array_index (shader->uniforms, GskGLUniform, idx);
  g_assert (u->type == GSK_GL_UNIFORM_TYPE_VEC3);

  args_src = data + u->offset;
  graphene_vec3_init_from_float (out_value, (float *)args_src);
}

/**
 * gsk_gl_shader_get_arg_vec4:
 * @shader: A #GskGLShader
 * @args: The uniform arguments
 * @idx: The index of the uniform
 * @out_value: Location to store set the uniform value too
 *
 * Gets the value of the uniform @idx in the @args block.
 * The uniform must be of vec4 type.
 */
void
gsk_gl_shader_get_arg_vec4 (GskGLShader           *shader,
                            GBytes                *args,
                            int                    idx,
                            graphene_vec4_t       *out_value)
{
  const GskGLUniform *u;
  const guchar *args_src;
  gsize size;
  const guchar *data = g_bytes_get_data (args, &size);

  g_assert (size == shader->uniforms_size);
  g_assert (idx < shader->uniforms->len);
  u = &g_array_index (shader->uniforms, GskGLUniform, idx);
  g_assert (u->type == GSK_GL_UNIFORM_TYPE_VEC4);

  args_src = data + u->offset;
  graphene_vec4_init_from_float (out_value, (float *)args_src);
}

/**
 * gsk_gl_shader_format_args_va:
 * @shader: A #GskGLShader
 * @uniforms: Name-Value pairs for the uniforms of @shader, ending with a %NULL name, all values are passed by reference.
 *
 * Formats the uniform data as needed for feeding the named uniforms values into the shader.
 * The argument list is a list of pairs of names, and pointers to data of the types
 * that match the declared uniforms (i.e. `float *` for float uniforms and `graphene_vec4_t *` f
 * or vec3 uniforms).
 *
 * Returns: (transfer full): A newly allocated block of data which can be passed to gsk_gl_shader_node_new().
 */
GBytes *
gsk_gl_shader_format_args_va (GskGLShader *shader,
                              va_list uniforms)
{
  guchar *args = g_malloc0 (shader->uniforms_size);
  const char *name;

  while ((name = va_arg (uniforms, const char *)) != NULL)
    {
      const GskGLUniform *u;
      gpointer value = va_arg (uniforms, gpointer);
      guchar *args_dest;

      u = gsk_gl_shader_find_uniform (shader, name);
      if (u == NULL)
        {
          /* This isn't really an error, because we can easily imaging
             a shader interface that have input which isn't needed for
             a particular shader */
          g_debug ("No uniform named `%s` in shader", name);
          continue;
        }

      args_dest = args + u->offset;

      /* We use pointers-to-value so that all values are the same
         size, otherwise we couldn't handle the missing uniform case above */

      switch (u->type)
        {
        case GSK_GL_UNIFORM_TYPE_FLOAT:
          *(float *)args_dest = *(float *)value;
          break;

        case GSK_GL_UNIFORM_TYPE_INT:
          *(gint32 *)args_dest = *(gint32 *)value;
          break;

        case GSK_GL_UNIFORM_TYPE_UINT:
          *(guint32 *)args_dest = *(guint32 *)value;
          break;

        case GSK_GL_UNIFORM_TYPE_BOOL:
          *(guint32 *)args_dest = *(gboolean *)value;
          break;

        case GSK_GL_UNIFORM_TYPE_VEC2:
          graphene_vec2_to_float ((const graphene_vec2_t *)value,
                                  (float *)args_dest);
          break;

        case GSK_GL_UNIFORM_TYPE_VEC3:
          graphene_vec3_to_float ((const graphene_vec3_t *)value,
                                  (float *)args_dest);
          break;

        case GSK_GL_UNIFORM_TYPE_VEC4:
          graphene_vec4_to_float ((const graphene_vec4_t *)value,
                                  (float *)args_dest);
          break;

        case GSK_GL_UNIFORM_TYPE_NONE:
        default:
          g_assert_not_reached ();
        }
    }

  return g_bytes_new_take (args, shader->uniforms_size);
}

/**
 * gsk_gl_shader_format_args:
 * @shader: A #GskGLShader
 * @...: Name-Value pairs for the uniforms of @shader, ending with a %NULL name, all values are passed by reference.
 *
 * Formats the uniform data as needed for feeding the named uniforms values into the shader.
 * The argument list is a list of pairs of names, and pointers to data of the types
 * that match the declared uniforms (i.e. `float *` for float uniforms and `graphene_vec4_t *` f
 * or vec3 uniforms).
 *
 * Returns: (transfer full): A newly allocated block of data which can be passed to gsk_gl_shader_node_new().
 */
GBytes *
gsk_gl_shader_format_args (GskGLShader *shader,
                           ...)
{
  GBytes *bytes;
  va_list args;

  va_start (args, shader);
  bytes = gsk_gl_shader_format_args_va (shader, args);
  va_end (args);

  return bytes;
}

struct _GskShaderArgsBuilder {
  GskGLShader *shader;
  guchar *data;
};

G_DEFINE_BOXED_TYPE (GskShaderArgsBuilder, gsk_shader_args_builder,
                     gsk_shader_args_builder_copy,
                     gsk_shader_args_builder_free);


/**
 * gsk_gl_shader_build_args:
 * @shader: A #GskGLShader
 *
 * Allocates a builder that can be used to construct a new uniform data
 * chunk.
 *
 * Returns: (transfer full): The newly allocated builder, free with gsk_shader_args_builder_free()
 */
GskShaderArgsBuilder *
gsk_gl_shader_build_args (GskGLShader *shader)
{
  GskShaderArgsBuilder *builder = g_new0 (GskShaderArgsBuilder, 1);
  builder->shader = g_object_ref (shader);
  builder->data = g_malloc0 (shader->uniforms_size);

  return builder;
}

/**
 * gsk_shader_args_builder_finish:
 * @builder: A #GskShaderArgsBuilder
 *
 * Finishes building the uniform data and returns it as a GBytes. Once this
 * is called the builder can not be used anymore.
 *
 * Returns: (transfer full): The newly allocated builder, free with gsk_shader_args_builder_free()
 */
GBytes *
gsk_shader_args_builder_finish (GskShaderArgsBuilder *builder)
{
  return g_bytes_new_take (g_steal_pointer (&builder->data),
                           builder->shader->uniforms_size);
}

/**
 * gsk_shader_args_builder_free:
 * @builder: A #GskShaderArgsBuilder
 *
 * Frees the builder.
 */
void
gsk_shader_args_builder_free (GskShaderArgsBuilder *builder)
{
  g_object_unref (builder->shader);
  g_free (builder->data);
  g_free (builder);
}

/**
 * gsk_shader_args_builder_copy:
 * @builder: A #GskShaderArgsBuilder
 *
 * Makes a copy of the builder.
 *
 * Returns: (transfer full): A copy of the builder, free with gsk_shader_args_builder_free().
 */
GskShaderArgsBuilder *
gsk_shader_args_builder_copy (GskShaderArgsBuilder *builder)
{
  GskShaderArgsBuilder *new = g_new0 (GskShaderArgsBuilder, 1);
  new->data = g_memdup (builder->data, builder->shader->uniforms_size);
  new->shader = g_object_ref (builder->shader);
  return new;
}

/**
 * gsk_shader_args_builder_set_float:
 * @builder: A #GskShaderArgsBuilder
 * @idx: The index of the uniform
 * @value: The value to set the uniform too
 *
 * Sets the value of the uniform @idx.
 * The uniform must be of float type.
 */
void
gsk_shader_args_builder_set_float (GskShaderArgsBuilder *builder,
                                    int                    idx,
                                    float                  value)
{
  GskGLShader *shader = builder->shader;
  const GskGLUniform *u;
  guchar *args_dest;

  g_assert (idx < shader->uniforms->len);
  u = &g_array_index (shader->uniforms, GskGLUniform, idx);
  g_assert (u->type == GSK_GL_UNIFORM_TYPE_FLOAT);

  args_dest = builder->data + u->offset;
  *(float *)args_dest = value;
}

/**
 * gsk_shader_args_builder_set_int:
 * @builder: A #GskShaderArgsBuilder
 * @idx: The index of the uniform
 * @value: The value to set the uniform too
 *
 * Sets the value of the uniform @idx.
 * The uniform must be of int type.
 */
void
gsk_shader_args_builder_set_int (GskShaderArgsBuilder *builder,
                                 int                    idx,
                                 gint32                 value)
{
  GskGLShader *shader = builder->shader;
  const GskGLUniform *u;
  guchar *args_dest;

  g_assert (idx < shader->uniforms->len);
  u = &g_array_index (shader->uniforms, GskGLUniform, idx);
  g_assert (u->type == GSK_GL_UNIFORM_TYPE_INT);

  args_dest = builder->data + u->offset;
  *(gint32 *)args_dest = value;
}

/**
 * gsk_shader_args_builder_set_uint:
 * @builder: A #GskShaderArgsBuilder
 * @idx: The index of the uniform
 * @value: The value to set the uniform too
 *
 * Sets the value of the uniform @idx.
 * The uniform must be of uint type.
 */
void
gsk_shader_args_builder_set_uint (GskShaderArgsBuilder *builder,
                                  int                    idx,
                                  guint32                value)
{
  GskGLShader *shader = builder->shader;
  const GskGLUniform *u;
  guchar *args_dest;

  g_assert (idx < shader->uniforms->len);
  u = &g_array_index (shader->uniforms, GskGLUniform, idx);
  g_assert (u->type == GSK_GL_UNIFORM_TYPE_UINT);

  args_dest = builder->data + u->offset;
  *(guint32 *)args_dest = value;
}

/**
 * gsk_shader_args_builder_set_bool:
 * @builder: A #GskShaderArgsBuilder
 * @idx: The index of the uniform
 * @value: The value to set the uniform too
 *
 * Sets the value of the uniform @idx.
 * The uniform must be of bool type.
 */
void
gsk_shader_args_builder_set_bool (GskShaderArgsBuilder *builder,
                                  int                    idx,
                                  gboolean               value)
{
  GskGLShader *shader = builder->shader;
  const GskGLUniform *u;
  guchar *args_dest;

  g_assert (idx < shader->uniforms->len);
  u = &g_array_index (shader->uniforms, GskGLUniform, idx);
  g_assert (u->type == GSK_GL_UNIFORM_TYPE_BOOL);

  args_dest = builder->data + u->offset;
  *(guint32 *)args_dest = !!value;
}

/**
 * gsk_shader_args_builder_set_vec2:
 * @builder: A #GskShaderArgsBuilder
 * @idx: The index of the uniform
 * @value: The value to set the uniform too
 *
 * Sets the value of the uniform @idx.
 * The uniform must be of vec2 type.
 */
void
gsk_shader_args_builder_set_vec2 (GskShaderArgsBuilder *builder,
                                  int                    idx,
                                  const graphene_vec2_t *value)
{
  GskGLShader *shader = builder->shader;
  const GskGLUniform *u;
  guchar *args_dest;

  g_assert (idx < shader->uniforms->len);
  u = &g_array_index (shader->uniforms, GskGLUniform, idx);
  g_assert (u->type == GSK_GL_UNIFORM_TYPE_VEC2);

  args_dest = builder->data + u->offset;
  graphene_vec2_to_float (value, (float *)args_dest);
}

/**
 * gsk_shader_args_builder_set_vec3:
 * @builder: A #GskShaderArgsBuilder
 * @idx: The index of the uniform
 * @value: The value to set the uniform too
 *
 * Sets the value of the uniform @idx.
 * The uniform must be of vec3 type.
 */
void
gsk_shader_args_builder_set_vec3 (GskShaderArgsBuilder *builder,
                                  int                    idx,
                                  const graphene_vec3_t *value)
{
  GskGLShader *shader = builder->shader;
  const GskGLUniform *u;
  guchar *args_dest;

  g_assert (idx < shader->uniforms->len);
  u = &g_array_index (shader->uniforms, GskGLUniform, idx);
  g_assert (u->type == GSK_GL_UNIFORM_TYPE_VEC3);

  args_dest = builder->data + u->offset;
  graphene_vec3_to_float (value, (float *)args_dest);
}

/**
 * gsk_shader_args_builder_set_vec4:
 * @builder: A #GskShaderArgsBuilder
 * @idx: The index of the uniform
 * @value: The value to set the uniform too
 *
 * Sets the value of the uniform @idx.
 * The uniform must be of vec4 type.
 */
void
gsk_shader_args_builder_set_vec4 (GskShaderArgsBuilder *builder,
                                  int                    idx,
                                  const graphene_vec4_t *value)
{
  GskGLShader *shader = builder->shader;
  const GskGLUniform *u;
  guchar *args_dest;

  g_assert (idx < shader->uniforms->len);
  u = &g_array_index (shader->uniforms, GskGLUniform, idx);
  g_assert (u->type == GSK_GL_UNIFORM_TYPE_VEC4);

  args_dest = builder->data + u->offset;
  graphene_vec4_to_float (value, (float *)args_dest);
}