summaryrefslogtreecommitdiffstats
path: root/Source/WebCore/platform/graphics/android/rendering/ShaderProgram.cpp
blob: 5920007002cd7d59c8a24d0dc5a51e7089e36eb3 (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
/*
 * Copyright 2010, The Android Open Source Project
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *  * Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *  * Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#define LOG_TAG "ShaderProgram"
#define LOG_NDEBUG 1

#include "config.h"
#include "ShaderProgram.h"

#if USE(ACCELERATED_COMPOSITING)

#include "AndroidLog.h"
#include "DrawQuadData.h"
#include "FloatPoint3D.h"
#include "GLUtils.h"
#include "TilesManager.h"

#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>

#define EPSILON 0.00001f

namespace WebCore {

// fillPortion.xy = starting UV coordinates.
// fillPortion.zw = UV coordinates width and height.
static const char gVertexShader[] =
    "attribute vec4 vPosition;\n"
    "uniform mat4 projectionMatrix;\n"
    "uniform vec4 fillPortion;\n"
    "varying vec2 v_texCoord;\n"
    "void main() {\n"
    "  gl_Position = projectionMatrix * vPosition;\n"
    "  v_texCoord = vPosition.xy * fillPortion.zw + fillPortion.xy;\n"
    "}\n";

static const char gRepeatTexFragmentShader[] =
    "precision mediump float;\n"
    "varying vec2 v_texCoord; \n"
    "uniform float alpha; \n"
    "uniform sampler2D s_texture; \n"
    "uniform vec2 repeatScale;\n"
    "void main() {\n"
    "  vec2 repeatedTexCoord; "
    "  repeatedTexCoord.x = v_texCoord.x - floor(v_texCoord.x); "
    "  repeatedTexCoord.y = v_texCoord.y - floor(v_texCoord.y); "
    "  repeatedTexCoord.x = repeatedTexCoord.x * repeatScale.x; "
    "  repeatedTexCoord.y = repeatedTexCoord.y * repeatScale.y; "
    "  gl_FragColor = texture2D(s_texture, repeatedTexCoord); \n"
    "  gl_FragColor *= alpha; "
    "}\n";

static const char gRepeatTexFragmentShaderInverted[] =
    "precision mediump float;\n"
    "varying vec2 v_texCoord; \n"
    "uniform float alpha; \n"
    "uniform float contrast; \n"
    "uniform sampler2D s_texture; \n"
    "uniform vec2 repeatScale;\n"
    "void main() {\n"
    "  vec2 repeatedTexCoord; "
    "  repeatedTexCoord.x = v_texCoord.x - floor(v_texCoord.x); "
    "  repeatedTexCoord.y = v_texCoord.y - floor(v_texCoord.y); "
    "  repeatedTexCoord.x = repeatedTexCoord.x * repeatScale.x; "
    "  repeatedTexCoord.y = repeatedTexCoord.y * repeatScale.y; "
    "  vec4 pixel = texture2D(s_texture, repeatedTexCoord); \n"
    "  float a = pixel.a; \n"
    "  float color = a - (0.2989 * pixel.r + 0.5866 * pixel.g + 0.1145 * pixel.b);\n"
    "  color = ((color - a/2.0) * contrast) + a/2.0; \n"
    "  pixel.rgb = vec3(color, color, color); \n "
    "  gl_FragColor = pixel; \n"
    "  gl_FragColor *= alpha; "
    "}\n";

static const char gFragmentShader[] =
    "precision mediump float;\n"
    "varying vec2 v_texCoord; \n"
    "uniform float alpha; \n"
    "uniform sampler2D s_texture; \n"
    "void main() {\n"
    "  gl_FragColor = texture2D(s_texture, v_texCoord); \n"
    "  gl_FragColor *= alpha; "
    "}\n";

// We could pass the pureColor into either Vertex or Frag Shader.
// The reason we passed the color into the Vertex Shader is that some driver
// might create redundant copy when uniforms in fragment shader changed.
static const char gPureColorVertexShader[] =
    "attribute vec4 vPosition;\n"
    "uniform mat4 projectionMatrix;\n"
    "uniform vec4 inputColor;\n"
    "varying vec4 v_color;\n"
    "void main() {\n"
    "  gl_Position = projectionMatrix * vPosition;\n"
    "  v_color = inputColor;\n"
    "}\n";

static const char gPureColorFragmentShader[] =
    "precision mediump float;\n"
    "varying vec4 v_color;\n"
    "void main() {\n"
    "  gl_FragColor = v_color;\n"
    "}\n";

static const char gFragmentShaderInverted[] =
    "precision mediump float;\n"
    "varying vec2 v_texCoord; \n"
    "uniform float alpha; \n"
    "uniform float contrast; \n"
    "uniform sampler2D s_texture; \n"
    "void main() {\n"
    "  vec4 pixel = texture2D(s_texture, v_texCoord); \n"
    "  float a = pixel.a; \n"
    "  float color = a - (0.2989 * pixel.r + 0.5866 * pixel.g + 0.1145 * pixel.b);\n"
    "  color = ((color - a/2.0) * contrast) + a/2.0; \n"
    "  pixel.rgb = vec3(color, color, color); \n "
    "  gl_FragColor = pixel; \n"
    "  gl_FragColor *= alpha; \n"
    "}\n";

static const char gVideoVertexShader[] =
    "attribute vec4 vPosition;\n"
    "uniform mat4 textureMatrix;\n"
    "uniform mat4 projectionMatrix;\n"
    "varying vec2 v_texCoord;\n"
    "void main() {\n"
    "  gl_Position = projectionMatrix * vPosition;\n"
    "  v_texCoord = vec2(textureMatrix * vec4(vPosition.x, 1.0 - vPosition.y, 0.0, 1.0));\n"
    "}\n";

static const char gVideoFragmentShader[] =
    "#extension GL_OES_EGL_image_external : require\n"
    "precision mediump float;\n"
    "uniform samplerExternalOES s_yuvTexture;\n"
    "varying vec2 v_texCoord;\n"
    "void main() {\n"
    "  gl_FragColor = texture2D(s_yuvTexture, v_texCoord);\n"
    "}\n";

static const char gSurfaceTextureOESFragmentShader[] =
    "#extension GL_OES_EGL_image_external : require\n"
    "precision mediump float;\n"
    "varying vec2 v_texCoord; \n"
    "uniform float alpha; \n"
    "uniform samplerExternalOES s_texture; \n"
    "void main() {\n"
    "  gl_FragColor = texture2D(s_texture, v_texCoord); \n"
    "  gl_FragColor *= alpha; "
    "}\n";

static const char gSurfaceTextureOESFragmentShaderInverted[] =
    "#extension GL_OES_EGL_image_external : require\n"
    "precision mediump float;\n"
    "varying vec2 v_texCoord; \n"
    "uniform float alpha; \n"
    "uniform float contrast; \n"
    "uniform samplerExternalOES s_texture; \n"
    "void main() {\n"
    "  vec4 pixel = texture2D(s_texture, v_texCoord); \n"
    "  float a = pixel.a; \n"
    "  float color = a - (0.2989 * pixel.r + 0.5866 * pixel.g + 0.1145 * pixel.b);\n"
    "  color = ((color - a/2.0) * contrast) + a/2.0; \n"
    "  pixel.rgb = vec3(color, color, color); \n "
    "  gl_FragColor = pixel; \n"
    "  gl_FragColor *= alpha; \n"
    "}\n";

GLuint ShaderProgram::loadShader(GLenum shaderType, const char* pSource)
{
    GLuint shader = glCreateShader(shaderType);
    if (shader) {
        glShaderSource(shader, 1, &pSource, 0);
        glCompileShader(shader);
        GLint compiled = 0;
        glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
        if (!compiled) {
            GLint infoLen = 0;
            glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLen);
            if (infoLen) {
                char* buf = (char*) malloc(infoLen);
                if (buf) {
                glGetShaderInfoLog(shader, infoLen, 0, buf);
                ALOGE("could not compile shader %d:\n%s\n", shaderType, buf);
                free(buf);
            }
            glDeleteShader(shader);
            shader = 0;
            }
        }
    }
    return shader;
}

GLint ShaderProgram::createProgram(const char* pVertexSource, const char* pFragmentSource)
{
    GLuint vertexShader = loadShader(GL_VERTEX_SHADER, pVertexSource);
    if (!vertexShader) {
        ALOGE("couldn't load the vertex shader!");
        return -1;
    }

    GLuint pixelShader = loadShader(GL_FRAGMENT_SHADER, pFragmentSource);
    if (!pixelShader) {
        ALOGE("couldn't load the pixel shader!");
        return -1;
    }

    GLuint program = glCreateProgram();
    if (program) {
        glAttachShader(program, vertexShader);
        GLUtils::checkGlError("glAttachShader vertex");
        glAttachShader(program, pixelShader);
        GLUtils::checkGlError("glAttachShader pixel");
        glLinkProgram(program);
        GLint linkStatus = GL_FALSE;
        glGetProgramiv(program, GL_LINK_STATUS, &linkStatus);
        if (linkStatus != GL_TRUE) {
            GLint bufLength = 0;
            glGetProgramiv(program, GL_INFO_LOG_LENGTH, &bufLength);
            if (bufLength) {
                char* buf = (char*) malloc(bufLength);
                if (buf) {
                    glGetProgramInfoLog(program, bufLength, 0, buf);
                    ALOGE("could not link program:\n%s\n", buf);
                    free(buf);
                }
            }
            glDeleteProgram(program);
            program = -1;
        }
    }

    ShaderResource newResource(program, vertexShader, pixelShader);
    m_resources.append(newResource);
    return program;
}

void ShaderProgram::initProgram(ShaderType type)
{
    // initialize shader's static texSampler and position values
    glUseProgram(m_handleArray[type].programHandle);

    if (m_handleArray[type].texSamplerHandle != -1)
        glUniform1i(m_handleArray[type].texSamplerHandle, 0);
    glEnableVertexAttribArray(m_handleArray[type].positionHandle);
}

ShaderProgram::ShaderProgram()
    : m_blendingEnabled(false)
    , m_contrast(1)
    , m_alphaLayer(false)
    , m_currentScale(1.0f)
    , m_needsInit(true)
{
    // initialize the matrix to calculate z values correctly, since it can be
    // used for that before setupDrawing is called.
    GLUtils::setOrthographicMatrix(m_visibleContentRectProjectionMatrix,
                                   0,0,1,1,
                                   -1000, 1000);
}

void ShaderProgram::cleanupGLResources()
{
    for (unsigned int i = 0; i < m_resources.size(); i++) {
        glDetachShader(m_resources[i].program, m_resources[i].vertexShader);
        glDetachShader(m_resources[i].program, m_resources[i].fragmentShader);
        glDeleteShader(m_resources[i].vertexShader);
        glDeleteShader(m_resources[i].fragmentShader);
        glDeleteProgram(m_resources[i].program);
    }
    glDeleteBuffers(1, m_textureBuffer);

    m_resources.clear();
    m_needsInit = true;
    GLUtils::checkGlError("cleanupGLResources");

    return;
}

void ShaderProgram::initGLResources()
{
    // To detect whether or not resources for ShaderProgram allocated
    // successfully, we clean up pre-existing errors here and will check for
    // new errors at the end of this function.
    GLUtils::checkGlError("before initGLResources");

    GLint tex2DProgram = createProgram(gVertexShader, gFragmentShader);
    GLint pureColorProgram = createProgram(gPureColorVertexShader, gPureColorFragmentShader);
    GLint tex2DInvProgram = createProgram(gVertexShader, gFragmentShaderInverted);
    GLint videoProgram = createProgram(gVideoVertexShader, gVideoFragmentShader);
    GLint texOESProgram =
        createProgram(gVertexShader, gSurfaceTextureOESFragmentShader);
    GLint texOESInvProgram =
        createProgram(gVertexShader, gSurfaceTextureOESFragmentShaderInverted);
    GLint repeatTexProgram =
        createProgram(gVertexShader, gRepeatTexFragmentShader);
    GLint repeatTexInvProgram =
        createProgram(gVertexShader, gRepeatTexFragmentShaderInverted);

    if (tex2DProgram == -1
        || pureColorProgram == -1
        || tex2DInvProgram == -1
        || videoProgram == -1
        || texOESProgram == -1
        || texOESInvProgram == -1
        || repeatTexProgram == -1
        || repeatTexInvProgram == -1) {
        m_needsInit = true;
        return;
    }

    GLint pureColorPosition = glGetAttribLocation(pureColorProgram, "vPosition");
    GLint pureColorProjMtx = glGetUniformLocation(pureColorProgram, "projectionMatrix");
    GLint pureColorValue = glGetUniformLocation(pureColorProgram, "inputColor");
    m_handleArray[PureColor].init(-1, -1, pureColorPosition, pureColorProgram,
                                  pureColorProjMtx, pureColorValue, -1, -1, -1, -1);
    initProgram(PureColor);

    GLint tex2DAlpha = glGetUniformLocation(tex2DProgram, "alpha");
    GLint tex2DPosition = glGetAttribLocation(tex2DProgram, "vPosition");
    GLint tex2DProjMtx = glGetUniformLocation(tex2DProgram, "projectionMatrix");
    GLint tex2DTexSampler = glGetUniformLocation(tex2DProgram, "s_texture");
    GLint tex2DFillPortion = glGetUniformLocation(tex2DProgram, "fillPortion");
    m_handleArray[Tex2D].init(tex2DAlpha, -1, tex2DPosition, tex2DProgram,
                              tex2DProjMtx, -1, tex2DTexSampler, -1, tex2DFillPortion, -1);
    initProgram(Tex2D);

    GLint tex2DInvAlpha = glGetUniformLocation(tex2DInvProgram, "alpha");
    GLint tex2DInvContrast = glGetUniformLocation(tex2DInvProgram, "contrast");
    GLint tex2DInvPosition = glGetAttribLocation(tex2DInvProgram, "vPosition");
    GLint tex2DInvProjMtx = glGetUniformLocation(tex2DInvProgram, "projectionMatrix");
    GLint tex2DInvTexSampler = glGetUniformLocation(tex2DInvProgram, "s_texture");
    GLint tex2DInvFillPortion = glGetUniformLocation(tex2DInvProgram, "fillPortion");
    m_handleArray[Tex2DInv].init(tex2DInvAlpha, tex2DInvContrast,
                                 tex2DInvPosition, tex2DInvProgram,
                                 tex2DInvProjMtx, -1,
                                 tex2DInvTexSampler, -1, tex2DInvFillPortion, -1);
    initProgram(Tex2DInv);

    GLint repeatTexAlpha = glGetUniformLocation(repeatTexProgram, "alpha");
    GLint repeatTexPosition = glGetAttribLocation(repeatTexProgram, "vPosition");
    GLint repeatTexProjMtx = glGetUniformLocation(repeatTexProgram, "projectionMatrix");
    GLint repeatTexTexSampler = glGetUniformLocation(repeatTexProgram, "s_texture");
    GLint repeatTexFillPortion = glGetUniformLocation(repeatTexProgram, "fillPortion");
    GLint repeatTexScale = glGetUniformLocation(repeatTexProgram, "repeatScale");
    m_handleArray[RepeatTex].init(repeatTexAlpha, -1, repeatTexPosition,
                                  repeatTexProgram,repeatTexProjMtx, -1,
                                  repeatTexTexSampler, -1, repeatTexFillPortion,
                                  repeatTexScale);
    initProgram(RepeatTex);

    GLint repeatTexInvAlpha = glGetUniformLocation(repeatTexInvProgram, "alpha");
    GLint repeatTexInvContrast = glGetUniformLocation(tex2DInvProgram, "contrast");
    GLint repeatTexInvPosition = glGetAttribLocation(repeatTexInvProgram, "vPosition");
    GLint repeatTexInvProjMtx = glGetUniformLocation(repeatTexInvProgram, "projectionMatrix");
    GLint repeatTexInvTexSampler = glGetUniformLocation(repeatTexInvProgram, "s_texture");
    GLint repeatTexInvFillPortion = glGetUniformLocation(repeatTexInvProgram, "fillPortion");
    GLint repeatTexInvScale = glGetUniformLocation(repeatTexInvProgram, "repeatScale");
    m_handleArray[RepeatTexInv].init(repeatTexInvAlpha, repeatTexInvContrast,
                                     repeatTexInvPosition, repeatTexInvProgram,
                                     repeatTexInvProjMtx, -1,
                                     repeatTexInvTexSampler, -1,
                                     repeatTexInvFillPortion, repeatTexInvScale);
    initProgram(RepeatTexInv);

    GLint texOESAlpha = glGetUniformLocation(texOESProgram, "alpha");
    GLint texOESPosition = glGetAttribLocation(texOESProgram, "vPosition");
    GLint texOESProjMtx = glGetUniformLocation(texOESProgram, "projectionMatrix");
    GLint texOESTexSampler = glGetUniformLocation(texOESProgram, "s_texture");
    GLint texOESFillPortion = glGetUniformLocation(texOESProgram, "fillPortion");
    m_handleArray[TexOES].init(texOESAlpha, -1, texOESPosition, texOESProgram,
                               texOESProjMtx, -1, texOESTexSampler, -1, texOESFillPortion, -1);
    initProgram(TexOES);

    GLint texOESInvAlpha = glGetUniformLocation(texOESInvProgram, "alpha");
    GLint texOESInvContrast = glGetUniformLocation(texOESInvProgram, "contrast");
    GLint texOESInvPosition = glGetAttribLocation(texOESInvProgram, "vPosition");
    GLint texOESInvProjMtx = glGetUniformLocation(texOESInvProgram, "projectionMatrix");
    GLint texOESInvTexSampler = glGetUniformLocation(texOESInvProgram, "s_texture");
    GLint texOESInvFillPortion = glGetUniformLocation(texOESInvProgram, "fillPortion");
    m_handleArray[TexOESInv].init(texOESInvAlpha, texOESInvContrast,
                                  texOESInvPosition, texOESInvProgram,
                                  texOESInvProjMtx, -1,
                                  texOESInvTexSampler, -1, texOESInvFillPortion, -1);
    initProgram(TexOESInv);

    GLint videoPosition = glGetAttribLocation(videoProgram, "vPosition");
    GLint videoProjMtx = glGetUniformLocation(videoProgram, "projectionMatrix");
    GLint videoTexSampler = glGetUniformLocation(videoProgram, "s_yuvTexture");
    GLint videoTexMtx = glGetUniformLocation(videoProgram, "textureMatrix");
    m_handleArray[Video].init(-1, -1, videoPosition, videoProgram,
                              videoProjMtx, -1, videoTexSampler,
                              videoTexMtx, -1, -1);
    initProgram(Video);

    const GLfloat coord[] = {
        0.0f, 0.0f, // C
        1.0f, 0.0f, // D
        0.0f, 1.0f, // A
        1.0f, 1.0f // B
    };

    glGenBuffers(1, m_textureBuffer);
    glBindBuffer(GL_ARRAY_BUFFER, m_textureBuffer[0]);
    glBufferData(GL_ARRAY_BUFFER, 2 * 4 * sizeof(GLfloat), coord, GL_STATIC_DRAW);

    TransformationMatrix matrix;
    // Map x,y from (0,1) to (-1, 1)
    matrix.scale3d(2, 2, 1);
    matrix.translate3d(-0.5, -0.5, 0);
    GLUtils::toGLMatrix(m_transferProjMtx, matrix);

    m_needsInit = GLUtils::checkGlError("initGLResources");
    return;
}

void ShaderProgram::resetBlending()
{
    glDisable(GL_BLEND);
    glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
    glBlendEquation(GL_FUNC_ADD);
    m_blendingEnabled = false;
}

void ShaderProgram::setBlendingState(bool enableBlending)
{
    if (enableBlending == m_blendingEnabled)
        return;

    if (enableBlending)
        glEnable(GL_BLEND);
    else
        glDisable(GL_BLEND);

    m_blendingEnabled = enableBlending;
}

/////////////////////////////////////////////////////////////////////////////////////////
// Drawing
/////////////////////////////////////////////////////////////////////////////////////////

// We have multiple coordinates to deal with: first is the screen coordinates,
// second is the view coordinates and the last one is content(document) coordinates.
// Both screen and view coordinates are in pixels.
// All these coordinates start from upper left, but for the purpose of OpenGL
// operations, we may need a inverted Y version of such coordinates which
// start from lower left.
//
// invScreenRect - inv screen coordinates starting from lower left.
// visibleContentRect - local content(document) coordinates starting from upper left.
// screenRect - screen coordinates starting from upper left.
// screenClip - screen coordinates starting from upper left.
//    ------------------------------------------
//    |(origin of screen)                      |
//    |screen                                  |
//    |   ---------------------------------    |
//    |   | (origin of view)              |    |
//    |   | webview                       |    |
//    |   |        --------               |    |
//    |   |        | clip |               |    |
//    |   |        |      |               |    |
//    |   |        --------               |    |
//    |   |                               |    |
//    |   |(origin of inv view)           |    |
//    |   ---------------------------------    |
//    |(origin of inv screen)                  |
//    ------------------------------------------
void ShaderProgram::setupDrawing(const IntRect& invScreenRect,
                                 const SkRect& visibleContentRect,
                                 const IntRect& screenRect, int titleBarHeight,
                                 const IntRect& screenClip, float scale)
{
    m_screenRect = screenRect;
    m_titleBarHeight = titleBarHeight;

    //// viewport ////
    GLUtils::setOrthographicMatrix(m_visibleContentRectProjectionMatrix,
                                   visibleContentRect.fLeft,
                                   visibleContentRect.fTop,
                                   visibleContentRect.fRight,
                                   visibleContentRect.fBottom,
                                   -1000, 1000);

    ALOGV("set m_clipProjectionMatrix, %d, %d, %d, %d",
          screenClip.x(), screenClip.y(), screenClip.x() + screenClip.width(),
          screenClip.y() + screenClip.height());

    // In order to incorporate the animation delta X and Y, using the clip as
    // the GL viewport can save all the trouble of re-position from screenRect
    // to final position.
    GLUtils::setOrthographicMatrix(m_clipProjectionMatrix, screenClip.x(), screenClip.y(),
                                   screenClip.x() + screenClip.width(),
                                   screenClip.y() + screenClip.height(), -1000, 1000);

    glViewport(screenClip.x(), m_targetHeight - screenClip.y() - screenClip.height() ,
               screenClip.width(), screenClip.height());

    m_visibleContentRect = visibleContentRect;
    m_currentScale = scale;


    //// viewRect ////
    m_invScreenRect = invScreenRect;

    // The following matrices transform content coordinates into view coordinates
    // and inv view coordinates.
    // Note that GLUtils::setOrthographicMatrix is inverting the Y.
    TransformationMatrix viewTranslate;
    viewTranslate.translate(1.0, 1.0);

    TransformationMatrix viewScale;
    viewScale.scale3d(m_invScreenRect.width() * 0.5f, m_invScreenRect.height() * 0.5f, 1);

    m_contentToInvViewMatrix = viewScale * viewTranslate * m_visibleContentRectProjectionMatrix;

    viewTranslate.scale3d(1, -1, 1);
    m_contentToViewMatrix = viewScale * viewTranslate * m_visibleContentRectProjectionMatrix;

    IntRect invViewRect(0, 0, m_screenRect.width(), m_screenRect.height());
    m_contentViewport = m_contentToInvViewMatrix.inverse().mapRect(invViewRect);


    //// clipping ////
    IntRect viewClip = screenClip;

    // The incoming screenClip is in screen coordinates, we first
    // translate it into view coordinates.
    // Then we convert it into inverted view coordinates.
    // Therefore, in the clip() function, we need to convert things back from
    // inverted view coordinates to inverted screen coordinates which is used by GL.
    viewClip.setX(screenClip.x() - m_screenRect.x());
    viewClip.setY(screenClip.y() - m_screenRect.y() - m_titleBarHeight);
    FloatRect invViewClip = convertViewCoordToInvViewCoord(viewClip);
    m_invViewClip.setLocation(IntPoint(invViewClip.x(), invViewClip.y()));
    // use ceilf to handle view -> doc -> view coord rounding errors
    m_invViewClip.setSize(IntSize(ceilf(invViewClip.width()), ceilf(invViewClip.height())));

    resetBlending();

    // Set up m_clipProjectionMatrix, m_currentScale and m_webViewMatrix before
    // calling this function.
    setupSurfaceProjectionMatrix();

    //// initialize frame-constant values ////
    glActiveTexture(GL_TEXTURE0);
    glBindBuffer(GL_ARRAY_BUFFER, m_textureBuffer[0]);

    //// initialize GL cache ////
    m_cachedProgramType = UndefinedShader;
    m_cachedOpacity = -1;
    m_cachedFillPortion = FloatRect();
    m_cachedPureColor = Color();
}

// Calculate the right color value sent into the shader considering the (0,1)
// clamp and alpha blending.
Color ShaderProgram::shaderColor(Color pureColor, float opacity)
{
    float r = pureColor.red() / 255.0;
    float g = pureColor.green() / 255.0;
    float b = pureColor.blue() / 255.0;
    float a = pureColor.alpha() / 255.0;

    if (TilesManager::instance()->invertedScreen()) {
        float intensity = a - (0.2989 * r + 0.5866 * g + 0.1145 * b);
        intensity = ((intensity - a / 2.0) * m_contrast) + a / 2.0;
        intensity *= opacity;
        return Color(intensity, intensity, intensity, a * opacity);
    }
    return Color(r * opacity, g * opacity, b * opacity, a * opacity);
}

// For shaders using texture, it is easy to get the type from the textureTarget.
ShaderType ShaderProgram::getTextureShaderType(GLenum textureTarget,
                                               bool hasRepeatScale)
{
    ShaderType type = UndefinedShader;
    if (textureTarget == GL_TEXTURE_2D) {
        if (!TilesManager::instance()->invertedScreen())
            type = hasRepeatScale ?  RepeatTex : Tex2D;
        else {
            // With the new GPU texture upload path, we do not use an FBO
            // to blit the texture we receive from the TexturesGenerator thread.
            // To implement inverted rendering, we thus have to do the rendering
            // live, by using a different shader.
            type = hasRepeatScale ?  RepeatTexInv : Tex2DInv;
        }
    } else if (textureTarget == GL_TEXTURE_EXTERNAL_OES) {
        if (!TilesManager::instance()->invertedScreen())
            type = TexOES;
        else
            type = TexOESInv;
    }
    return type;
}

// This function transform a clip rect extracted from the current layer
// into a clip rect in InvView coordinates -- used by the clipping rects
FloatRect ShaderProgram::rectInInvViewCoord(const TransformationMatrix& drawMatrix, const IntSize& size)
{
    FloatRect srect(0, 0, size.width(), size.height());
    TransformationMatrix renderMatrix = m_contentToInvViewMatrix * drawMatrix;
    return renderMatrix.mapRect(srect);
}

// used by the partial screen invals
FloatRect ShaderProgram::rectInViewCoord(const TransformationMatrix& drawMatrix, const IntSize& size)
{
    FloatRect srect(0, 0, size.width(), size.height());
    TransformationMatrix renderMatrix = m_contentToViewMatrix * drawMatrix;
    return renderMatrix.mapRect(srect);
}

FloatRect ShaderProgram::rectInViewCoord(const FloatRect& rect)
{
    return m_contentToViewMatrix.mapRect(rect);
}

FloatRect ShaderProgram::rectInInvViewCoord(const FloatRect& rect)
{
    return m_contentToInvViewMatrix.mapRect(rect);
}

FloatRect ShaderProgram::convertInvViewCoordToContentCoord(const FloatRect& rect)
{
    return m_contentToInvViewMatrix.inverse().mapRect(rect);
}

FloatRect ShaderProgram::convertViewCoordToInvViewCoord(const FloatRect& rect)
{
    FloatRect visibleContentRect = m_contentToViewMatrix.inverse().mapRect(rect);
    return rectInInvViewCoord(visibleContentRect);
}

FloatRect ShaderProgram::convertInvViewCoordToViewCoord(const FloatRect& rect)
{
    FloatRect visibleContentRect = m_contentToInvViewMatrix.inverse().mapRect(rect);
    return rectInViewCoord(visibleContentRect);
}

// clip is in screen coordinates
void ShaderProgram::clip(const FloatRect& clip)
{
    if (clip == m_clipRect)
        return;

    ALOGV("--clipping rect %f %f, %f x %f",
          clip.x(), clip.y(), clip.width(), clip.height());

    // we should only call glScissor in this function, so that we can easily
    // track the current clipping rect.

    IntRect screenClip(clip.x(),
                       clip.y(),
                       clip.width(), clip.height());

    if (!m_invViewClip.isEmpty())
        screenClip.intersect(m_invViewClip);

    // The previous intersection calculation is using local screen coordinates.
    // Now we need to convert things from local screen coordinates to global
    // screen coordinates and pass to the GL functions.
    screenClip.setX(screenClip.x() + m_invScreenRect.x());
    screenClip.setY(screenClip.y() + m_invScreenRect.y());
    if (screenClip.x() < 0) {
        int w = screenClip.width();
        w += screenClip.x();
        screenClip.setX(0);
        screenClip.setWidth(w);
    }
    if (screenClip.y() < 0) {
        int h = screenClip.height();
        h += screenClip.y();
        screenClip.setY(0);
        screenClip.setHeight(h);
    }

    glScissor(screenClip.x(), screenClip.y(), screenClip.width(), screenClip.height());

    m_clipRect = clip;
}

IntRect ShaderProgram::clippedRectWithVisibleContentRect(const IntRect& rect, int margin)
{
    IntRect viewport(m_visibleContentRect.fLeft - margin, m_visibleContentRect.fTop - margin,
                     m_visibleContentRect.width() + margin,
                     m_visibleContentRect.height() + margin);
    viewport.intersect(rect);
    return viewport;
}

float ShaderProgram::zValue(const TransformationMatrix& drawMatrix, float w, float h)
{
    TransformationMatrix modifiedDrawMatrix = drawMatrix;
    modifiedDrawMatrix.scale3d(w, h, 1);
    TransformationMatrix renderMatrix =
        m_visibleContentRectProjectionMatrix * modifiedDrawMatrix;
    FloatPoint3D point(0.5, 0.5, 0.0);
    FloatPoint3D result = renderMatrix.mapPoint(point);
    return result.z();
}

void ShaderProgram::drawQuadInternal(ShaderType type, const GLfloat* matrix,
                                     int textureId, float opacity,
                                     GLenum textureTarget, GLenum filter,
                                     const Color& pureColor, const FloatRect& fillPortion,
                                     const FloatSize& repeatScale)
{
    if (m_cachedProgramType != type) {
        glUseProgram(m_handleArray[type].programHandle);
        glVertexAttribPointer(m_handleArray[type].positionHandle,
                              2, GL_FLOAT, GL_FALSE, 0, 0);
        m_cachedProgramType = type;
        m_cachedOpacity = -1; // reset cache for variable shared by multiple programs
    }
    glUniformMatrix4fv(m_handleArray[type].projMtxHandle, 1, GL_FALSE, matrix);

    if (type != PureColor) {
        glBindTexture(textureTarget, textureId);
        glTexParameteri(textureTarget, GL_TEXTURE_MIN_FILTER, filter);
        glTexParameteri(textureTarget, GL_TEXTURE_MAG_FILTER, filter);

        if (m_cachedOpacity != opacity) {
            glUniform1f(m_handleArray[type].alphaHandle, opacity);
            m_cachedOpacity = opacity;
        }

        GLint contrastHandle = m_handleArray[type].contrastHandle;
        if (contrastHandle != -1)
            glUniform1f(contrastHandle, m_contrast);

        if (m_cachedFillPortion != fillPortion) {
            glUniform4f(m_handleArray[type].fillPortionHandle, fillPortion.x(), fillPortion.y(),
                        fillPortion.width(), fillPortion.height());
            m_cachedFillPortion = fillPortion;
        }

        // Only when we have repeat scale, this handle can be >= 0;
        if (m_handleArray[type].scaleHandle != -1) {
            glUniform2f(m_handleArray[type].scaleHandle,
                        repeatScale.width(), repeatScale.height());
        }
    } else {
        if (m_cachedPureColor != pureColor) {
            glUniform4f(m_handleArray[type].pureColorHandle,
                        pureColor.red() / 255.0, pureColor.green() / 255.0,
                        pureColor.blue() / 255.0, pureColor.alpha() / 255.0);
            m_cachedPureColor = pureColor;
        }
    }

    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
}

// Put the common matrix computation at higher level to avoid redundancy.
void ShaderProgram::setupSurfaceProjectionMatrix()
{
    TransformationMatrix scaleMatrix;
    scaleMatrix.scale3d(m_currentScale, m_currentScale, 1);
    m_surfaceProjectionMatrix = m_clipProjectionMatrix * m_webViewMatrix * scaleMatrix;
}

// Calculate the matrix given the geometry.
GLfloat* ShaderProgram::getTileProjectionMatrix(const DrawQuadData* data)
{
    DrawQuadType type = data->type();
    if (type == Blit)
        return m_transferProjMtx;

    const TransformationMatrix* matrix = data->drawMatrix();
    const SkRect* geometry = data->geometry();
    FloatRect fillPortion = data->fillPortion();
    ALOGV("fillPortion " FLOAT_RECT_FORMAT, FLOAT_RECT_ARGS(fillPortion));

    // This modifiedDrawMatrix tranform (0,0)(1x1) to the final rect in screen
    // coordinates, before applying the m_webViewMatrix.
    // It first scale and translate the vertex array from (0,0)(1x1) to real
    // tile position and size. Then apply the transform from the layer's.
    // Finally scale to the currentScale to support zooming.
    // Note the geometry contains the tile zoom scale, so visually we will see
    // the tiles scale at a ratio as (m_currentScale/tile's scale).
    TransformationMatrix modifiedDrawMatrix;
    if (type == LayerQuad)
        modifiedDrawMatrix = *matrix;
    modifiedDrawMatrix.translate(geometry->fLeft + geometry->width() * fillPortion.x(),
                                 geometry->fTop + geometry->height() * fillPortion.y());
    modifiedDrawMatrix.scale3d(geometry->width() * fillPortion.width(),
                               geometry->height() * fillPortion.height(), 1);

    // Even when we are on a alpha layer or not, we need to respect the
    // m_webViewMatrix, it may contain the layout offset. Normally it is
    // identity.
    TransformationMatrix renderMatrix;
    renderMatrix = m_surfaceProjectionMatrix * modifiedDrawMatrix;

#if DEBUG_MATRIX
    debugMatrixInfo(m_currentScale, m_clipProjectionMatrix, m_webViewMatrix,
                    modifiedDrawMatrix, matrix);
#endif

    GLUtils::toGLMatrix(m_tileProjMatrix, renderMatrix);
    return m_tileProjMatrix;
}

void ShaderProgram::drawQuad(const DrawQuadData* data)
{
    GLfloat* matrix = getTileProjectionMatrix(data);

    float opacity = data->opacity();
    bool forceBlending = data->forceBlending();
    bool enableBlending = forceBlending || opacity < 1.0;

    ShaderType shaderType = UndefinedShader;
    int textureId = 0;
    GLint textureFilter = 0;
    GLenum textureTarget = 0;

    Color quadColor = data->quadColor();
    if (data->pureColor()) {
        shaderType = PureColor;
        quadColor = shaderColor(quadColor, opacity);
        enableBlending = enableBlending || quadColor.hasAlpha();
        if (!quadColor.alpha() && enableBlending)
            return;
    } else {
        textureId = data->textureId();
        textureFilter = data->textureFilter();
        textureTarget = data->textureTarget();
        shaderType = getTextureShaderType(textureTarget, data->hasRepeatScale());
    }
    setBlendingState(enableBlending);
    drawQuadInternal(shaderType, matrix, textureId, opacity,
                     textureTarget, textureFilter, quadColor, data->fillPortion(),
                     data->repeatScale());
}

void ShaderProgram::drawVideoLayerQuad(const TransformationMatrix& drawMatrix,
                                       float* textureMatrix, SkRect& geometry,
                                       int textureId)
{
    // switch to our custom yuv video rendering program
    if (m_cachedProgramType != Video) {
        glUseProgram(m_handleArray[Video].programHandle);
        glVertexAttribPointer(m_handleArray[Video].positionHandle,
                              2, GL_FLOAT, GL_FALSE, 0, 0);
        m_cachedProgramType = Video;
    }

    // TODO: Merge drawVideoLayerQuad into drawQuad.
    TransformationMatrix modifiedDrawMatrix;
    modifiedDrawMatrix.scale3d(m_currentScale, m_currentScale, 1);
    modifiedDrawMatrix.multiply(drawMatrix);
    modifiedDrawMatrix.translate(geometry.fLeft, geometry.fTop);
    modifiedDrawMatrix.scale3d(geometry.width(), geometry.height(), 1);
    TransformationMatrix renderMatrix =
        m_clipProjectionMatrix * m_webViewMatrix * modifiedDrawMatrix;

    GLfloat projectionMatrix[16];
    GLUtils::toGLMatrix(projectionMatrix, renderMatrix);
    glUniformMatrix4fv(m_handleArray[Video].projMtxHandle, 1, GL_FALSE,
                       projectionMatrix);
    glUniformMatrix4fv(m_handleArray[Video].videoMtxHandle, 1, GL_FALSE,
                       textureMatrix);
    glBindTexture(GL_TEXTURE_EXTERNAL_OES, textureId);

    setBlendingState(false);
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
}

void ShaderProgram::setGLDrawInfo(const android::uirenderer::DrawGlInfo* info)
{
    GLUtils::convertToTransformationMatrix(info->transform, m_webViewMatrix);
    m_alphaLayer = info->isLayer;
    m_targetHeight = info->height;
}

// This function is called per tileGrid to minimize the computation overhead.
// The ortho projection and glViewport will map 1:1, so we don't need to
// worry about them here. Basically, if the current zoom scale / tile's scale
// plus the webview and layer transformation ends up at scale factor 1.0,
// then we can use point sampling.
bool ShaderProgram::usePointSampling(float tileScale,
                                     const TransformationMatrix* layerTransform)
{
    const float testSize = 1.0;
    FloatRect rect(0, 0, testSize, testSize);
    TransformationMatrix matrix;
    matrix.scale3d(m_currentScale, m_currentScale, 1);
    if (layerTransform)
        matrix.multiply(*layerTransform);
    matrix.scale3d(1.0 / tileScale, 1.0 / tileScale, 1);

    matrix = m_webViewMatrix * matrix;

    rect = matrix.mapRect(rect);

    float deltaWidth = abs(rect.width() - testSize);
    float deltaHeight = abs(rect.height() - testSize);

    if (deltaWidth < EPSILON && deltaHeight < EPSILON) {
        ALOGV("Point sampling : deltaWidth is %f, deltaHeight is %f", deltaWidth, deltaHeight);
        return true;
    }
    return false;
}

#if DEBUG_MATRIX
FloatRect ShaderProgram::debugMatrixTransform(const TransformationMatrix& matrix,
                                              const char* matrixName)
{
    FloatRect rect(0.0, 0.0, 1.0, 1.0);
    rect = matrix.mapRect(rect);
    ALOGV("After %s matrix:\n %f, %f rect.width() %f rect.height() %f",
          matrixName, rect.x(), rect.y(), rect.width(), rect.height());
    return rect;

}

void ShaderProgram::debugMatrixInfo(float currentScale,
                                    const TransformationMatrix& clipProjectionMatrix,
                                    const TransformationMatrix& webViewMatrix,
                                    const TransformationMatrix& modifiedDrawMatrix,
                                    const TransformationMatrix* layerMatrix)
{
    int viewport[4];
    glGetIntegerv(GL_VIEWPORT, viewport);
    ALOGV("viewport %d, %d, %d, %d , currentScale %f",
          viewport[0], viewport[1], viewport[2], viewport[3], currentScale);
    IntRect currentGLViewport(viewport[0], viewport[1], viewport[2], viewport[3]);

    TransformationMatrix scaleMatrix;
    scaleMatrix.scale3d(currentScale, currentScale, 1.0);

    if (layerMatrix)
        debugMatrixTransform(*layerMatrix, "layerMatrix");

    TransformationMatrix debugMatrix = scaleMatrix * modifiedDrawMatrix;
    debugMatrixTransform(debugMatrix, "scaleMatrix * modifiedDrawMatrix");

    debugMatrix = webViewMatrix * debugMatrix;
    debugMatrixTransform(debugMatrix, "webViewMatrix * scaleMatrix * modifiedDrawMatrix");

    debugMatrix = clipProjectionMatrix * debugMatrix;
    FloatRect finalRect =
        debugMatrixTransform(debugMatrix, "all Matrix");
    // After projection, we will be in a (-1, 1) range and now we can map it back
    // to the (x,y) -> (x+width, y+height)
    ALOGV("final convert to screen coord x, y %f, %f width %f height %f , ",
          (finalRect.x() + 1) / 2 * currentGLViewport.width() + currentGLViewport.x(),
          (finalRect.y() + 1) / 2 * currentGLViewport.height() + currentGLViewport.y(),
          finalRect.width() * currentGLViewport.width() / 2,
          finalRect.height() * currentGLViewport.height() / 2);
}
#endif // DEBUG_MATRIX

} // namespace WebCore
#endif // USE(ACCELERATED_COMPOSITING)