summaryrefslogtreecommitdiff
path: root/cogl/driver/gl/cogl-pipeline-fragend-glsl.c
blob: 6fdb3a12792b1c7f08ba137ae825da61f6629b70 (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
/*
 * Cogl
 *
 * A Low Level GPU Graphics and Utilities API
 *
 * Copyright (C) 2008,2009,2010,2013 Intel Corporation.
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 *
 *
 * Authors:
 *   Robert Bragg <robert@linux.intel.com>
 *   Neil Roberts <neil@linux.intel.com>
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <string.h>

#include "cogl-context-private.h"
#include "cogl-util-gl-private.h"
#include "cogl-pipeline-private.h"
#include "cogl-pipeline-layer-private.h"
#include "cogl-blend-string.h"
#include "cogl-snippet-private.h"
#include "cogl-list.h"

#ifdef COGL_PIPELINE_FRAGEND_GLSL

#include "cogl-context-private.h"
#include "cogl-object-private.h"
#include "cogl-shader-private.h"
#include "cogl-program-private.h"
#include "cogl-pipeline-cache.h"
#include "cogl-pipeline-fragend-glsl-private.h"
#include "cogl-glsl-shader-private.h"

#include <glib.h>

/*
 * GL/GLES compatability defines for pipeline thingies:
 */

/* This might not be defined on GLES */
#ifndef GL_TEXTURE_3D
#define GL_TEXTURE_3D                           0x806F
#endif

const CoglPipelineFragend _cogl_pipeline_glsl_backend;

typedef struct _UnitState
{
  unsigned int sampled:1;
  unsigned int combine_constant_used:1;
} UnitState;

typedef struct _LayerData
{
  CoglList link;

  /* Layer index for the for the previous layer. This isn't
     necessarily the same as this layer's index - 1 because the
     indices can have gaps. If this is the first layer then it will be
     -1 */
  int previous_layer_index;

  CoglPipelineLayer *layer;
} LayerData;

typedef struct
{
  int ref_count;

  GLuint gl_shader;
  GString *header, *source;
  UnitState *unit_state;

  /* List of layers that we haven't generated code for yet. These are
     in reverse order. As soon as we're about to generate code for
     layer we'll remove it from the list so we don't generate it
     again */
  CoglList layers;

  CoglPipelineCacheEntry *cache_entry;
} CoglPipelineShaderState;

static CoglUserDataKey shader_state_key;

static void
ensure_layer_generated (CoglPipeline *pipeline,
                        int layer_num);

static CoglPipelineShaderState *
shader_state_new (int n_layers,
                  CoglPipelineCacheEntry *cache_entry)
{
  CoglPipelineShaderState *shader_state;

  shader_state = g_slice_new0 (CoglPipelineShaderState);
  shader_state->ref_count = 1;
  shader_state->unit_state = g_new0 (UnitState, n_layers);
  shader_state->cache_entry = cache_entry;

  return shader_state;
}

static CoglPipelineShaderState *
get_shader_state (CoglPipeline *pipeline)
{
  return cogl_object_get_user_data (COGL_OBJECT (pipeline), &shader_state_key);
}

static void
destroy_shader_state (void *user_data,
                      void *instance)
{
  CoglPipelineShaderState *shader_state = user_data;

  _COGL_GET_CONTEXT (ctx, NO_RETVAL);

  if (shader_state->cache_entry &&
      shader_state->cache_entry->pipeline != instance)
    shader_state->cache_entry->usage_count--;

  if (--shader_state->ref_count == 0)
    {
      if (shader_state->gl_shader)
        GE( ctx, glDeleteShader (shader_state->gl_shader) );

      g_free (shader_state->unit_state);

      g_slice_free (CoglPipelineShaderState, shader_state);
    }
}

static void
set_shader_state (CoglPipeline *pipeline, CoglPipelineShaderState *shader_state)
{
  if (shader_state)
    {
      shader_state->ref_count++;

      /* If we're not setting the state on the template pipeline then
       * mark it as a usage of the pipeline cache entry */
      if (shader_state->cache_entry &&
          shader_state->cache_entry->pipeline != pipeline)
        shader_state->cache_entry->usage_count++;
    }

  _cogl_object_set_user_data (COGL_OBJECT (pipeline),
                              &shader_state_key,
                              shader_state,
                              destroy_shader_state);
}

static void
dirty_shader_state (CoglPipeline *pipeline)
{
  cogl_object_set_user_data (COGL_OBJECT (pipeline),
                             &shader_state_key,
                             NULL,
                             NULL);
}

GLuint
_cogl_pipeline_fragend_glsl_get_shader (CoglPipeline *pipeline)
{
  CoglPipelineShaderState *shader_state = get_shader_state (pipeline);

  if (shader_state)
    return shader_state->gl_shader;
  else
    return 0;
}

static CoglPipelineSnippetList *
get_fragment_snippets (CoglPipeline *pipeline)
{
  pipeline =
    _cogl_pipeline_get_authority (pipeline,
                                  COGL_PIPELINE_STATE_FRAGMENT_SNIPPETS);

  return &pipeline->big_state->fragment_snippets;
}

static CoglPipelineSnippetList *
get_layer_fragment_snippets (CoglPipelineLayer *layer)
{
  unsigned long state = COGL_PIPELINE_LAYER_STATE_FRAGMENT_SNIPPETS;
  layer = _cogl_pipeline_layer_get_authority (layer, state);

  return &layer->big_state->fragment_snippets;
}

static CoglBool
has_replace_hook (CoglPipelineLayer *layer,
                  CoglSnippetHook hook)
{
  GList *l;

  for (l = get_layer_fragment_snippets (layer)->entries; l; l = l->next)
    {
      CoglSnippet *snippet = l->data;

      if (snippet->hook == hook && snippet->replace)
        return TRUE;
    }

  return FALSE;
}

static CoglBool
add_layer_declaration_cb (CoglPipelineLayer *layer,
                          void *user_data)
{
  CoglPipelineShaderState *shader_state = user_data;
  CoglTextureType texture_type =
    _cogl_pipeline_layer_get_texture_type (layer);
  const char *target_string;

  _cogl_gl_util_get_texture_target_string (texture_type, &target_string, NULL);

  g_string_append_printf (shader_state->header,
                          "uniform sampler%s cogl_sampler%i;\n",
                          target_string,
                          layer->index);

  return TRUE;
}

static void
add_layer_declarations (CoglPipeline *pipeline,
                        CoglPipelineShaderState *shader_state)
{
  /* We always emit sampler uniforms in case there will be custom
   * layer snippets that want to sample arbitrary layers. */

  _cogl_pipeline_foreach_layer_internal (pipeline,
                                         add_layer_declaration_cb,
                                         shader_state);
}

static void
add_global_declarations (CoglPipeline *pipeline,
                         CoglPipelineShaderState *shader_state)
{
  CoglSnippetHook hook = COGL_SNIPPET_HOOK_FRAGMENT_GLOBALS;
  CoglPipelineSnippetList *snippets = get_fragment_snippets (pipeline);

  /* Add the global data hooks. All of the code in these snippets is
   * always added and only the declarations data is used */

  _cogl_pipeline_snippet_generate_declarations (shader_state->header,
                                                hook,
                                                snippets);
}

static void
_cogl_pipeline_fragend_glsl_start (CoglPipeline *pipeline,
                                   int n_layers,
                                   unsigned long pipelines_difference)
{
  CoglPipelineShaderState *shader_state;
  CoglPipeline *authority;
  CoglPipelineCacheEntry *cache_entry = NULL;
  CoglProgram *user_program = cogl_pipeline_get_user_program (pipeline);
  int i;

  _COGL_GET_CONTEXT (ctx, NO_RETVAL);

  /* Now lookup our glsl backend private state */
  shader_state = get_shader_state (pipeline);

  if (shader_state == NULL)
    {
      /* If we don't have an associated glsl shader yet then find the
       * glsl-authority (the oldest ancestor whose state will result in
       * the same shader being generated as for this pipeline).
       *
       * We always make sure to associate new shader with the
       * glsl-authority to maximize the chance that other pipelines can
       * share it.
       */
      authority = _cogl_pipeline_find_equivalent_parent
        (pipeline,
         _cogl_pipeline_get_state_for_fragment_codegen (ctx) &
         ~COGL_PIPELINE_STATE_LAYERS,
         _cogl_pipeline_get_layer_state_for_fragment_codegen (ctx));

      shader_state = get_shader_state (authority);

      /* If we don't have an existing program associated with the
       * glsl-authority then start generating code for a new shader...
       */
      if (shader_state == NULL)
        {
          /* Check if there is already a similar cached pipeline whose
             shader state we can share */
          if (G_LIKELY (!(COGL_DEBUG_ENABLED
                          (COGL_DEBUG_DISABLE_PROGRAM_CACHES))))
            {
              cache_entry =
                _cogl_pipeline_cache_get_fragment_template (ctx->pipeline_cache,
                                                            authority);

              shader_state = get_shader_state (cache_entry->pipeline);
            }

          if (shader_state)
            shader_state->ref_count++;
          else
            shader_state = shader_state_new (n_layers, cache_entry);

          set_shader_state (authority, shader_state);

          shader_state->ref_count--;

          if (cache_entry)
            set_shader_state (cache_entry->pipeline, shader_state);
        }

      /* If the pipeline isn't actually its own glsl-authority
       * then take a reference to the program state associated
       * with the glsl-authority... */
      if (authority != pipeline)
        set_shader_state (pipeline, shader_state);
    }

  if (user_program)
    {
      /* If the user program contains a fragment shader then we don't need
         to generate one */
      if (_cogl_program_has_fragment_shader (user_program))
        {
          if (shader_state->gl_shader)
            {
              GE( ctx, glDeleteShader (shader_state->gl_shader) );
              shader_state->gl_shader = 0;
            }
          return;
        }
    }

  if (shader_state->gl_shader)
    return;

  /* If we make it here then we have a glsl_shader_state struct
     without a gl_shader either because this is the first time we've
     encountered it or because the user program has changed */

  /* We reuse two grow-only GStrings for code-gen. One string
     contains the uniform and attribute declarations while the
     other contains the main function. We need two strings
     because we need to dynamically declare attributes as the
     add_layer callback is invoked */
  g_string_set_size (ctx->codegen_header_buffer, 0);
  g_string_set_size (ctx->codegen_source_buffer, 0);
  shader_state->header = ctx->codegen_header_buffer;
  shader_state->source = ctx->codegen_source_buffer;
  _cogl_list_init (&shader_state->layers);

  add_layer_declarations (pipeline, shader_state);
  add_global_declarations (pipeline, shader_state);

  g_string_append (shader_state->source,
                   "void\n"
                   "cogl_generated_source ()\n"
                   "{\n");

  for (i = 0; i < n_layers; i++)
    {
      shader_state->unit_state[i].sampled = FALSE;
      shader_state->unit_state[i].combine_constant_used = FALSE;
    }
}

static void
add_constant_lookup (CoglPipelineShaderState *shader_state,
                     CoglPipeline *pipeline,
                     CoglPipelineLayer *layer,
                     const char *swizzle)
{
  g_string_append_printf (shader_state->header,
                          "_cogl_layer_constant_%i.%s",
                          layer->index, swizzle);
}

static void
ensure_texture_lookup_generated (CoglPipelineShaderState *shader_state,
                                 CoglPipeline *pipeline,
                                 CoglPipelineLayer *layer)
{
  int unit_index = _cogl_pipeline_layer_get_unit_index (layer);
  CoglPipelineSnippetData snippet_data;
  CoglTextureType texture_type;
  const char *target_string, *tex_coord_swizzle;

  _COGL_GET_CONTEXT (ctx, NO_RETVAL);

  if (shader_state->unit_state[unit_index].sampled)
    return;

  texture_type =
    _cogl_pipeline_layer_get_texture_type (layer);
  _cogl_gl_util_get_texture_target_string (texture_type,
                                           &target_string,
                                           &tex_coord_swizzle);

  shader_state->unit_state[unit_index].sampled = TRUE;

  g_string_append_printf (shader_state->header,
                          "vec4 cogl_texel%i;\n",
                          layer->index);

  g_string_append_printf (shader_state->source,
                          "  cogl_texel%i = cogl_texture_lookup%i ("
                          "cogl_sampler%i, ",
                          layer->index,
                          layer->index,
                          layer->index);

  if (cogl_pipeline_get_layer_point_sprite_coords_enabled (pipeline,
                                                           layer->index))
    g_string_append_printf (shader_state->source,
                            "vec4 (cogl_point_coord, 0.0, 1.0)");
  else
    g_string_append_printf (shader_state->source,
                            "cogl_tex_coord%i_in",
                            layer->index);

  g_string_append (shader_state->source, ");\n");

  /* There's no need to generate the real texture lookup if it's going
     to be replaced */
  if (!has_replace_hook (layer, COGL_SNIPPET_HOOK_TEXTURE_LOOKUP))
    {
      g_string_append_printf (shader_state->header,
                              "vec4\n"
                              "cogl_real_texture_lookup%i (sampler%s tex,\n"
                              "                            vec4 coords)\n"
                              "{\n"
                              "  return ",
                              layer->index,
                              target_string);

      if (G_UNLIKELY (COGL_DEBUG_ENABLED (COGL_DEBUG_DISABLE_TEXTURING)))
        g_string_append (shader_state->header,
                         "vec4 (1.0, 1.0, 1.0, 1.0);\n");
      else
        g_string_append_printf (shader_state->header,
                                "texture%s (tex, coords.%s);\n",
                                target_string, tex_coord_swizzle);

      g_string_append (shader_state->header, "}\n");
    }

  /* Wrap the texture lookup in any snippets that have been hooked */
  memset (&snippet_data, 0, sizeof (snippet_data));
  snippet_data.snippets = get_layer_fragment_snippets (layer);
  snippet_data.hook = COGL_SNIPPET_HOOK_TEXTURE_LOOKUP;
  snippet_data.chain_function = g_strdup_printf ("cogl_real_texture_lookup%i",
                                                 layer->index);
  snippet_data.final_name = g_strdup_printf ("cogl_texture_lookup%i",
                                             layer->index);
  snippet_data.function_prefix = g_strdup_printf ("cogl_texture_lookup_hook%i",
                                                  layer->index);
  snippet_data.return_type = "vec4";
  snippet_data.return_variable = "cogl_texel";
  snippet_data.arguments = "cogl_sampler, cogl_tex_coord";
  snippet_data.argument_declarations =
    g_strdup_printf ("sampler%s cogl_sampler, vec4 cogl_tex_coord",
                     target_string);
  snippet_data.source_buf = shader_state->header;

  _cogl_pipeline_snippet_generate_code (&snippet_data);

  g_free ((char *) snippet_data.chain_function);
  g_free ((char *) snippet_data.final_name);
  g_free ((char *) snippet_data.function_prefix);
  g_free ((char *) snippet_data.argument_declarations);
}

static void
add_arg (CoglPipelineShaderState *shader_state,
         CoglPipeline *pipeline,
         CoglPipelineLayer *layer,
         int previous_layer_index,
         CoglPipelineCombineSource src,
         CoglPipelineCombineOp operand,
         const char *swizzle)
{
  GString *shader_source = shader_state->header;
  char alpha_swizzle[5] = "aaaa";

  g_string_append_c (shader_source, '(');

  if (operand == COGL_PIPELINE_COMBINE_OP_ONE_MINUS_SRC_COLOR ||
      operand == COGL_PIPELINE_COMBINE_OP_ONE_MINUS_SRC_ALPHA)
    g_string_append_printf (shader_source,
                            "vec4(1.0, 1.0, 1.0, 1.0).%s - ",
                            swizzle);

  /* If the operand is reading from the alpha then replace the swizzle
     with the same number of copies of the alpha */
  if (operand == COGL_PIPELINE_COMBINE_OP_SRC_ALPHA ||
      operand == COGL_PIPELINE_COMBINE_OP_ONE_MINUS_SRC_ALPHA)
    {
      alpha_swizzle[strlen (swizzle)] = '\0';
      swizzle = alpha_swizzle;
    }

  switch (src)
    {
    case COGL_PIPELINE_COMBINE_SOURCE_TEXTURE:
      g_string_append_printf (shader_source,
                              "cogl_texel%i.%s",
                              layer->index,
                              swizzle);
      break;

    case COGL_PIPELINE_COMBINE_SOURCE_CONSTANT:
      add_constant_lookup (shader_state,
                           pipeline,
                           layer,
                           swizzle);
      break;

    case COGL_PIPELINE_COMBINE_SOURCE_PREVIOUS:
      if (previous_layer_index >= 0)
        {
          g_string_append_printf (shader_source,
                                  "cogl_layer%i.%s",
                                  previous_layer_index,
                                  swizzle);
          break;
        }
      /* flow through */
    case COGL_PIPELINE_COMBINE_SOURCE_PRIMARY_COLOR:
      g_string_append_printf (shader_source, "cogl_color_in.%s", swizzle);
      break;

    default:
      {
        int layer_num = src - COGL_PIPELINE_COMBINE_SOURCE_TEXTURE0;
        CoglPipelineGetLayerFlags flags = COGL_PIPELINE_GET_LAYER_NO_CREATE;
        CoglPipelineLayer *other_layer =
          _cogl_pipeline_get_layer_with_flags (pipeline, layer_num, flags);

        if (other_layer == NULL)
          {
            static CoglBool warning_seen = FALSE;
            if (!warning_seen)
              {
                g_warning ("The application is trying to use a texture "
                           "combine with a layer number that does not exist");
                warning_seen = TRUE;
              }
            g_string_append_printf (shader_source,
                                    "vec4 (1.0, 1.0, 1.0, 1.0).%s",
                                    swizzle);
          }
        else
          g_string_append_printf (shader_source,
                                  "cogl_texel%i.%s",
                                  other_layer->index,
                                  swizzle);
      }
      break;
    }

  g_string_append_c (shader_source, ')');
}

static void
ensure_arg_generated (CoglPipeline *pipeline,
                      CoglPipelineLayer *layer,
                      int previous_layer_index,
                      CoglPipelineCombineSource src)
{
  CoglPipelineShaderState *shader_state = get_shader_state (pipeline);

  switch (src)
    {
    case COGL_PIPELINE_COMBINE_SOURCE_PRIMARY_COLOR:
      /* This doesn't involve any other layers */
      break;

    case COGL_PIPELINE_COMBINE_SOURCE_CONSTANT:
      {
        int unit_index = _cogl_pipeline_layer_get_unit_index (layer);
        /* Create a sampler uniform for this layer if we haven't already */
        if (!shader_state->unit_state[unit_index].combine_constant_used)
          {
            g_string_append_printf (shader_state->header,
                                    "uniform vec4 _cogl_layer_constant_%i;\n",
                                    layer->index);
            shader_state->unit_state[unit_index].combine_constant_used = TRUE;
          }
      }
      break;

    case COGL_PIPELINE_COMBINE_SOURCE_PREVIOUS:
      if (previous_layer_index >= 0)
        ensure_layer_generated (pipeline, previous_layer_index);
      break;

    case COGL_PIPELINE_COMBINE_SOURCE_TEXTURE:
      ensure_texture_lookup_generated (shader_state,
                                       pipeline,
                                       layer);
      break;

    default:
      if (src >= COGL_PIPELINE_COMBINE_SOURCE_TEXTURE0)
        {
          int layer_num = src - COGL_PIPELINE_COMBINE_SOURCE_TEXTURE0;
          CoglPipelineGetLayerFlags flags = COGL_PIPELINE_GET_LAYER_NO_CREATE;
          CoglPipelineLayer *other_layer =
            _cogl_pipeline_get_layer_with_flags (pipeline, layer_num, flags);

          if (other_layer)
            ensure_texture_lookup_generated (shader_state,
                                             pipeline,
                                             other_layer);
        }
      break;
    }
}

static void
ensure_args_for_func (CoglPipeline *pipeline,
                      CoglPipelineLayer *layer,
                      int previous_layer_index,
                      CoglPipelineCombineFunc function,
                      CoglPipelineCombineSource *src)
{
  int n_args = _cogl_get_n_args_for_combine_func (function);
  int i;

  for (i = 0; i < n_args; i++)
    ensure_arg_generated (pipeline, layer, previous_layer_index, src[i]);
}

static void
append_masked_combine (CoglPipeline *pipeline,
                       CoglPipelineLayer *layer,
                       int previous_layer_index,
                       const char *swizzle,
                       CoglPipelineCombineFunc function,
                       CoglPipelineCombineSource *src,
                       CoglPipelineCombineOp *op)
{
  CoglPipelineShaderState *shader_state = get_shader_state (pipeline);
  GString *shader_source = shader_state->header;

  g_string_append_printf (shader_state->header,
                          "  cogl_layer.%s = ",
                          swizzle);

  switch (function)
    {
    case COGL_PIPELINE_COMBINE_FUNC_REPLACE:
      add_arg (shader_state, pipeline, layer, previous_layer_index,
               src[0], op[0], swizzle);
      break;

    case COGL_PIPELINE_COMBINE_FUNC_MODULATE:
      add_arg (shader_state, pipeline, layer, previous_layer_index,
               src[0], op[0], swizzle);
      g_string_append (shader_source, " * ");
      add_arg (shader_state, pipeline, layer, previous_layer_index,
               src[1], op[1], swizzle);
      break;

    case COGL_PIPELINE_COMBINE_FUNC_ADD:
      add_arg (shader_state, pipeline, layer, previous_layer_index,
               src[0], op[0], swizzle);
      g_string_append (shader_source, " + ");
      add_arg (shader_state, pipeline, layer, previous_layer_index,
               src[1], op[1], swizzle);
      break;

    case COGL_PIPELINE_COMBINE_FUNC_ADD_SIGNED:
      add_arg (shader_state, pipeline, layer, previous_layer_index,
               src[0], op[0], swizzle);
      g_string_append (shader_source, " + ");
      add_arg (shader_state, pipeline, layer, previous_layer_index,
               src[1], op[1], swizzle);
      g_string_append_printf (shader_source,
                              " - vec4(0.5, 0.5, 0.5, 0.5).%s",
                              swizzle);
      break;

    case COGL_PIPELINE_COMBINE_FUNC_SUBTRACT:
      add_arg (shader_state, pipeline, layer, previous_layer_index,
               src[0], op[0], swizzle);
      g_string_append (shader_source, " - ");
      add_arg (shader_state, pipeline, layer, previous_layer_index,
               src[1], op[1], swizzle);
      break;

    case COGL_PIPELINE_COMBINE_FUNC_INTERPOLATE:
      add_arg (shader_state, pipeline, layer, previous_layer_index,
               src[0], op[0], swizzle);
      g_string_append (shader_source, " * ");
      add_arg (shader_state, pipeline, layer, previous_layer_index,
               src[2], op[2], swizzle);
      g_string_append (shader_source, " + ");
      add_arg (shader_state, pipeline, layer, previous_layer_index,
               src[1], op[1], swizzle);
      g_string_append_printf (shader_source,
                              " * (vec4(1.0, 1.0, 1.0, 1.0).%s - ",
                              swizzle);
      add_arg (shader_state, pipeline, layer, previous_layer_index,
               src[2], op[2], swizzle);
      g_string_append_c (shader_source, ')');
      break;

    case COGL_PIPELINE_COMBINE_FUNC_DOT3_RGB:
    case COGL_PIPELINE_COMBINE_FUNC_DOT3_RGBA:
      g_string_append (shader_source, "vec4(4.0 * ((");
      add_arg (shader_state, pipeline, layer, previous_layer_index,
               src[0], op[0], "r");
      g_string_append (shader_source, " - 0.5) * (");
      add_arg (shader_state, pipeline, layer, previous_layer_index,
               src[1], op[1], "r");
      g_string_append (shader_source, " - 0.5) + (");
      add_arg (shader_state, pipeline, layer, previous_layer_index,
               src[0], op[0], "g");
      g_string_append (shader_source, " - 0.5) * (");
      add_arg (shader_state, pipeline, layer, previous_layer_index,
               src[1], op[1], "g");
      g_string_append (shader_source, " - 0.5) + (");
      add_arg (shader_state, pipeline, layer, previous_layer_index,
               src[0], op[0], "b");
      g_string_append (shader_source, " - 0.5) * (");
      add_arg (shader_state, pipeline, layer, previous_layer_index,
               src[1], op[1], "b");
      g_string_append_printf (shader_source, " - 0.5))).%s", swizzle);
      break;
    }

  g_string_append_printf (shader_source, ";\n");
}

static void
ensure_layer_generated (CoglPipeline *pipeline,
                        int layer_index)
{
  CoglPipelineShaderState *shader_state = get_shader_state (pipeline);
  CoglPipelineLayer *combine_authority;
  CoglPipelineLayerBigState *big_state;
  CoglPipelineLayer *layer;
  CoglPipelineSnippetData snippet_data;
  LayerData *layer_data;

  /* Find the layer that corresponds to this layer_num */
  _cogl_list_for_each (layer_data, &shader_state->layers, link)
    {
      layer = layer_data->layer;

      if (layer->index == layer_index)
        goto found;
    }

  /* If we didn't find it then we can assume the layer has already
     been generated */
  return;

 found:

  /* Remove the layer from the list so we don't generate it again */
  _cogl_list_remove (&layer_data->link);

  combine_authority =
    _cogl_pipeline_layer_get_authority (layer,
                                        COGL_PIPELINE_LAYER_STATE_COMBINE);
  big_state = combine_authority->big_state;

  /* Make a global variable for the result of the layer code */
  g_string_append_printf (shader_state->header,
                          "vec4 cogl_layer%i;\n",
                          layer_index);

  /* Skip the layer generation if there is a snippet that replaces the
     default layer code. This is important because generating this
     code may cause the code for other layers to be generated and
     stored in the global variable. If this code isn't actually used
     then the global variables would be uninitialised and they may be
     used from other layers */
  if (!has_replace_hook (layer, COGL_SNIPPET_HOOK_LAYER_FRAGMENT))
    {
      ensure_args_for_func (pipeline,
                            layer,
                            layer_data->previous_layer_index,
                            big_state->texture_combine_rgb_func,
                            big_state->texture_combine_rgb_src);
      ensure_args_for_func (pipeline,
                            layer,
                            layer_data->previous_layer_index,
                            big_state->texture_combine_alpha_func,
                            big_state->texture_combine_alpha_src);

      g_string_append_printf (shader_state->header,
                              "vec4\n"
                              "cogl_real_generate_layer%i ()\n"
                              "{\n"
                              "  vec4 cogl_layer;\n",
                              layer_index);

      if (!_cogl_pipeline_layer_needs_combine_separate (combine_authority) ||
          /* GL_DOT3_RGBA Is a bit weird as a GL_COMBINE_RGB function
           * since if you use it, it overrides your ALPHA function...
           */
          big_state->texture_combine_rgb_func ==
          COGL_PIPELINE_COMBINE_FUNC_DOT3_RGBA)
        append_masked_combine (pipeline,
                               layer,
                               layer_data->previous_layer_index,
                               "rgba",
                               big_state->texture_combine_rgb_func,
                               big_state->texture_combine_rgb_src,
                               big_state->texture_combine_rgb_op);
      else
        {
          append_masked_combine (pipeline,
                                 layer,
                                 layer_data->previous_layer_index,
                                 "rgb",
                                 big_state->texture_combine_rgb_func,
                                 big_state->texture_combine_rgb_src,
                                 big_state->texture_combine_rgb_op);
          append_masked_combine (pipeline,
                                 layer,
                                 layer_data->previous_layer_index,
                                 "a",
                                 big_state->texture_combine_alpha_func,
                                 big_state->texture_combine_alpha_src,
                                 big_state->texture_combine_alpha_op);
        }

      g_string_append (shader_state->header,
                       "  return cogl_layer;\n"
                       "}\n");
    }

  /* Wrap the layer code in any snippets that have been hooked */
  memset (&snippet_data, 0, sizeof (snippet_data));
  snippet_data.snippets = get_layer_fragment_snippets (layer);
  snippet_data.hook = COGL_SNIPPET_HOOK_LAYER_FRAGMENT;
  snippet_data.chain_function = g_strdup_printf ("cogl_real_generate_layer%i",
                                                 layer_index);
  snippet_data.final_name = g_strdup_printf ("cogl_generate_layer%i",
                                             layer_index);
  snippet_data.function_prefix = g_strdup_printf ("cogl_generate_layer%i",
                                                  layer_index);
  snippet_data.return_type = "vec4";
  snippet_data.return_variable = "cogl_layer";
  snippet_data.source_buf = shader_state->header;

  _cogl_pipeline_snippet_generate_code (&snippet_data);

  g_free ((char *) snippet_data.chain_function);
  g_free ((char *) snippet_data.final_name);
  g_free ((char *) snippet_data.function_prefix);

  g_string_append_printf (shader_state->source,
                          "  cogl_layer%i = cogl_generate_layer%i ();\n",
                          layer_index,
                          layer_index);

  g_slice_free (LayerData, layer_data);
}

static CoglBool
_cogl_pipeline_fragend_glsl_add_layer (CoglPipeline *pipeline,
                                        CoglPipelineLayer *layer,
                                        unsigned long layers_difference)
{
  CoglPipelineShaderState *shader_state = get_shader_state (pipeline);
  LayerData *layer_data;

  if (!shader_state->source)
    return TRUE;

  /* Store the layers in reverse order */
  layer_data = g_slice_new (LayerData);
  layer_data->layer = layer;

  if (_cogl_list_empty (&shader_state->layers))
    {
      layer_data->previous_layer_index = -1;
    }
  else
    {
      LayerData *first =
        _cogl_container_of (shader_state->layers.next, LayerData, link);
      layer_data->previous_layer_index = first->layer->index;
    }

  _cogl_list_insert (&shader_state->layers, &layer_data->link);

  return TRUE;
}

/* GLES2 and GL3 don't have alpha testing so we need to implement it
   in the shader */

#if defined(HAVE_COGL_GLES2) || defined(HAVE_COGL_GL)

static void
add_alpha_test_snippet (CoglPipeline *pipeline,
                        CoglPipelineShaderState *shader_state)
{
  CoglPipelineAlphaFunc alpha_func;

  alpha_func = cogl_pipeline_get_alpha_test_function (pipeline);

  if (alpha_func == COGL_PIPELINE_ALPHA_FUNC_ALWAYS)
    /* Do nothing */
    return;

  if (alpha_func == COGL_PIPELINE_ALPHA_FUNC_NEVER)
    {
      /* Always discard the fragment */
      g_string_append (shader_state->source,
                       "  discard;\n");
      return;
    }

  /* For all of the other alpha functions we need a uniform for the
     reference */

  g_string_append (shader_state->header,
                   "uniform float _cogl_alpha_test_ref;\n");

  g_string_append (shader_state->source,
                   "  if (cogl_color_out.a ");

  switch (alpha_func)
    {
    case COGL_PIPELINE_ALPHA_FUNC_LESS:
      g_string_append (shader_state->source, ">=");
      break;
    case COGL_PIPELINE_ALPHA_FUNC_EQUAL:
      g_string_append (shader_state->source, "!=");
      break;
    case COGL_PIPELINE_ALPHA_FUNC_LEQUAL:
      g_string_append (shader_state->source, ">");
      break;
    case COGL_PIPELINE_ALPHA_FUNC_GREATER:
      g_string_append (shader_state->source, "<=");
      break;
    case COGL_PIPELINE_ALPHA_FUNC_NOTEQUAL:
      g_string_append (shader_state->source, "==");
      break;
    case COGL_PIPELINE_ALPHA_FUNC_GEQUAL:
      g_string_append (shader_state->source, "< ");
      break;

    case COGL_PIPELINE_ALPHA_FUNC_ALWAYS:
    case COGL_PIPELINE_ALPHA_FUNC_NEVER:
      g_assert_not_reached ();
      break;
    }

  g_string_append (shader_state->source,
                   " _cogl_alpha_test_ref)\n    discard;\n");
}

#endif /*  HAVE_COGL_GLES2 */

static CoglBool
_cogl_pipeline_fragend_glsl_end (CoglPipeline *pipeline,
                                 unsigned long pipelines_difference)
{
  CoglPipelineShaderState *shader_state = get_shader_state (pipeline);

  _COGL_GET_CONTEXT (ctx, FALSE);

  if (shader_state->source)
    {
      const char *source_strings[2];
      GLint lengths[2];
      GLint compile_status;
      GLuint shader;
      CoglPipelineSnippetData snippet_data;

      COGL_STATIC_COUNTER (fragend_glsl_compile_counter,
                           "glsl fragment compile counter",
                           "Increments each time a new GLSL "
                           "fragment shader is compiled",
                           0 /* no application private data */);
      COGL_COUNTER_INC (_cogl_uprof_context, fragend_glsl_compile_counter);

      /* We only need to generate code to calculate the fragment value
         for the last layer. If the value of this layer depends on any
         previous layers then it will recursively generate the code
         for those layers */
      if (!_cogl_list_empty (&shader_state->layers))
        {
          CoglPipelineLayer *last_layer;
          LayerData *layer_data, *tmp;

          layer_data = _cogl_container_of (shader_state->layers.next,
                                           LayerData,
                                           link);
          last_layer = layer_data->layer;

          ensure_layer_generated (pipeline, last_layer->index);
          g_string_append_printf (shader_state->source,
                                  "  cogl_color_out = cogl_layer%i;\n",
                                  last_layer->index);

          _cogl_list_for_each_safe (layer_data,
                                    tmp,
                                    &shader_state->layers,
                                    link)
            g_slice_free (LayerData, layer_data);
        }
      else
        g_string_append (shader_state->source,
                         "  cogl_color_out = cogl_color_in;\n");

#if defined(HAVE_COGL_GLES2) || defined (HAVE_COGL_GL)
      if (!_cogl_has_private_feature (ctx, COGL_PRIVATE_FEATURE_ALPHA_TEST))
        add_alpha_test_snippet (pipeline, shader_state);
#endif

      /* Close the function surrounding the generated fragment processing */
      g_string_append (shader_state->source, "}\n");

      /* Add all of the hooks for fragment processing */
      memset (&snippet_data, 0, sizeof (snippet_data));
      snippet_data.snippets = get_fragment_snippets (pipeline);
      snippet_data.hook = COGL_SNIPPET_HOOK_FRAGMENT;
      snippet_data.chain_function = "cogl_generated_source";
      snippet_data.final_name = "main";
      snippet_data.function_prefix = "cogl_fragment_hook";
      snippet_data.source_buf = shader_state->source;
      _cogl_pipeline_snippet_generate_code (&snippet_data);

      GE_RET( shader, ctx, glCreateShader (GL_FRAGMENT_SHADER) );

      lengths[0] = shader_state->header->len;
      source_strings[0] = shader_state->header->str;
      lengths[1] = shader_state->source->len;
      source_strings[1] = shader_state->source->str;

      _cogl_glsl_shader_set_source_with_boilerplate (ctx,
                                                     shader, GL_FRAGMENT_SHADER,
                                                     pipeline,
                                                     2, /* count */
                                                     source_strings, lengths);

      GE( ctx, glCompileShader (shader) );
      GE( ctx, glGetShaderiv (shader, GL_COMPILE_STATUS, &compile_status) );

      if (!compile_status)
        {
          GLint len = 0;
          char *shader_log;

          GE( ctx, glGetShaderiv (shader, GL_INFO_LOG_LENGTH, &len) );
          shader_log = g_alloca (len);
          GE( ctx, glGetShaderInfoLog (shader, len, &len, shader_log) );
          g_warning ("Shader compilation failed:\n%s", shader_log);
        }

      shader_state->header = NULL;
      shader_state->source = NULL;
      shader_state->gl_shader = shader;
    }

  return TRUE;
}

static void
_cogl_pipeline_fragend_glsl_pre_change_notify (CoglPipeline *pipeline,
                                               CoglPipelineState change,
                                               const CoglColor *new_color)
{
  _COGL_GET_CONTEXT (ctx, NO_RETVAL);

  if ((change & _cogl_pipeline_get_state_for_fragment_codegen (ctx)))
    dirty_shader_state (pipeline);
}

/* NB: layers are considered immutable once they have any dependants
 * so although multiple pipelines can end up depending on a single
 * static layer, we can guarantee that if a layer is being *changed*
 * then it can only have one pipeline depending on it.
 *
 * XXX: Don't forget this is *pre* change, we can't read the new value
 * yet!
 */
static void
_cogl_pipeline_fragend_glsl_layer_pre_change_notify (
                                                CoglPipeline *owner,
                                                CoglPipelineLayer *layer,
                                                CoglPipelineLayerState change)
{
  _COGL_GET_CONTEXT (ctx, NO_RETVAL);

  if ((change & _cogl_pipeline_get_layer_state_for_fragment_codegen (ctx)))
    {
      dirty_shader_state (owner);
      return;
    }

  /* TODO: we could be saving snippets of texture combine code along
   * with each layer and then when a layer changes we would just free
   * the snippet. */
}

const CoglPipelineFragend _cogl_pipeline_glsl_fragend =
{
  _cogl_pipeline_fragend_glsl_start,
  _cogl_pipeline_fragend_glsl_add_layer,
  NULL, /* passthrough */
  _cogl_pipeline_fragend_glsl_end,
  _cogl_pipeline_fragend_glsl_pre_change_notify,
  NULL, /* pipeline_set_parent_notify */
  _cogl_pipeline_fragend_glsl_layer_pre_change_notify
};

#endif /* COGL_PIPELINE_FRAGEND_GLSL */