ProgramCache.cpp revision 253f2c213f6ecda63b6872aee77bd30d5ec07c82
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <utils/String8.h>
18
19#include "Caches.h"
20#include "ProgramCache.h"
21#include "Properties.h"
22
23namespace android {
24namespace uirenderer {
25
26///////////////////////////////////////////////////////////////////////////////
27// Defines
28///////////////////////////////////////////////////////////////////////////////
29
30#define MODULATE_OP_NO_MODULATE 0
31#define MODULATE_OP_MODULATE 1
32#define MODULATE_OP_MODULATE_A8 2
33
34#define STR(x) STR1(x)
35#define STR1(x) #x
36
37///////////////////////////////////////////////////////////////////////////////
38// Vertex shaders snippets
39///////////////////////////////////////////////////////////////////////////////
40
41const char* gVS_Header_Start =
42        "#version 100\n"
43        "attribute vec4 position;\n";
44const char* gVS_Header_Attributes_TexCoords =
45        "attribute vec2 texCoords;\n";
46const char* gVS_Header_Attributes_Colors =
47        "attribute vec4 colors;\n";
48const char* gVS_Header_Attributes_VertexAlphaParameters =
49        "attribute float vtxAlpha;\n";
50const char* gVS_Header_Uniforms_TextureTransform =
51        "uniform mat4 mainTextureTransform;\n";
52const char* gVS_Header_Uniforms =
53        "uniform mat4 projection;\n" \
54        "uniform mat4 transform;\n";
55const char* gVS_Header_Uniforms_HasGradient =
56        "uniform mat4 screenSpace;\n";
57const char* gVS_Header_Uniforms_HasBitmap =
58        "uniform mat4 textureTransform;\n"
59        "uniform mediump vec2 textureDimension;\n";
60const char* gVS_Header_Uniforms_HasRoundRectClip =
61        "uniform mat4 roundRectInvTransform;\n";
62const char* gVS_Header_Varyings_HasTexture =
63        "varying vec2 outTexCoords;\n";
64const char* gVS_Header_Varyings_HasColors =
65        "varying vec4 outColors;\n";
66const char* gVS_Header_Varyings_HasVertexAlpha =
67        "varying float alpha;\n";
68const char* gVS_Header_Varyings_HasBitmap =
69        "varying highp vec2 outBitmapTexCoords;\n";
70const char* gVS_Header_Varyings_HasGradient[6] = {
71        // Linear
72        "varying highp vec2 linear;\n",
73        "varying float linear;\n",
74
75        // Circular
76        "varying highp vec2 circular;\n",
77        "varying highp vec2 circular;\n",
78
79        // Sweep
80        "varying highp vec2 sweep;\n",
81        "varying highp vec2 sweep;\n",
82};
83const char* gVS_Header_Varyings_HasRoundRectClip =
84        "varying highp vec2 roundRectPos;\n";
85const char* gVS_Main =
86        "\nvoid main(void) {\n";
87const char* gVS_Main_OutTexCoords =
88        "    outTexCoords = texCoords;\n";
89const char* gVS_Main_OutColors =
90        "    outColors = colors;\n";
91const char* gVS_Main_OutTransformedTexCoords =
92        "    outTexCoords = (mainTextureTransform * vec4(texCoords, 0.0, 1.0)).xy;\n";
93const char* gVS_Main_OutGradient[6] = {
94        // Linear
95        "    linear = vec2((screenSpace * position).x, 0.5);\n",
96        "    linear = (screenSpace * position).x;\n",
97
98        // Circular
99        "    circular = (screenSpace * position).xy;\n",
100        "    circular = (screenSpace * position).xy;\n",
101
102        // Sweep
103        "    sweep = (screenSpace * position).xy;\n",
104        "    sweep = (screenSpace * position).xy;\n"
105};
106const char* gVS_Main_OutBitmapTexCoords =
107        "    outBitmapTexCoords = (textureTransform * position).xy * textureDimension;\n";
108const char* gVS_Main_Position =
109        "    vec4 transformedPosition = projection * transform * position;\n"
110        "    gl_Position = transformedPosition;\n";
111
112const char* gVS_Main_VertexAlpha =
113        "    alpha = vtxAlpha;\n";
114
115const char* gVS_Main_HasRoundRectClip =
116        "    roundRectPos = (roundRectInvTransform * transformedPosition).xy;\n";
117const char* gVS_Footer =
118        "}\n\n";
119
120///////////////////////////////////////////////////////////////////////////////
121// Fragment shaders snippets
122///////////////////////////////////////////////////////////////////////////////
123
124const char* gFS_Header_Start =
125        "#version 100\n";
126const char* gFS_Header_Extension_FramebufferFetch =
127        "#extension GL_NV_shader_framebuffer_fetch : enable\n\n";
128const char* gFS_Header_Extension_ExternalTexture =
129        "#extension GL_OES_EGL_image_external : require\n\n";
130const char* gFS_Header =
131        "precision mediump float;\n\n";
132const char* gFS_Uniforms_Color =
133        "uniform vec4 color;\n";
134const char* gFS_Uniforms_TextureSampler =
135        "uniform sampler2D baseSampler;\n";
136const char* gFS_Uniforms_ExternalTextureSampler =
137        "uniform samplerExternalOES baseSampler;\n";
138const char* gFS_Uniforms_GradientSampler[2] = {
139        "uniform vec2 screenSize;\n"
140        "uniform sampler2D gradientSampler;\n",
141
142        "uniform vec2 screenSize;\n"
143        "uniform vec4 startColor;\n"
144        "uniform vec4 endColor;\n"
145};
146const char* gFS_Uniforms_BitmapSampler =
147        "uniform sampler2D bitmapSampler;\n";
148const char* gFS_Uniforms_ColorOp[3] = {
149        // None
150        "",
151        // Matrix
152        "uniform mat4 colorMatrix;\n"
153        "uniform vec4 colorMatrixVector;\n",
154        // PorterDuff
155        "uniform vec4 colorBlend;\n"
156};
157
158const char* gFS_Uniforms_HasRoundRectClip =
159        "uniform vec4 roundRectInnerRectLTRB;\n"
160        "uniform float roundRectRadius;\n";
161
162// Dithering must be done in the quantization space
163// When we are writing to an sRGB framebuffer, we must do the following:
164//     EOCF(OECF(color) + dither)
165// We approximate the transfer functions with gamma 2.0 to avoid branches and pow()
166// The dithering pattern is generated with a triangle noise generator in the range [-0.5,1.5[
167// TODO: Handle linear fp16 render targets
168const char* gFS_Dither_Functions =
169        "\nmediump float triangleNoise(const highp vec2 n) {\n"
170        "    highp vec2 p = fract(n * vec2(5.3987, 5.4421));\n"
171        "    p += dot(p.yx, p.xy + vec2(21.5351, 14.3137));\n"
172        "    highp float xy = p.x * p.y;\n"
173        "    return fract(xy * 95.4307) + fract(xy * 75.04961) - 0.5;\n"
174        "}\n";
175const char* gFS_Dither_Preamble[2] = {
176        // Linear framebuffer
177        "\nvec4 dither(const vec4 color) {\n"
178        "    return vec4(color.rgb + (triangleNoise(gl_FragCoord.xy * screenSize.xy) / 255.0), color.a);"
179        "}\n",
180        // sRGB framebuffer
181        "\nvec4 dither(const vec4 color) {\n"
182        "    vec3 dithered = sqrt(color.rgb) + (triangleNoise(gl_FragCoord.xy * screenSize.xy) / 255.0);\n"
183        "    return vec4(dithered * dithered, color.a);\n"
184        "}\n"
185};
186
187// Uses luminance coefficients from Rec.709 to choose the appropriate gamma
188// The gamma() function assumes that bright text will be displayed on a dark
189// background and that dark text will be displayed on bright background
190// The gamma coefficient is chosen to thicken or thin the text accordingly
191// The dot product used to compute the luminance could be approximated with
192// a simple max(color.r, color.g, color.b)
193const char* gFS_Gamma_Preamble =
194        "\n#define GAMMA (%.2f)\n"
195        "#define GAMMA_INV (%.2f)\n"
196        "\nfloat gamma(float a, const vec3 color) {\n"
197        "    float luminance = dot(color, vec3(0.2126, 0.7152, 0.0722));\n"
198        "    return pow(a, luminance < 0.5 ? GAMMA_INV : GAMMA);\n"
199        "}\n";
200
201const char* gFS_Main =
202        "\nvoid main(void) {\n"
203        "    vec4 fragColor;\n";
204
205const char* gFS_Main_AddDither =
206        "    fragColor = dither(fragColor);\n";
207
208// Fast cases
209const char* gFS_Fast_SingleColor =
210        "\nvoid main(void) {\n"
211        "    gl_FragColor = color;\n"
212        "}\n\n";
213const char* gFS_Fast_SingleTexture =
214        "\nvoid main(void) {\n"
215        "    gl_FragColor = texture2D(baseSampler, outTexCoords);\n"
216        "}\n\n";
217const char* gFS_Fast_SingleModulateTexture =
218        "\nvoid main(void) {\n"
219        "    gl_FragColor = color.a * texture2D(baseSampler, outTexCoords);\n"
220        "}\n\n";
221const char* gFS_Fast_SingleA8Texture =
222        "\nvoid main(void) {\n"
223        "    gl_FragColor = texture2D(baseSampler, outTexCoords);\n"
224        "}\n\n";
225const char* gFS_Fast_SingleA8Texture_ApplyGamma =
226        "\nvoid main(void) {\n"
227        "    gl_FragColor = vec4(0.0, 0.0, 0.0, pow(texture2D(baseSampler, outTexCoords).a, GAMMA));\n"
228        "}\n\n";
229const char* gFS_Fast_SingleModulateA8Texture =
230        "\nvoid main(void) {\n"
231        "    gl_FragColor = color * texture2D(baseSampler, outTexCoords).a;\n"
232        "}\n\n";
233const char* gFS_Fast_SingleModulateA8Texture_ApplyGamma =
234        "\nvoid main(void) {\n"
235        "    gl_FragColor = color * gamma(texture2D(baseSampler, outTexCoords).a, color.rgb);\n"
236        "}\n\n";
237const char* gFS_Fast_SingleGradient[2] = {
238        "\nvoid main(void) {\n"
239        "    gl_FragColor = dither(texture2D(gradientSampler, linear));\n"
240        "}\n\n",
241        "\nvoid main(void) {\n"
242        "    gl_FragColor = dither(mix(startColor, endColor, clamp(linear, 0.0, 1.0)));\n"
243        "}\n\n",
244};
245const char* gFS_Fast_SingleModulateGradient[2] = {
246        "\nvoid main(void) {\n"
247        "    gl_FragColor = dither(color.a * texture2D(gradientSampler, linear));\n"
248        "}\n\n",
249        "\nvoid main(void) {\n"
250        "    gl_FragColor = dither(color.a * mix(startColor, endColor, clamp(linear, 0.0, 1.0)));\n"
251        "}\n\n"
252};
253
254// General case
255const char* gFS_Main_FetchColor =
256        "    fragColor = color;\n";
257const char* gFS_Main_ModulateColor =
258        "    fragColor *= color.a;\n";
259const char* gFS_Main_ApplyVertexAlphaLinearInterp =
260        "    fragColor *= alpha;\n";
261const char* gFS_Main_ApplyVertexAlphaShadowInterp =
262        // map alpha through shadow alpha sampler
263        "    fragColor *= texture2D(baseSampler, vec2(alpha, 0.5)).a;\n";
264const char* gFS_Main_FetchTexture[2] = {
265        // Don't modulate
266        "    fragColor = texture2D(baseSampler, outTexCoords);\n",
267        // Modulate
268        "    fragColor = color * texture2D(baseSampler, outTexCoords);\n"
269};
270const char* gFS_Main_FetchA8Texture[4] = {
271        // Don't modulate
272        "    fragColor = texture2D(baseSampler, outTexCoords);\n",
273        "    fragColor = texture2D(baseSampler, outTexCoords);\n",
274        // Modulate
275        "    fragColor = color * texture2D(baseSampler, outTexCoords).a;\n",
276        "    fragColor = color * gamma(texture2D(baseSampler, outTexCoords).a, color.rgb);\n",
277};
278const char* gFS_Main_FetchGradient[6] = {
279        // Linear
280        "    vec4 gradientColor = texture2D(gradientSampler, linear);\n",
281
282        "    vec4 gradientColor = mix(startColor, endColor, clamp(linear, 0.0, 1.0));\n",
283
284        // Circular
285        "    vec4 gradientColor = texture2D(gradientSampler, vec2(length(circular), 0.5));\n",
286
287        "    vec4 gradientColor = mix(startColor, endColor, clamp(length(circular), 0.0, 1.0));\n",
288
289        // Sweep
290        "    highp float index = atan(sweep.y, sweep.x) * 0.15915494309; // inv(2 * PI)\n"
291        "    vec4 gradientColor = texture2D(gradientSampler, vec2(index - floor(index), 0.5));\n",
292
293        "    highp float index = atan(sweep.y, sweep.x) * 0.15915494309; // inv(2 * PI)\n"
294        "    vec4 gradientColor = mix(startColor, endColor, clamp(index - floor(index), 0.0, 1.0));\n"
295};
296const char* gFS_Main_FetchBitmap =
297        "    vec4 bitmapColor = texture2D(bitmapSampler, outBitmapTexCoords);\n";
298const char* gFS_Main_FetchBitmapNpot =
299        "    vec4 bitmapColor = texture2D(bitmapSampler, wrap(outBitmapTexCoords));\n";
300const char* gFS_Main_BlendShadersBG =
301        "    fragColor = blendShaders(gradientColor, bitmapColor)";
302const char* gFS_Main_BlendShadersGB =
303        "    fragColor = blendShaders(bitmapColor, gradientColor)";
304const char* gFS_Main_BlendShaders_Modulate[6] = {
305        // Don't modulate
306        ";\n",
307        ";\n",
308        // Modulate
309        " * color.a;\n",
310        " * color.a;\n",
311        // Modulate with alpha 8 texture
312        " * texture2D(baseSampler, outTexCoords).a;\n",
313        " * gamma(texture2D(baseSampler, outTexCoords).a, color.rgb);\n",
314};
315const char* gFS_Main_GradientShader_Modulate[6] = {
316        // Don't modulate
317        "    fragColor = gradientColor;\n",
318        "    fragColor = gradientColor;\n",
319        // Modulate
320        "    fragColor = gradientColor * color.a;\n",
321        "    fragColor = gradientColor * color.a;\n",
322        // Modulate with alpha 8 texture
323        "    fragColor = gradientColor * texture2D(baseSampler, outTexCoords).a;\n",
324        "    fragColor = gradientColor * gamma(texture2D(baseSampler, outTexCoords).a, gradientColor.rgb);\n",
325    };
326const char* gFS_Main_BitmapShader_Modulate[6] = {
327        // Don't modulate
328        "    fragColor = bitmapColor;\n",
329        "    fragColor = bitmapColor;\n",
330        // Modulate
331        "    fragColor = bitmapColor * color.a;\n",
332        "    fragColor = bitmapColor * color.a;\n",
333        // Modulate with alpha 8 texture
334        "    fragColor = bitmapColor * texture2D(baseSampler, outTexCoords).a;\n",
335        "    fragColor = bitmapColor * gamma(texture2D(baseSampler, outTexCoords).a, bitmapColor.rgb);\n",
336    };
337const char* gFS_Main_FragColor =
338        "    gl_FragColor = fragColor;\n";
339const char* gFS_Main_FragColor_HasColors =
340        "    gl_FragColor *= outColors;\n";
341const char* gFS_Main_FragColor_Blend =
342        "    gl_FragColor = blendFramebuffer(fragColor, gl_LastFragColor);\n";
343const char* gFS_Main_FragColor_Blend_Swap =
344        "    gl_FragColor = blendFramebuffer(gl_LastFragColor, fragColor);\n";
345const char* gFS_Main_ApplyColorOp[3] = {
346        // None
347        "",
348        // Matrix
349        "    fragColor.rgb /= (fragColor.a + 0.0019);\n" // un-premultiply
350        "    fragColor *= colorMatrix;\n"
351        "    fragColor += colorMatrixVector;\n"
352        "    fragColor.rgb *= (fragColor.a + 0.0019);\n", // re-premultiply
353        // PorterDuff
354        "    fragColor = blendColors(colorBlend, fragColor);\n"
355};
356
357// Note: LTRB -> xyzw
358const char* gFS_Main_FragColor_HasRoundRectClip =
359        "    mediump vec2 fragToLT = roundRectInnerRectLTRB.xy - roundRectPos;\n"
360        "    mediump vec2 fragFromRB = roundRectPos - roundRectInnerRectLTRB.zw;\n"
361
362        // divide + multiply by 128 to avoid falling out of range in length() function
363        "    mediump vec2 dist = max(max(fragToLT, fragFromRB), vec2(0.0, 0.0)) / 128.0;\n"
364        "    mediump float linearDist = roundRectRadius - (length(dist) * 128.0);\n"
365        "    gl_FragColor *= clamp(linearDist, 0.0, 1.0);\n";
366
367const char* gFS_Main_DebugHighlight =
368        "    gl_FragColor.rgb = vec3(0.0, gl_FragColor.a, 0.0);\n";
369const char* gFS_Footer =
370        "}\n\n";
371
372///////////////////////////////////////////////////////////////////////////////
373// PorterDuff snippets
374///////////////////////////////////////////////////////////////////////////////
375
376const char* gBlendOps[18] = {
377        // Clear
378        "return vec4(0.0, 0.0, 0.0, 0.0);\n",
379        // Src
380        "return src;\n",
381        // Dst
382        "return dst;\n",
383        // SrcOver
384        "return src + dst * (1.0 - src.a);\n",
385        // DstOver
386        "return dst + src * (1.0 - dst.a);\n",
387        // SrcIn
388        "return src * dst.a;\n",
389        // DstIn
390        "return dst * src.a;\n",
391        // SrcOut
392        "return src * (1.0 - dst.a);\n",
393        // DstOut
394        "return dst * (1.0 - src.a);\n",
395        // SrcAtop
396        "return vec4(src.rgb * dst.a + (1.0 - src.a) * dst.rgb, dst.a);\n",
397        // DstAtop
398        "return vec4(dst.rgb * src.a + (1.0 - dst.a) * src.rgb, src.a);\n",
399        // Xor
400        "return vec4(src.rgb * (1.0 - dst.a) + (1.0 - src.a) * dst.rgb, "
401                "src.a + dst.a - 2.0 * src.a * dst.a);\n",
402        // Plus
403        "return min(src + dst, 1.0);\n",
404        // Modulate
405        "return src * dst;\n",
406        // Screen
407        "return src + dst - src * dst;\n",
408        // Overlay
409        "return clamp(vec4(mix("
410                "2.0 * src.rgb * dst.rgb + src.rgb * (1.0 - dst.a) + dst.rgb * (1.0 - src.a), "
411                "src.a * dst.a - 2.0 * (dst.a - dst.rgb) * (src.a - src.rgb) + src.rgb * (1.0 - dst.a) + dst.rgb * (1.0 - src.a), "
412                "step(dst.a, 2.0 * dst.rgb)), "
413                "src.a + dst.a - src.a * dst.a), 0.0, 1.0);\n",
414        // Darken
415        "return vec4(src.rgb * (1.0 - dst.a) + (1.0 - src.a) * dst.rgb + "
416                "min(src.rgb * dst.a, dst.rgb * src.a), src.a + dst.a - src.a * dst.a);\n",
417        // Lighten
418        "return vec4(src.rgb * (1.0 - dst.a) + (1.0 - src.a) * dst.rgb + "
419                "max(src.rgb * dst.a, dst.rgb * src.a), src.a + dst.a - src.a * dst.a);\n",
420};
421
422///////////////////////////////////////////////////////////////////////////////
423// Constructors/destructors
424///////////////////////////////////////////////////////////////////////////////
425
426ProgramCache::ProgramCache(Extensions& extensions)
427        : mHasES3(extensions.getMajorGlVersion() >= 3)
428        , mHasSRGB(extensions.hasSRGB()) {
429}
430
431ProgramCache::~ProgramCache() {
432    clear();
433}
434
435///////////////////////////////////////////////////////////////////////////////
436// Cache management
437///////////////////////////////////////////////////////////////////////////////
438
439void ProgramCache::clear() {
440    PROGRAM_LOGD("Clearing program cache");
441    mCache.clear();
442}
443
444Program* ProgramCache::get(const ProgramDescription& description) {
445    programid key = description.key();
446    if (key == (PROGRAM_KEY_TEXTURE | PROGRAM_KEY_A8_TEXTURE)) {
447        // program for A8, unmodulated, texture w/o shader (black text/path textures) is equivalent
448        // to standard texture program (bitmaps, patches). Consider them equivalent.
449        key = PROGRAM_KEY_TEXTURE;
450    }
451
452    auto iter = mCache.find(key);
453    Program* program = nullptr;
454    if (iter == mCache.end()) {
455        description.log("Could not find program");
456        program = generateProgram(description, key);
457        mCache[key] = std::unique_ptr<Program>(program);
458    } else {
459        program = iter->second.get();
460    }
461    return program;
462}
463
464///////////////////////////////////////////////////////////////////////////////
465// Program generation
466///////////////////////////////////////////////////////////////////////////////
467
468Program* ProgramCache::generateProgram(const ProgramDescription& description, programid key) {
469    String8 vertexShader = generateVertexShader(description);
470    String8 fragmentShader = generateFragmentShader(description);
471
472    return new Program(description, vertexShader.string(), fragmentShader.string());
473}
474
475static inline size_t gradientIndex(const ProgramDescription& description) {
476    return description.gradientType * 2 + description.isSimpleGradient;
477}
478
479String8 ProgramCache::generateVertexShader(const ProgramDescription& description) {
480    // Add attributes
481    String8 shader(gVS_Header_Start);
482    if (description.hasTexture || description.hasExternalTexture) {
483        shader.append(gVS_Header_Attributes_TexCoords);
484    }
485    if (description.hasVertexAlpha) {
486        shader.append(gVS_Header_Attributes_VertexAlphaParameters);
487    }
488    if (description.hasColors) {
489        shader.append(gVS_Header_Attributes_Colors);
490    }
491    // Uniforms
492    shader.append(gVS_Header_Uniforms);
493    if (description.hasTextureTransform) {
494        shader.append(gVS_Header_Uniforms_TextureTransform);
495    }
496    if (description.hasGradient) {
497        shader.append(gVS_Header_Uniforms_HasGradient);
498    }
499    if (description.hasBitmap) {
500        shader.append(gVS_Header_Uniforms_HasBitmap);
501    }
502    if (description.hasRoundRectClip) {
503        shader.append(gVS_Header_Uniforms_HasRoundRectClip);
504    }
505    // Varyings
506    if (description.hasTexture || description.hasExternalTexture) {
507        shader.append(gVS_Header_Varyings_HasTexture);
508    }
509    if (description.hasVertexAlpha) {
510        shader.append(gVS_Header_Varyings_HasVertexAlpha);
511    }
512    if (description.hasColors) {
513        shader.append(gVS_Header_Varyings_HasColors);
514    }
515    if (description.hasGradient) {
516        shader.append(gVS_Header_Varyings_HasGradient[gradientIndex(description)]);
517    }
518    if (description.hasBitmap) {
519        shader.append(gVS_Header_Varyings_HasBitmap);
520    }
521    if (description.hasRoundRectClip) {
522        shader.append(gVS_Header_Varyings_HasRoundRectClip);
523    }
524
525    // Begin the shader
526    shader.append(gVS_Main); {
527        if (description.hasTextureTransform) {
528            shader.append(gVS_Main_OutTransformedTexCoords);
529        } else if (description.hasTexture || description.hasExternalTexture) {
530            shader.append(gVS_Main_OutTexCoords);
531        }
532        if (description.hasVertexAlpha) {
533            shader.append(gVS_Main_VertexAlpha);
534        }
535        if (description.hasColors) {
536            shader.append(gVS_Main_OutColors);
537        }
538        if (description.hasBitmap) {
539            shader.append(gVS_Main_OutBitmapTexCoords);
540        }
541        // Output transformed position
542        shader.append(gVS_Main_Position);
543        if (description.hasGradient) {
544            shader.append(gVS_Main_OutGradient[gradientIndex(description)]);
545        }
546        if (description.hasRoundRectClip) {
547            shader.append(gVS_Main_HasRoundRectClip);
548        }
549    }
550    // End the shader
551    shader.append(gVS_Footer);
552
553    PROGRAM_LOGD("*** Generated vertex shader:\n\n%s", shader.string());
554
555    return shader;
556}
557
558static bool shaderOp(const ProgramDescription& description, String8& shader,
559        const int modulateOp, const char** snippets) {
560    int op = description.hasAlpha8Texture ? MODULATE_OP_MODULATE_A8 : modulateOp;
561    op = op * 2 + description.hasGammaCorrection;
562    shader.append(snippets[op]);
563    return description.hasAlpha8Texture;
564}
565
566String8 ProgramCache::generateFragmentShader(const ProgramDescription& description) {
567    String8 shader(gFS_Header_Start);
568
569    const bool blendFramebuffer = description.framebufferMode >= SkXfermode::kPlus_Mode;
570    if (blendFramebuffer) {
571        shader.append(gFS_Header_Extension_FramebufferFetch);
572    }
573    if (description.hasExternalTexture) {
574        shader.append(gFS_Header_Extension_ExternalTexture);
575    }
576
577    shader.append(gFS_Header);
578
579    // Varyings
580    if (description.hasTexture || description.hasExternalTexture) {
581        shader.append(gVS_Header_Varyings_HasTexture);
582    }
583    if (description.hasVertexAlpha) {
584        shader.append(gVS_Header_Varyings_HasVertexAlpha);
585    }
586    if (description.hasColors) {
587        shader.append(gVS_Header_Varyings_HasColors);
588    }
589    if (description.hasGradient) {
590        shader.append(gVS_Header_Varyings_HasGradient[gradientIndex(description)]);
591    }
592    if (description.hasBitmap) {
593        shader.append(gVS_Header_Varyings_HasBitmap);
594    }
595    if (description.hasRoundRectClip) {
596        shader.append(gVS_Header_Varyings_HasRoundRectClip);
597    }
598
599    // Uniforms
600    int modulateOp = MODULATE_OP_NO_MODULATE;
601    const bool singleColor = !description.hasTexture && !description.hasExternalTexture &&
602            !description.hasGradient && !description.hasBitmap;
603
604    if (description.modulate || singleColor) {
605        shader.append(gFS_Uniforms_Color);
606        if (!singleColor) modulateOp = MODULATE_OP_MODULATE;
607    }
608    if (description.hasTexture || description.useShadowAlphaInterp) {
609        shader.append(gFS_Uniforms_TextureSampler);
610    } else if (description.hasExternalTexture) {
611        shader.append(gFS_Uniforms_ExternalTextureSampler);
612    }
613    if (description.hasGradient) {
614        shader.append(gFS_Uniforms_GradientSampler[description.isSimpleGradient]);
615    }
616    if (description.hasRoundRectClip) {
617        shader.append(gFS_Uniforms_HasRoundRectClip);
618    }
619
620    if (description.hasGammaCorrection) {
621        shader.appendFormat(gFS_Gamma_Preamble, Properties::textGamma, 1.0f / Properties::textGamma);
622    }
623
624    // Optimization for common cases
625    if (!description.hasVertexAlpha
626            && !blendFramebuffer
627            && !description.hasColors
628            && description.colorOp == ProgramDescription::ColorFilterMode::None
629            && !description.hasDebugHighlight
630            && !description.hasRoundRectClip) {
631        bool fast = false;
632
633        const bool noShader = !description.hasGradient && !description.hasBitmap;
634        const bool singleTexture = (description.hasTexture || description.hasExternalTexture) &&
635                !description.hasAlpha8Texture && noShader;
636        const bool singleA8Texture = description.hasTexture &&
637                description.hasAlpha8Texture && noShader;
638        const bool singleGradient = !description.hasTexture && !description.hasExternalTexture &&
639                description.hasGradient && !description.hasBitmap &&
640                description.gradientType == ProgramDescription::kGradientLinear;
641
642        if (singleColor) {
643            shader.append(gFS_Fast_SingleColor);
644            fast = true;
645        } else if (singleTexture) {
646            if (!description.modulate) {
647                shader.append(gFS_Fast_SingleTexture);
648            } else {
649                shader.append(gFS_Fast_SingleModulateTexture);
650            }
651            fast = true;
652        } else if (singleA8Texture) {
653            if (!description.modulate) {
654                if (description.hasGammaCorrection) {
655                    shader.append(gFS_Fast_SingleA8Texture_ApplyGamma);
656                } else {
657                    shader.append(gFS_Fast_SingleA8Texture);
658                }
659            } else {
660                if (description.hasGammaCorrection) {
661                    shader.append(gFS_Fast_SingleModulateA8Texture_ApplyGamma);
662                } else {
663                    shader.append(gFS_Fast_SingleModulateA8Texture);
664                }
665            }
666            fast = true;
667        } else if (singleGradient) {
668            shader.append(gFS_Dither_Functions);
669            shader.append(gFS_Dither_Preamble[mHasSRGB]);
670            if (!description.modulate) {
671                shader.append(gFS_Fast_SingleGradient[description.isSimpleGradient]);
672            } else {
673                shader.append(gFS_Fast_SingleModulateGradient[description.isSimpleGradient]);
674            }
675            fast = true;
676        }
677
678        if (fast) {
679#if DEBUG_PROGRAMS
680                PROGRAM_LOGD("*** Fast case:\n");
681                PROGRAM_LOGD("*** Generated fragment shader:\n\n");
682                printLongString(shader);
683#endif
684
685            return shader;
686        }
687    }
688
689    if (description.hasBitmap) {
690        shader.append(gFS_Uniforms_BitmapSampler);
691    }
692    shader.append(gFS_Uniforms_ColorOp[static_cast<int>(description.colorOp)]);
693
694    // Generate required functions
695    if (description.hasGradient && description.hasBitmap) {
696        generateBlend(shader, "blendShaders", description.shadersMode);
697    }
698    if (description.colorOp == ProgramDescription::ColorFilterMode::Blend) {
699        generateBlend(shader, "blendColors", description.colorMode);
700    }
701    if (blendFramebuffer) {
702        generateBlend(shader, "blendFramebuffer", description.framebufferMode);
703    }
704    if (description.isBitmapNpot) {
705        generateTextureWrap(shader, description.bitmapWrapS, description.bitmapWrapT);
706    }
707    if (description.hasGradient) {
708        shader.append(gFS_Dither_Functions);
709        shader.append(gFS_Dither_Preamble[mHasSRGB]);
710    }
711
712    // Begin the shader
713    shader.append(gFS_Main); {
714        // Stores the result in fragColor directly
715        if (description.hasTexture || description.hasExternalTexture) {
716            if (description.hasAlpha8Texture) {
717                if (!description.hasGradient && !description.hasBitmap) {
718                    shader.append(
719                            gFS_Main_FetchA8Texture[modulateOp * 2 + description.hasGammaCorrection]);
720                }
721            } else {
722                shader.append(gFS_Main_FetchTexture[modulateOp]);
723            }
724        } else {
725            if (!description.hasGradient && !description.hasBitmap) {
726                shader.append(gFS_Main_FetchColor);
727            }
728        }
729        if (description.hasGradient) {
730            shader.append(gFS_Main_FetchGradient[gradientIndex(description)]);
731        }
732        if (description.hasBitmap) {
733            if (!description.isBitmapNpot) {
734                shader.append(gFS_Main_FetchBitmap);
735            } else {
736                shader.append(gFS_Main_FetchBitmapNpot);
737            }
738        }
739        bool applyModulate = false;
740        // Case when we have two shaders set
741        if (description.hasGradient && description.hasBitmap) {
742            if (description.isBitmapFirst) {
743                shader.append(gFS_Main_BlendShadersBG);
744            } else {
745                shader.append(gFS_Main_BlendShadersGB);
746            }
747            applyModulate = shaderOp(description, shader, modulateOp,
748                    gFS_Main_BlendShaders_Modulate);
749        } else {
750            if (description.hasGradient) {
751                applyModulate = shaderOp(description, shader, modulateOp,
752                        gFS_Main_GradientShader_Modulate);
753            } else if (description.hasBitmap) {
754                applyModulate = shaderOp(description, shader, modulateOp,
755                        gFS_Main_BitmapShader_Modulate);
756            }
757        }
758
759        if (description.modulate && applyModulate) {
760            shader.append(gFS_Main_ModulateColor);
761        }
762
763        // Apply the color op if needed
764        shader.append(gFS_Main_ApplyColorOp[static_cast<int>(description.colorOp)]);
765
766        if (description.hasVertexAlpha) {
767            if (description.useShadowAlphaInterp) {
768                shader.append(gFS_Main_ApplyVertexAlphaShadowInterp);
769            } else {
770                shader.append(gFS_Main_ApplyVertexAlphaLinearInterp);
771            }
772        }
773
774        if (description.hasGradient) {
775            shader.append(gFS_Main_AddDither);
776        }
777
778        // Output the fragment
779        if (!blendFramebuffer) {
780            shader.append(gFS_Main_FragColor);
781        } else {
782            shader.append(!description.swapSrcDst ?
783                    gFS_Main_FragColor_Blend : gFS_Main_FragColor_Blend_Swap);
784        }
785        if (description.hasColors) {
786            shader.append(gFS_Main_FragColor_HasColors);
787        }
788        if (description.hasRoundRectClip) {
789            shader.append(gFS_Main_FragColor_HasRoundRectClip);
790        }
791        if (description.hasDebugHighlight) {
792            shader.append(gFS_Main_DebugHighlight);
793        }
794    }
795    // End the shader
796    shader.append(gFS_Footer);
797
798#if DEBUG_PROGRAMS
799        PROGRAM_LOGD("*** Generated fragment shader:\n\n");
800        printLongString(shader);
801#endif
802
803    return shader;
804}
805
806void ProgramCache::generateBlend(String8& shader, const char* name, SkXfermode::Mode mode) {
807    shader.append("\nvec4 ");
808    shader.append(name);
809    shader.append("(vec4 src, vec4 dst) {\n");
810    shader.append("    ");
811    shader.append(gBlendOps[mode]);
812    shader.append("}\n");
813}
814
815void ProgramCache::generateTextureWrap(String8& shader, GLenum wrapS, GLenum wrapT) {
816    shader.append("\nhighp vec2 wrap(highp vec2 texCoords) {\n");
817    if (wrapS == GL_MIRRORED_REPEAT) {
818        shader.append("    highp float xMod2 = mod(texCoords.x, 2.0);\n");
819        shader.append("    if (xMod2 > 1.0) xMod2 = 2.0 - xMod2;\n");
820    }
821    if (wrapT == GL_MIRRORED_REPEAT) {
822        shader.append("    highp float yMod2 = mod(texCoords.y, 2.0);\n");
823        shader.append("    if (yMod2 > 1.0) yMod2 = 2.0 - yMod2;\n");
824    }
825    shader.append("    return vec2(");
826    switch (wrapS) {
827        case GL_CLAMP_TO_EDGE:
828            shader.append("texCoords.x");
829            break;
830        case GL_REPEAT:
831            shader.append("mod(texCoords.x, 1.0)");
832            break;
833        case GL_MIRRORED_REPEAT:
834            shader.append("xMod2");
835            break;
836    }
837    shader.append(", ");
838    switch (wrapT) {
839        case GL_CLAMP_TO_EDGE:
840            shader.append("texCoords.y");
841            break;
842        case GL_REPEAT:
843            shader.append("mod(texCoords.y, 1.0)");
844            break;
845        case GL_MIRRORED_REPEAT:
846            shader.append("yMod2");
847            break;
848    }
849    shader.append(");\n");
850    shader.append("}\n");
851}
852
853void ProgramCache::printLongString(const String8& shader) const {
854    ssize_t index = 0;
855    ssize_t lastIndex = 0;
856    const char* str = shader.string();
857    while ((index = shader.find("\n", index)) > -1) {
858        String8 line(str, index - lastIndex);
859        if (line.length() == 0) line.append("\n");
860        ALOGD("%s", line.string());
861        index++;
862        str += (index - lastIndex);
863        lastIndex = index;
864    }
865}
866
867}; // namespace uirenderer
868}; // namespace android
869